blob: 15aa4531b8cd747aa917a7dc14b1f3054ec46075 [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 {
Sjoerd Meijercc623ad2017-09-08 15:15:00 +000060 Float16Rank, 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
Alexander Richardson6d989432017-10-15 18:48:14 +0000700static const LangASMap *getAddressSpaceMap(const TargetInfo &T,
701 const LangOptions &LOpts) {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000702 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
Yaxun Liub7318e02017-10-13 03:37:48 +0000710 0, // opencl_private
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +0000711 4, // opencl_generic
712 5, // cuda_device
713 6, // cuda_constant
714 7 // cuda_shared
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000715 };
Douglas Gregore8bbc122011-09-02 00:18:52 +0000716 return &FakeAddrSpaceMap;
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000717 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000718 return &T.getAddressSpaceMap();
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000719 }
720}
721
David Tweed31d09b02013-09-13 12:04:22 +0000722static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI,
723 const LangOptions &LangOpts) {
724 switch (LangOpts.getAddressSpaceMapMangling()) {
David Tweed31d09b02013-09-13 12:04:22 +0000725 case LangOptions::ASMM_Target:
726 return TI.useAddressSpaceMapMangling();
727 case LangOptions::ASMM_On:
728 return true;
729 case LangOptions::ASMM_Off:
730 return false;
731 }
NAKAMURA Takumi5c81ca42013-09-13 17:12:09 +0000732 llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.");
David Tweed31d09b02013-09-13 12:04:22 +0000733}
734
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000735ASTContext::ASTContext(LangOptions &LOpts, SourceManager &SM,
Daniel Dunbar221fa942008-08-11 04:54:23 +0000736 IdentifierTable &idents, SelectorTable &sels,
Alp Toker08043432014-05-03 03:46:04 +0000737 Builtin::Context &builtins)
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000738 : FunctionProtoTypes(this_()), TemplateSpecializationTypes(this_()),
739 DependentTemplateSpecializationTypes(this_()),
740 SubstTemplateTemplateParmPacks(this_()),
741 GlobalNestedNameSpecifier(nullptr), Int128Decl(nullptr),
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +0000742 UInt128Decl(nullptr), BuiltinVaListDecl(nullptr),
743 BuiltinMSVaListDecl(nullptr), ObjCIdDecl(nullptr), ObjCSelDecl(nullptr),
744 ObjCClassDecl(nullptr), ObjCProtocolClassDecl(nullptr), BOOLDecl(nullptr),
Ben Langmuirf5416742016-02-04 00:55:24 +0000745 CFConstantStringTagDecl(nullptr), CFConstantStringTypeDecl(nullptr),
746 ObjCInstanceTypeDecl(nullptr), FILEDecl(nullptr), jmp_bufDecl(nullptr),
747 sigjmp_bufDecl(nullptr), ucontext_tDecl(nullptr),
748 BlockDescriptorType(nullptr), BlockDescriptorExtendedType(nullptr),
749 cudaConfigureCallDecl(nullptr), FirstLocalImport(), LastLocalImport(),
Eric Fiselier6ad68552016-07-01 01:24:09 +0000750 ExternCContext(nullptr), MakeIntegerSeqDecl(nullptr),
751 TypePackElementDecl(nullptr), SourceMgr(SM), LangOpts(LOpts),
Alexey Samsonova511cdd2015-02-04 17:40:08 +0000752 SanitizerBL(new SanitizerBlacklist(LangOpts.SanitizerBlacklistFiles, SM)),
Dean Michael Berris835832d2017-03-30 00:29:36 +0000753 XRayFilter(new XRayFunctionFilter(LangOpts.XRayAlwaysInstrumentFiles,
754 LangOpts.XRayNeverInstrumentFiles, SM)),
Artem Belevichb5bc9232015-09-22 17:23:22 +0000755 AddrSpaceMap(nullptr), Target(nullptr), AuxTarget(nullptr),
756 PrintingPolicy(LOpts), Idents(idents), Selectors(sels),
757 BuiltinInfo(builtins), DeclarationNames(*this), ExternalSource(nullptr),
758 Listener(nullptr), Comments(SM), CommentsLoaded(false),
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000759 CommentCommandTraits(BumpAlloc, LOpts.CommentOpts), LastSDM(nullptr, 0) {
Daniel Dunbar221fa942008-08-11 04:54:23 +0000760 TUDecl = TranslationUnitDecl::Create(*this);
761}
762
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000763ASTContext::~ASTContext() {
Manuel Klimek95403e62014-05-21 13:28:59 +0000764 ReleaseParentMapEntries();
765
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000766 // Release the DenseMaps associated with DeclContext objects.
767 // FIXME: Is this the ideal solution?
768 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-03-02 23:58:15 +0000769
Manuel Klimeka7328992013-06-03 13:51:33 +0000770 // Call all of the deallocation functions on all of their targets.
Chandler Carruthff5a01a2015-12-30 03:00:23 +0000771 for (auto &Pair : Deallocations)
772 (Pair.first)(Pair.second);
Manuel Klimeka7328992013-06-03 13:51:33 +0000773
Ted Kremenek076baeb2010-06-08 23:00:58 +0000774 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor5b11d492010-07-25 17:53:33 +0000775 // because they can contain DenseMaps.
776 for (llvm::DenseMap<const ObjCContainerDecl*,
777 const ASTRecordLayout*>::iterator
778 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
779 // Increment in loop to prevent using deallocated memory.
780 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
781 R->Destroy(*this);
782
Ted Kremenek076baeb2010-06-08 23:00:58 +0000783 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
784 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
785 // Increment in loop to prevent using deallocated memory.
786 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
787 R->Destroy(*this);
788 }
Douglas Gregor561eceb2010-08-30 16:49:28 +0000789
790 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
791 AEnd = DeclAttrs.end();
792 A != AEnd; ++A)
793 A->second->~AttrVec();
Reid Klecknerd8110b62013-09-10 20:14:30 +0000794
David Majnemere694f3e2015-08-14 14:43:50 +0000795 for (std::pair<const MaterializeTemporaryExpr *, APValue *> &MTVPair :
796 MaterializedTemporaryValues)
797 MTVPair.second->~APValue();
798
Richard Smith423f46f2016-07-20 21:38:26 +0000799 for (const auto &Value : ModuleInitializers)
800 Value.second->~PerModuleInitializers();
Douglas Gregor561eceb2010-08-30 16:49:28 +0000801}
Douglas Gregorf21eb492009-03-26 23:50:42 +0000802
Manuel Klimek95403e62014-05-21 13:28:59 +0000803void ASTContext::ReleaseParentMapEntries() {
Benjamin Kramer94355ae2015-10-23 09:04:55 +0000804 if (!PointerParents) return;
805 for (const auto &Entry : *PointerParents) {
806 if (Entry.second.is<ast_type_traits::DynTypedNode *>()) {
807 delete Entry.second.get<ast_type_traits::DynTypedNode *>();
808 } else if (Entry.second.is<ParentVector *>()) {
809 delete Entry.second.get<ParentVector *>();
810 }
811 }
812 for (const auto &Entry : *OtherParents) {
Manuel Klimek95403e62014-05-21 13:28:59 +0000813 if (Entry.second.is<ast_type_traits::DynTypedNode *>()) {
814 delete Entry.second.get<ast_type_traits::DynTypedNode *>();
Benjamin Kramer8e4a1762015-10-22 11:21:40 +0000815 } else if (Entry.second.is<ParentVector *>()) {
Manuel Klimek95403e62014-05-21 13:28:59 +0000816 delete Entry.second.get<ParentVector *>();
817 }
818 }
819}
820
Douglas Gregor1a809332010-05-23 18:26:36 +0000821void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
Chandler Carruthff5a01a2015-12-30 03:00:23 +0000822 Deallocations.push_back({Callback, Data});
Douglas Gregor1a809332010-05-23 18:26:36 +0000823}
824
Mike Stump11289f42009-09-09 15:08:12 +0000825void
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000826ASTContext::setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source) {
Benjamin Kramerd6da1a02016-06-12 20:05:23 +0000827 ExternalSource = std::move(Source);
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000828}
829
Chris Lattner4eb445d2007-01-26 01:27:23 +0000830void ASTContext::PrintStats() const {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000831 llvm::errs() << "\n*** AST Context Stats:\n";
832 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000833
Douglas Gregora30d0462009-05-26 14:40:08 +0000834 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000835#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000836#define ABSTRACT_TYPE(Name, Parent)
837#include "clang/AST/TypeNodes.def"
838 0 // Extra
839 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000840
Chris Lattner4eb445d2007-01-26 01:27:23 +0000841 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
842 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000843 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000844 }
845
Douglas Gregora30d0462009-05-26 14:40:08 +0000846 unsigned Idx = 0;
847 unsigned TotalBytes = 0;
848#define TYPE(Name, Parent) \
849 if (counts[Idx]) \
Chandler Carruth3c147a72011-07-04 05:32:14 +0000850 llvm::errs() << " " << counts[Idx] << " " << #Name \
851 << " types\n"; \
Douglas Gregora30d0462009-05-26 14:40:08 +0000852 TotalBytes += counts[Idx] * sizeof(Name##Type); \
853 ++Idx;
854#define ABSTRACT_TYPE(Name, Parent)
855#include "clang/AST/TypeNodes.def"
Mike Stump11289f42009-09-09 15:08:12 +0000856
Chandler Carruth3c147a72011-07-04 05:32:14 +0000857 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
858
Douglas Gregor7454c562010-07-02 20:37:36 +0000859 // Implicit special member functions.
Chandler Carruth3c147a72011-07-04 05:32:14 +0000860 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
861 << NumImplicitDefaultConstructors
862 << " implicit default constructors created\n";
863 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
864 << NumImplicitCopyConstructors
865 << " implicit copy constructors created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000866 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000867 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
868 << NumImplicitMoveConstructors
869 << " implicit move constructors created\n";
870 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
871 << NumImplicitCopyAssignmentOperators
872 << " implicit copy assignment operators created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000873 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000874 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
875 << NumImplicitMoveAssignmentOperators
876 << " implicit move assignment operators created\n";
877 llvm::errs() << NumImplicitDestructorsDeclared << "/"
878 << NumImplicitDestructors
879 << " implicit destructors created\n";
880
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000881 if (ExternalSource) {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000882 llvm::errs() << "\n";
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000883 ExternalSource->PrintStats();
884 }
Chandler Carruth3c147a72011-07-04 05:32:14 +0000885
Douglas Gregor5b11d492010-07-25 17:53:33 +0000886 BumpAlloc.PrintStats();
Chris Lattner4eb445d2007-01-26 01:27:23 +0000887}
888
Richard Smith42413142015-05-15 20:05:43 +0000889void ASTContext::mergeDefinitionIntoModule(NamedDecl *ND, Module *M,
890 bool NotifyListeners) {
891 if (NotifyListeners)
892 if (auto *Listener = getASTMutationListener())
893 Listener->RedefinedHiddenDefinition(ND, M);
894
Benjamin Kramera72a70a2016-10-17 13:00:44 +0000895 if (getLangOpts().ModulesLocalVisibility)
896 MergedDefModules[ND].push_back(M);
897 else
Richard Smith90dc5252017-06-23 01:04:34 +0000898 ND->setVisibleDespiteOwningModule();
Richard Smith42413142015-05-15 20:05:43 +0000899}
900
901void ASTContext::deduplicateMergedDefinitonsFor(NamedDecl *ND) {
902 auto It = MergedDefModules.find(ND);
903 if (It == MergedDefModules.end())
904 return;
905
Benjamin Kramera72a70a2016-10-17 13:00:44 +0000906 auto &Merged = It->second;
Richard Smith42413142015-05-15 20:05:43 +0000907 llvm::DenseSet<Module*> Found;
908 for (Module *&M : Merged)
909 if (!Found.insert(M).second)
910 M = nullptr;
911 Merged.erase(std::remove(Merged.begin(), Merged.end(), nullptr), Merged.end());
912}
913
Richard Smithdc1f0422016-07-20 19:10:16 +0000914void ASTContext::PerModuleInitializers::resolve(ASTContext &Ctx) {
915 if (LazyInitializers.empty())
916 return;
917
918 auto *Source = Ctx.getExternalSource();
919 assert(Source && "lazy initializers but no external source");
920
921 auto LazyInits = std::move(LazyInitializers);
922 LazyInitializers.clear();
923
924 for (auto ID : LazyInits)
925 Initializers.push_back(Source->GetExternalDecl(ID));
926
927 assert(LazyInitializers.empty() &&
928 "GetExternalDecl for lazy module initializer added more inits");
929}
930
931void ASTContext::addModuleInitializer(Module *M, Decl *D) {
932 // One special case: if we add a module initializer that imports another
933 // module, and that module's only initializer is an ImportDecl, simplify.
934 if (auto *ID = dyn_cast<ImportDecl>(D)) {
935 auto It = ModuleInitializers.find(ID->getImportedModule());
936
937 // Maybe the ImportDecl does nothing at all. (Common case.)
938 if (It == ModuleInitializers.end())
939 return;
940
941 // Maybe the ImportDecl only imports another ImportDecl.
942 auto &Imported = *It->second;
943 if (Imported.Initializers.size() + Imported.LazyInitializers.size() == 1) {
944 Imported.resolve(*this);
945 auto *OnlyDecl = Imported.Initializers.front();
946 if (isa<ImportDecl>(OnlyDecl))
947 D = OnlyDecl;
948 }
949 }
950
951 auto *&Inits = ModuleInitializers[M];
952 if (!Inits)
953 Inits = new (*this) PerModuleInitializers;
954 Inits->Initializers.push_back(D);
955}
956
957void ASTContext::addLazyModuleInitializers(Module *M, ArrayRef<uint32_t> IDs) {
958 auto *&Inits = ModuleInitializers[M];
959 if (!Inits)
960 Inits = new (*this) PerModuleInitializers;
961 Inits->LazyInitializers.insert(Inits->LazyInitializers.end(),
962 IDs.begin(), IDs.end());
963}
964
965ArrayRef<Decl*> ASTContext::getModuleInitializers(Module *M) {
966 auto It = ModuleInitializers.find(M);
967 if (It == ModuleInitializers.end())
968 return None;
969
970 auto *Inits = It->second;
971 Inits->resolve(*this);
972 return Inits->Initializers;
973}
974
Richard Smithf19e1272015-03-07 00:04:49 +0000975ExternCContextDecl *ASTContext::getExternCContextDecl() const {
976 if (!ExternCContext)
977 ExternCContext = ExternCContextDecl::Create(*this, getTranslationUnitDecl());
978
979 return ExternCContext;
980}
981
David Majnemerd9b1a4f2015-11-04 03:40:30 +0000982BuiltinTemplateDecl *
983ASTContext::buildBuiltinTemplateDecl(BuiltinTemplateKind BTK,
984 const IdentifierInfo *II) const {
985 auto *BuiltinTemplate = BuiltinTemplateDecl::Create(*this, TUDecl, II, BTK);
986 BuiltinTemplate->setImplicit();
987 TUDecl->addDecl(BuiltinTemplate);
988
989 return BuiltinTemplate;
990}
991
992BuiltinTemplateDecl *
993ASTContext::getMakeIntegerSeqDecl() const {
994 if (!MakeIntegerSeqDecl)
995 MakeIntegerSeqDecl = buildBuiltinTemplateDecl(BTK__make_integer_seq,
996 getMakeIntegerSeqName());
997 return MakeIntegerSeqDecl;
998}
999
Eric Fiselier6ad68552016-07-01 01:24:09 +00001000BuiltinTemplateDecl *
1001ASTContext::getTypePackElementDecl() const {
1002 if (!TypePackElementDecl)
1003 TypePackElementDecl = buildBuiltinTemplateDecl(BTK__type_pack_element,
1004 getTypePackElementName());
1005 return TypePackElementDecl;
1006}
1007
Alp Toker2dea15b2013-12-17 01:22:38 +00001008RecordDecl *ASTContext::buildImplicitRecord(StringRef Name,
1009 RecordDecl::TagKind TK) const {
Alp Toker56b5cc92013-12-15 10:36:26 +00001010 SourceLocation Loc;
1011 RecordDecl *NewDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00001012 if (getLangOpts().CPlusPlus)
1013 NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc,
1014 Loc, &Idents.get(Name));
Alp Toker56b5cc92013-12-15 10:36:26 +00001015 else
Alp Toker2dea15b2013-12-17 01:22:38 +00001016 NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
1017 &Idents.get(Name));
Alp Toker56b5cc92013-12-15 10:36:26 +00001018 NewDecl->setImplicit();
David Majnemerf8637362015-01-15 08:41:25 +00001019 NewDecl->addAttr(TypeVisibilityAttr::CreateImplicit(
1020 const_cast<ASTContext &>(*this), TypeVisibilityAttr::Default));
Alp Toker56b5cc92013-12-15 10:36:26 +00001021 return NewDecl;
1022}
1023
1024TypedefDecl *ASTContext::buildImplicitTypedef(QualType T,
1025 StringRef Name) const {
1026 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
1027 TypedefDecl *NewDecl = TypedefDecl::Create(
1028 const_cast<ASTContext &>(*this), getTranslationUnitDecl(),
1029 SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo);
1030 NewDecl->setImplicit();
1031 return NewDecl;
1032}
1033
Douglas Gregor801c99d2011-08-12 06:49:56 +00001034TypedefDecl *ASTContext::getInt128Decl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00001035 if (!Int128Decl)
1036 Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t");
Douglas Gregor801c99d2011-08-12 06:49:56 +00001037 return Int128Decl;
1038}
1039
1040TypedefDecl *ASTContext::getUInt128Decl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00001041 if (!UInt128Decl)
1042 UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t");
Douglas Gregor801c99d2011-08-12 06:49:56 +00001043 return UInt128Decl;
1044}
Chris Lattner4eb445d2007-01-26 01:27:23 +00001045
John McCall48f2d582009-10-23 23:03:21 +00001046void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall90d1c2d2009-09-24 23:30:46 +00001047 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +00001048 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +00001049 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +00001050}
1051
Artem Belevichb5bc9232015-09-22 17:23:22 +00001052void ASTContext::InitBuiltinTypes(const TargetInfo &Target,
1053 const TargetInfo *AuxTarget) {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001054 assert((!this->Target || this->Target == &Target) &&
1055 "Incorrect target reinitialization");
Chris Lattner970e54e2006-11-12 00:37:36 +00001056 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +00001057
Douglas Gregore8bbc122011-09-02 00:18:52 +00001058 this->Target = &Target;
Artem Belevichb5bc9232015-09-22 17:23:22 +00001059 this->AuxTarget = AuxTarget;
1060
Douglas Gregore8bbc122011-09-02 00:18:52 +00001061 ABI.reset(createCXXABI(Target));
1062 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
David Tweed31d09b02013-09-13 12:04:22 +00001063 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
Douglas Gregore8bbc122011-09-02 00:18:52 +00001064
Chris Lattner970e54e2006-11-12 00:37:36 +00001065 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +00001066 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +00001067
Chris Lattner970e54e2006-11-12 00:37:36 +00001068 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +00001069 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +00001070 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +00001071 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +00001072 InitBuiltinType(CharTy, BuiltinType::Char_S);
1073 else
1074 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +00001075 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +00001076 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
1077 InitBuiltinType(ShortTy, BuiltinType::Short);
1078 InitBuiltinType(IntTy, BuiltinType::Int);
1079 InitBuiltinType(LongTy, BuiltinType::Long);
1080 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +00001081
Chris Lattner970e54e2006-11-12 00:37:36 +00001082 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +00001083 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
1084 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
1085 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
1086 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
1087 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +00001088
Chris Lattner970e54e2006-11-12 00:37:36 +00001089 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +00001090 InitBuiltinType(FloatTy, BuiltinType::Float);
1091 InitBuiltinType(DoubleTy, BuiltinType::Double);
1092 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001093
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001094 // GNU extension, __float128 for IEEE quadruple precision
1095 InitBuiltinType(Float128Ty, BuiltinType::Float128);
1096
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00001097 // C11 extension ISO/IEC TS 18661-3
1098 InitBuiltinType(Float16Ty, BuiltinType::Float16);
1099
Chris Lattnerf122cef2009-04-30 02:43:43 +00001100 // GNU extension, 128-bit integers.
1101 InitBuiltinType(Int128Ty, BuiltinType::Int128);
1102 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
1103
Hans Wennborg0d81e012013-05-10 10:08:40 +00001104 // C++ 3.9.1p5
1105 if (TargetInfo::isTypeSigned(Target.getWCharType()))
1106 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
1107 else // -fshort-wchar makes wchar_t be unsigned.
1108 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
1109 if (LangOpts.CPlusPlus && LangOpts.WChar)
1110 WideCharTy = WCharTy;
1111 else {
1112 // C99 (or C++ using -fno-wchar).
1113 WideCharTy = getFromTargetType(Target.getWCharType());
1114 }
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001115
James Molloy36365542012-05-04 10:55:22 +00001116 WIntTy = getFromTargetType(Target.getWIntType());
1117
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001118 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1119 InitBuiltinType(Char16Ty, BuiltinType::Char16);
1120 else // C99
1121 Char16Ty = getFromTargetType(Target.getChar16Type());
1122
1123 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1124 InitBuiltinType(Char32Ty, BuiltinType::Char32);
1125 else // C99
1126 Char32Ty = getFromTargetType(Target.getChar32Type());
1127
Douglas Gregor4619e432008-12-05 23:32:09 +00001128 // Placeholder type for type-dependent expressions whose type is
1129 // completely unknown. No code should ever check a type against
1130 // DependentTy and users should never see it; however, it is here to
1131 // help diagnose failures to properly check for type-dependent
1132 // expressions.
1133 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001134
John McCall36e7fe32010-10-12 00:20:44 +00001135 // Placeholder type for functions.
1136 InitBuiltinType(OverloadTy, BuiltinType::Overload);
1137
John McCall0009fcc2011-04-26 20:42:42 +00001138 // Placeholder type for bound members.
1139 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
1140
John McCall526ab472011-10-25 17:37:35 +00001141 // Placeholder type for pseudo-objects.
1142 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
1143
John McCall31996342011-04-07 08:22:57 +00001144 // "any" type; useful for debugger-like clients.
1145 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
1146
John McCall8a6b59a2011-10-17 18:09:15 +00001147 // Placeholder type for unbridged ARC casts.
1148 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
1149
Eli Friedman34866c72012-08-31 00:14:07 +00001150 // Placeholder type for builtin functions.
1151 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
1152
Alexey Bataev1a3320e2015-08-25 14:24:04 +00001153 // Placeholder type for OMP array sections.
1154 if (LangOpts.OpenMP)
1155 InitBuiltinType(OMPArraySectionTy, BuiltinType::OMPArraySection);
1156
Chris Lattner970e54e2006-11-12 00:37:36 +00001157 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +00001158 FloatComplexTy = getComplexType(FloatTy);
1159 DoubleComplexTy = getComplexType(DoubleTy);
1160 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001161 Float128ComplexTy = getComplexType(Float128Ty);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001162
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001163 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +00001164 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
1165 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001166 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001167
Alexey Bader954ba212016-04-08 13:40:33 +00001168 if (LangOpts.OpenCL) {
1169#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1170 InitBuiltinType(SingletonId, BuiltinType::Id);
Alexey Baderb62f1442016-04-13 08:33:41 +00001171#include "clang/Basic/OpenCLImageTypes.def"
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001172
Guy Benyei61054192013-02-07 10:55:47 +00001173 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001174 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
Alexey Bader9c8453f2015-09-15 11:18:52 +00001175 InitBuiltinType(OCLClkEventTy, BuiltinType::OCLClkEvent);
1176 InitBuiltinType(OCLQueueTy, BuiltinType::OCLQueue);
Alexey Bader9c8453f2015-09-15 11:18:52 +00001177 InitBuiltinType(OCLReserveIDTy, BuiltinType::OCLReserveID);
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001178 }
Ted Kremeneke65b0862012-03-06 20:05:56 +00001179
1180 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian29898f42012-04-16 21:03:30 +00001181 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1182 SignedCharTy : BoolTy);
Ted Kremeneke65b0862012-03-06 20:05:56 +00001183
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001184 ObjCConstantStringType = QualType();
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00001185
1186 ObjCSuperType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +00001187
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00001188 // void * type
Yaxun Liu39195062017-08-04 18:16:31 +00001189 if (LangOpts.OpenCLVersion >= 200) {
1190 auto Q = VoidTy.getQualifiers();
1191 Q.setAddressSpace(LangAS::opencl_generic);
1192 VoidPtrTy = getPointerType(getCanonicalType(
1193 getQualifiedType(VoidTy.getUnqualifiedType(), Q)));
1194 } else {
1195 VoidPtrTy = getPointerType(VoidTy);
1196 }
Sebastian Redl576fd422009-05-10 18:38:11 +00001197
1198 // nullptr type (C++0x 2.14.7)
1199 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001200
1201 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1202 InitBuiltinType(HalfTy, BuiltinType::Half);
Meador Ingecfb60902012-07-01 15:57:25 +00001203
1204 // Builtin type used to help define __builtin_va_list.
Richard Smith9b88a4c2015-07-27 05:40:23 +00001205 VaListTagDecl = nullptr;
Chris Lattner970e54e2006-11-12 00:37:36 +00001206}
1207
David Blaikie9c902b52011-09-25 23:23:43 +00001208DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001209 return SourceMgr.getDiagnostics();
1210}
1211
Douglas Gregor561eceb2010-08-30 16:49:28 +00001212AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
1213 AttrVec *&Result = DeclAttrs[D];
1214 if (!Result) {
1215 void *Mem = Allocate(sizeof(AttrVec));
1216 Result = new (Mem) AttrVec;
1217 }
1218
1219 return *Result;
1220}
1221
1222/// \brief Erase the attributes corresponding to the given declaration.
1223void ASTContext::eraseDeclAttrs(const Decl *D) {
1224 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1225 if (Pos != DeclAttrs.end()) {
1226 Pos->second->~AttrVec();
1227 DeclAttrs.erase(Pos);
1228 }
1229}
1230
Larisse Voufo39a1e502013-08-06 01:03:05 +00001231// FIXME: Remove ?
Douglas Gregor86d142a2009-10-08 07:24:58 +00001232MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +00001233ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001234 assert(Var->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001235 return getTemplateOrSpecializationInfo(Var)
1236 .dyn_cast<MemberSpecializationInfo *>();
1237}
1238
1239ASTContext::TemplateOrSpecializationInfo
1240ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) {
1241 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1242 TemplateOrInstantiation.find(Var);
1243 if (Pos == TemplateOrInstantiation.end())
1244 return TemplateOrSpecializationInfo();
Mike Stump11289f42009-09-09 15:08:12 +00001245
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001246 return Pos->second;
1247}
1248
Mike Stump11289f42009-09-09 15:08:12 +00001249void
Douglas Gregor86d142a2009-10-08 07:24:58 +00001250ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +00001251 TemplateSpecializationKind TSK,
1252 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001253 assert(Inst->isStaticDataMember() && "Not a static data member");
1254 assert(Tmpl->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001255 setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo(
1256 Tmpl, TSK, PointOfInstantiation));
1257}
1258
1259void
1260ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst,
1261 TemplateOrSpecializationInfo TSI) {
1262 assert(!TemplateOrInstantiation[Inst] &&
1263 "Already noted what the variable was instantiated from");
1264 TemplateOrInstantiation[Inst] = TSI;
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001265}
1266
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001267FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
1268 const FunctionDecl *FD){
1269 assert(FD && "Specialization is 0");
1270 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet57928252011-08-14 14:28:49 +00001271 = ClassScopeSpecializationPattern.find(FD);
1272 if (Pos == ClassScopeSpecializationPattern.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001273 return nullptr;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001274
1275 return Pos->second;
1276}
1277
1278void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
1279 FunctionDecl *Pattern) {
1280 assert(FD && "Specialization is 0");
1281 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet57928252011-08-14 14:28:49 +00001282 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001283}
1284
John McCalle61f2ba2009-11-18 02:36:19 +00001285NamedDecl *
Richard Smithd8a9e372016-12-18 21:39:37 +00001286ASTContext::getInstantiatedFromUsingDecl(NamedDecl *UUD) {
1287 auto Pos = InstantiatedFromUsingDecl.find(UUD);
John McCallb96ec562009-12-04 22:46:56 +00001288 if (Pos == InstantiatedFromUsingDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001289 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001290
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001291 return Pos->second;
1292}
1293
1294void
Richard Smithd8a9e372016-12-18 21:39:37 +00001295ASTContext::setInstantiatedFromUsingDecl(NamedDecl *Inst, NamedDecl *Pattern) {
John McCallb96ec562009-12-04 22:46:56 +00001296 assert((isa<UsingDecl>(Pattern) ||
1297 isa<UnresolvedUsingValueDecl>(Pattern) ||
1298 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1299 "pattern decl is not a using decl");
Richard Smithd8a9e372016-12-18 21:39:37 +00001300 assert((isa<UsingDecl>(Inst) ||
1301 isa<UnresolvedUsingValueDecl>(Inst) ||
1302 isa<UnresolvedUsingTypenameDecl>(Inst)) &&
1303 "instantiation did not produce a using decl");
John McCallb96ec562009-12-04 22:46:56 +00001304 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1305 InstantiatedFromUsingDecl[Inst] = Pattern;
1306}
1307
1308UsingShadowDecl *
1309ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1310 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1311 = InstantiatedFromUsingShadowDecl.find(Inst);
1312 if (Pos == InstantiatedFromUsingShadowDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001313 return nullptr;
John McCallb96ec562009-12-04 22:46:56 +00001314
1315 return Pos->second;
1316}
1317
1318void
1319ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1320 UsingShadowDecl *Pattern) {
1321 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1322 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001323}
1324
Anders Carlsson5da84842009-09-01 04:26:58 +00001325FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1326 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1327 = InstantiatedFromUnnamedFieldDecl.find(Field);
1328 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001329 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001330
Anders Carlsson5da84842009-09-01 04:26:58 +00001331 return Pos->second;
1332}
1333
1334void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1335 FieldDecl *Tmpl) {
1336 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1337 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1338 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1339 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +00001340
Anders Carlsson5da84842009-09-01 04:26:58 +00001341 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1342}
1343
Douglas Gregor832940b2010-03-02 23:58:15 +00001344ASTContext::overridden_cxx_method_iterator
1345ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
Clement Courbet6ecaec82016-07-05 07:49:31 +00001346 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1347 OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001348 if (Pos == OverriddenMethods.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001349 return nullptr;
Douglas Gregor832940b2010-03-02 23:58:15 +00001350 return Pos->second.begin();
1351}
1352
1353ASTContext::overridden_cxx_method_iterator
1354ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
Clement Courbet6ecaec82016-07-05 07:49:31 +00001355 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1356 OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001357 if (Pos == OverriddenMethods.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001358 return nullptr;
Douglas Gregor832940b2010-03-02 23:58:15 +00001359 return Pos->second.end();
1360}
1361
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001362unsigned
1363ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
Clement Courbet6ecaec82016-07-05 07:49:31 +00001364 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1365 OverriddenMethods.find(Method->getCanonicalDecl());
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001366 if (Pos == OverriddenMethods.end())
1367 return 0;
Chandler Carruthb1bcd5d2016-06-11 04:45:38 +00001368 return Pos->second.size();
Clement Courbet8251ebf2016-06-10 11:54:43 +00001369}
1370
Clement Courbet6ecaec82016-07-05 07:49:31 +00001371ASTContext::overridden_method_range
1372ASTContext::overridden_methods(const CXXMethodDecl *Method) const {
1373 return overridden_method_range(overridden_methods_begin(Method),
1374 overridden_methods_end(Method));
1375}
1376
Douglas Gregor832940b2010-03-02 23:58:15 +00001377void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1378 const CXXMethodDecl *Overridden) {
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001379 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001380 OverriddenMethods[Method].push_back(Overridden);
1381}
1382
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +00001383void ASTContext::getOverriddenMethods(
1384 const NamedDecl *D,
1385 SmallVectorImpl<const NamedDecl *> &Overridden) const {
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001386 assert(D);
1387
1388 if (const CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidisc8e70082013-04-17 00:09:03 +00001389 Overridden.append(overridden_methods_begin(CXXMethod),
1390 overridden_methods_end(CXXMethod));
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001391 return;
1392 }
1393
1394 const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
1395 if (!Method)
1396 return;
1397
Argyrios Kyrtzidis353f6a42012-10-09 18:19:01 +00001398 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1399 Method->getOverriddenMethods(OverDecls);
Argyrios Kyrtzidisa7a10812012-10-09 20:08:43 +00001400 Overridden.append(OverDecls.begin(), OverDecls.end());
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001401}
1402
Douglas Gregor0f2a3602011-12-03 00:30:27 +00001403void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1404 assert(!Import->NextLocalImport && "Import declaration already in the chain");
1405 assert(!Import->isFromASTFile() && "Non-local import declaration");
1406 if (!FirstLocalImport) {
1407 FirstLocalImport = Import;
1408 LastLocalImport = Import;
1409 return;
1410 }
1411
1412 LastLocalImport->NextLocalImport = Import;
1413 LastLocalImport = Import;
1414}
1415
Chris Lattner53cfe802007-07-18 17:52:12 +00001416//===----------------------------------------------------------------------===//
1417// Type Sizing and Analysis
1418//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +00001419
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001420/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1421/// scalar floating point type.
1422const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +00001423 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001424 assert(BT && "Not a floating point type!");
1425 switch (BT->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001426 default: llvm_unreachable("Not a floating point type!");
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00001427 case BuiltinType::Float16:
1428 case BuiltinType::Half:
1429 return Target->getHalfFormat();
Douglas Gregore8bbc122011-09-02 00:18:52 +00001430 case BuiltinType::Float: return Target->getFloatFormat();
1431 case BuiltinType::Double: return Target->getDoubleFormat();
1432 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001433 case BuiltinType::Float128: return Target->getFloat128Format();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001434 }
1435}
1436
Rafael Espindola71eccb32013-08-08 19:53:46 +00001437CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001438 unsigned Align = Target->getCharWidth();
Eli Friedman19a546c2009-02-22 02:56:25 +00001439
John McCall94268702010-10-08 18:24:19 +00001440 bool UseAlignAttrOnly = false;
1441 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1442 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +00001443
John McCall94268702010-10-08 18:24:19 +00001444 // __attribute__((aligned)) can increase or decrease alignment
1445 // *except* on a struct or struct member, where it only increases
1446 // alignment unless 'packed' is also specified.
1447 //
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00001448 // It is an error for alignas to decrease alignment, so we can
John McCall94268702010-10-08 18:24:19 +00001449 // ignore that possibility; Sema should diagnose it.
1450 if (isa<FieldDecl>(D)) {
1451 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1452 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1453 } else {
1454 UseAlignAttrOnly = true;
1455 }
1456 }
Fariborz Jahanian9f107182011-05-05 21:19:14 +00001457 else if (isa<FieldDecl>(D))
1458 UseAlignAttrOnly =
1459 D->hasAttr<PackedAttr>() ||
1460 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall94268702010-10-08 18:24:19 +00001461
John McCall4e819612011-01-20 07:57:12 +00001462 // If we're using the align attribute only, just ignore everything
1463 // else about the declaration and its type.
John McCall94268702010-10-08 18:24:19 +00001464 if (UseAlignAttrOnly) {
John McCall4e819612011-01-20 07:57:12 +00001465 // do nothing
1466
John McCall94268702010-10-08 18:24:19 +00001467 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +00001468 QualType T = VD->getType();
Richard Smithf6d70302014-06-10 23:34:28 +00001469 if (const ReferenceType *RT = T->getAs<ReferenceType>()) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001470 if (ForAlignof)
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001471 T = RT->getPointeeType();
1472 else
1473 T = getPointerType(RT->getPointeeType());
1474 }
Richard Smithf6d70302014-06-10 23:34:28 +00001475 QualType BaseT = getBaseElementType(T);
Akira Hatanakad62f2c82017-01-06 17:56:15 +00001476 if (T->isFunctionType())
1477 Align = getTypeInfoImpl(T.getTypePtr()).Align;
1478 else if (!BaseT->isIncompleteType()) {
John McCall33ddac02011-01-19 10:06:00 +00001479 // Adjust alignments of declarations with array type by the
1480 // large-array alignment on the target.
Rafael Espindola88572752013-08-07 18:08:19 +00001481 if (const ArrayType *arrayType = getAsArrayType(T)) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001482 unsigned MinWidth = Target->getLargeArrayMinWidth();
1483 if (!ForAlignof && MinWidth) {
Rafael Espindola88572752013-08-07 18:08:19 +00001484 if (isa<VariableArrayType>(arrayType))
1485 Align = std::max(Align, Target->getLargeArrayAlign());
1486 else if (isa<ConstantArrayType>(arrayType) &&
1487 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
1488 Align = std::max(Align, Target->getLargeArrayAlign());
1489 }
John McCall33ddac02011-01-19 10:06:00 +00001490 }
Chad Rosier99ee7822011-07-26 07:03:04 +00001491 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Roger Ferrer Ibanez3fa38a12017-03-08 14:00:44 +00001492 if (BaseT.getQualifiers().hasUnaligned())
1493 Align = Target->getCharWidth();
Ulrich Weigandfa806422013-05-06 16:23:57 +00001494 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Ulrich Weigandb63f7792015-04-21 17:26:18 +00001495 if (VD->hasGlobalStorage() && !ForAlignof)
Ulrich Weigandfa806422013-05-06 16:23:57 +00001496 Align = std::max(Align, getTargetInfo().getMinGlobalAlign());
1497 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001498 }
John McCall4e819612011-01-20 07:57:12 +00001499
1500 // Fields can be subject to extra alignment constraints, like if
1501 // the field is packed, the struct is packed, or the struct has a
1502 // a max-field-alignment constraint (#pragma pack). So calculate
1503 // the actual alignment of the field within the struct, and then
1504 // (as we're expected to) constrain that by the alignment of the type.
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001505 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
1506 const RecordDecl *Parent = Field->getParent();
1507 // We can only produce a sensible answer if the record is valid.
1508 if (!Parent->isInvalidDecl()) {
1509 const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
John McCall4e819612011-01-20 07:57:12 +00001510
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001511 // Start with the record's overall alignment.
1512 unsigned FieldAlign = toBits(Layout.getAlignment());
John McCall4e819612011-01-20 07:57:12 +00001513
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001514 // Use the GCD of that and the offset within the record.
1515 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1516 if (Offset > 0) {
1517 // Alignment is always a power of 2, so the GCD will be a power of 2,
1518 // which means we get to do this crazy thing instead of Euclid's.
1519 uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1520 if (LowBitOfOffset < FieldAlign)
1521 FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1522 }
1523
1524 Align = std::min(Align, FieldAlign);
John McCall4e819612011-01-20 07:57:12 +00001525 }
Charles Davis3fc51072010-02-23 04:52:00 +00001526 }
Chris Lattner68061312009-01-24 21:53:27 +00001527 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001528
Ken Dyckcc56c542011-01-15 18:38:59 +00001529 return toCharUnitsFromBits(Align);
Chris Lattner68061312009-01-24 21:53:27 +00001530}
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001531
John McCallf1249922012-08-21 04:10:00 +00001532// getTypeInfoDataSizeInChars - Return the size of a type, in
1533// chars. If the type is a record, its data size is returned. This is
1534// the size of the memcpy that's performed when assigning this type
1535// using a trivial copy/move assignment operator.
1536std::pair<CharUnits, CharUnits>
1537ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1538 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1539
1540 // In C++, objects can sometimes be allocated into the tail padding
1541 // of a base-class subobject. We decide whether that's possible
1542 // during class layout, so here we can just trust the layout results.
1543 if (getLangOpts().CPlusPlus) {
1544 if (const RecordType *RT = T->getAs<RecordType>()) {
1545 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1546 sizeAndAlign.first = layout.getDataSize();
1547 }
1548 }
1549
1550 return sizeAndAlign;
1551}
1552
Richard Trieu04d2d942013-05-14 21:59:17 +00001553/// getConstantArrayInfoInChars - Performing the computation in CharUnits
1554/// instead of in bits prevents overflowing the uint64_t for some large arrays.
1555std::pair<CharUnits, CharUnits>
1556static getConstantArrayInfoInChars(const ASTContext &Context,
1557 const ConstantArrayType *CAT) {
1558 std::pair<CharUnits, CharUnits> EltInfo =
1559 Context.getTypeInfoInChars(CAT->getElementType());
1560 uint64_t Size = CAT->getSize().getZExtValue();
Richard Trieuc7509072013-05-14 23:41:50 +00001561 assert((Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity()) <=
1562 (uint64_t)(-1)/Size) &&
Richard Trieu04d2d942013-05-14 21:59:17 +00001563 "Overflow in array type char size evaluation");
1564 uint64_t Width = EltInfo.first.getQuantity() * Size;
1565 unsigned Align = EltInfo.second.getQuantity();
Warren Hunt5ae586a2013-11-01 23:59:41 +00001566 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1567 Context.getTargetInfo().getPointerWidth(0) == 64)
Rui Ueyama83aa9792016-01-14 21:00:27 +00001568 Width = llvm::alignTo(Width, Align);
Richard Trieu04d2d942013-05-14 21:59:17 +00001569 return std::make_pair(CharUnits::fromQuantity(Width),
1570 CharUnits::fromQuantity(Align));
1571}
1572
John McCall87fe5d52010-05-20 01:18:31 +00001573std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001574ASTContext::getTypeInfoInChars(const Type *T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001575 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(T))
1576 return getConstantArrayInfoInChars(*this, CAT);
David Majnemer34b57492014-07-30 01:30:47 +00001577 TypeInfo Info = getTypeInfo(T);
1578 return std::make_pair(toCharUnitsFromBits(Info.Width),
1579 toCharUnitsFromBits(Info.Align));
John McCall87fe5d52010-05-20 01:18:31 +00001580}
1581
1582std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001583ASTContext::getTypeInfoInChars(QualType T) const {
John McCall87fe5d52010-05-20 01:18:31 +00001584 return getTypeInfoInChars(T.getTypePtr());
1585}
1586
David Majnemer34b57492014-07-30 01:30:47 +00001587bool ASTContext::isAlignmentRequired(const Type *T) const {
1588 return getTypeInfo(T).AlignIsRequired;
1589}
Daniel Dunbarc6475872012-03-09 04:12:54 +00001590
David Majnemer34b57492014-07-30 01:30:47 +00001591bool ASTContext::isAlignmentRequired(QualType T) const {
1592 return isAlignmentRequired(T.getTypePtr());
1593}
1594
Richard Smithb2f0f052016-10-10 18:54:32 +00001595unsigned ASTContext::getTypeAlignIfKnown(QualType T) const {
1596 // An alignment on a typedef overrides anything else.
1597 if (auto *TT = T->getAs<TypedefType>())
1598 if (unsigned Align = TT->getDecl()->getMaxAlignment())
1599 return Align;
1600
1601 // If we have an (array of) complete type, we're done.
1602 T = getBaseElementType(T);
1603 if (!T->isIncompleteType())
1604 return getTypeAlign(T);
1605
1606 // If we had an array type, its element type might be a typedef
1607 // type with an alignment attribute.
1608 if (auto *TT = T->getAs<TypedefType>())
1609 if (unsigned Align = TT->getDecl()->getMaxAlignment())
1610 return Align;
1611
1612 // Otherwise, see if the declaration of the type had an attribute.
1613 if (auto *TT = T->getAs<TagType>())
1614 return TT->getDecl()->getMaxAlignment();
1615
1616 return 0;
1617}
1618
David Majnemer34b57492014-07-30 01:30:47 +00001619TypeInfo ASTContext::getTypeInfo(const Type *T) const {
David Majnemerf8d38642014-07-30 08:42:33 +00001620 TypeInfoMap::iterator I = MemoizedTypeInfo.find(T);
1621 if (I != MemoizedTypeInfo.end())
1622 return I->second;
1623
1624 // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup.
1625 TypeInfo TI = getTypeInfoImpl(T);
1626 MemoizedTypeInfo[T] = TI;
Rafael Espindolaeaa88c12014-07-30 04:40:23 +00001627 return TI;
Daniel Dunbarc6475872012-03-09 04:12:54 +00001628}
1629
1630/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1631/// method does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +00001632///
1633/// FIXME: Pointers into different addr spaces could have different sizes and
1634/// alignment requirements: getPointerInfo should take an AddrSpace, this
1635/// should take a QualType, &c.
David Majnemer34b57492014-07-30 01:30:47 +00001636TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
1637 uint64_t Width = 0;
1638 unsigned Align = 8;
1639 bool AlignIsRequired = false;
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00001640 unsigned AS = 0;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001641 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001642#define TYPE(Class, Base)
1643#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +00001644#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001645#define DEPENDENT_TYPE(Class, Base) case Type::Class:
David Blaikieab277d62013-07-13 21:08:03 +00001646#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
1647 case Type::Class: \
1648 assert(!T->isDependentType() && "should not see dependent types here"); \
1649 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001650#include "clang/AST/TypeNodes.def"
John McCall15547bb2011-06-28 16:49:23 +00001651 llvm_unreachable("Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001652
Chris Lattner355332d2007-07-13 22:27:08 +00001653 case Type::FunctionNoProto:
1654 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +00001655 // GCC extension: alignof(function) = 32 bits
1656 Width = 0;
1657 Align = 32;
1658 break;
1659
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001660 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +00001661 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +00001662 Width = 0;
1663 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1664 break;
1665
Steve Naroff5c131802007-08-30 01:06:46 +00001666 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001667 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +00001668
David Majnemer34b57492014-07-30 01:30:47 +00001669 TypeInfo EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001670 uint64_t Size = CAT->getSize().getZExtValue();
David Majnemer34b57492014-07-30 01:30:47 +00001671 assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
Daniel Dunbarc6475872012-03-09 04:12:54 +00001672 "Overflow in array type bit size evaluation");
David Majnemer34b57492014-07-30 01:30:47 +00001673 Width = EltInfo.Width * Size;
1674 Align = EltInfo.Align;
Warren Hunt5ae586a2013-11-01 23:59:41 +00001675 if (!getTargetInfo().getCXXABI().isMicrosoft() ||
1676 getTargetInfo().getPointerWidth(0) == 64)
Rui Ueyama83aa9792016-01-14 21:00:27 +00001677 Width = llvm::alignTo(Width, Align);
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001678 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +00001679 }
Nate Begemance4d7fc2008-04-18 23:10:10 +00001680 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001681 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +00001682 const VectorType *VT = cast<VectorType>(T);
David Majnemer34b57492014-07-30 01:30:47 +00001683 TypeInfo EltInfo = getTypeInfo(VT->getElementType());
1684 Width = EltInfo.Width * VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +00001685 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +00001686 // If the alignment is not a power of 2, round up to the next power of 2.
1687 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +00001688 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +00001689 Align = llvm::NextPowerOf2(Align);
Rui Ueyama83aa9792016-01-14 21:00:27 +00001690 Width = llvm::alignTo(Width, Align);
Chris Lattner63d2b362009-10-22 05:17:15 +00001691 }
Chad Rosiercc40ea72012-07-13 23:57:43 +00001692 // Adjust the alignment based on the target max.
1693 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1694 if (TargetVectorAlign && TargetVectorAlign < Align)
1695 Align = TargetVectorAlign;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001696 break;
1697 }
Chris Lattner647fb222007-07-18 18:26:58 +00001698
Chris Lattner7570e9c2008-03-08 08:52:55 +00001699 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +00001700 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001701 default: llvm_unreachable("Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +00001702 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +00001703 // GCC extension: alignof(void) = 8 bits.
1704 Width = 0;
1705 Align = 8;
1706 break;
1707
Chris Lattner6a4f7452007-12-19 19:23:28 +00001708 case BuiltinType::Bool:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001709 Width = Target->getBoolWidth();
1710 Align = Target->getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001711 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001712 case BuiltinType::Char_S:
1713 case BuiltinType::Char_U:
1714 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001715 case BuiltinType::SChar:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001716 Width = Target->getCharWidth();
1717 Align = Target->getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001718 break;
Chris Lattnerad3467e2010-12-25 23:25:43 +00001719 case BuiltinType::WChar_S:
1720 case BuiltinType::WChar_U:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001721 Width = Target->getWCharWidth();
1722 Align = Target->getWCharAlign();
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001723 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001724 case BuiltinType::Char16:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001725 Width = Target->getChar16Width();
1726 Align = Target->getChar16Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001727 break;
1728 case BuiltinType::Char32:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001729 Width = Target->getChar32Width();
1730 Align = Target->getChar32Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001731 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001732 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001733 case BuiltinType::Short:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001734 Width = Target->getShortWidth();
1735 Align = Target->getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001736 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001737 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001738 case BuiltinType::Int:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001739 Width = Target->getIntWidth();
1740 Align = Target->getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001741 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001742 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001743 case BuiltinType::Long:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001744 Width = Target->getLongWidth();
1745 Align = Target->getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001746 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001747 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001748 case BuiltinType::LongLong:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001749 Width = Target->getLongLongWidth();
1750 Align = Target->getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001751 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +00001752 case BuiltinType::Int128:
1753 case BuiltinType::UInt128:
1754 Width = 128;
1755 Align = 128; // int128_t is 128-bit aligned on all targets.
1756 break;
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00001757 case BuiltinType::Float16:
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001758 case BuiltinType::Half:
1759 Width = Target->getHalfWidth();
1760 Align = Target->getHalfAlign();
1761 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +00001762 case BuiltinType::Float:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001763 Width = Target->getFloatWidth();
1764 Align = Target->getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001765 break;
1766 case BuiltinType::Double:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001767 Width = Target->getDoubleWidth();
1768 Align = Target->getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001769 break;
1770 case BuiltinType::LongDouble:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001771 Width = Target->getLongDoubleWidth();
1772 Align = Target->getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001773 break;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001774 case BuiltinType::Float128:
1775 Width = Target->getFloat128Width();
1776 Align = Target->getFloat128Align();
1777 break;
Sebastian Redl576fd422009-05-10 18:38:11 +00001778 case BuiltinType::NullPtr:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001779 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1780 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +00001781 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001782 case BuiltinType::ObjCId:
1783 case BuiltinType::ObjCClass:
1784 case BuiltinType::ObjCSel:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001785 Width = Target->getPointerWidth(0);
1786 Align = Target->getPointerAlign(0);
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001787 break;
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00001788 case BuiltinType::OCLSampler:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001789 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00001790 case BuiltinType::OCLClkEvent:
1791 case BuiltinType::OCLQueue:
Alexey Bader9c8453f2015-09-15 11:18:52 +00001792 case BuiltinType::OCLReserveID:
Yaxun Liu99444cb2016-08-03 20:38:06 +00001793#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1794 case BuiltinType::Id:
1795#include "clang/Basic/OpenCLImageTypes.def"
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00001796 AS = getTargetAddressSpace(Target->getOpenCLTypeAddrSpace(T));
1797 Width = Target->getPointerWidth(AS);
1798 Align = Target->getPointerAlign(AS);
1799 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001800 }
Chris Lattner48f84b82007-07-15 23:46:53 +00001801 break;
Steve Narofffb4330f2009-06-17 22:40:22 +00001802 case Type::ObjCObjectPointer:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001803 Width = Target->getPointerWidth(0);
1804 Align = Target->getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +00001805 break;
Steve Naroff921a45c2008-09-24 15:05:44 +00001806 case Type::BlockPointer: {
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00001807 AS = getTargetAddressSpace(cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001808 Width = Target->getPointerWidth(AS);
1809 Align = Target->getPointerAlign(AS);
Steve Naroff921a45c2008-09-24 15:05:44 +00001810 break;
1811 }
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001812 case Type::LValueReference:
1813 case Type::RValueReference: {
1814 // alignof and sizeof should never enter this code path here, so we go
1815 // the pointer route.
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00001816 AS = getTargetAddressSpace(cast<ReferenceType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001817 Width = Target->getPointerWidth(AS);
1818 Align = Target->getPointerAlign(AS);
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001819 break;
1820 }
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001821 case Type::Pointer: {
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00001822 AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001823 Width = Target->getPointerWidth(AS);
1824 Align = Target->getPointerAlign(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001825 break;
1826 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001827 case Type::MemberPointer: {
Charles Davis53c59df2010-08-16 03:33:14 +00001828 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001829 std::tie(Width, Align) = ABI->getMemberPointerWidthAndAlign(MPT);
Anders Carlsson32440a02009-05-17 02:06:04 +00001830 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001831 }
Chris Lattner647fb222007-07-18 18:26:58 +00001832 case Type::Complex: {
1833 // Complex types have the same alignment as their elements, but twice the
1834 // size.
David Majnemer34b57492014-07-30 01:30:47 +00001835 TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType());
1836 Width = EltInfo.Width * 2;
1837 Align = EltInfo.Align;
Chris Lattner647fb222007-07-18 18:26:58 +00001838 break;
1839 }
John McCall8b07ec22010-05-15 11:32:37 +00001840 case Type::ObjCObject:
1841 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Reid Kleckner0503a872013-12-05 01:23:43 +00001842 case Type::Adjusted:
Reid Kleckner8a365022013-06-24 17:51:48 +00001843 case Type::Decayed:
Reid Kleckner0503a872013-12-05 01:23:43 +00001844 return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +00001845 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001846 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +00001847 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001848 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001849 Align = toBits(Layout.getAlignment());
Devang Pateldbb72632008-06-04 21:54:36 +00001850 break;
1851 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001852 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001853 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001854 const TagType *TT = cast<TagType>(T);
1855
1856 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor7f971892011-04-20 17:29:44 +00001857 Width = 8;
1858 Align = 8;
Chris Lattner572100b2008-08-09 21:35:13 +00001859 break;
1860 }
Mike Stump11289f42009-09-09 15:08:12 +00001861
David Majnemer475b25e2015-01-21 10:54:38 +00001862 if (const EnumType *ET = dyn_cast<EnumType>(TT)) {
1863 const EnumDecl *ED = ET->getDecl();
1864 TypeInfo Info =
1865 getTypeInfo(ED->getIntegerType()->getUnqualifiedDesugaredType());
1866 if (unsigned AttrAlign = ED->getMaxAlignment()) {
1867 Info.Align = AttrAlign;
1868 Info.AlignIsRequired = true;
1869 }
1870 return Info;
1871 }
Chris Lattner8b23c252008-04-06 22:05:18 +00001872
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001873 const RecordType *RT = cast<RecordType>(TT);
David Majnemer5821ff72015-02-03 08:49:29 +00001874 const RecordDecl *RD = RT->getDecl();
1875 const ASTRecordLayout &Layout = getASTRecordLayout(RD);
Ken Dyckb0fcc592011-02-11 01:54:29 +00001876 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001877 Align = toBits(Layout.getAlignment());
David Majnemer5821ff72015-02-03 08:49:29 +00001878 AlignIsRequired = RD->hasAttr<AlignedAttr>();
Chris Lattner49a953a2007-07-23 22:46:22 +00001879 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001880 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001881
Chris Lattner63d2b362009-10-22 05:17:15 +00001882 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +00001883 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1884 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +00001885
Richard Smith600b5262017-01-26 20:40:47 +00001886 case Type::Auto:
1887 case Type::DeducedTemplateSpecialization: {
1888 const DeducedType *A = cast<DeducedType>(T);
Richard Smith27d807c2013-04-30 13:56:41 +00001889 assert(!A->getDeducedType().isNull() &&
1890 "cannot request the size of an undeduced or dependent auto type");
Matt Beaumont-Gay7a24210e2011-02-22 20:00:16 +00001891 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith30482bc2011-02-20 03:19:35 +00001892 }
1893
Abramo Bagnara924a8f32010-12-10 16:29:40 +00001894 case Type::Paren:
1895 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1896
Manman Rene6be26c2016-09-13 17:25:08 +00001897 case Type::ObjCTypeParam:
1898 return getTypeInfo(cast<ObjCTypeParamType>(T)->desugar().getTypePtr());
1899
Douglas Gregoref462e62009-04-30 17:32:17 +00001900 case Type::Typedef: {
Richard Smithdda56e42011-04-15 14:24:37 +00001901 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
David Majnemer34b57492014-07-30 01:30:47 +00001902 TypeInfo Info = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattner29eb47b2011-02-19 22:55:41 +00001903 // If the typedef has an aligned attribute on it, it overrides any computed
1904 // alignment we have. This violates the GCC documentation (which says that
1905 // attribute(aligned) can only round up) but matches its implementation.
David Majnemer34b57492014-07-30 01:30:47 +00001906 if (unsigned AttrAlign = Typedef->getMaxAlignment()) {
Chris Lattner29eb47b2011-02-19 22:55:41 +00001907 Align = AttrAlign;
David Majnemer34b57492014-07-30 01:30:47 +00001908 AlignIsRequired = true;
David Majnemer37bffb62014-08-04 05:11:01 +00001909 } else {
David Majnemer34b57492014-07-30 01:30:47 +00001910 Align = Info.Align;
David Majnemer37bffb62014-08-04 05:11:01 +00001911 AlignIsRequired = Info.AlignIsRequired;
1912 }
David Majnemer34b57492014-07-30 01:30:47 +00001913 Width = Info.Width;
Douglas Gregordc572a32009-03-30 22:58:21 +00001914 break;
Chris Lattner8b23c252008-04-06 22:05:18 +00001915 }
Douglas Gregoref462e62009-04-30 17:32:17 +00001916
Abramo Bagnara6150c882010-05-11 21:36:43 +00001917 case Type::Elaborated:
1918 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +00001919
John McCall81904512011-01-06 01:58:22 +00001920 case Type::Attributed:
1921 return getTypeInfo(
1922 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1923
Eli Friedman0dfb8892011-10-06 23:00:33 +00001924 case Type::Atomic: {
John McCalla8ec7eb2013-03-07 21:37:17 +00001925 // Start with the base type information.
David Majnemer34b57492014-07-30 01:30:47 +00001926 TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType());
1927 Width = Info.Width;
1928 Align = Info.Align;
John McCalla8ec7eb2013-03-07 21:37:17 +00001929
1930 // If the size of the type doesn't exceed the platform's max
1931 // atomic promotion width, make the size and alignment more
1932 // favorable to atomic operations:
1933 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth()) {
1934 // Round the size up to a power of 2.
1935 if (!llvm::isPowerOf2_64(Width))
1936 Width = llvm::NextPowerOf2(Width);
1937
1938 // Set the alignment equal to the size.
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001939 Align = static_cast<unsigned>(Width);
1940 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00001941 }
Xiuli Pan9c14e282016-01-09 12:53:17 +00001942 break;
1943
1944 case Type::Pipe: {
Anastasia Stulovab3398932017-06-05 11:27:03 +00001945 Width = Target->getPointerWidth(getTargetAddressSpace(LangAS::opencl_global));
1946 Align = Target->getPointerAlign(getTargetAddressSpace(LangAS::opencl_global));
Xiuli Pan9c14e282016-01-09 12:53:17 +00001947 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00001948
Douglas Gregoref462e62009-04-30 17:32:17 +00001949 }
Mike Stump11289f42009-09-09 15:08:12 +00001950
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001951 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
David Majnemer34b57492014-07-30 01:30:47 +00001952 return TypeInfo(Width, Align, AlignIsRequired);
Chris Lattner983a8bb2007-07-13 22:13:22 +00001953}
1954
Alexey Bataev00396512015-07-02 03:40:19 +00001955unsigned ASTContext::getOpenMPDefaultSimdAlign(QualType T) const {
1956 unsigned SimdAlign = getTargetInfo().getSimdDefaultAlign();
1957 // Target ppc64 with QPX: simd default alignment for pointer to double is 32.
1958 if ((getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64 ||
1959 getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64le) &&
1960 getTargetInfo().getABI() == "elfv1-qpx" &&
1961 T->isSpecificBuiltinType(BuiltinType::Double))
1962 SimdAlign = 256;
1963 return SimdAlign;
1964}
1965
Ken Dyckcc56c542011-01-15 18:38:59 +00001966/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1967CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1968 return CharUnits::fromQuantity(BitSize / getCharWidth());
1969}
1970
Ken Dyckb0fcc592011-02-11 01:54:29 +00001971/// toBits - Convert a size in characters to a size in characters.
1972int64_t ASTContext::toBits(CharUnits CharSize) const {
1973 return CharSize.getQuantity() * getCharWidth();
1974}
1975
Ken Dyck8c89d592009-12-22 14:23:30 +00001976/// getTypeSizeInChars - Return the size of the specified type, in characters.
1977/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001978CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001979 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00001980}
Jay Foad39c79802011-01-12 09:06:06 +00001981CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001982 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00001983}
1984
Ken Dycka6046ab2010-01-26 17:25:18 +00001985/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +00001986/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001987CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001988 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001989}
Jay Foad39c79802011-01-12 09:06:06 +00001990CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001991 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001992}
1993
Chris Lattnera3402cd2009-01-27 18:08:34 +00001994/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1995/// type for the current target in bits. This can be different than the ABI
1996/// alignment in cases where it is beneficial for performance to overalign
1997/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +00001998unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
David Majnemer34b57492014-07-30 01:30:47 +00001999 TypeInfo TI = getTypeInfo(T);
2000 unsigned ABIAlign = TI.Align;
Eli Friedman7ab09572009-05-25 21:27:19 +00002001
David Majnemere1544562015-04-24 01:25:05 +00002002 T = T->getBaseElementTypeUnsafe();
2003
2004 // The preferred alignment of member pointers is that of a pointer.
2005 if (T->isMemberPointerType())
2006 return getPreferredTypeAlign(getPointerDiffType().getTypePtr());
2007
Andrey Turetskiydb6655f2016-02-10 11:58:46 +00002008 if (!Target->allowsLargerPreferedTypeAlignment())
2009 return ABIAlign;
Robert Lyttoneaf6f362013-11-12 10:09:34 +00002010
Eli Friedman7ab09572009-05-25 21:27:19 +00002011 // Double and long long should be naturally aligned if possible.
David Majnemer1d4db8f2014-02-24 23:43:27 +00002012 if (const ComplexType *CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +00002013 T = CT->getElementType().getTypePtr();
David Majnemer475b25e2015-01-21 10:54:38 +00002014 if (const EnumType *ET = T->getAs<EnumType>())
2015 T = ET->getDecl()->getIntegerType().getTypePtr();
Eli Friedman7ab09572009-05-25 21:27:19 +00002016 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosierb57321a2012-03-21 20:20:47 +00002017 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
2018 T->isSpecificBuiltinType(BuiltinType::ULongLong))
David Majnemer8b6bd572014-02-24 23:34:17 +00002019 // Don't increase the alignment if an alignment attribute was specified on a
2020 // typedef declaration.
David Majnemer34b57492014-07-30 01:30:47 +00002021 if (!TI.AlignIsRequired)
David Majnemer8b6bd572014-02-24 23:34:17 +00002022 return std::max(ABIAlign, (unsigned)getTypeSize(T));
Eli Friedman7ab09572009-05-25 21:27:19 +00002023
Chris Lattnera3402cd2009-01-27 18:08:34 +00002024 return ABIAlign;
2025}
2026
Ulrich Weigandca3cb7f2015-04-21 17:29:35 +00002027/// getTargetDefaultAlignForAttributeAligned - Return the default alignment
2028/// for __attribute__((aligned)) on this target, to be used if no alignment
2029/// value is specified.
Eugene Zelenkod4304d22015-11-04 21:37:17 +00002030unsigned ASTContext::getTargetDefaultAlignForAttributeAligned() const {
Ulrich Weigandca3cb7f2015-04-21 17:29:35 +00002031 return getTargetInfo().getDefaultAlignForAttributeAligned();
2032}
2033
Ulrich Weigandfa806422013-05-06 16:23:57 +00002034/// getAlignOfGlobalVar - Return the alignment in bits that should be given
2035/// to a global variable of the specified type.
2036unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
2037 return std::max(getTypeAlign(T), getTargetInfo().getMinGlobalAlign());
2038}
2039
2040/// getAlignOfGlobalVarInChars - Return the alignment in characters that
2041/// should be given to a global variable of the specified type.
2042CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
2043 return toCharUnitsFromBits(getAlignOfGlobalVar(T));
2044}
2045
David Majnemer08ef2ba2015-06-23 20:34:18 +00002046CharUnits ASTContext::getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const {
2047 CharUnits Offset = CharUnits::Zero();
2048 const ASTRecordLayout *Layout = &getASTRecordLayout(RD);
2049 while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) {
2050 Offset += Layout->getBaseClassOffset(Base);
2051 Layout = &getASTRecordLayout(Base);
2052 }
2053 return Offset;
2054}
2055
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00002056/// DeepCollectObjCIvars -
2057/// This routine first collects all declared, but not synthesized, ivars in
2058/// super class and then collects all ivars, including those synthesized for
2059/// current class. This routine is used for implementation of current class
2060/// when all ivars, declared and synthesized are known.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00002061///
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00002062void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
2063 bool leafClass,
Jordy Rosea91768e2011-07-22 02:08:32 +00002064 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00002065 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
2066 DeepCollectObjCIvars(SuperClass, false, Ivars);
2067 if (!leafClass) {
Aaron Ballman59abbd42014-03-13 21:09:43 +00002068 for (const auto *I : OI->ivars())
2069 Ivars.push_back(I);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00002070 } else {
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00002071 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosea91768e2011-07-22 02:08:32 +00002072 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00002073 Iv= Iv->getNextIvar())
2074 Ivars.push_back(Iv);
2075 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00002076}
2077
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002078/// CollectInheritedProtocols - Collect all protocols in current class and
2079/// those inherited by it.
2080void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00002081 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002082 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00002083 // We can use protocol_iterator here instead of
2084 // all_referenced_protocol_iterator since we are walking all categories.
Aaron Ballmana9f49e32014-03-13 20:55:22 +00002085 for (auto *Proto : OI->all_referenced_protocols()) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00002086 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00002087 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002088
2089 // Categories of this Interface.
Aaron Ballman3fe486a2014-03-13 21:23:55 +00002090 for (const auto *Cat : OI->visible_categories())
2091 CollectInheritedProtocols(Cat, Protocols);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002092
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002093 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
2094 while (SD) {
2095 CollectInheritedProtocols(SD, Protocols);
2096 SD = SD->getSuperClass();
2097 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00002098 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Aaron Ballman19a41762014-03-14 12:55:57 +00002099 for (auto *Proto : OC->protocols()) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00002100 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002101 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00002102 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00002103 // Insert the protocol.
2104 if (!Protocols.insert(
2105 const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second)
2106 return;
2107
2108 for (auto *Proto : OP->protocols())
2109 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002110 }
2111}
2112
Jay Foad39c79802011-01-12 09:06:06 +00002113unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00002114 unsigned count = 0;
2115 // Count ivars declared in class extension.
Aaron Ballmanb4a53452014-03-13 21:57:01 +00002116 for (const auto *Ext : OI->known_extensions())
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002117 count += Ext->ivar_size();
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002118
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00002119 // Count ivar defined in this class's implementation. This
2120 // includes synthesized ivars.
2121 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00002122 count += ImplDecl->ivar_size();
2123
Fariborz Jahanian7c809592009-06-04 01:19:09 +00002124 return count;
2125}
2126
Argyrios Kyrtzidis2e809ce2012-02-03 05:58:16 +00002127bool ASTContext::isSentinelNullExpr(const Expr *E) {
2128 if (!E)
2129 return false;
2130
2131 // nullptr_t is always treated as null.
2132 if (E->getType()->isNullPtrType()) return true;
2133
2134 if (E->getType()->isAnyPointerType() &&
2135 E->IgnoreParenCasts()->isNullPointerConstant(*this,
2136 Expr::NPC_ValueDependentIsNull))
2137 return true;
2138
2139 // Unfortunately, __null has type 'int'.
2140 if (isa<GNUNullExpr>(E)) return true;
2141
2142 return false;
2143}
2144
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002145/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
2146ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
2147 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2148 I = ObjCImpls.find(D);
2149 if (I != ObjCImpls.end())
2150 return cast<ObjCImplementationDecl>(I->second);
Craig Topper36250ad2014-05-12 05:36:57 +00002151 return nullptr;
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002152}
2153/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
2154ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
2155 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2156 I = ObjCImpls.find(D);
2157 if (I != ObjCImpls.end())
2158 return cast<ObjCCategoryImplDecl>(I->second);
Craig Topper36250ad2014-05-12 05:36:57 +00002159 return nullptr;
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002160}
2161
2162/// \brief Set the implementation of ObjCInterfaceDecl.
2163void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
2164 ObjCImplementationDecl *ImplD) {
2165 assert(IFaceD && ImplD && "Passed null params");
2166 ObjCImpls[IFaceD] = ImplD;
2167}
2168/// \brief Set the implementation of ObjCCategoryDecl.
2169void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
2170 ObjCCategoryImplDecl *ImplD) {
2171 assert(CatD && ImplD && "Passed null params");
2172 ObjCImpls[CatD] = ImplD;
2173}
2174
Chandler Carruth21c90602015-12-30 03:24:14 +00002175const ObjCMethodDecl *
2176ASTContext::getObjCMethodRedeclaration(const ObjCMethodDecl *MD) const {
2177 return ObjCMethodRedecls.lookup(MD);
2178}
2179
2180void ASTContext::setObjCMethodRedeclaration(const ObjCMethodDecl *MD,
2181 const ObjCMethodDecl *Redecl) {
2182 assert(!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration");
2183 ObjCMethodRedecls[MD] = Redecl;
2184}
2185
Dmitri Gribenko37527c22013-02-03 13:23:21 +00002186const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
2187 const NamedDecl *ND) const {
2188 if (const ObjCInterfaceDecl *ID =
2189 dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002190 return ID;
Dmitri Gribenko37527c22013-02-03 13:23:21 +00002191 if (const ObjCCategoryDecl *CD =
2192 dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002193 return CD->getClassInterface();
Dmitri Gribenko37527c22013-02-03 13:23:21 +00002194 if (const ObjCImplDecl *IMD =
2195 dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002196 return IMD->getClassInterface();
2197
Craig Topper36250ad2014-05-12 05:36:57 +00002198 return nullptr;
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002199}
2200
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002201/// \brief Get the copy initialization expression of VarDecl,or NULL if
2202/// none exists.
Fariborz Jahanian50198092010-12-02 17:02:11 +00002203Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002204 assert(VD && "Passed null params");
2205 assert(VD->hasAttr<BlocksAttr>() &&
2206 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian50198092010-12-02 17:02:11 +00002207 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002208 I = BlockVarCopyInits.find(VD);
Craig Topper36250ad2014-05-12 05:36:57 +00002209 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : nullptr;
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002210}
2211
2212/// \brief Set the copy inialization expression of a block var decl.
2213void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
2214 assert(VD && Init && "Passed null params");
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002215 assert(VD->hasAttr<BlocksAttr>() &&
2216 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002217 BlockVarCopyInits[VD] = Init;
2218}
2219
John McCallbcd03502009-12-07 02:54:59 +00002220TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00002221 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00002222 if (!DataSize)
2223 DataSize = TypeLoc::getFullDataSizeForType(T);
2224 else
2225 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00002226 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00002227
John McCallbcd03502009-12-07 02:54:59 +00002228 TypeSourceInfo *TInfo =
2229 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
2230 new (TInfo) TypeSourceInfo(T);
2231 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00002232}
2233
John McCallbcd03502009-12-07 02:54:59 +00002234TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002235 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00002236 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00002237 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00002238 return DI;
2239}
2240
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002241const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00002242ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Craig Topper36250ad2014-05-12 05:36:57 +00002243 return getObjCLayout(D, nullptr);
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002244}
2245
2246const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00002247ASTContext::getASTObjCImplementationLayout(
2248 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002249 return getObjCLayout(D->getClassInterface(), D);
2250}
2251
Chris Lattner983a8bb2007-07-13 22:13:22 +00002252//===----------------------------------------------------------------------===//
2253// Type creation/memoization methods
2254//===----------------------------------------------------------------------===//
2255
Jay Foad39c79802011-01-12 09:06:06 +00002256QualType
John McCall33ddac02011-01-19 10:06:00 +00002257ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
2258 unsigned fastQuals = quals.getFastQualifiers();
2259 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00002260
2261 // Check if we've already instantiated this type.
2262 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002263 ExtQuals::Profile(ID, baseType, quals);
Craig Topper36250ad2014-05-12 05:36:57 +00002264 void *insertPos = nullptr;
John McCall33ddac02011-01-19 10:06:00 +00002265 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
2266 assert(eq->getQualifiers() == quals);
2267 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002268 }
2269
John McCall33ddac02011-01-19 10:06:00 +00002270 // If the base type is not canonical, make the appropriate canonical type.
2271 QualType canon;
2272 if (!baseType->isCanonicalUnqualified()) {
2273 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall18ce25e2012-02-08 00:46:36 +00002274 canonSplit.Quals.addConsistentQualifiers(quals);
2275 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002276
2277 // Re-find the insert position.
2278 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
2279 }
2280
2281 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
2282 ExtQualNodes.InsertNode(eq, insertPos);
2283 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002284}
2285
Alexander Richardson6d989432017-10-15 18:48:14 +00002286QualType ASTContext::getAddrSpaceQualType(QualType T,
2287 LangAS AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002288 QualType CanT = getCanonicalType(T);
2289 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00002290 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00002291
John McCall8ccfcb52009-09-24 19:53:00 +00002292 // If we are composing extended qualifiers together, merge together
2293 // into one ExtQuals node.
2294 QualifierCollector Quals;
2295 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002296
John McCall8ccfcb52009-09-24 19:53:00 +00002297 // If this type already has an address space specified, it cannot get
2298 // another one.
2299 assert(!Quals.hasAddressSpace() &&
2300 "Type cannot be in multiple addr spaces!");
2301 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00002302
John McCall8ccfcb52009-09-24 19:53:00 +00002303 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00002304}
2305
Andrew Gozillon572bbb02017-10-02 06:25:51 +00002306QualType ASTContext::removeAddrSpaceQualType(QualType T) const {
2307 // If we are composing extended qualifiers together, merge together
2308 // into one ExtQuals node.
2309 QualifierCollector Quals;
2310 const Type *TypeNode = Quals.strip(T);
2311
2312 // If the qualifier doesn't have an address space just return it.
2313 if (!Quals.hasAddressSpace())
2314 return T;
2315
2316 Quals.removeAddressSpace();
2317
2318 // Removal of the address space can mean there are no longer any
2319 // non-fast qualifiers, so creating an ExtQualType isn't possible (asserts)
2320 // or required.
2321 if (Quals.hasNonFastQualifiers())
2322 return getExtQualType(TypeNode, Quals);
2323 else
2324 return QualType(TypeNode, Quals.getFastQualifiers());
2325}
2326
Chris Lattnerd60183d2009-02-18 22:53:11 +00002327QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00002328 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002329 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00002330 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002331 return T;
Mike Stump11289f42009-09-09 15:08:12 +00002332
John McCall53fa7142010-12-24 02:08:15 +00002333 if (const PointerType *ptr = T->getAs<PointerType>()) {
2334 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00002335 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00002336 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
2337 return getPointerType(ResultType);
2338 }
2339 }
Mike Stump11289f42009-09-09 15:08:12 +00002340
John McCall8ccfcb52009-09-24 19:53:00 +00002341 // If we are composing extended qualifiers together, merge together
2342 // into one ExtQuals node.
2343 QualifierCollector Quals;
2344 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002345
John McCall8ccfcb52009-09-24 19:53:00 +00002346 // If this type already has an ObjCGC specified, it cannot get
2347 // another one.
2348 assert(!Quals.hasObjCGCAttr() &&
2349 "Type cannot have multiple ObjCGCs!");
2350 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00002351
John McCall8ccfcb52009-09-24 19:53:00 +00002352 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002353}
Chris Lattner983a8bb2007-07-13 22:13:22 +00002354
John McCall4f5019e2010-12-19 02:44:49 +00002355const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
2356 FunctionType::ExtInfo Info) {
2357 if (T->getExtInfo() == Info)
2358 return T;
2359
2360 QualType Result;
2361 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
Alp Toker314cc812014-01-25 16:55:45 +00002362 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
John McCall4f5019e2010-12-19 02:44:49 +00002363 } else {
2364 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
2365 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2366 EPI.ExtInfo = Info;
Alp Toker314cc812014-01-25 16:55:45 +00002367 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
John McCall4f5019e2010-12-19 02:44:49 +00002368 }
2369
2370 return cast<FunctionType>(Result.getTypePtr());
2371}
2372
Richard Smith2a7d4812013-05-04 07:00:32 +00002373void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
2374 QualType ResultType) {
Richard Smith1fa5d642013-05-11 05:45:24 +00002375 FD = FD->getMostRecentDecl();
2376 while (true) {
Richard Smith2a7d4812013-05-04 07:00:32 +00002377 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
2378 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
Alp Toker9cacbab2014-01-20 20:26:09 +00002379 FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI));
Richard Smith1fa5d642013-05-11 05:45:24 +00002380 if (FunctionDecl *Next = FD->getPreviousDecl())
2381 FD = Next;
2382 else
2383 break;
Richard Smith2a7d4812013-05-04 07:00:32 +00002384 }
Richard Smith1fa5d642013-05-11 05:45:24 +00002385 if (ASTMutationListener *L = getASTMutationListener())
2386 L->DeducedReturnType(FD, ResultType);
Richard Smith2a7d4812013-05-04 07:00:32 +00002387}
2388
Richard Smith0b3a4622014-11-13 20:01:57 +00002389/// Get a function type and produce the equivalent function type with the
2390/// specified exception specification. Type sugar that can be present on a
2391/// declaration of a function with an exception specification is permitted
2392/// and preserved. Other type sugar (for instance, typedefs) is not.
2393static QualType getFunctionTypeWithExceptionSpec(
2394 ASTContext &Context, QualType Orig,
2395 const FunctionProtoType::ExceptionSpecInfo &ESI) {
2396 // Might have some parens.
2397 if (auto *PT = dyn_cast<ParenType>(Orig))
2398 return Context.getParenType(
2399 getFunctionTypeWithExceptionSpec(Context, PT->getInnerType(), ESI));
2400
2401 // Might have a calling-convention attribute.
2402 if (auto *AT = dyn_cast<AttributedType>(Orig))
2403 return Context.getAttributedType(
2404 AT->getAttrKind(),
2405 getFunctionTypeWithExceptionSpec(Context, AT->getModifiedType(), ESI),
2406 getFunctionTypeWithExceptionSpec(Context, AT->getEquivalentType(),
2407 ESI));
2408
2409 // Anything else must be a function type. Rebuild it with the new exception
2410 // specification.
2411 const FunctionProtoType *Proto = cast<FunctionProtoType>(Orig);
2412 return Context.getFunctionType(
2413 Proto->getReturnType(), Proto->getParamTypes(),
2414 Proto->getExtProtoInfo().withExceptionSpec(ESI));
2415}
2416
Richard Smithdfe85e22016-12-15 02:35:39 +00002417bool ASTContext::hasSameFunctionTypeIgnoringExceptionSpec(QualType T,
2418 QualType U) {
2419 return hasSameType(T, U) ||
2420 (getLangOpts().CPlusPlus1z &&
2421 hasSameType(getFunctionTypeWithExceptionSpec(*this, T, EST_None),
2422 getFunctionTypeWithExceptionSpec(*this, U, EST_None)));
2423}
2424
Richard Smith0b3a4622014-11-13 20:01:57 +00002425void ASTContext::adjustExceptionSpec(
2426 FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI,
2427 bool AsWritten) {
2428 // Update the type.
2429 QualType Updated =
2430 getFunctionTypeWithExceptionSpec(*this, FD->getType(), ESI);
2431 FD->setType(Updated);
2432
2433 if (!AsWritten)
2434 return;
2435
2436 // Update the type in the type source information too.
2437 if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
2438 // If the type and the type-as-written differ, we may need to update
2439 // the type-as-written too.
2440 if (TSInfo->getType() != FD->getType())
2441 Updated = getFunctionTypeWithExceptionSpec(*this, TSInfo->getType(), ESI);
2442
2443 // FIXME: When we get proper type location information for exceptions,
2444 // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
2445 // up the TypeSourceInfo;
2446 assert(TypeLoc::getFullDataSizeForType(Updated) ==
2447 TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
2448 "TypeLoc size mismatch from updating exception specification");
2449 TSInfo->overrideType(Updated);
2450 }
2451}
2452
Chris Lattnerc6395932007-06-22 20:56:16 +00002453/// getComplexType - Return the uniqued reference to the type for a complex
2454/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00002455QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00002456 // Unique pointers, to guarantee there is only one pointer of a particular
2457 // structure.
2458 llvm::FoldingSetNodeID ID;
2459 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002460
Craig Topper36250ad2014-05-12 05:36:57 +00002461 void *InsertPos = nullptr;
Chris Lattnerc6395932007-06-22 20:56:16 +00002462 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
2463 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002464
Chris Lattnerc6395932007-06-22 20:56:16 +00002465 // If the pointee type isn't canonical, this won't be a canonical type either,
2466 // so fill in the canonical type field.
2467 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002468 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002469 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002470
Chris Lattnerc6395932007-06-22 20:56:16 +00002471 // Get the new insert position for the node we care about.
2472 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002473 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00002474 }
John McCall90d1c2d2009-09-24 23:30:46 +00002475 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00002476 Types.push_back(New);
2477 ComplexTypes.InsertNode(New, InsertPos);
2478 return QualType(New, 0);
2479}
2480
Chris Lattner970e54e2006-11-12 00:37:36 +00002481/// getPointerType - Return the uniqued reference to the type for a pointer to
2482/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002483QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00002484 // Unique pointers, to guarantee there is only one pointer of a particular
2485 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002486 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00002487 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002488
Craig Topper36250ad2014-05-12 05:36:57 +00002489 void *InsertPos = nullptr;
Chris Lattner67521df2007-01-27 01:29:36 +00002490 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002491 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002492
Chris Lattner7ccecb92006-11-12 08:50:50 +00002493 // If the pointee type isn't canonical, this won't be a canonical type either,
2494 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002495 QualType Canonical;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002496 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002497 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002498
Bob Wilsonc8541f22013-03-15 17:12:43 +00002499 // Get the new insert position for the node we care about.
2500 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002501 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002502 }
John McCall90d1c2d2009-09-24 23:30:46 +00002503 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00002504 Types.push_back(New);
2505 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002506 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00002507}
2508
Reid Kleckner0503a872013-12-05 01:23:43 +00002509QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const {
2510 llvm::FoldingSetNodeID ID;
2511 AdjustedType::Profile(ID, Orig, New);
Craig Topper36250ad2014-05-12 05:36:57 +00002512 void *InsertPos = nullptr;
Reid Kleckner0503a872013-12-05 01:23:43 +00002513 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2514 if (AT)
2515 return QualType(AT, 0);
2516
2517 QualType Canonical = getCanonicalType(New);
2518
2519 // Get the new insert position for the node we care about.
2520 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002521 assert(!AT && "Shouldn't be in the map!");
Reid Kleckner0503a872013-12-05 01:23:43 +00002522
2523 AT = new (*this, TypeAlignment)
2524 AdjustedType(Type::Adjusted, Orig, New, Canonical);
2525 Types.push_back(AT);
2526 AdjustedTypes.InsertNode(AT, InsertPos);
2527 return QualType(AT, 0);
2528}
2529
Reid Kleckner8a365022013-06-24 17:51:48 +00002530QualType ASTContext::getDecayedType(QualType T) const {
2531 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
2532
Reid Kleckner8a365022013-06-24 17:51:48 +00002533 QualType Decayed;
2534
2535 // C99 6.7.5.3p7:
2536 // A declaration of a parameter as "array of type" shall be
2537 // adjusted to "qualified pointer to type", where the type
2538 // qualifiers (if any) are those specified within the [ and ] of
2539 // the array type derivation.
2540 if (T->isArrayType())
2541 Decayed = getArrayDecayedType(T);
2542
2543 // C99 6.7.5.3p8:
2544 // A declaration of a parameter as "function returning type"
2545 // shall be adjusted to "pointer to function returning type", as
2546 // in 6.3.2.1.
2547 if (T->isFunctionType())
2548 Decayed = getPointerType(T);
2549
Reid Kleckner0503a872013-12-05 01:23:43 +00002550 llvm::FoldingSetNodeID ID;
2551 AdjustedType::Profile(ID, T, Decayed);
Craig Topper36250ad2014-05-12 05:36:57 +00002552 void *InsertPos = nullptr;
Reid Kleckner0503a872013-12-05 01:23:43 +00002553 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2554 if (AT)
2555 return QualType(AT, 0);
2556
Reid Kleckner8a365022013-06-24 17:51:48 +00002557 QualType Canonical = getCanonicalType(Decayed);
2558
2559 // Get the new insert position for the node we care about.
Reid Kleckner0503a872013-12-05 01:23:43 +00002560 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002561 assert(!AT && "Shouldn't be in the map!");
Reid Kleckner8a365022013-06-24 17:51:48 +00002562
Reid Kleckner0503a872013-12-05 01:23:43 +00002563 AT = new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical);
2564 Types.push_back(AT);
2565 AdjustedTypes.InsertNode(AT, InsertPos);
2566 return QualType(AT, 0);
Reid Kleckner8a365022013-06-24 17:51:48 +00002567}
2568
Mike Stump11289f42009-09-09 15:08:12 +00002569/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00002570/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00002571QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00002572 assert(T->isFunctionType() && "block of function types only");
2573 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00002574 // structure.
2575 llvm::FoldingSetNodeID ID;
2576 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002577
Craig Topper36250ad2014-05-12 05:36:57 +00002578 void *InsertPos = nullptr;
Steve Naroffec33ed92008-08-27 16:04:49 +00002579 if (BlockPointerType *PT =
2580 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2581 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002582
2583 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00002584 // type either so fill in the canonical type field.
2585 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002586 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00002587 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002588
Steve Naroffec33ed92008-08-27 16:04:49 +00002589 // Get the new insert position for the node we care about.
2590 BlockPointerType *NewIP =
2591 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002592 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00002593 }
John McCall90d1c2d2009-09-24 23:30:46 +00002594 BlockPointerType *New
2595 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00002596 Types.push_back(New);
2597 BlockPointerTypes.InsertNode(New, InsertPos);
2598 return QualType(New, 0);
2599}
2600
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002601/// getLValueReferenceType - Return the uniqued reference to the type for an
2602/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002603QualType
2604ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor291e8ee2011-05-21 22:16:50 +00002605 assert(getCanonicalType(T) != OverloadTy &&
2606 "Unresolved overloaded function type");
2607
Bill Wendling3708c182007-05-27 10:15:43 +00002608 // Unique pointers, to guarantee there is only one pointer of a particular
2609 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002610 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002611 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002612
Craig Topper36250ad2014-05-12 05:36:57 +00002613 void *InsertPos = nullptr;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002614 if (LValueReferenceType *RT =
2615 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00002616 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002617
John McCallfc93cf92009-10-22 22:37:11 +00002618 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2619
Bill Wendling3708c182007-05-27 10:15:43 +00002620 // If the referencee type isn't canonical, this won't be a canonical type
2621 // either, so fill in the canonical type field.
2622 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002623 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
2624 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2625 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002626
Bill Wendling3708c182007-05-27 10:15:43 +00002627 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002628 LValueReferenceType *NewIP =
2629 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002630 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00002631 }
2632
John McCall90d1c2d2009-09-24 23:30:46 +00002633 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00002634 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
2635 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002636 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002637 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00002638
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002639 return QualType(New, 0);
2640}
2641
2642/// getRValueReferenceType - Return the uniqued reference to the type for an
2643/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002644QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002645 // Unique pointers, to guarantee there is only one pointer of a particular
2646 // structure.
2647 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002648 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002649
Craig Topper36250ad2014-05-12 05:36:57 +00002650 void *InsertPos = nullptr;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002651 if (RValueReferenceType *RT =
2652 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2653 return QualType(RT, 0);
2654
John McCallfc93cf92009-10-22 22:37:11 +00002655 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2656
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002657 // If the referencee type isn't canonical, this won't be a canonical type
2658 // either, so fill in the canonical type field.
2659 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002660 if (InnerRef || !T.isCanonical()) {
2661 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2662 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002663
2664 // Get the new insert position for the node we care about.
2665 RValueReferenceType *NewIP =
2666 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002667 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002668 }
2669
John McCall90d1c2d2009-09-24 23:30:46 +00002670 RValueReferenceType *New
2671 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002672 Types.push_back(New);
2673 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00002674 return QualType(New, 0);
2675}
2676
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002677/// getMemberPointerType - Return the uniqued reference to the type for a
2678/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00002679QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002680 // Unique pointers, to guarantee there is only one pointer of a particular
2681 // structure.
2682 llvm::FoldingSetNodeID ID;
2683 MemberPointerType::Profile(ID, T, Cls);
2684
Craig Topper36250ad2014-05-12 05:36:57 +00002685 void *InsertPos = nullptr;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002686 if (MemberPointerType *PT =
2687 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2688 return QualType(PT, 0);
2689
2690 // If the pointee or class type isn't canonical, this won't be a canonical
2691 // type either, so fill in the canonical type field.
2692 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00002693 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002694 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
2695
2696 // Get the new insert position for the node we care about.
2697 MemberPointerType *NewIP =
2698 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002699 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002700 }
John McCall90d1c2d2009-09-24 23:30:46 +00002701 MemberPointerType *New
2702 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002703 Types.push_back(New);
2704 MemberPointerTypes.InsertNode(New, InsertPos);
2705 return QualType(New, 0);
2706}
2707
Mike Stump11289f42009-09-09 15:08:12 +00002708/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00002709/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00002710QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00002711 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002712 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002713 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00002714 assert((EltTy->isDependentType() ||
2715 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00002716 "Constant array of VLAs is illegal!");
2717
Chris Lattnere2df3f92009-05-13 04:12:56 +00002718 // Convert the array size into a canonical width matching the pointer size for
2719 // the target.
2720 llvm::APInt ArySize(ArySizeIn);
Konstantin Zhuravlyov9c1e3102017-03-21 18:55:39 +00002721 ArySize = ArySize.zextOrTrunc(Target->getMaxPointerWidth());
Mike Stump11289f42009-09-09 15:08:12 +00002722
Chris Lattner23b7eb62007-06-15 23:05:46 +00002723 llvm::FoldingSetNodeID ID;
Abramo Bagnara92141d22011-01-27 19:55:10 +00002724 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00002725
Craig Topper36250ad2014-05-12 05:36:57 +00002726 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002727 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002728 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002729 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002730
John McCall33ddac02011-01-19 10:06:00 +00002731 // If the element type isn't canonical or has qualifiers, this won't
2732 // be a canonical type either, so fill in the canonical type field.
2733 QualType Canon;
2734 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2735 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002736 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002737 ASM, IndexTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002738 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002739
Chris Lattner36f8e652007-01-27 08:31:04 +00002740 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00002741 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002742 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002743 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00002744 }
Mike Stump11289f42009-09-09 15:08:12 +00002745
John McCall90d1c2d2009-09-24 23:30:46 +00002746 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002747 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00002748 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00002749 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002750 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00002751}
2752
John McCall06549462011-01-18 08:40:38 +00002753/// getVariableArrayDecayedType - Turns the given type, which may be
2754/// variably-modified, into the corresponding type with all the known
2755/// sizes replaced with [*].
2756QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
2757 // Vastly most common case.
2758 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002759
John McCall06549462011-01-18 08:40:38 +00002760 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002761
John McCall06549462011-01-18 08:40:38 +00002762 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00002763 const Type *ty = split.Ty;
John McCall06549462011-01-18 08:40:38 +00002764 switch (ty->getTypeClass()) {
2765#define TYPE(Class, Base)
2766#define ABSTRACT_TYPE(Class, Base)
2767#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2768#include "clang/AST/TypeNodes.def"
2769 llvm_unreachable("didn't desugar past all non-canonical types?");
2770
2771 // These types should never be variably-modified.
2772 case Type::Builtin:
2773 case Type::Complex:
2774 case Type::Vector:
2775 case Type::ExtVector:
2776 case Type::DependentSizedExtVector:
Andrew Gozillon572bbb02017-10-02 06:25:51 +00002777 case Type::DependentAddressSpace:
John McCall06549462011-01-18 08:40:38 +00002778 case Type::ObjCObject:
2779 case Type::ObjCInterface:
2780 case Type::ObjCObjectPointer:
2781 case Type::Record:
2782 case Type::Enum:
2783 case Type::UnresolvedUsing:
2784 case Type::TypeOfExpr:
2785 case Type::TypeOf:
2786 case Type::Decltype:
Alexis Hunte852b102011-05-24 22:41:36 +00002787 case Type::UnaryTransform:
John McCall06549462011-01-18 08:40:38 +00002788 case Type::DependentName:
2789 case Type::InjectedClassName:
2790 case Type::TemplateSpecialization:
2791 case Type::DependentTemplateSpecialization:
2792 case Type::TemplateTypeParm:
2793 case Type::SubstTemplateTypeParmPack:
Richard Smith30482bc2011-02-20 03:19:35 +00002794 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00002795 case Type::DeducedTemplateSpecialization:
John McCall06549462011-01-18 08:40:38 +00002796 case Type::PackExpansion:
2797 llvm_unreachable("type should never be variably-modified");
2798
2799 // These types can be variably-modified but should never need to
2800 // further decay.
2801 case Type::FunctionNoProto:
2802 case Type::FunctionProto:
2803 case Type::BlockPointer:
2804 case Type::MemberPointer:
Xiuli Pan9c14e282016-01-09 12:53:17 +00002805 case Type::Pipe:
John McCall06549462011-01-18 08:40:38 +00002806 return type;
2807
2808 // These types can be variably-modified. All these modifications
2809 // preserve structure except as noted by comments.
2810 // TODO: if we ever care about optimizing VLAs, there are no-op
2811 // optimizations available here.
2812 case Type::Pointer:
2813 result = getPointerType(getVariableArrayDecayedType(
2814 cast<PointerType>(ty)->getPointeeType()));
2815 break;
2816
2817 case Type::LValueReference: {
2818 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
2819 result = getLValueReferenceType(
2820 getVariableArrayDecayedType(lv->getPointeeType()),
2821 lv->isSpelledAsLValue());
2822 break;
2823 }
2824
2825 case Type::RValueReference: {
2826 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
2827 result = getRValueReferenceType(
2828 getVariableArrayDecayedType(lv->getPointeeType()));
2829 break;
2830 }
2831
Eli Friedman0dfb8892011-10-06 23:00:33 +00002832 case Type::Atomic: {
2833 const AtomicType *at = cast<AtomicType>(ty);
2834 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
2835 break;
2836 }
2837
John McCall06549462011-01-18 08:40:38 +00002838 case Type::ConstantArray: {
2839 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
2840 result = getConstantArrayType(
2841 getVariableArrayDecayedType(cat->getElementType()),
2842 cat->getSize(),
2843 cat->getSizeModifier(),
2844 cat->getIndexTypeCVRQualifiers());
2845 break;
2846 }
2847
2848 case Type::DependentSizedArray: {
2849 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
2850 result = getDependentSizedArrayType(
2851 getVariableArrayDecayedType(dat->getElementType()),
2852 dat->getSizeExpr(),
2853 dat->getSizeModifier(),
2854 dat->getIndexTypeCVRQualifiers(),
2855 dat->getBracketsRange());
2856 break;
2857 }
2858
2859 // Turn incomplete types into [*] types.
2860 case Type::IncompleteArray: {
2861 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
2862 result = getVariableArrayType(
2863 getVariableArrayDecayedType(iat->getElementType()),
Craig Topper36250ad2014-05-12 05:36:57 +00002864 /*size*/ nullptr,
John McCall06549462011-01-18 08:40:38 +00002865 ArrayType::Normal,
2866 iat->getIndexTypeCVRQualifiers(),
2867 SourceRange());
2868 break;
2869 }
2870
2871 // Turn VLA types into [*] types.
2872 case Type::VariableArray: {
2873 const VariableArrayType *vat = cast<VariableArrayType>(ty);
2874 result = getVariableArrayType(
2875 getVariableArrayDecayedType(vat->getElementType()),
Craig Topper36250ad2014-05-12 05:36:57 +00002876 /*size*/ nullptr,
John McCall06549462011-01-18 08:40:38 +00002877 ArrayType::Star,
2878 vat->getIndexTypeCVRQualifiers(),
2879 vat->getBracketsRange());
2880 break;
2881 }
2882 }
2883
2884 // Apply the top-level qualifiers from the original.
John McCall18ce25e2012-02-08 00:46:36 +00002885 return getQualifiedType(result, split.Quals);
John McCall06549462011-01-18 08:40:38 +00002886}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002887
Steve Naroffcadebd02007-08-30 18:14:25 +00002888/// getVariableArrayType - Returns a non-unique reference to the type for a
2889/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00002890QualType ASTContext::getVariableArrayType(QualType EltTy,
2891 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002892 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002893 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00002894 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002895 // Since we don't unique expressions, it isn't possible to unique VLA's
2896 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00002897 QualType Canon;
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002898
John McCall33ddac02011-01-19 10:06:00 +00002899 // Be sure to pull qualifiers off the element type.
2900 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2901 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002902 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002903 IndexTypeQuals, Brackets);
John McCall18ce25e2012-02-08 00:46:36 +00002904 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002905 }
2906
John McCall90d1c2d2009-09-24 23:30:46 +00002907 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002908 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00002909
2910 VariableArrayTypes.push_back(New);
2911 Types.push_back(New);
2912 return QualType(New, 0);
2913}
2914
Douglas Gregor4619e432008-12-05 23:32:09 +00002915/// getDependentSizedArrayType - Returns a non-unique reference to
2916/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00002917/// type.
John McCall33ddac02011-01-19 10:06:00 +00002918QualType ASTContext::getDependentSizedArrayType(QualType elementType,
2919 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00002920 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002921 unsigned elementTypeQuals,
2922 SourceRange brackets) const {
2923 assert((!numElements || numElements->isTypeDependent() ||
2924 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00002925 "Size must be type- or value-dependent!");
2926
John McCall33ddac02011-01-19 10:06:00 +00002927 // Dependently-sized array types that do not have a specified number
2928 // of elements will have their sizes deduced from a dependent
2929 // initializer. We do no canonicalization here at all, which is okay
2930 // because they can't be used in most locations.
2931 if (!numElements) {
2932 DependentSizedArrayType *newType
2933 = new (*this, TypeAlignment)
2934 DependentSizedArrayType(*this, elementType, QualType(),
2935 numElements, ASM, elementTypeQuals,
2936 brackets);
2937 Types.push_back(newType);
2938 return QualType(newType, 0);
2939 }
2940
2941 // Otherwise, we actually build a new type every time, but we
2942 // also build a canonical type.
2943
2944 SplitQualType canonElementType = getCanonicalType(elementType).split();
2945
Craig Topper36250ad2014-05-12 05:36:57 +00002946 void *insertPos = nullptr;
Douglas Gregorc42075a2010-02-04 18:10:26 +00002947 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002948 DependentSizedArrayType::Profile(ID, *this,
John McCall18ce25e2012-02-08 00:46:36 +00002949 QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002950 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002951
John McCall33ddac02011-01-19 10:06:00 +00002952 // Look for an existing type with these properties.
2953 DependentSizedArrayType *canonTy =
2954 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002955
John McCall33ddac02011-01-19 10:06:00 +00002956 // If we don't have one, build one.
2957 if (!canonTy) {
2958 canonTy = new (*this, TypeAlignment)
John McCall18ce25e2012-02-08 00:46:36 +00002959 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002960 QualType(), numElements, ASM, elementTypeQuals,
2961 brackets);
2962 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2963 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002964 }
2965
John McCall33ddac02011-01-19 10:06:00 +00002966 // Apply qualifiers from the element type to the array.
2967 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall18ce25e2012-02-08 00:46:36 +00002968 canonElementType.Quals);
Mike Stump11289f42009-09-09 15:08:12 +00002969
David Majnemer16a74702015-07-24 05:54:19 +00002970 // If we didn't need extra canonicalization for the element type or the size
2971 // expression, then just use that as our result.
2972 if (QualType(canonElementType.Ty, 0) == elementType &&
2973 canonTy->getSizeExpr() == numElements)
John McCall33ddac02011-01-19 10:06:00 +00002974 return canon;
2975
2976 // Otherwise, we need to build a type which follows the spelling
2977 // of the element type.
2978 DependentSizedArrayType *sugaredType
2979 = new (*this, TypeAlignment)
2980 DependentSizedArrayType(*this, elementType, canon, numElements,
2981 ASM, elementTypeQuals, brackets);
2982 Types.push_back(sugaredType);
2983 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00002984}
2985
John McCall33ddac02011-01-19 10:06:00 +00002986QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00002987 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002988 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002989 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002990 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002991
Craig Topper36250ad2014-05-12 05:36:57 +00002992 void *insertPos = nullptr;
John McCall33ddac02011-01-19 10:06:00 +00002993 if (IncompleteArrayType *iat =
2994 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2995 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00002996
2997 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00002998 // either, so fill in the canonical type field. We also have to pull
2999 // qualifiers off the element type.
3000 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00003001
John McCall33ddac02011-01-19 10:06:00 +00003002 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
3003 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall18ce25e2012-02-08 00:46:36 +00003004 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00003005 ASM, elementTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00003006 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanbd258282008-02-15 18:16:39 +00003007
3008 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00003009 IncompleteArrayType *existing =
3010 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
3011 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00003012 }
Eli Friedmanbd258282008-02-15 18:16:39 +00003013
John McCall33ddac02011-01-19 10:06:00 +00003014 IncompleteArrayType *newType = new (*this, TypeAlignment)
3015 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00003016
John McCall33ddac02011-01-19 10:06:00 +00003017 IncompleteArrayTypes.InsertNode(newType, insertPos);
3018 Types.push_back(newType);
3019 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00003020}
3021
Steve Naroff91fcddb2007-07-18 18:00:27 +00003022/// getVectorType - Return the unique reference to a vector type of
3023/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00003024QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00003025 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00003026 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00003027
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003028 // Check if we've already instantiated a vector of this type.
3029 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00003030 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00003031
Craig Topper36250ad2014-05-12 05:36:57 +00003032 void *InsertPos = nullptr;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003033 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
3034 return QualType(VTP, 0);
3035
3036 // If the element type isn't canonical, this won't be a canonical type either,
3037 // so fill in the canonical type field.
3038 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00003039 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00003040 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00003041
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003042 // Get the new insert position for the node we care about.
3043 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003044 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003045 }
John McCall90d1c2d2009-09-24 23:30:46 +00003046 VectorType *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00003047 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003048 VectorTypes.InsertNode(New, InsertPos);
3049 Types.push_back(New);
3050 return QualType(New, 0);
3051}
3052
Nate Begemance4d7fc2008-04-18 23:10:10 +00003053/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00003054/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00003055QualType
3056ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor39c02722011-06-15 16:02:29 +00003057 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump11289f42009-09-09 15:08:12 +00003058
Steve Naroff91fcddb2007-07-18 18:00:27 +00003059 // Check if we've already instantiated a vector of this type.
3060 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00003061 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00003062 VectorType::GenericVector);
Craig Topper36250ad2014-05-12 05:36:57 +00003063 void *InsertPos = nullptr;
Steve Naroff91fcddb2007-07-18 18:00:27 +00003064 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
3065 return QualType(VTP, 0);
3066
3067 // If the element type isn't canonical, this won't be a canonical type either,
3068 // so fill in the canonical type field.
3069 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00003070 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00003071 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00003072
Steve Naroff91fcddb2007-07-18 18:00:27 +00003073 // Get the new insert position for the node we care about.
3074 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003075 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00003076 }
John McCall90d1c2d2009-09-24 23:30:46 +00003077 ExtVectorType *New = new (*this, TypeAlignment)
3078 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00003079 VectorTypes.InsertNode(New, InsertPos);
3080 Types.push_back(New);
3081 return QualType(New, 0);
3082}
3083
Jay Foad39c79802011-01-12 09:06:06 +00003084QualType
3085ASTContext::getDependentSizedExtVectorType(QualType vecType,
3086 Expr *SizeExpr,
3087 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00003088 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00003089 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00003090 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00003091
Craig Topper36250ad2014-05-12 05:36:57 +00003092 void *InsertPos = nullptr;
Douglas Gregor352169a2009-07-31 03:54:25 +00003093 DependentSizedExtVectorType *Canon
3094 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3095 DependentSizedExtVectorType *New;
3096 if (Canon) {
3097 // We already have a canonical version of this array type; use it as
3098 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00003099 New = new (*this, TypeAlignment)
3100 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
3101 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00003102 } else {
3103 QualType CanonVecTy = getCanonicalType(vecType);
3104 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00003105 New = new (*this, TypeAlignment)
3106 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
3107 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003108
3109 DependentSizedExtVectorType *CanonCheck
3110 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3111 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
3112 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00003113 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
3114 } else {
3115 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
3116 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00003117 New = new (*this, TypeAlignment)
3118 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00003119 }
3120 }
Mike Stump11289f42009-09-09 15:08:12 +00003121
Douglas Gregor758a8692009-06-17 21:51:59 +00003122 Types.push_back(New);
3123 return QualType(New, 0);
3124}
3125
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003126QualType ASTContext::getDependentAddressSpaceType(QualType PointeeType,
3127 Expr *AddrSpaceExpr,
3128 SourceLocation AttrLoc) const {
3129 assert(AddrSpaceExpr->isInstantiationDependent());
3130
3131 QualType canonPointeeType = getCanonicalType(PointeeType);
3132
3133 void *insertPos = nullptr;
3134 llvm::FoldingSetNodeID ID;
3135 DependentAddressSpaceType::Profile(ID, *this, canonPointeeType,
3136 AddrSpaceExpr);
3137
3138 DependentAddressSpaceType *canonTy =
3139 DependentAddressSpaceTypes.FindNodeOrInsertPos(ID, insertPos);
3140
3141 if (!canonTy) {
3142 canonTy = new (*this, TypeAlignment)
3143 DependentAddressSpaceType(*this, canonPointeeType,
3144 QualType(), AddrSpaceExpr, AttrLoc);
3145 DependentAddressSpaceTypes.InsertNode(canonTy, insertPos);
3146 Types.push_back(canonTy);
3147 }
3148
3149 if (canonPointeeType == PointeeType &&
3150 canonTy->getAddrSpaceExpr() == AddrSpaceExpr)
3151 return QualType(canonTy, 0);
3152
3153 DependentAddressSpaceType *sugaredType
3154 = new (*this, TypeAlignment)
3155 DependentAddressSpaceType(*this, PointeeType, QualType(canonTy, 0),
3156 AddrSpaceExpr, AttrLoc);
3157 Types.push_back(sugaredType);
3158 return QualType(sugaredType, 0);
3159}
3160
John McCall18afab72016-03-01 00:49:02 +00003161/// \brief Determine whether \p T is canonical as the result type of a function.
3162static bool isCanonicalResultType(QualType T) {
3163 return T.isCanonical() &&
3164 (T.getObjCLifetime() == Qualifiers::OCL_None ||
3165 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
3166}
3167
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003168/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003169///
Jay Foad39c79802011-01-12 09:06:06 +00003170QualType
3171ASTContext::getFunctionNoProtoType(QualType ResultTy,
3172 const FunctionType::ExtInfo &Info) const {
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003173 // Unique functions, to guarantee there is only one function of a particular
3174 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00003175 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00003176 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00003177
Craig Topper36250ad2014-05-12 05:36:57 +00003178 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003179 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003180 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003181 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003182
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003183 QualType Canonical;
John McCall18afab72016-03-01 00:49:02 +00003184 if (!isCanonicalResultType(ResultTy)) {
3185 Canonical =
3186 getFunctionNoProtoType(getCanonicalFunctionResultType(ResultTy), Info);
Mike Stump11289f42009-09-09 15:08:12 +00003187
Chris Lattner47955de2007-01-27 08:37:20 +00003188 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003189 FunctionNoProtoType *NewIP =
3190 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003191 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00003192 }
Mike Stump11289f42009-09-09 15:08:12 +00003193
John McCall90d1c2d2009-09-24 23:30:46 +00003194 FunctionNoProtoType *New = new (*this, TypeAlignment)
John McCall18afab72016-03-01 00:49:02 +00003195 FunctionNoProtoType(ResultTy, Canonical, Info);
Chris Lattner47955de2007-01-27 08:37:20 +00003196 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003197 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003198 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003199}
3200
Douglas Gregora602a152015-10-01 20:20:47 +00003201CanQualType
3202ASTContext::getCanonicalFunctionResultType(QualType ResultType) const {
3203 CanQualType CanResultType = getCanonicalType(ResultType);
3204
3205 // Canonical result types do not have ARC lifetime qualifiers.
3206 if (CanResultType.getQualifiers().hasObjCLifetime()) {
3207 Qualifiers Qs = CanResultType.getQualifiers();
3208 Qs.removeObjCLifetime();
3209 return CanQualType::CreateUnsafe(
3210 getQualifiedType(CanResultType.getUnqualifiedType(), Qs));
3211 }
3212
3213 return CanResultType;
3214}
3215
Richard Smith3c4f8d22016-10-16 17:54:23 +00003216static bool isCanonicalExceptionSpecification(
3217 const FunctionProtoType::ExceptionSpecInfo &ESI, bool NoexceptInType) {
3218 if (ESI.Type == EST_None)
3219 return true;
3220 if (!NoexceptInType)
3221 return false;
3222
3223 // C++17 onwards: exception specification is part of the type, as a simple
3224 // boolean "can this function type throw".
3225 if (ESI.Type == EST_BasicNoexcept)
3226 return true;
3227
3228 // A dynamic exception specification is canonical if it only contains pack
Richard Smith2a2cda52016-10-18 19:29:18 +00003229 // expansions (so we can't tell whether it's non-throwing) and all its
3230 // contained types are canonical.
Richard Smith3c4f8d22016-10-16 17:54:23 +00003231 if (ESI.Type == EST_Dynamic) {
Richard Smithfda59e52016-10-26 01:05:54 +00003232 bool AnyPackExpansions = false;
3233 for (QualType ET : ESI.Exceptions) {
3234 if (!ET.isCanonical())
Richard Smith3c4f8d22016-10-16 17:54:23 +00003235 return false;
Richard Smithfda59e52016-10-26 01:05:54 +00003236 if (ET->getAs<PackExpansionType>())
3237 AnyPackExpansions = true;
3238 }
3239 return AnyPackExpansions;
Richard Smith3c4f8d22016-10-16 17:54:23 +00003240 }
3241
Richard Smith2a2cda52016-10-18 19:29:18 +00003242 // A noexcept(expr) specification is (possibly) canonical if expr is
3243 // value-dependent.
Richard Smith3c4f8d22016-10-16 17:54:23 +00003244 if (ESI.Type == EST_ComputedNoexcept)
3245 return ESI.NoexceptExpr && ESI.NoexceptExpr->isValueDependent();
3246
3247 return false;
3248}
3249
Richard Smith304b1242016-10-18 20:13:25 +00003250QualType ASTContext::getFunctionTypeInternal(
3251 QualType ResultTy, ArrayRef<QualType> ArgArray,
3252 const FunctionProtoType::ExtProtoInfo &EPI, bool OnlyWantCanonical) const {
Jordan Rose5c382722013-03-08 21:51:21 +00003253 size_t NumArgs = ArgArray.size();
3254
Richard Smith2a2cda52016-10-18 19:29:18 +00003255 // Unique functions, to guarantee there is only one function of a particular
3256 // structure.
3257 llvm::FoldingSetNodeID ID;
3258 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
3259 *this, true);
Richard Smith3c4f8d22016-10-16 17:54:23 +00003260
Richard Smith2a2cda52016-10-18 19:29:18 +00003261 QualType Canonical;
3262 bool Unique = false;
3263
3264 void *InsertPos = nullptr;
3265 if (FunctionProtoType *FPT =
3266 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) {
3267 QualType Existing = QualType(FPT, 0);
3268
3269 // If we find a pre-existing equivalent FunctionProtoType, we can just reuse
3270 // it so long as our exception specification doesn't contain a dependent
Richard Smith304b1242016-10-18 20:13:25 +00003271 // noexcept expression, or we're just looking for a canonical type.
3272 // Otherwise, we're going to need to create a type
Richard Smith2a2cda52016-10-18 19:29:18 +00003273 // sugar node to hold the concrete expression.
Richard Smith304b1242016-10-18 20:13:25 +00003274 if (OnlyWantCanonical || EPI.ExceptionSpec.Type != EST_ComputedNoexcept ||
Richard Smith2a2cda52016-10-18 19:29:18 +00003275 EPI.ExceptionSpec.NoexceptExpr == FPT->getNoexceptExpr())
3276 return Existing;
3277
3278 // We need a new type sugar node for this one, to hold the new noexcept
3279 // expression. We do no canonicalization here, but that's OK since we don't
3280 // expect to see the same noexcept expression much more than once.
3281 Canonical = getCanonicalType(Existing);
3282 Unique = true;
3283 }
3284
3285 bool NoexceptInType = getLangOpts().CPlusPlus1z;
Richard Smith3c4f8d22016-10-16 17:54:23 +00003286 bool IsCanonicalExceptionSpec =
3287 isCanonicalExceptionSpecification(EPI.ExceptionSpec, NoexceptInType);
3288
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003289 // Determine whether the type being created is already canonical or not.
Richard Smith2a2cda52016-10-18 19:29:18 +00003290 bool isCanonical = !Unique && IsCanonicalExceptionSpec &&
Richard Smith3c4f8d22016-10-16 17:54:23 +00003291 isCanonicalResultType(ResultTy) && !EPI.HasTrailingReturn;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003292 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00003293 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003294 isCanonical = false;
3295
Richard Smith304b1242016-10-18 20:13:25 +00003296 if (OnlyWantCanonical)
3297 assert(isCanonical &&
3298 "given non-canonical parameters constructing canonical type");
3299
Richard Smith2a2cda52016-10-18 19:29:18 +00003300 // If this type isn't canonical, get the canonical version of it if we don't
3301 // already have it. The exception spec is only partially part of the
3302 // canonical type, and only in C++17 onwards.
3303 if (!isCanonical && Canonical.isNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003304 SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003305 CanonicalArgs.reserve(NumArgs);
3306 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00003307 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003308
Benjamin Kramer3f515cd2016-10-26 12:51:45 +00003309 llvm::SmallVector<QualType, 8> ExceptionTypeStorage;
John McCalldb40c7f2010-12-14 08:05:40 +00003310 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smith5e580292012-02-10 09:58:53 +00003311 CanonicalEPI.HasTrailingReturn = false;
Richard Smith3c4f8d22016-10-16 17:54:23 +00003312
3313 if (IsCanonicalExceptionSpec) {
3314 // Exception spec is already OK.
3315 } else if (NoexceptInType) {
3316 switch (EPI.ExceptionSpec.Type) {
3317 case EST_Unparsed: case EST_Unevaluated: case EST_Uninstantiated:
3318 // We don't know yet. It shouldn't matter what we pick here; no-one
3319 // should ever look at this.
3320 LLVM_FALLTHROUGH;
Richard Smith2a2cda52016-10-18 19:29:18 +00003321 case EST_None: case EST_MSAny:
Richard Smith3c4f8d22016-10-16 17:54:23 +00003322 CanonicalEPI.ExceptionSpec.Type = EST_None;
3323 break;
3324
Richard Smith2a2cda52016-10-18 19:29:18 +00003325 // A dynamic exception specification is almost always "not noexcept",
3326 // with the exception that a pack expansion might expand to no types.
3327 case EST_Dynamic: {
3328 bool AnyPacks = false;
3329 for (QualType ET : EPI.ExceptionSpec.Exceptions) {
3330 if (ET->getAs<PackExpansionType>())
3331 AnyPacks = true;
3332 ExceptionTypeStorage.push_back(getCanonicalType(ET));
3333 }
3334 if (!AnyPacks)
3335 CanonicalEPI.ExceptionSpec.Type = EST_None;
3336 else {
3337 CanonicalEPI.ExceptionSpec.Type = EST_Dynamic;
3338 CanonicalEPI.ExceptionSpec.Exceptions = ExceptionTypeStorage;
3339 }
3340 break;
3341 }
3342
Richard Smith3c4f8d22016-10-16 17:54:23 +00003343 case EST_DynamicNone: case EST_BasicNoexcept:
3344 CanonicalEPI.ExceptionSpec.Type = EST_BasicNoexcept;
3345 break;
3346
3347 case EST_ComputedNoexcept:
3348 llvm::APSInt Value(1);
3349 auto *E = CanonicalEPI.ExceptionSpec.NoexceptExpr;
3350 if (!E || !E->isIntegerConstantExpr(Value, *this, nullptr,
3351 /*IsEvaluated*/false)) {
3352 // This noexcept specification is invalid.
3353 // FIXME: Should this be able to happen?
3354 CanonicalEPI.ExceptionSpec.Type = EST_None;
3355 break;
3356 }
3357
3358 CanonicalEPI.ExceptionSpec.Type =
3359 Value.getBoolValue() ? EST_BasicNoexcept : EST_None;
3360 break;
3361 }
Richard Smith3c4f8d22016-10-16 17:54:23 +00003362 } else {
3363 CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo();
3364 }
John McCalldb40c7f2010-12-14 08:05:40 +00003365
Douglas Gregora602a152015-10-01 20:20:47 +00003366 // Adjust the canonical function result type.
3367 CanQualType CanResultTy = getCanonicalFunctionResultType(ResultTy);
Richard Smith304b1242016-10-18 20:13:25 +00003368 Canonical =
3369 getFunctionTypeInternal(CanResultTy, CanonicalArgs, CanonicalEPI, true);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003370
Chris Lattnerfd4de792007-01-27 01:15:32 +00003371 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003372 FunctionProtoType *NewIP =
3373 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003374 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003375 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003376
John McCall31168b02011-06-15 23:02:42 +00003377 // FunctionProtoType objects are allocated with extra bytes after
3378 // them for three variable size arrays at the end:
3379 // - parameter types
3380 // - exception types
John McCall18afab72016-03-01 00:49:02 +00003381 // - extended parameter information
John McCall31168b02011-06-15 23:02:42 +00003382 // Instead of the exception types, there could be a noexcept
Richard Smithd3b5c9082012-07-27 04:22:15 +00003383 // expression, or information used to resolve the exception
3384 // specification.
John McCalldb40c7f2010-12-14 08:05:40 +00003385 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003386 NumArgs * sizeof(QualType);
John McCall18afab72016-03-01 00:49:02 +00003387
Richard Smith8acb4282014-07-31 21:57:55 +00003388 if (EPI.ExceptionSpec.Type == EST_Dynamic) {
3389 Size += EPI.ExceptionSpec.Exceptions.size() * sizeof(QualType);
3390 } else if (EPI.ExceptionSpec.Type == EST_ComputedNoexcept) {
Sebastian Redl31ad7542011-03-13 17:09:40 +00003391 Size += sizeof(Expr*);
Richard Smith8acb4282014-07-31 21:57:55 +00003392 } else if (EPI.ExceptionSpec.Type == EST_Uninstantiated) {
Richard Smithd3729422012-04-19 00:08:28 +00003393 Size += 2 * sizeof(FunctionDecl*);
Richard Smith8acb4282014-07-31 21:57:55 +00003394 } else if (EPI.ExceptionSpec.Type == EST_Unevaluated) {
Richard Smithd3b5c9082012-07-27 04:22:15 +00003395 Size += sizeof(FunctionDecl*);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003396 }
John McCall18afab72016-03-01 00:49:02 +00003397
3398 // Put the ExtParameterInfos last. If all were equal, it would make
3399 // more sense to put these before the exception specification, because
3400 // it's much easier to skip past them compared to the elaborate switch
3401 // required to skip the exception specification. However, all is not
3402 // equal; ExtParameterInfos are used to model very uncommon features,
3403 // and it's better not to burden the more common paths.
3404 if (EPI.ExtParameterInfos) {
3405 Size += NumArgs * sizeof(FunctionProtoType::ExtParameterInfo);
3406 }
John McCall31168b02011-06-15 23:02:42 +00003407
John McCalldb40c7f2010-12-14 08:05:40 +00003408 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divacky65b88cd2011-03-01 17:40:53 +00003409 FunctionProtoType::ExtProtoInfo newEPI = EPI;
Jordan Rose5c382722013-03-08 21:51:21 +00003410 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003411 Types.push_back(FTP);
Richard Smith2a2cda52016-10-18 19:29:18 +00003412 if (!Unique)
3413 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003414 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003415}
Chris Lattneref51c202006-11-10 07:17:23 +00003416
Joey Goulye3c85de2016-12-01 11:30:49 +00003417QualType ASTContext::getPipeType(QualType T, bool ReadOnly) const {
Xiuli Pan9c14e282016-01-09 12:53:17 +00003418 llvm::FoldingSetNodeID ID;
Joey Goulye3c85de2016-12-01 11:30:49 +00003419 PipeType::Profile(ID, T, ReadOnly);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003420
3421 void *InsertPos = 0;
Joey Goulye3c85de2016-12-01 11:30:49 +00003422 if (PipeType *PT = PipeTypes.FindNodeOrInsertPos(ID, InsertPos))
Xiuli Pan9c14e282016-01-09 12:53:17 +00003423 return QualType(PT, 0);
3424
3425 // If the pipe element type isn't canonical, this won't be a canonical type
3426 // either, so fill in the canonical type field.
3427 QualType Canonical;
3428 if (!T.isCanonical()) {
Joey Goulye3c85de2016-12-01 11:30:49 +00003429 Canonical = getPipeType(getCanonicalType(T), ReadOnly);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003430
3431 // Get the new insert position for the node we care about.
Joey Goulye3c85de2016-12-01 11:30:49 +00003432 PipeType *NewIP = PipeTypes.FindNodeOrInsertPos(ID, InsertPos);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003433 assert(!NewIP && "Shouldn't be in the map!");
3434 (void)NewIP;
3435 }
Joey Goulye3c85de2016-12-01 11:30:49 +00003436 PipeType *New = new (*this, TypeAlignment) PipeType(T, Canonical, ReadOnly);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003437 Types.push_back(New);
Joey Goulye3c85de2016-12-01 11:30:49 +00003438 PipeTypes.InsertNode(New, InsertPos);
Joey Gouly5788b782016-11-18 14:10:54 +00003439 return QualType(New, 0);
3440}
3441
Joey Goulye3c85de2016-12-01 11:30:49 +00003442QualType ASTContext::getReadPipeType(QualType T) const {
3443 return getPipeType(T, true);
3444}
3445
Joey Gouly5788b782016-11-18 14:10:54 +00003446QualType ASTContext::getWritePipeType(QualType T) const {
Joey Goulye3c85de2016-12-01 11:30:49 +00003447 return getPipeType(T, false);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003448}
3449
John McCalle78aac42010-03-10 03:28:59 +00003450#ifndef NDEBUG
3451static bool NeedsInjectedClassNameType(const RecordDecl *D) {
3452 if (!isa<CXXRecordDecl>(D)) return false;
3453 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
3454 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
3455 return true;
3456 if (RD->getDescribedClassTemplate() &&
3457 !isa<ClassTemplateSpecializationDecl>(RD))
3458 return true;
3459 return false;
3460}
3461#endif
3462
3463/// getInjectedClassNameType - Return the unique reference to the
3464/// injected class name type for the specified templated declaration.
3465QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00003466 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00003467 assert(NeedsInjectedClassNameType(Decl));
3468 if (Decl->TypeForDecl) {
3469 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregorec9fd132012-01-14 16:38:05 +00003470 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCalle78aac42010-03-10 03:28:59 +00003471 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
3472 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3473 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
3474 } else {
John McCall424cec92011-01-19 06:33:43 +00003475 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00003476 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00003477 Decl->TypeForDecl = newType;
3478 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00003479 }
3480 return QualType(Decl->TypeForDecl, 0);
3481}
3482
Douglas Gregor83a586e2008-04-13 21:07:44 +00003483/// getTypeDeclType - Return the unique reference to the type for the
3484/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00003485QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00003486 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00003487 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00003488
Richard Smithdda56e42011-04-15 14:24:37 +00003489 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00003490 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00003491
John McCall96f0b5f2010-03-10 06:48:02 +00003492 assert(!isa<TemplateTypeParmDecl>(Decl) &&
3493 "Template type parameter types are always available.");
3494
John McCall81e38502010-02-16 03:57:14 +00003495 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00003496 assert(Record->isFirstDecl() && "struct/union has previous declaration");
John McCall96f0b5f2010-03-10 06:48:02 +00003497 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003498 return getRecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00003499 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00003500 assert(Enum->isFirstDecl() && "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003501 return getEnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00003502 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00003503 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00003504 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
3505 Decl->TypeForDecl = newType;
3506 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00003507 } else
John McCall96f0b5f2010-03-10 06:48:02 +00003508 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00003509
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00003510 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00003511}
3512
Chris Lattner32d920b2007-01-26 02:01:53 +00003513/// getTypedefType - Return the unique reference to the type for the
Richard Smithdda56e42011-04-15 14:24:37 +00003514/// specified typedef name decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003515QualType
Richard Smithdda56e42011-04-15 14:24:37 +00003516ASTContext::getTypedefType(const TypedefNameDecl *Decl,
3517 QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003518 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003519
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003520 if (Canonical.isNull())
3521 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall424cec92011-01-19 06:33:43 +00003522 TypedefType *newType = new(*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00003523 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00003524 Decl->TypeForDecl = newType;
3525 Types.push_back(newType);
3526 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00003527}
3528
Jay Foad39c79802011-01-12 09:06:06 +00003529QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003530 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3531
Douglas Gregorec9fd132012-01-14 16:38:05 +00003532 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003533 if (PrevDecl->TypeForDecl)
3534 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3535
John McCall424cec92011-01-19 06:33:43 +00003536 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
3537 Decl->TypeForDecl = newType;
3538 Types.push_back(newType);
3539 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003540}
3541
Jay Foad39c79802011-01-12 09:06:06 +00003542QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003543 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3544
Douglas Gregorec9fd132012-01-14 16:38:05 +00003545 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003546 if (PrevDecl->TypeForDecl)
3547 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3548
John McCall424cec92011-01-19 06:33:43 +00003549 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
3550 Decl->TypeForDecl = newType;
3551 Types.push_back(newType);
3552 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003553}
3554
John McCall81904512011-01-06 01:58:22 +00003555QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
3556 QualType modifiedType,
3557 QualType equivalentType) {
3558 llvm::FoldingSetNodeID id;
3559 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
3560
Craig Topper36250ad2014-05-12 05:36:57 +00003561 void *insertPos = nullptr;
John McCall81904512011-01-06 01:58:22 +00003562 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
3563 if (type) return QualType(type, 0);
3564
3565 QualType canon = getCanonicalType(equivalentType);
3566 type = new (*this, TypeAlignment)
3567 AttributedType(canon, attrKind, modifiedType, equivalentType);
3568
3569 Types.push_back(type);
3570 AttributedTypes.InsertNode(type, insertPos);
3571
3572 return QualType(type, 0);
3573}
3574
John McCallcebee162009-10-18 09:09:24 +00003575/// \brief Retrieve a substitution-result type.
3576QualType
3577ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00003578 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00003579 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00003580 && "replacement types must always be canonical");
3581
3582 llvm::FoldingSetNodeID ID;
3583 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
Craig Topper36250ad2014-05-12 05:36:57 +00003584 void *InsertPos = nullptr;
John McCallcebee162009-10-18 09:09:24 +00003585 SubstTemplateTypeParmType *SubstParm
3586 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3587
3588 if (!SubstParm) {
3589 SubstParm = new (*this, TypeAlignment)
3590 SubstTemplateTypeParmType(Parm, Replacement);
3591 Types.push_back(SubstParm);
3592 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3593 }
3594
3595 return QualType(SubstParm, 0);
3596}
3597
Douglas Gregorada4b792011-01-14 02:55:32 +00003598/// \brief Retrieve a
3599QualType ASTContext::getSubstTemplateTypeParmPackType(
3600 const TemplateTypeParmType *Parm,
3601 const TemplateArgument &ArgPack) {
3602#ifndef NDEBUG
Aaron Ballman2a89e852014-07-15 21:32:31 +00003603 for (const auto &P : ArgPack.pack_elements()) {
3604 assert(P.getKind() == TemplateArgument::Type &&"Pack contains a non-type");
3605 assert(P.getAsType().isCanonical() && "Pack contains non-canonical type");
Douglas Gregorada4b792011-01-14 02:55:32 +00003606 }
3607#endif
3608
3609 llvm::FoldingSetNodeID ID;
3610 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
Craig Topper36250ad2014-05-12 05:36:57 +00003611 void *InsertPos = nullptr;
Douglas Gregorada4b792011-01-14 02:55:32 +00003612 if (SubstTemplateTypeParmPackType *SubstParm
3613 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
3614 return QualType(SubstParm, 0);
3615
3616 QualType Canon;
3617 if (!Parm->isCanonicalUnqualified()) {
3618 Canon = getCanonicalType(QualType(Parm, 0));
3619 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
3620 ArgPack);
3621 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
3622 }
3623
3624 SubstTemplateTypeParmPackType *SubstParm
3625 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
3626 ArgPack);
3627 Types.push_back(SubstParm);
George Burgess IVb5fe8552017-06-12 17:44:30 +00003628 SubstTemplateTypeParmPackTypes.InsertNode(SubstParm, InsertPos);
Douglas Gregorada4b792011-01-14 02:55:32 +00003629 return QualType(SubstParm, 0);
3630}
3631
Douglas Gregoreff93e02009-02-05 23:33:38 +00003632/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00003633/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00003634/// name.
Mike Stump11289f42009-09-09 15:08:12 +00003635QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00003636 bool ParameterPack,
Chandler Carruth08836322011-05-01 00:51:33 +00003637 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00003638 llvm::FoldingSetNodeID ID;
Chandler Carruth08836322011-05-01 00:51:33 +00003639 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Craig Topper36250ad2014-05-12 05:36:57 +00003640 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003641 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00003642 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3643
3644 if (TypeParm)
3645 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003646
Chandler Carruth08836322011-05-01 00:51:33 +00003647 if (TTPDecl) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00003648 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth08836322011-05-01 00:51:33 +00003649 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003650
3651 TemplateTypeParmType *TypeCheck
3652 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3653 assert(!TypeCheck && "Template type parameter canonical type broken");
3654 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00003655 } else
John McCall90d1c2d2009-09-24 23:30:46 +00003656 TypeParm = new (*this, TypeAlignment)
3657 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00003658
3659 Types.push_back(TypeParm);
3660 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
3661
3662 return QualType(TypeParm, 0);
3663}
3664
John McCalle78aac42010-03-10 03:28:59 +00003665TypeSourceInfo *
3666ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
3667 SourceLocation NameLoc,
3668 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003669 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003670 assert(!Name.getAsDependentTemplateName() &&
3671 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003672 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCalle78aac42010-03-10 03:28:59 +00003673
3674 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
David Blaikie6adc78e2013-02-18 22:06:02 +00003675 TemplateSpecializationTypeLoc TL =
3676 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003677 TL.setTemplateKeywordLoc(SourceLocation());
John McCalle78aac42010-03-10 03:28:59 +00003678 TL.setTemplateNameLoc(NameLoc);
3679 TL.setLAngleLoc(Args.getLAngleLoc());
3680 TL.setRAngleLoc(Args.getRAngleLoc());
3681 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
3682 TL.setArgLocInfo(i, Args[i].getLocInfo());
3683 return DI;
3684}
3685
Mike Stump11289f42009-09-09 15:08:12 +00003686QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00003687ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00003688 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003689 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003690 assert(!Template.getAsDependentTemplateName() &&
3691 "No dependent template names here!");
John McCall6b51f282009-11-23 01:53:49 +00003692
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003693 SmallVector<TemplateArgument, 4> ArgVec;
David Majnemer6fbeee32016-07-07 04:43:07 +00003694 ArgVec.reserve(Args.size());
3695 for (const TemplateArgumentLoc &Arg : Args.arguments())
3696 ArgVec.push_back(Arg.getArgument());
John McCall0ad16662009-10-29 08:12:44 +00003697
David Majnemer6fbeee32016-07-07 04:43:07 +00003698 return getTemplateSpecializationType(Template, ArgVec, Underlying);
John McCall0ad16662009-10-29 08:12:44 +00003699}
3700
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003701#ifndef NDEBUG
David Majnemer6fbeee32016-07-07 04:43:07 +00003702static bool hasAnyPackExpansions(ArrayRef<TemplateArgument> Args) {
3703 for (const TemplateArgument &Arg : Args)
3704 if (Arg.isPackExpansion())
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003705 return true;
3706
3707 return true;
3708}
3709#endif
3710
John McCall0ad16662009-10-29 08:12:44 +00003711QualType
3712ASTContext::getTemplateSpecializationType(TemplateName Template,
David Majnemer6fbeee32016-07-07 04:43:07 +00003713 ArrayRef<TemplateArgument> Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003714 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003715 assert(!Template.getAsDependentTemplateName() &&
3716 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00003717 // Look through qualified template names.
3718 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3719 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003720
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003721 bool IsTypeAlias =
Richard Smith3f1b5d02011-05-05 21:57:07 +00003722 Template.getAsTemplateDecl() &&
3723 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00003724 QualType CanonType;
3725 if (!Underlying.isNull())
3726 CanonType = getCanonicalType(Underlying);
3727 else {
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003728 // We can get here with an alias template when the specialization contains
3729 // a pack expansion that does not match up with a parameter pack.
David Majnemer6fbeee32016-07-07 04:43:07 +00003730 assert((!IsTypeAlias || hasAnyPackExpansions(Args)) &&
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003731 "Caller must compute aliased type");
3732 IsTypeAlias = false;
David Majnemer6fbeee32016-07-07 04:43:07 +00003733 CanonType = getCanonicalTemplateSpecializationType(Template, Args);
Richard Smith3f1b5d02011-05-05 21:57:07 +00003734 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00003735
Douglas Gregora8e02e72009-07-28 23:00:59 +00003736 // Allocate the (non-canonical) template specialization type, but don't
3737 // try to unique it: these types typically have location information that
3738 // we don't unique and don't want to lose.
Richard Smith3f1b5d02011-05-05 21:57:07 +00003739 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
David Majnemer6fbeee32016-07-07 04:43:07 +00003740 sizeof(TemplateArgument) * Args.size() +
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003741 (IsTypeAlias? sizeof(QualType) : 0),
John McCall90d1c2d2009-09-24 23:30:46 +00003742 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00003743 TemplateSpecializationType *Spec
David Majnemer6fbeee32016-07-07 04:43:07 +00003744 = new (Mem) TemplateSpecializationType(Template, Args, CanonType,
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003745 IsTypeAlias ? Underlying : QualType());
Mike Stump11289f42009-09-09 15:08:12 +00003746
Douglas Gregor8bf42052009-02-09 18:46:07 +00003747 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00003748 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00003749}
3750
David Majnemer6fbeee32016-07-07 04:43:07 +00003751QualType ASTContext::getCanonicalTemplateSpecializationType(
3752 TemplateName Template, ArrayRef<TemplateArgument> Args) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003753 assert(!Template.getAsDependentTemplateName() &&
3754 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003755
Douglas Gregore29139c2011-03-03 17:04:51 +00003756 // Look through qualified template names.
3757 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3758 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003759
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003760 // Build the canonical template specialization type.
3761 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003762 SmallVector<TemplateArgument, 4> CanonArgs;
David Majnemer6fbeee32016-07-07 04:43:07 +00003763 unsigned NumArgs = Args.size();
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003764 CanonArgs.reserve(NumArgs);
David Majnemer6fbeee32016-07-07 04:43:07 +00003765 for (const TemplateArgument &Arg : Args)
3766 CanonArgs.push_back(getCanonicalTemplateArgument(Arg));
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003767
3768 // Determine whether this canonical template specialization type already
3769 // exists.
3770 llvm::FoldingSetNodeID ID;
3771 TemplateSpecializationType::Profile(ID, CanonTemplate,
David Majnemer6fbeee32016-07-07 04:43:07 +00003772 CanonArgs, *this);
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003773
Craig Topper36250ad2014-05-12 05:36:57 +00003774 void *InsertPos = nullptr;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003775 TemplateSpecializationType *Spec
3776 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3777
3778 if (!Spec) {
3779 // Allocate a new canonical template specialization type.
3780 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
3781 sizeof(TemplateArgument) * NumArgs),
3782 TypeAlignment);
3783 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
David Majnemer6fbeee32016-07-07 04:43:07 +00003784 CanonArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003785 QualType(), QualType());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003786 Types.push_back(Spec);
3787 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
3788 }
3789
3790 assert(Spec->isDependentType() &&
3791 "Non-dependent template-id type must have a canonical type");
3792 return QualType(Spec, 0);
3793}
3794
3795QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00003796ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
3797 NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00003798 QualType NamedType) const {
Douglas Gregor52537682009-03-19 00:18:19 +00003799 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003800 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00003801
Craig Topper36250ad2014-05-12 05:36:57 +00003802 void *InsertPos = nullptr;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003803 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003804 if (T)
3805 return QualType(T, 0);
3806
Douglas Gregorc42075a2010-02-04 18:10:26 +00003807 QualType Canon = NamedType;
3808 if (!Canon.isCanonical()) {
3809 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003810 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
3811 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00003812 (void)CheckT;
3813 }
3814
Benjamin Kramer8adeef92015-04-02 16:19:54 +00003815 T = new (*this, TypeAlignment) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00003816 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003817 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003818 return QualType(T, 0);
3819}
3820
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003821QualType
Jay Foad39c79802011-01-12 09:06:06 +00003822ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003823 llvm::FoldingSetNodeID ID;
3824 ParenType::Profile(ID, InnerType);
3825
Craig Topper36250ad2014-05-12 05:36:57 +00003826 void *InsertPos = nullptr;
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003827 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3828 if (T)
3829 return QualType(T, 0);
3830
3831 QualType Canon = InnerType;
3832 if (!Canon.isCanonical()) {
3833 Canon = getCanonicalType(InnerType);
3834 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3835 assert(!CheckT && "Paren canonical type broken");
3836 (void)CheckT;
3837 }
3838
Benjamin Kramer8adeef92015-04-02 16:19:54 +00003839 T = new (*this, TypeAlignment) ParenType(InnerType, Canon);
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003840 Types.push_back(T);
3841 ParenTypes.InsertNode(T, InsertPos);
3842 return QualType(T, 0);
3843}
3844
Douglas Gregor02085352010-03-31 20:19:30 +00003845QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
3846 NestedNameSpecifier *NNS,
3847 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003848 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00003849 if (Canon.isNull()) {
3850 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Richard Smith74f02342017-01-19 21:00:13 +00003851 if (CanonNNS != NNS)
3852 Canon = getDependentNameType(Keyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003853 }
3854
3855 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00003856 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003857
Craig Topper36250ad2014-05-12 05:36:57 +00003858 void *InsertPos = nullptr;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003859 DependentNameType *T
3860 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00003861 if (T)
3862 return QualType(T, 0);
3863
Benjamin Kramer8adeef92015-04-02 16:19:54 +00003864 T = new (*this, TypeAlignment) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00003865 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003866 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003867 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00003868}
3869
Mike Stump11289f42009-09-09 15:08:12 +00003870QualType
John McCallc392f372010-06-11 00:33:02 +00003871ASTContext::getDependentTemplateSpecializationType(
3872 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00003873 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00003874 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003875 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00003876 // TODO: avoid this copy
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003877 SmallVector<TemplateArgument, 16> ArgCopy;
John McCallc392f372010-06-11 00:33:02 +00003878 for (unsigned I = 0, E = Args.size(); I != E; ++I)
3879 ArgCopy.push_back(Args[I].getArgument());
David Majnemer6fbeee32016-07-07 04:43:07 +00003880 return getDependentTemplateSpecializationType(Keyword, NNS, Name, ArgCopy);
John McCallc392f372010-06-11 00:33:02 +00003881}
3882
3883QualType
3884ASTContext::getDependentTemplateSpecializationType(
3885 ElaboratedTypeKeyword Keyword,
3886 NestedNameSpecifier *NNS,
3887 const IdentifierInfo *Name,
David Majnemer6fbeee32016-07-07 04:43:07 +00003888 ArrayRef<TemplateArgument> Args) const {
Douglas Gregor6e068012011-02-28 00:04:36 +00003889 assert((!NNS || NNS->isDependent()) &&
3890 "nested-name-specifier must be dependent");
Douglas Gregordce2b622009-04-01 00:28:59 +00003891
Douglas Gregorc42075a2010-02-04 18:10:26 +00003892 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00003893 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
David Majnemer6fbeee32016-07-07 04:43:07 +00003894 Name, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003895
Craig Topper36250ad2014-05-12 05:36:57 +00003896 void *InsertPos = nullptr;
John McCallc392f372010-06-11 00:33:02 +00003897 DependentTemplateSpecializationType *T
3898 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003899 if (T)
3900 return QualType(T, 0);
3901
John McCallc392f372010-06-11 00:33:02 +00003902 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003903
John McCallc392f372010-06-11 00:33:02 +00003904 ElaboratedTypeKeyword CanonKeyword = Keyword;
3905 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
3906
3907 bool AnyNonCanonArgs = false;
David Majnemer6fbeee32016-07-07 04:43:07 +00003908 unsigned NumArgs = Args.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003909 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCallc392f372010-06-11 00:33:02 +00003910 for (unsigned I = 0; I != NumArgs; ++I) {
3911 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
3912 if (!CanonArgs[I].structurallyEquals(Args[I]))
3913 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00003914 }
3915
John McCallc392f372010-06-11 00:33:02 +00003916 QualType Canon;
3917 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
3918 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
David Majnemer6fbeee32016-07-07 04:43:07 +00003919 Name,
3920 CanonArgs);
John McCallc392f372010-06-11 00:33:02 +00003921
3922 // Find the insert position again.
3923 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3924 }
3925
3926 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
3927 sizeof(TemplateArgument) * NumArgs),
3928 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00003929 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
David Majnemer6fbeee32016-07-07 04:43:07 +00003930 Name, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00003931 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00003932 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003933 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00003934}
3935
Richard Smith32918772017-02-14 00:25:28 +00003936TemplateArgument ASTContext::getInjectedTemplateArg(NamedDecl *Param) {
3937 TemplateArgument Arg;
3938 if (auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
3939 QualType ArgType = getTypeDeclType(TTP);
3940 if (TTP->isParameterPack())
3941 ArgType = getPackExpansionType(ArgType, None);
3942
3943 Arg = TemplateArgument(ArgType);
3944 } else if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3945 Expr *E = new (*this) DeclRefExpr(
3946 NTTP, /*enclosing*/false,
3947 NTTP->getType().getNonLValueExprType(*this),
3948 Expr::getValueKindForType(NTTP->getType()), NTTP->getLocation());
3949
3950 if (NTTP->isParameterPack())
3951 E = new (*this) PackExpansionExpr(DependentTy, E, NTTP->getLocation(),
3952 None);
3953 Arg = TemplateArgument(E);
3954 } else {
3955 auto *TTP = cast<TemplateTemplateParmDecl>(Param);
3956 if (TTP->isParameterPack())
3957 Arg = TemplateArgument(TemplateName(TTP), Optional<unsigned>());
3958 else
3959 Arg = TemplateArgument(TemplateName(TTP));
3960 }
3961
3962 if (Param->isTemplateParameterPack())
3963 Arg = TemplateArgument::CreatePackCopy(*this, Arg);
3964
3965 return Arg;
3966}
3967
Richard Smith43e14d22016-12-23 02:10:11 +00003968void
3969ASTContext::getInjectedTemplateArgs(const TemplateParameterList *Params,
3970 SmallVectorImpl<TemplateArgument> &Args) {
3971 Args.reserve(Args.size() + Params->size());
3972
Richard Smith32918772017-02-14 00:25:28 +00003973 for (NamedDecl *Param : *Params)
3974 Args.push_back(getInjectedTemplateArg(Param));
Richard Smith43e14d22016-12-23 02:10:11 +00003975}
3976
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003977QualType ASTContext::getPackExpansionType(QualType Pattern,
David Blaikie05785d12013-02-20 22:23:23 +00003978 Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00003979 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003980 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003981
3982 assert(Pattern->containsUnexpandedParameterPack() &&
3983 "Pack expansions must expand one or more parameter packs");
Craig Topper36250ad2014-05-12 05:36:57 +00003984 void *InsertPos = nullptr;
Douglas Gregord2fa7662010-12-20 02:24:11 +00003985 PackExpansionType *T
3986 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3987 if (T)
3988 return QualType(T, 0);
3989
3990 QualType Canon;
3991 if (!Pattern.isCanonical()) {
Richard Smith68eea502012-07-16 00:20:35 +00003992 Canon = getCanonicalType(Pattern);
3993 // The canonical type might not contain an unexpanded parameter pack, if it
3994 // contains an alias template specialization which ignores one of its
3995 // parameters.
3996 if (Canon->containsUnexpandedParameterPack()) {
Richard Smith8b4e1e22014-07-10 01:20:17 +00003997 Canon = getPackExpansionType(Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003998
Richard Smith68eea502012-07-16 00:20:35 +00003999 // Find the insert position again, in case we inserted an element into
4000 // PackExpansionTypes and invalidated our insert position.
4001 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
4002 }
Douglas Gregord2fa7662010-12-20 02:24:11 +00004003 }
4004
Benjamin Kramer8adeef92015-04-02 16:19:54 +00004005 T = new (*this, TypeAlignment)
4006 PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00004007 Types.push_back(T);
4008 PackExpansionTypes.InsertNode(T, InsertPos);
Richard Smith8b4e1e22014-07-10 01:20:17 +00004009 return QualType(T, 0);
Douglas Gregord2fa7662010-12-20 02:24:11 +00004010}
4011
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004012/// CmpProtocolNames - Comparison predicate for sorting protocols
4013/// alphabetically.
Benjamin Kramer0eb262f2015-03-14 13:32:49 +00004014static int CmpProtocolNames(ObjCProtocolDecl *const *LHS,
4015 ObjCProtocolDecl *const *RHS) {
4016 return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName());
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004017}
4018
Craig Topper1f26d5b2016-01-03 19:43:23 +00004019static bool areSortedAndUniqued(ArrayRef<ObjCProtocolDecl *> Protocols) {
4020 if (Protocols.empty()) return true;
John McCallfc93cf92009-10-22 22:37:11 +00004021
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00004022 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
4023 return false;
4024
Craig Topper1f26d5b2016-01-03 19:43:23 +00004025 for (unsigned i = 1; i != Protocols.size(); ++i)
Benjamin Kramer0eb262f2015-03-14 13:32:49 +00004026 if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 ||
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00004027 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCallfc93cf92009-10-22 22:37:11 +00004028 return false;
4029 return true;
4030}
4031
Craig Topper6a8c1512015-10-22 01:56:18 +00004032static void
4033SortAndUniqueProtocols(SmallVectorImpl<ObjCProtocolDecl *> &Protocols) {
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004034 // Sort protocols, keyed by name.
Craig Topper6a8c1512015-10-22 01:56:18 +00004035 llvm::array_pod_sort(Protocols.begin(), Protocols.end(), CmpProtocolNames);
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004036
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00004037 // Canonicalize.
Craig Topper6a8c1512015-10-22 01:56:18 +00004038 for (ObjCProtocolDecl *&P : Protocols)
4039 P = P->getCanonicalDecl();
4040
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004041 // Remove duplicates.
Craig Topper6a8c1512015-10-22 01:56:18 +00004042 auto ProtocolsEnd = std::unique(Protocols.begin(), Protocols.end());
4043 Protocols.erase(ProtocolsEnd, Protocols.end());
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004044}
4045
John McCall8b07ec22010-05-15 11:32:37 +00004046QualType ASTContext::getObjCObjectType(QualType BaseType,
4047 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00004048 unsigned NumProtocols) const {
Douglas Gregore9d95f12015-07-07 03:57:35 +00004049 return getObjCObjectType(BaseType, { },
Douglas Gregorab209d82015-07-07 03:58:42 +00004050 llvm::makeArrayRef(Protocols, NumProtocols),
4051 /*isKindOf=*/false);
Douglas Gregore9d95f12015-07-07 03:57:35 +00004052}
4053
4054QualType ASTContext::getObjCObjectType(
4055 QualType baseType,
4056 ArrayRef<QualType> typeArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00004057 ArrayRef<ObjCProtocolDecl *> protocols,
4058 bool isKindOf) const {
Douglas Gregore9d95f12015-07-07 03:57:35 +00004059 // If the base type is an interface and there aren't any protocols or
4060 // type arguments to add, then the interface type will do just fine.
Douglas Gregorab209d82015-07-07 03:58:42 +00004061 if (typeArgs.empty() && protocols.empty() && !isKindOf &&
4062 isa<ObjCInterfaceType>(baseType))
Douglas Gregore9d95f12015-07-07 03:57:35 +00004063 return baseType;
John McCall8b07ec22010-05-15 11:32:37 +00004064
4065 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00004066 llvm::FoldingSetNodeID ID;
Douglas Gregorab209d82015-07-07 03:58:42 +00004067 ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols, isKindOf);
Craig Topper36250ad2014-05-12 05:36:57 +00004068 void *InsertPos = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00004069 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
4070 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00004071
Douglas Gregore9d95f12015-07-07 03:57:35 +00004072 // Determine the type arguments to be used for canonicalization,
4073 // which may be explicitly specified here or written on the base
4074 // type.
4075 ArrayRef<QualType> effectiveTypeArgs = typeArgs;
4076 if (effectiveTypeArgs.empty()) {
4077 if (auto baseObject = baseType->getAs<ObjCObjectType>())
4078 effectiveTypeArgs = baseObject->getTypeArgs();
4079 }
John McCallfc93cf92009-10-22 22:37:11 +00004080
Douglas Gregore9d95f12015-07-07 03:57:35 +00004081 // Build the canonical type, which has the canonical base type and a
4082 // sorted-and-uniqued list of protocols and the type arguments
4083 // canonicalized.
4084 QualType canonical;
4085 bool typeArgsAreCanonical = std::all_of(effectiveTypeArgs.begin(),
4086 effectiveTypeArgs.end(),
4087 [&](QualType type) {
4088 return type.isCanonical();
4089 });
Craig Topper1f26d5b2016-01-03 19:43:23 +00004090 bool protocolsSorted = areSortedAndUniqued(protocols);
Douglas Gregore9d95f12015-07-07 03:57:35 +00004091 if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) {
4092 // Determine the canonical type arguments.
4093 ArrayRef<QualType> canonTypeArgs;
4094 SmallVector<QualType, 4> canonTypeArgsVec;
4095 if (!typeArgsAreCanonical) {
4096 canonTypeArgsVec.reserve(effectiveTypeArgs.size());
4097 for (auto typeArg : effectiveTypeArgs)
4098 canonTypeArgsVec.push_back(getCanonicalType(typeArg));
4099 canonTypeArgs = canonTypeArgsVec;
John McCallfc93cf92009-10-22 22:37:11 +00004100 } else {
Douglas Gregore9d95f12015-07-07 03:57:35 +00004101 canonTypeArgs = effectiveTypeArgs;
John McCallfc93cf92009-10-22 22:37:11 +00004102 }
4103
Douglas Gregore9d95f12015-07-07 03:57:35 +00004104 ArrayRef<ObjCProtocolDecl *> canonProtocols;
4105 SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec;
4106 if (!protocolsSorted) {
Craig Topper6a8c1512015-10-22 01:56:18 +00004107 canonProtocolsVec.append(protocols.begin(), protocols.end());
4108 SortAndUniqueProtocols(canonProtocolsVec);
4109 canonProtocols = canonProtocolsVec;
Douglas Gregore9d95f12015-07-07 03:57:35 +00004110 } else {
4111 canonProtocols = protocols;
4112 }
4113
4114 canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00004115 canonProtocols, isKindOf);
Douglas Gregore9d95f12015-07-07 03:57:35 +00004116
John McCallfc93cf92009-10-22 22:37:11 +00004117 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00004118 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
4119 }
4120
Douglas Gregore9d95f12015-07-07 03:57:35 +00004121 unsigned size = sizeof(ObjCObjectTypeImpl);
4122 size += typeArgs.size() * sizeof(QualType);
4123 size += protocols.size() * sizeof(ObjCProtocolDecl *);
4124 void *mem = Allocate(size, TypeAlignment);
John McCall8b07ec22010-05-15 11:32:37 +00004125 ObjCObjectTypeImpl *T =
Douglas Gregorab209d82015-07-07 03:58:42 +00004126 new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols,
4127 isKindOf);
John McCall8b07ec22010-05-15 11:32:37 +00004128
4129 Types.push_back(T);
4130 ObjCObjectTypes.InsertNode(T, InsertPos);
4131 return QualType(T, 0);
4132}
4133
Manman Ren3569eb52016-09-13 17:03:12 +00004134/// Apply Objective-C protocol qualifiers to the given type.
4135/// If this is for the canonical type of a type parameter, we can apply
4136/// protocol qualifiers on the ObjCObjectPointerType.
4137QualType
4138ASTContext::applyObjCProtocolQualifiers(QualType type,
4139 ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError,
4140 bool allowOnPointerType) const {
4141 hasError = false;
4142
Manman Renc5705ba2016-09-13 17:41:05 +00004143 if (const ObjCTypeParamType *objT =
4144 dyn_cast<ObjCTypeParamType>(type.getTypePtr())) {
4145 return getObjCTypeParamType(objT->getDecl(), protocols);
4146 }
4147
Manman Ren3569eb52016-09-13 17:03:12 +00004148 // Apply protocol qualifiers to ObjCObjectPointerType.
4149 if (allowOnPointerType) {
4150 if (const ObjCObjectPointerType *objPtr =
4151 dyn_cast<ObjCObjectPointerType>(type.getTypePtr())) {
4152 const ObjCObjectType *objT = objPtr->getObjectType();
4153 // Merge protocol lists and construct ObjCObjectType.
4154 SmallVector<ObjCProtocolDecl*, 8> protocolsVec;
4155 protocolsVec.append(objT->qual_begin(),
4156 objT->qual_end());
4157 protocolsVec.append(protocols.begin(), protocols.end());
4158 ArrayRef<ObjCProtocolDecl *> protocols = protocolsVec;
4159 type = getObjCObjectType(
4160 objT->getBaseType(),
4161 objT->getTypeArgsAsWritten(),
4162 protocols,
4163 objT->isKindOfTypeAsWritten());
4164 return getObjCObjectPointerType(type);
4165 }
4166 }
4167
4168 // Apply protocol qualifiers to ObjCObjectType.
4169 if (const ObjCObjectType *objT = dyn_cast<ObjCObjectType>(type.getTypePtr())){
4170 // FIXME: Check for protocols to which the class type is already
4171 // known to conform.
4172
4173 return getObjCObjectType(objT->getBaseType(),
4174 objT->getTypeArgsAsWritten(),
4175 protocols,
4176 objT->isKindOfTypeAsWritten());
4177 }
4178
4179 // If the canonical type is ObjCObjectType, ...
4180 if (type->isObjCObjectType()) {
4181 // Silently overwrite any existing protocol qualifiers.
4182 // TODO: determine whether that's the right thing to do.
4183
4184 // FIXME: Check for protocols to which the class type is already
4185 // known to conform.
4186 return getObjCObjectType(type, { }, protocols, false);
4187 }
4188
4189 // id<protocol-list>
4190 if (type->isObjCIdType()) {
4191 const ObjCObjectPointerType *objPtr = type->castAs<ObjCObjectPointerType>();
4192 type = getObjCObjectType(ObjCBuiltinIdTy, { }, protocols,
4193 objPtr->isKindOfType());
4194 return getObjCObjectPointerType(type);
4195 }
4196
4197 // Class<protocol-list>
4198 if (type->isObjCClassType()) {
4199 const ObjCObjectPointerType *objPtr = type->castAs<ObjCObjectPointerType>();
4200 type = getObjCObjectType(ObjCBuiltinClassTy, { }, protocols,
4201 objPtr->isKindOfType());
4202 return getObjCObjectPointerType(type);
4203 }
4204
4205 hasError = true;
4206 return type;
4207}
4208
Manman Rene6be26c2016-09-13 17:25:08 +00004209QualType
4210ASTContext::getObjCTypeParamType(const ObjCTypeParamDecl *Decl,
4211 ArrayRef<ObjCProtocolDecl *> protocols,
4212 QualType Canonical) const {
4213 // Look in the folding set for an existing type.
4214 llvm::FoldingSetNodeID ID;
4215 ObjCTypeParamType::Profile(ID, Decl, protocols);
4216 void *InsertPos = nullptr;
4217 if (ObjCTypeParamType *TypeParam =
4218 ObjCTypeParamTypes.FindNodeOrInsertPos(ID, InsertPos))
4219 return QualType(TypeParam, 0);
4220
4221 if (Canonical.isNull()) {
4222 // We canonicalize to the underlying type.
4223 Canonical = getCanonicalType(Decl->getUnderlyingType());
4224 if (!protocols.empty()) {
4225 // Apply the protocol qualifers.
4226 bool hasError;
4227 Canonical = applyObjCProtocolQualifiers(Canonical, protocols, hasError,
4228 true/*allowOnPointerType*/);
4229 assert(!hasError && "Error when apply protocol qualifier to bound type");
4230 }
4231 }
4232
4233 unsigned size = sizeof(ObjCTypeParamType);
4234 size += protocols.size() * sizeof(ObjCProtocolDecl *);
4235 void *mem = Allocate(size, TypeAlignment);
4236 ObjCTypeParamType *newType = new (mem)
4237 ObjCTypeParamType(Decl, Canonical, protocols);
4238
4239 Types.push_back(newType);
4240 ObjCTypeParamTypes.InsertNode(newType, InsertPos);
4241 return QualType(newType, 0);
4242}
4243
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004244/// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
4245/// protocol list adopt all protocols in QT's qualified-id protocol
4246/// list.
4247bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT,
4248 ObjCInterfaceDecl *IC) {
4249 if (!QT->isObjCQualifiedIdType())
4250 return false;
4251
4252 if (const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>()) {
4253 // If both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00004254 for (auto *Proto : OPT->quals()) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004255 if (!IC->ClassImplementsProtocol(Proto, false))
4256 return false;
4257 }
4258 return true;
4259 }
4260 return false;
4261}
4262
4263/// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
4264/// QT's qualified-id protocol list adopt all protocols in IDecl's list
4265/// of protocols.
4266bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
4267 ObjCInterfaceDecl *IDecl) {
4268 if (!QT->isObjCQualifiedIdType())
4269 return false;
4270 const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>();
4271 if (!OPT)
4272 return false;
4273 if (!IDecl->hasDefinition())
4274 return false;
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00004275 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols;
4276 CollectInheritedProtocols(IDecl, InheritedProtocols);
4277 if (InheritedProtocols.empty())
4278 return false;
Fariborz Jahanian48a01cb2014-04-04 23:53:45 +00004279 // Check that if every protocol in list of id<plist> conforms to a protcol
4280 // of IDecl's, then bridge casting is ok.
4281 bool Conforms = false;
4282 for (auto *Proto : OPT->quals()) {
4283 Conforms = false;
4284 for (auto *PI : InheritedProtocols) {
4285 if (ProtocolCompatibleWithProtocol(Proto, PI)) {
4286 Conforms = true;
4287 break;
4288 }
4289 }
4290 if (!Conforms)
4291 break;
4292 }
4293 if (Conforms)
4294 return true;
4295
Aaron Ballman83731462014-03-17 16:14:00 +00004296 for (auto *PI : InheritedProtocols) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004297 // If both the right and left sides have qualifiers.
4298 bool Adopts = false;
Aaron Ballman83731462014-03-17 16:14:00 +00004299 for (auto *Proto : OPT->quals()) {
Fariborz Jahanian48a01cb2014-04-04 23:53:45 +00004300 // return 'true' if 'PI' is in the inheritance hierarchy of Proto
Aaron Ballman83731462014-03-17 16:14:00 +00004301 if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004302 break;
4303 }
4304 if (!Adopts)
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00004305 return false;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004306 }
4307 return true;
4308}
4309
John McCall8b07ec22010-05-15 11:32:37 +00004310/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
4311/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00004312QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00004313 llvm::FoldingSetNodeID ID;
4314 ObjCObjectPointerType::Profile(ID, ObjectT);
4315
Craig Topper36250ad2014-05-12 05:36:57 +00004316 void *InsertPos = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00004317 if (ObjCObjectPointerType *QT =
4318 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
4319 return QualType(QT, 0);
4320
4321 // Find the canonical object type.
4322 QualType Canonical;
4323 if (!ObjectT.isCanonical()) {
4324 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
4325
4326 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00004327 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
4328 }
4329
Douglas Gregorf85bee62010-02-08 22:59:26 +00004330 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00004331 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
4332 ObjCObjectPointerType *QType =
4333 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00004334
Steve Narofffb4330f2009-06-17 22:40:22 +00004335 Types.push_back(QType);
4336 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00004337 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00004338}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004339
Douglas Gregor1c283312010-08-11 12:19:30 +00004340/// getObjCInterfaceType - Return the unique reference to the type for the
4341/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00004342QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
4343 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00004344 if (Decl->TypeForDecl)
4345 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00004346
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00004347 if (PrevDecl) {
4348 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
4349 Decl->TypeForDecl = PrevDecl->TypeForDecl;
4350 return QualType(PrevDecl->TypeForDecl, 0);
4351 }
4352
Douglas Gregor7671e532011-12-16 16:34:57 +00004353 // Prefer the definition, if there is one.
4354 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
4355 Decl = Def;
4356
Douglas Gregor1c283312010-08-11 12:19:30 +00004357 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
4358 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
4359 Decl->TypeForDecl = T;
4360 Types.push_back(T);
4361 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00004362}
4363
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004364/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
4365/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00004366/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00004367/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00004368/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00004369QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00004370 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004371 if (tofExpr->isTypeDependent()) {
4372 llvm::FoldingSetNodeID ID;
4373 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00004374
Craig Topper36250ad2014-05-12 05:36:57 +00004375 void *InsertPos = nullptr;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004376 DependentTypeOfExprType *Canon
4377 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
4378 if (Canon) {
4379 // We already have a "canonical" version of an identical, dependent
4380 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00004381 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004382 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00004383 } else {
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004384 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00004385 Canon
4386 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004387 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
4388 toe = Canon;
4389 }
4390 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00004391 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00004392 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00004393 }
Steve Naroffa773cd52007-08-01 18:02:17 +00004394 Types.push_back(toe);
4395 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00004396}
4397
Steve Naroffa773cd52007-08-01 18:02:17 +00004398/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
Richard Smith8eb1d322014-06-05 20:13:13 +00004399/// TypeOfType nodes. The only motivation to unique these nodes would be
Steve Naroffa773cd52007-08-01 18:02:17 +00004400/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Richard Smith8eb1d322014-06-05 20:13:13 +00004401/// an issue. This doesn't affect the type checker, since it operates
4402/// on canonical types (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00004403QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00004404 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00004405 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00004406 Types.push_back(tot);
4407 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00004408}
4409
Richard Smith8eb1d322014-06-05 20:13:13 +00004410/// \brief Unlike many "get<Type>" functions, we don't unique DecltypeType
4411/// nodes. This would never be helpful, since each such type has its own
4412/// expression, and would not give a significant memory saving, since there
4413/// is an Expr tree under each such type.
Douglas Gregor81495f32012-02-12 18:42:33 +00004414QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00004415 DecltypeType *dt;
Richard Smith8eb1d322014-06-05 20:13:13 +00004416
4417 // C++11 [temp.type]p2:
Douglas Gregor678d76c2011-07-01 01:22:09 +00004418 // If an expression e involves a template parameter, decltype(e) denotes a
Richard Smith8eb1d322014-06-05 20:13:13 +00004419 // unique dependent type. Two such decltype-specifiers refer to the same
4420 // type only if their expressions are equivalent (14.5.6.1).
Douglas Gregor678d76c2011-07-01 01:22:09 +00004421 if (e->isInstantiationDependent()) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00004422 llvm::FoldingSetNodeID ID;
4423 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00004424
Craig Topper36250ad2014-05-12 05:36:57 +00004425 void *InsertPos = nullptr;
Douglas Gregora21f6c32009-07-30 23:36:40 +00004426 DependentDecltypeType *Canon
4427 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
Richard Smith8eb1d322014-06-05 20:13:13 +00004428 if (!Canon) {
Yaron Keren633e14a2016-11-29 10:08:20 +00004429 // Build a new, canonical decltype(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00004430 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00004431 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
Douglas Gregora21f6c32009-07-30 23:36:40 +00004432 }
Richard Smith8eb1d322014-06-05 20:13:13 +00004433 dt = new (*this, TypeAlignment)
4434 DecltypeType(e, UnderlyingType, QualType((DecltypeType *)Canon, 0));
Douglas Gregora21f6c32009-07-30 23:36:40 +00004435 } else {
Richard Smith8eb1d322014-06-05 20:13:13 +00004436 dt = new (*this, TypeAlignment)
4437 DecltypeType(e, UnderlyingType, getCanonicalType(UnderlyingType));
Douglas Gregorabd68132009-07-08 00:03:05 +00004438 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00004439 Types.push_back(dt);
4440 return QualType(dt, 0);
4441}
4442
Alexis Hunte852b102011-05-24 22:41:36 +00004443/// getUnaryTransformationType - We don't unique these, since the memory
4444/// savings are minimal and these are rare.
4445QualType ASTContext::getUnaryTransformType(QualType BaseType,
4446 QualType UnderlyingType,
4447 UnaryTransformType::UTTKind Kind)
4448 const {
Vassil Vassilevbab6f962016-03-30 22:18:29 +00004449 UnaryTransformType *ut = nullptr;
4450
4451 if (BaseType->isDependentType()) {
4452 // Look in the folding set for an existing type.
4453 llvm::FoldingSetNodeID ID;
4454 DependentUnaryTransformType::Profile(ID, getCanonicalType(BaseType), Kind);
4455
4456 void *InsertPos = nullptr;
4457 DependentUnaryTransformType *Canon
4458 = DependentUnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos);
4459
4460 if (!Canon) {
4461 // Build a new, canonical __underlying_type(type) type.
4462 Canon = new (*this, TypeAlignment)
4463 DependentUnaryTransformType(*this, getCanonicalType(BaseType),
4464 Kind);
4465 DependentUnaryTransformTypes.InsertNode(Canon, InsertPos);
4466 }
4467 ut = new (*this, TypeAlignment) UnaryTransformType (BaseType,
4468 QualType(), Kind,
4469 QualType(Canon, 0));
4470 } else {
4471 QualType CanonType = getCanonicalType(UnderlyingType);
4472 ut = new (*this, TypeAlignment) UnaryTransformType (BaseType,
4473 UnderlyingType, Kind,
4474 CanonType);
4475 }
4476 Types.push_back(ut);
4477 return QualType(ut, 0);
Alexis Hunte852b102011-05-24 22:41:36 +00004478}
4479
Richard Smith2a7d4812013-05-04 07:00:32 +00004480/// getAutoType - Return the uniqued reference to the 'auto' type which has been
4481/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
4482/// canonical deduced-but-dependent 'auto' type.
Richard Smithe301ba22015-11-11 02:02:15 +00004483QualType ASTContext::getAutoType(QualType DeducedType, AutoTypeKeyword Keyword,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00004484 bool IsDependent) const {
Richard Smithe301ba22015-11-11 02:02:15 +00004485 if (DeducedType.isNull() && Keyword == AutoTypeKeyword::Auto && !IsDependent)
Richard Smith2a7d4812013-05-04 07:00:32 +00004486 return getAutoDeductType();
Manuel Klimek2fdbea22013-08-22 12:12:24 +00004487
Richard Smith2a7d4812013-05-04 07:00:32 +00004488 // Look in the folding set for an existing type.
Craig Topper36250ad2014-05-12 05:36:57 +00004489 void *InsertPos = nullptr;
Richard Smith2a7d4812013-05-04 07:00:32 +00004490 llvm::FoldingSetNodeID ID;
Richard Smithe301ba22015-11-11 02:02:15 +00004491 AutoType::Profile(ID, DeducedType, Keyword, IsDependent);
Richard Smith2a7d4812013-05-04 07:00:32 +00004492 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
4493 return QualType(AT, 0);
Richard Smithb2bc2e62011-02-21 20:05:19 +00004494
Richard Smith74aeef52013-04-26 16:15:35 +00004495 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType,
Richard Smithe301ba22015-11-11 02:02:15 +00004496 Keyword,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00004497 IsDependent);
Richard Smithb2bc2e62011-02-21 20:05:19 +00004498 Types.push_back(AT);
4499 if (InsertPos)
4500 AutoTypes.InsertNode(AT, InsertPos);
4501 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00004502}
4503
Richard Smith600b5262017-01-26 20:40:47 +00004504/// Return the uniqued reference to the deduced template specialization type
4505/// which has been deduced to the given type, or to the canonical undeduced
4506/// such type, or the canonical deduced-but-dependent such type.
4507QualType ASTContext::getDeducedTemplateSpecializationType(
4508 TemplateName Template, QualType DeducedType, bool IsDependent) const {
4509 // Look in the folding set for an existing type.
4510 void *InsertPos = nullptr;
4511 llvm::FoldingSetNodeID ID;
4512 DeducedTemplateSpecializationType::Profile(ID, Template, DeducedType,
4513 IsDependent);
4514 if (DeducedTemplateSpecializationType *DTST =
4515 DeducedTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos))
4516 return QualType(DTST, 0);
4517
4518 DeducedTemplateSpecializationType *DTST = new (*this, TypeAlignment)
4519 DeducedTemplateSpecializationType(Template, DeducedType, IsDependent);
4520 Types.push_back(DTST);
4521 if (InsertPos)
4522 DeducedTemplateSpecializationTypes.InsertNode(DTST, InsertPos);
4523 return QualType(DTST, 0);
4524}
4525
Eli Friedman0dfb8892011-10-06 23:00:33 +00004526/// getAtomicType - Return the uniqued reference to the atomic type for
4527/// the given value type.
4528QualType ASTContext::getAtomicType(QualType T) const {
4529 // Unique pointers, to guarantee there is only one pointer of a particular
4530 // structure.
4531 llvm::FoldingSetNodeID ID;
4532 AtomicType::Profile(ID, T);
4533
Craig Topper36250ad2014-05-12 05:36:57 +00004534 void *InsertPos = nullptr;
Eli Friedman0dfb8892011-10-06 23:00:33 +00004535 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
4536 return QualType(AT, 0);
4537
4538 // If the atomic value type isn't canonical, this won't be a canonical type
4539 // either, so fill in the canonical type field.
4540 QualType Canonical;
4541 if (!T.isCanonical()) {
4542 Canonical = getAtomicType(getCanonicalType(T));
4543
4544 // Get the new insert position for the node we care about.
4545 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00004546 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Eli Friedman0dfb8892011-10-06 23:00:33 +00004547 }
4548 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
4549 Types.push_back(New);
4550 AtomicTypes.InsertNode(New, InsertPos);
4551 return QualType(New, 0);
4552}
4553
Richard Smith02e85f32011-04-14 22:09:26 +00004554/// getAutoDeductType - Get type pattern for deducing against 'auto'.
4555QualType ASTContext::getAutoDeductType() const {
4556 if (AutoDeductTy.isNull())
Richard Smith2a7d4812013-05-04 07:00:32 +00004557 AutoDeductTy = QualType(
Richard Smithe301ba22015-11-11 02:02:15 +00004558 new (*this, TypeAlignment) AutoType(QualType(), AutoTypeKeyword::Auto,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00004559 /*dependent*/false),
Richard Smith2a7d4812013-05-04 07:00:32 +00004560 0);
Richard Smith02e85f32011-04-14 22:09:26 +00004561 return AutoDeductTy;
4562}
4563
4564/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
4565QualType ASTContext::getAutoRRefDeductType() const {
4566 if (AutoRRefDeductTy.isNull())
4567 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
4568 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
4569 return AutoRRefDeductTy;
4570}
4571
Chris Lattnerfb072462007-01-23 05:45:31 +00004572/// getTagDeclType - Return the unique reference to the type for the
4573/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00004574QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00004575 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00004576 // FIXME: What is the design on getTagDeclType when it requires casting
4577 // away const? mutable?
4578 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00004579}
4580
Mike Stump11289f42009-09-09 15:08:12 +00004581/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
4582/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
4583/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00004584CanQualType ASTContext::getSizeType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00004585 return getFromTargetType(Target->getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00004586}
Chris Lattnerfb072462007-01-23 05:45:31 +00004587
Alexander Shaposhnikov1e898d92017-07-14 17:30:14 +00004588/// Return the unique signed counterpart of the integer type
4589/// corresponding to size_t.
4590CanQualType ASTContext::getSignedSizeType() const {
4591 return getFromTargetType(Target->getSignedSizeType());
4592}
4593
Hans Wennborg27541db2011-10-27 08:29:09 +00004594/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
4595CanQualType ASTContext::getIntMaxType() const {
4596 return getFromTargetType(Target->getIntMaxType());
4597}
4598
4599/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
4600CanQualType ASTContext::getUIntMaxType() const {
4601 return getFromTargetType(Target->getUIntMaxType());
4602}
4603
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00004604/// getSignedWCharType - Return the type of "signed wchar_t".
4605/// Used when in C++, as a GCC extension.
4606QualType ASTContext::getSignedWCharType() const {
4607 // FIXME: derive from "Target" ?
4608 return WCharTy;
4609}
4610
4611/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
4612/// Used when in C++, as a GCC extension.
4613QualType ASTContext::getUnsignedWCharType() const {
4614 // FIXME: derive from "Target" ?
4615 return UnsignedIntTy;
4616}
4617
Enea Zaffanellaf11ceb62013-01-26 17:08:37 +00004618QualType ASTContext::getIntPtrType() const {
4619 return getFromTargetType(Target->getIntPtrType());
4620}
4621
4622QualType ASTContext::getUIntPtrType() const {
4623 return getCorrespondingUnsignedType(getIntPtrType());
4624}
4625
Hans Wennborg27541db2011-10-27 08:29:09 +00004626/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00004627/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
4628QualType ASTContext::getPointerDiffType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00004629 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00004630}
4631
Alexander Shaposhnikov195b25c2017-09-28 23:11:31 +00004632/// \brief Return the unique unsigned counterpart of "ptrdiff_t"
4633/// integer type. The standard (C11 7.21.6.1p7) refers to this type
4634/// in the definition of %tu format specifier.
4635QualType ASTContext::getUnsignedPointerDiffType() const {
4636 return getFromTargetType(Target->getUnsignedPtrDiffType(0));
4637}
4638
Eli Friedman4e91899e2012-11-27 02:58:24 +00004639/// \brief Return the unique type for "pid_t" defined in
4640/// <sys/types.h>. We need this to compute the correct type for vfork().
4641QualType ASTContext::getProcessIDType() const {
4642 return getFromTargetType(Target->getProcessIDType());
4643}
4644
Chris Lattnera21ad802008-04-02 05:18:44 +00004645//===----------------------------------------------------------------------===//
4646// Type Operators
4647//===----------------------------------------------------------------------===//
4648
Jay Foad39c79802011-01-12 09:06:06 +00004649CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00004650 // Push qualifiers into arrays, and then discard any remaining
4651 // qualifiers.
4652 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00004653 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00004654 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00004655 QualType Result;
4656 if (isa<ArrayType>(Ty)) {
4657 Result = getArrayDecayedType(QualType(Ty,0));
4658 } else if (isa<FunctionType>(Ty)) {
4659 Result = getPointerType(QualType(Ty, 0));
4660 } else {
4661 Result = QualType(Ty, 0);
4662 }
4663
4664 return CanQualType::CreateUnsafe(Result);
4665}
4666
John McCall6c9dd522011-01-18 07:41:22 +00004667QualType ASTContext::getUnqualifiedArrayType(QualType type,
4668 Qualifiers &quals) {
4669 SplitQualType splitType = type.getSplitUnqualifiedType();
4670
4671 // FIXME: getSplitUnqualifiedType() actually walks all the way to
4672 // the unqualified desugared type and then drops it on the floor.
4673 // We then have to strip that sugar back off with
4674 // getUnqualifiedDesugaredType(), which is silly.
4675 const ArrayType *AT =
John McCall18ce25e2012-02-08 00:46:36 +00004676 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall6c9dd522011-01-18 07:41:22 +00004677
4678 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004679 if (!AT) {
John McCall18ce25e2012-02-08 00:46:36 +00004680 quals = splitType.Quals;
4681 return QualType(splitType.Ty, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00004682 }
4683
John McCall6c9dd522011-01-18 07:41:22 +00004684 // Otherwise, recurse on the array's element type.
4685 QualType elementType = AT->getElementType();
4686 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
4687
4688 // If that didn't change the element type, AT has no qualifiers, so we
4689 // can just use the results in splitType.
4690 if (elementType == unqualElementType) {
4691 assert(quals.empty()); // from the recursive call
John McCall18ce25e2012-02-08 00:46:36 +00004692 quals = splitType.Quals;
4693 return QualType(splitType.Ty, 0);
John McCall6c9dd522011-01-18 07:41:22 +00004694 }
4695
4696 // Otherwise, add in the qualifiers from the outermost type, then
4697 // build the type back up.
John McCall18ce25e2012-02-08 00:46:36 +00004698 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00004699
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004700 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00004701 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00004702 CAT->getSizeModifier(), 0);
4703 }
4704
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004705 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00004706 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00004707 }
4708
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004709 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00004710 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00004711 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004712 VAT->getSizeModifier(),
4713 VAT->getIndexTypeCVRQualifiers(),
4714 VAT->getBracketsRange());
4715 }
4716
4717 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00004718 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00004719 DSAT->getSizeModifier(), 0,
4720 SourceRange());
4721}
4722
Douglas Gregor1fc3d662010-06-09 03:53:18 +00004723/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
4724/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
4725/// they point to and return true. If T1 and T2 aren't pointer types
4726/// or pointer-to-member types, or if they are not similar at this
4727/// level, returns false and leaves T1 and T2 unchanged. Top-level
4728/// qualifiers on T1 and T2 are ignored. This function will typically
4729/// be called in a loop that successively "unwraps" pointer and
4730/// pointer-to-member types to compare them at each level.
4731bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
4732 const PointerType *T1PtrType = T1->getAs<PointerType>(),
4733 *T2PtrType = T2->getAs<PointerType>();
4734 if (T1PtrType && T2PtrType) {
4735 T1 = T1PtrType->getPointeeType();
4736 T2 = T2PtrType->getPointeeType();
4737 return true;
4738 }
4739
4740 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
4741 *T2MPType = T2->getAs<MemberPointerType>();
4742 if (T1MPType && T2MPType &&
4743 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
4744 QualType(T2MPType->getClass(), 0))) {
4745 T1 = T1MPType->getPointeeType();
4746 T2 = T2MPType->getPointeeType();
4747 return true;
4748 }
4749
David Blaikiebbafb8a2012-03-11 07:00:24 +00004750 if (getLangOpts().ObjC1) {
Douglas Gregor1fc3d662010-06-09 03:53:18 +00004751 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
4752 *T2OPType = T2->getAs<ObjCObjectPointerType>();
4753 if (T1OPType && T2OPType) {
4754 T1 = T1OPType->getPointeeType();
4755 T2 = T2OPType->getPointeeType();
4756 return true;
4757 }
4758 }
4759
4760 // FIXME: Block pointers, too?
4761
4762 return false;
4763}
4764
Jay Foad39c79802011-01-12 09:06:06 +00004765DeclarationNameInfo
4766ASTContext::getNameForTemplate(TemplateName Name,
4767 SourceLocation NameLoc) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00004768 switch (Name.getKind()) {
4769 case TemplateName::QualifiedTemplate:
4770 case TemplateName::Template:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004771 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCalld9dfe3a2011-06-30 08:33:18 +00004772 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
4773 NameLoc);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004774
John McCalld9dfe3a2011-06-30 08:33:18 +00004775 case TemplateName::OverloadedTemplate: {
4776 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
4777 // DNInfo work in progress: CHECKME: what about DNLoc?
4778 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
4779 }
4780
4781 case TemplateName::DependentTemplate: {
4782 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004783 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00004784 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004785 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
4786 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00004787 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004788 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
4789 // DNInfo work in progress: FIXME: source locations?
4790 DeclarationNameLoc DNLoc;
4791 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
4792 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
4793 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00004794 }
4795 }
4796
John McCalld9dfe3a2011-06-30 08:33:18 +00004797 case TemplateName::SubstTemplateTemplateParm: {
4798 SubstTemplateTemplateParmStorage *subst
4799 = Name.getAsSubstTemplateTemplateParm();
4800 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
4801 NameLoc);
4802 }
4803
4804 case TemplateName::SubstTemplateTemplateParmPack: {
4805 SubstTemplateTemplateParmPackStorage *subst
4806 = Name.getAsSubstTemplateTemplateParmPack();
4807 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
4808 NameLoc);
4809 }
4810 }
4811
4812 llvm_unreachable("bad template name kind!");
John McCall847e2a12009-11-24 18:42:40 +00004813}
4814
Jay Foad39c79802011-01-12 09:06:06 +00004815TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00004816 switch (Name.getKind()) {
4817 case TemplateName::QualifiedTemplate:
4818 case TemplateName::Template: {
4819 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004820 if (TemplateTemplateParmDecl *TTP
John McCalld9dfe3a2011-06-30 08:33:18 +00004821 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004822 Template = getCanonicalTemplateTemplateParmDecl(TTP);
4823
4824 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00004825 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004826 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00004827
John McCalld9dfe3a2011-06-30 08:33:18 +00004828 case TemplateName::OverloadedTemplate:
4829 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump11289f42009-09-09 15:08:12 +00004830
John McCalld9dfe3a2011-06-30 08:33:18 +00004831 case TemplateName::DependentTemplate: {
4832 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
4833 assert(DTN && "Non-dependent template names must refer to template decls.");
4834 return DTN->CanonicalTemplateName;
4835 }
4836
4837 case TemplateName::SubstTemplateTemplateParm: {
4838 SubstTemplateTemplateParmStorage *subst
4839 = Name.getAsSubstTemplateTemplateParm();
4840 return getCanonicalTemplateName(subst->getReplacement());
4841 }
4842
4843 case TemplateName::SubstTemplateTemplateParmPack: {
4844 SubstTemplateTemplateParmPackStorage *subst
4845 = Name.getAsSubstTemplateTemplateParmPack();
4846 TemplateTemplateParmDecl *canonParameter
4847 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
4848 TemplateArgument canonArgPack
4849 = getCanonicalTemplateArgument(subst->getArgumentPack());
4850 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
4851 }
4852 }
4853
4854 llvm_unreachable("bad template name!");
Douglas Gregor6bc50582009-05-07 06:41:52 +00004855}
4856
Douglas Gregoradee3e32009-11-11 23:06:43 +00004857bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
4858 X = getCanonicalTemplateName(X);
4859 Y = getCanonicalTemplateName(Y);
4860 return X.getAsVoidPointer() == Y.getAsVoidPointer();
4861}
4862
Mike Stump11289f42009-09-09 15:08:12 +00004863TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00004864ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00004865 switch (Arg.getKind()) {
4866 case TemplateArgument::Null:
4867 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00004868
Douglas Gregora8e02e72009-07-28 23:00:59 +00004869 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00004870 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00004871
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004872 case TemplateArgument::Declaration: {
Eli Friedmanb826a002012-09-26 02:36:12 +00004873 ValueDecl *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
David Blaikie952a9b12014-10-17 18:00:12 +00004874 return TemplateArgument(D, Arg.getParamTypeForDecl());
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004875 }
Mike Stump11289f42009-09-09 15:08:12 +00004876
Eli Friedmanb826a002012-09-26 02:36:12 +00004877 case TemplateArgument::NullPtr:
4878 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
4879 /*isNullPtr*/true);
4880
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004881 case TemplateArgument::Template:
4882 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004883
4884 case TemplateArgument::TemplateExpansion:
4885 return TemplateArgument(getCanonicalTemplateName(
4886 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00004887 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004888
Douglas Gregora8e02e72009-07-28 23:00:59 +00004889 case TemplateArgument::Integral:
Benjamin Kramer6003ad52012-06-07 15:09:51 +00004890 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00004891
Douglas Gregora8e02e72009-07-28 23:00:59 +00004892 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00004893 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00004894
Douglas Gregora8e02e72009-07-28 23:00:59 +00004895 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00004896 if (Arg.pack_size() == 0)
4897 return Arg;
4898
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004899 TemplateArgument *CanonArgs
4900 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00004901 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004902 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00004903 AEnd = Arg.pack_end();
4904 A != AEnd; (void)++A, ++Idx)
4905 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00004906
Benjamin Kramercce63472015-08-05 09:40:22 +00004907 return TemplateArgument(llvm::makeArrayRef(CanonArgs, Arg.pack_size()));
Douglas Gregora8e02e72009-07-28 23:00:59 +00004908 }
4909 }
4910
4911 // Silence GCC warning
David Blaikie83d382b2011-09-23 05:06:16 +00004912 llvm_unreachable("Unhandled template argument kind");
Douglas Gregora8e02e72009-07-28 23:00:59 +00004913}
4914
Douglas Gregor333489b2009-03-27 23:10:48 +00004915NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00004916ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00004917 if (!NNS)
Craig Topper36250ad2014-05-12 05:36:57 +00004918 return nullptr;
Douglas Gregor333489b2009-03-27 23:10:48 +00004919
4920 switch (NNS->getKind()) {
4921 case NestedNameSpecifier::Identifier:
4922 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00004923 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00004924 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
4925 NNS->getAsIdentifier());
4926
4927 case NestedNameSpecifier::Namespace:
4928 // A namespace is canonical; build a nested-name-specifier with
4929 // this namespace and no prefix.
Craig Topper36250ad2014-05-12 05:36:57 +00004930 return NestedNameSpecifier::Create(*this, nullptr,
Douglas Gregor7b26ff92011-02-24 02:36:08 +00004931 NNS->getAsNamespace()->getOriginalNamespace());
4932
4933 case NestedNameSpecifier::NamespaceAlias:
4934 // A namespace is canonical; build a nested-name-specifier with
4935 // this namespace and no prefix.
Craig Topper36250ad2014-05-12 05:36:57 +00004936 return NestedNameSpecifier::Create(*this, nullptr,
Douglas Gregor7b26ff92011-02-24 02:36:08 +00004937 NNS->getAsNamespaceAlias()->getNamespace()
4938 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00004939
4940 case NestedNameSpecifier::TypeSpec:
4941 case NestedNameSpecifier::TypeSpecWithTemplate: {
4942 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor3ade5702010-11-04 00:09:33 +00004943
4944 // If we have some kind of dependent-named type (e.g., "typename T::type"),
4945 // break it apart into its prefix and identifier, then reconsititute those
4946 // as the canonical nested-name-specifier. This is required to canonicalize
4947 // a dependent nested-name-specifier involving typedefs of dependent-name
4948 // types, e.g.,
4949 // typedef typename T::type T1;
4950 // typedef typename T1::type T2;
Eli Friedman5358a0a2012-03-03 04:09:56 +00004951 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
4952 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor3ade5702010-11-04 00:09:33 +00004953 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor3ade5702010-11-04 00:09:33 +00004954
Eli Friedman5358a0a2012-03-03 04:09:56 +00004955 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
4956 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
4957 // first place?
Craig Topper36250ad2014-05-12 05:36:57 +00004958 return NestedNameSpecifier::Create(*this, nullptr, false,
4959 const_cast<Type *>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00004960 }
4961
4962 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +00004963 case NestedNameSpecifier::Super:
4964 // The global specifier and __super specifer are canonical and unique.
Douglas Gregor333489b2009-03-27 23:10:48 +00004965 return NNS;
4966 }
4967
David Blaikie8a40f702012-01-17 06:56:22 +00004968 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor333489b2009-03-27 23:10:48 +00004969}
4970
Jay Foad39c79802011-01-12 09:06:06 +00004971const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00004972 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004973 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00004974 // Handle the common positive case fast.
4975 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
4976 return AT;
4977 }
Mike Stump11289f42009-09-09 15:08:12 +00004978
John McCall8ccfcb52009-09-24 19:53:00 +00004979 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00004980 if (!isa<ArrayType>(T.getCanonicalType()))
Craig Topper36250ad2014-05-12 05:36:57 +00004981 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00004982
John McCall8ccfcb52009-09-24 19:53:00 +00004983 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00004984 // implements C99 6.7.3p8: "If the specification of an array type includes
4985 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00004986
Chris Lattner7adf0762008-08-04 07:31:14 +00004987 // If we get here, we either have type qualifiers on the type, or we have
4988 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00004989 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00004990
John McCall33ddac02011-01-19 10:06:00 +00004991 SplitQualType split = T.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00004992 Qualifiers qs = split.Quals;
Mike Stump11289f42009-09-09 15:08:12 +00004993
Chris Lattner7adf0762008-08-04 07:31:14 +00004994 // If we have a simple case, just return now.
John McCall18ce25e2012-02-08 00:46:36 +00004995 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
Craig Topper36250ad2014-05-12 05:36:57 +00004996 if (!ATy || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00004997 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00004998
Chris Lattner7adf0762008-08-04 07:31:14 +00004999 // Otherwise, we have an array and we have qualifiers on it. Push the
5000 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00005001 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00005002
Chris Lattner7adf0762008-08-04 07:31:14 +00005003 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
5004 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
5005 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00005006 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00005007 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
5008 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
5009 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00005010 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00005011
Mike Stump11289f42009-09-09 15:08:12 +00005012 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00005013 = dyn_cast<DependentSizedArrayType>(ATy))
5014 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00005015 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00005016 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00005017 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00005018 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00005019 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00005020
Chris Lattner7adf0762008-08-04 07:31:14 +00005021 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00005022 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00005023 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00005024 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00005025 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00005026 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00005027}
5028
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00005029QualType ASTContext::getAdjustedParameterType(QualType T) const {
Reid Kleckner8a365022013-06-24 17:51:48 +00005030 if (T->isArrayType() || T->isFunctionType())
5031 return getDecayedType(T);
5032 return T;
Douglas Gregor84280642011-07-12 04:42:08 +00005033}
5034
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00005035QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00005036 T = getVariableArrayDecayedType(T);
5037 T = getAdjustedParameterType(T);
5038 return T.getUnqualifiedType();
5039}
5040
David Majnemerd09a51c2015-03-03 01:50:05 +00005041QualType ASTContext::getExceptionObjectType(QualType T) const {
5042 // C++ [except.throw]p3:
5043 // A throw-expression initializes a temporary object, called the exception
5044 // object, the type of which is determined by removing any top-level
5045 // cv-qualifiers from the static type of the operand of throw and adjusting
5046 // the type from "array of T" or "function returning T" to "pointer to T"
5047 // or "pointer to function returning T", [...]
5048 T = getVariableArrayDecayedType(T);
5049 if (T->isArrayType() || T->isFunctionType())
5050 T = getDecayedType(T);
5051 return T.getUnqualifiedType();
5052}
5053
Chris Lattnera21ad802008-04-02 05:18:44 +00005054/// getArrayDecayedType - Return the properly qualified result of decaying the
5055/// specified array type to a pointer. This operation is non-trivial when
5056/// handling typedefs etc. The canonical type of "T" must be an array type,
5057/// this returns a pointer to a properly qualified element of the array.
5058///
5059/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00005060QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00005061 // Get the element type with 'getAsArrayType' so that we don't lose any
5062 // typedefs in the element type of the array. This also handles propagation
5063 // of type qualifiers from the array type into the element type if present
5064 // (C99 6.7.3p8).
5065 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
5066 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00005067
Chris Lattner7adf0762008-08-04 07:31:14 +00005068 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00005069
5070 // int x[restrict 4] -> int *restrict
Jordan Rose303e2f12016-11-10 23:28:17 +00005071 QualType Result = getQualifiedType(PtrTy,
5072 PrettyArrayType->getIndexTypeQualifiers());
5073
5074 // int x[_Nullable] -> int * _Nullable
5075 if (auto Nullability = Ty->getNullability(*this)) {
5076 Result = const_cast<ASTContext *>(this)->getAttributedType(
5077 AttributedType::getNullabilityAttrKind(*Nullability), Result, Result);
5078 }
5079 return Result;
Chris Lattnera21ad802008-04-02 05:18:44 +00005080}
5081
John McCall33ddac02011-01-19 10:06:00 +00005082QualType ASTContext::getBaseElementType(const ArrayType *array) const {
5083 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00005084}
5085
John McCall33ddac02011-01-19 10:06:00 +00005086QualType ASTContext::getBaseElementType(QualType type) const {
5087 Qualifiers qs;
5088 while (true) {
5089 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00005090 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall33ddac02011-01-19 10:06:00 +00005091 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00005092
John McCall33ddac02011-01-19 10:06:00 +00005093 type = array->getElementType();
John McCall18ce25e2012-02-08 00:46:36 +00005094 qs.addConsistentQualifiers(split.Quals);
John McCall33ddac02011-01-19 10:06:00 +00005095 }
Mike Stump11289f42009-09-09 15:08:12 +00005096
John McCall33ddac02011-01-19 10:06:00 +00005097 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00005098}
5099
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00005100/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00005101uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00005102ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
5103 uint64_t ElementCount = 1;
5104 do {
5105 ElementCount *= CA->getSize().getZExtValue();
Richard Smith7808c6a2012-12-06 03:04:50 +00005106 CA = dyn_cast_or_null<ConstantArrayType>(
5107 CA->getElementType()->getAsArrayTypeUnsafe());
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00005108 } while (CA);
5109 return ElementCount;
5110}
5111
Steve Naroff0af91202007-04-27 21:51:21 +00005112/// getFloatingRank - Return a relative rank for floating point types.
5113/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00005114static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00005115 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00005116 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00005117
John McCall9dd450b2009-09-21 23:43:11 +00005118 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
5119 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00005120 default: llvm_unreachable("getFloatingRank(): not a floating type");
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00005121 case BuiltinType::Float16: return Float16Rank;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00005122 case BuiltinType::Half: return HalfRank;
Chris Lattnerc6395932007-06-22 20:56:16 +00005123 case BuiltinType::Float: return FloatRank;
5124 case BuiltinType::Double: return DoubleRank;
5125 case BuiltinType::LongDouble: return LongDoubleRank;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00005126 case BuiltinType::Float128: return Float128Rank;
Steve Naroffe4718892007-04-27 18:30:00 +00005127 }
5128}
5129
Mike Stump11289f42009-09-09 15:08:12 +00005130/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
5131/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00005132/// 'typeDomain' is a real floating point or complex type.
5133/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00005134QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
5135 QualType Domain) const {
5136 FloatingRank EltRank = getFloatingRank(Size);
5137 if (Domain->isComplexType()) {
5138 switch (EltRank) {
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00005139 case Float16Rank:
David Blaikief47fa302012-01-17 02:30:50 +00005140 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Naroff9091ef72007-08-27 01:27:54 +00005141 case FloatRank: return FloatComplexTy;
5142 case DoubleRank: return DoubleComplexTy;
5143 case LongDoubleRank: return LongDoubleComplexTy;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00005144 case Float128Rank: return Float128ComplexTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00005145 }
Steve Naroff0af91202007-04-27 21:51:21 +00005146 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00005147
5148 assert(Domain->isRealFloatingType() && "Unknown domain!");
5149 switch (EltRank) {
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00005150 case Float16Rank: return HalfTy;
Joey Goulydd7f4562013-01-23 11:56:20 +00005151 case HalfRank: return HalfTy;
Chris Lattnerb9dfb032008-04-06 23:58:54 +00005152 case FloatRank: return FloatTy;
5153 case DoubleRank: return DoubleTy;
5154 case LongDoubleRank: return LongDoubleTy;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00005155 case Float128Rank: return Float128Ty;
Steve Naroff9091ef72007-08-27 01:27:54 +00005156 }
David Blaikief47fa302012-01-17 02:30:50 +00005157 llvm_unreachable("getFloatingRank(): illegal value for rank");
Steve Naroffe4718892007-04-27 18:30:00 +00005158}
5159
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005160/// getFloatingTypeOrder - Compare the rank of the two specified floating
5161/// point types, ignoring the domain of the type (i.e. 'double' ==
5162/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00005163/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00005164int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00005165 FloatingRank LHSR = getFloatingRank(LHS);
5166 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00005167
Chris Lattnerb90739d2008-04-06 23:38:49 +00005168 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00005169 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00005170 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00005171 return 1;
5172 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00005173}
5174
Chris Lattner76a00cf2008-04-06 22:59:24 +00005175/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
5176/// routine will assert if passed a built-in type that isn't an integer or enum,
5177/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00005178unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00005179 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00005180
Chris Lattner76a00cf2008-04-06 22:59:24 +00005181 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00005182 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005183 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005184 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005185 case BuiltinType::Char_S:
5186 case BuiltinType::Char_U:
5187 case BuiltinType::SChar:
5188 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005189 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005190 case BuiltinType::Short:
5191 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005192 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005193 case BuiltinType::Int:
5194 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005195 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005196 case BuiltinType::Long:
5197 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005198 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005199 case BuiltinType::LongLong:
5200 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005201 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00005202 case BuiltinType::Int128:
5203 case BuiltinType::UInt128:
5204 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00005205 }
5206}
5207
Eli Friedman629ffb92009-08-20 04:21:42 +00005208/// \brief Whether this is a promotable bitfield reference according
5209/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
5210///
5211/// \returns the type this bit-field will promote to, or NULL if no
5212/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00005213QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00005214 if (E->isTypeDependent() || E->isValueDependent())
5215 return QualType();
Richard Smith5b571672014-09-24 23:55:00 +00005216
5217 // FIXME: We should not do this unless E->refersToBitField() is true. This
5218 // matters in C where getSourceBitField() will find bit-fields for various
5219 // cases where the source expression is not a bit-field designator.
5220
John McCalld25db7e2013-05-06 21:39:12 +00005221 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
Eli Friedman629ffb92009-08-20 04:21:42 +00005222 if (!Field)
5223 return QualType();
5224
5225 QualType FT = Field->getType();
5226
Richard Smithcaf33902011-10-10 18:28:20 +00005227 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman629ffb92009-08-20 04:21:42 +00005228 uint64_t IntSize = getTypeSize(IntTy);
Richard Smith5b571672014-09-24 23:55:00 +00005229 // C++ [conv.prom]p5:
5230 // A prvalue for an integral bit-field can be converted to a prvalue of type
5231 // int if int can represent all the values of the bit-field; otherwise, it
5232 // can be converted to unsigned int if unsigned int can represent all the
5233 // values of the bit-field. If the bit-field is larger yet, no integral
5234 // promotion applies to it.
5235 // C11 6.3.1.1/2:
5236 // [For a bit-field of type _Bool, int, signed int, or unsigned int:]
5237 // If an int can represent all values of the original type (as restricted by
5238 // the width, for a bit-field), the value is converted to an int; otherwise,
5239 // it is converted to an unsigned int.
5240 //
5241 // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
5242 // We perform that promotion here to match GCC and C++.
Eli Friedman629ffb92009-08-20 04:21:42 +00005243 if (BitWidth < IntSize)
5244 return IntTy;
5245
5246 if (BitWidth == IntSize)
5247 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
5248
5249 // Types bigger than int are not subject to promotions, and therefore act
Richard Smith5b571672014-09-24 23:55:00 +00005250 // like the base type. GCC has some weird bugs in this area that we
5251 // deliberately do not follow (GCC follows a pre-standard resolution to
5252 // C's DR315 which treats bit-width as being part of the type, and this leaks
5253 // into their semantics in some cases).
Eli Friedman629ffb92009-08-20 04:21:42 +00005254 return QualType();
5255}
5256
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005257/// getPromotedIntegerType - Returns the type that Promotable will
5258/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
5259/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00005260QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005261 assert(!Promotable.isNull());
5262 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00005263 if (const EnumType *ET = Promotable->getAs<EnumType>())
5264 return ET->getDecl()->getPromotionType();
Eli Friedman3f37c1c2011-10-26 07:22:48 +00005265
5266 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
5267 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
5268 // (3.9.1) can be converted to a prvalue of the first of the following
5269 // types that can represent all the values of its underlying type:
5270 // int, unsigned int, long int, unsigned long int, long long int, or
5271 // unsigned long long int [...]
5272 // FIXME: Is there some better way to compute this?
5273 if (BT->getKind() == BuiltinType::WChar_S ||
5274 BT->getKind() == BuiltinType::WChar_U ||
5275 BT->getKind() == BuiltinType::Char16 ||
5276 BT->getKind() == BuiltinType::Char32) {
5277 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
5278 uint64_t FromSize = getTypeSize(BT);
5279 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
5280 LongLongTy, UnsignedLongLongTy };
5281 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
5282 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
5283 if (FromSize < ToSize ||
5284 (FromSize == ToSize &&
5285 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
5286 return PromoteTypes[Idx];
5287 }
5288 llvm_unreachable("char type should fit into long long");
5289 }
5290 }
5291
5292 // At this point, we should have a signed or unsigned integer type.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005293 if (Promotable->isSignedIntegerType())
5294 return IntTy;
Eli Friedman6745c3b2012-11-15 01:21:59 +00005295 uint64_t PromotableSize = getIntWidth(Promotable);
5296 uint64_t IntSize = getIntWidth(IntTy);
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005297 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
5298 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
5299}
5300
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00005301/// \brief Recurses in pointer/array types until it finds an objc retainable
5302/// type and returns its ownership.
5303Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
5304 while (!T.isNull()) {
5305 if (T.getObjCLifetime() != Qualifiers::OCL_None)
5306 return T.getObjCLifetime();
5307 if (T->isArrayType())
5308 T = getBaseElementType(T);
5309 else if (const PointerType *PT = T->getAs<PointerType>())
5310 T = PT->getPointeeType();
5311 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis8e252532011-07-01 23:01:46 +00005312 T = RT->getPointeeType();
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00005313 else
5314 break;
5315 }
5316
5317 return Qualifiers::OCL_None;
5318}
5319
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00005320static const Type *getIntegerTypeForEnum(const EnumType *ET) {
5321 // Incomplete enum types are not treated as integer types.
5322 // FIXME: In C++, enum types are never integer types.
5323 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
5324 return ET->getDecl()->getIntegerType().getTypePtr();
Craig Topper36250ad2014-05-12 05:36:57 +00005325 return nullptr;
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00005326}
5327
Mike Stump11289f42009-09-09 15:08:12 +00005328/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005329/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00005330/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00005331int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00005332 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
5333 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00005334
5335 // Unwrap enums to their underlying type.
5336 if (const EnumType *ET = dyn_cast<EnumType>(LHSC))
5337 LHSC = getIntegerTypeForEnum(ET);
5338 if (const EnumType *ET = dyn_cast<EnumType>(RHSC))
5339 RHSC = getIntegerTypeForEnum(ET);
5340
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005341 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00005342
Chris Lattner76a00cf2008-04-06 22:59:24 +00005343 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
5344 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00005345
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005346 unsigned LHSRank = getIntegerRank(LHSC);
5347 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00005348
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005349 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
5350 if (LHSRank == RHSRank) return 0;
5351 return LHSRank > RHSRank ? 1 : -1;
5352 }
Mike Stump11289f42009-09-09 15:08:12 +00005353
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005354 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
5355 if (LHSUnsigned) {
5356 // If the unsigned [LHS] type is larger, return it.
5357 if (LHSRank >= RHSRank)
5358 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00005359
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005360 // If the signed type can represent all values of the unsigned type, it
5361 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00005362 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005363 return -1;
5364 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00005365
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005366 // If the unsigned [RHS] type is larger, return it.
5367 if (RHSRank >= LHSRank)
5368 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00005369
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005370 // If the signed type can represent all values of the unsigned type, it
5371 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00005372 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005373 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00005374}
Anders Carlsson98f07902007-08-17 05:31:46 +00005375
Ben Langmuirf5416742016-02-04 00:55:24 +00005376TypedefDecl *ASTContext::getCFConstantStringDecl() const {
Anders Carlsson98f07902007-08-17 05:31:46 +00005377 if (!CFConstantStringTypeDecl) {
Ben Langmuirf5416742016-02-04 00:55:24 +00005378 assert(!CFConstantStringTagDecl &&
5379 "tag and typedef should be initialized together");
5380 CFConstantStringTagDecl = buildImplicitRecord("__NSConstantString_tag");
5381 CFConstantStringTagDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00005382
Anders Carlsson9c1011c2007-11-19 00:25:30 +00005383 QualType FieldTypes[4];
Ben Langmuir4791a802016-02-25 16:36:26 +00005384 const char *FieldNames[4];
Mike Stump11289f42009-09-09 15:08:12 +00005385
Anders Carlsson98f07902007-08-17 05:31:46 +00005386 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00005387 FieldTypes[0] = getPointerType(IntTy.withConst());
Ben Langmuir4791a802016-02-25 16:36:26 +00005388 FieldNames[0] = "isa";
Anders Carlsson9c1011c2007-11-19 00:25:30 +00005389 // int flags;
5390 FieldTypes[1] = IntTy;
Ben Langmuir4791a802016-02-25 16:36:26 +00005391 FieldNames[1] = "flags";
Anders Carlsson98f07902007-08-17 05:31:46 +00005392 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00005393 FieldTypes[2] = getPointerType(CharTy.withConst());
Ben Langmuir4791a802016-02-25 16:36:26 +00005394 FieldNames[2] = "str";
Anders Carlsson98f07902007-08-17 05:31:46 +00005395 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00005396 FieldTypes[3] = LongTy;
Ben Langmuir4791a802016-02-25 16:36:26 +00005397 FieldNames[3] = "length";
Mike Stump11289f42009-09-09 15:08:12 +00005398
Anders Carlsson98f07902007-08-17 05:31:46 +00005399 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00005400 for (unsigned i = 0; i < 4; ++i) {
Ben Langmuirf5416742016-02-04 00:55:24 +00005401 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTagDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00005402 SourceLocation(),
Ben Langmuir4791a802016-02-25 16:36:26 +00005403 SourceLocation(),
5404 &Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00005405 FieldTypes[i], /*TInfo=*/nullptr,
5406 /*BitWidth=*/nullptr,
Richard Smith938f40b2011-06-11 17:19:42 +00005407 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00005408 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00005409 Field->setAccess(AS_public);
Ben Langmuirf5416742016-02-04 00:55:24 +00005410 CFConstantStringTagDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00005411 }
5412
Ben Langmuirf5416742016-02-04 00:55:24 +00005413 CFConstantStringTagDecl->completeDefinition();
5414 // This type is designed to be compatible with NSConstantString, but cannot
5415 // use the same name, since NSConstantString is an interface.
5416 auto tagType = getTagDeclType(CFConstantStringTagDecl);
5417 CFConstantStringTypeDecl =
5418 buildImplicitTypedef(tagType, "__NSConstantString");
Anders Carlsson98f07902007-08-17 05:31:46 +00005419 }
Mike Stump11289f42009-09-09 15:08:12 +00005420
Quentin Colombet043406b2016-02-03 22:41:00 +00005421 return CFConstantStringTypeDecl;
5422}
5423
Ben Langmuirf5416742016-02-04 00:55:24 +00005424RecordDecl *ASTContext::getCFConstantStringTagDecl() const {
5425 if (!CFConstantStringTagDecl)
5426 getCFConstantStringDecl(); // Build the tag and the typedef.
5427 return CFConstantStringTagDecl;
5428}
5429
Quentin Colombet043406b2016-02-03 22:41:00 +00005430// getCFConstantStringType - Return the type used for constant CFStrings.
5431QualType ASTContext::getCFConstantStringType() const {
Ben Langmuirf5416742016-02-04 00:55:24 +00005432 return getTypedefType(getCFConstantStringDecl());
Gabor Greif412af032007-09-11 15:32:40 +00005433}
Anders Carlsson87c149b2007-10-11 01:00:40 +00005434
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00005435QualType ASTContext::getObjCSuperType() const {
5436 if (ObjCSuperType.isNull()) {
Alp Toker2dea15b2013-12-17 01:22:38 +00005437 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00005438 TUDecl->addDecl(ObjCSuperTypeDecl);
5439 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
5440 }
5441 return ObjCSuperType;
5442}
5443
Douglas Gregor512b0772009-04-23 22:29:11 +00005444void ASTContext::setCFConstantStringType(QualType T) {
Ben Langmuirf5416742016-02-04 00:55:24 +00005445 const TypedefType *TD = T->getAs<TypedefType>();
5446 assert(TD && "Invalid CFConstantStringType");
5447 CFConstantStringTypeDecl = cast<TypedefDecl>(TD->getDecl());
5448 auto TagType =
5449 CFConstantStringTypeDecl->getUnderlyingType()->getAs<RecordType>();
5450 assert(TagType && "Invalid CFConstantStringType");
5451 CFConstantStringTagDecl = TagType->getDecl();
Douglas Gregor512b0772009-04-23 22:29:11 +00005452}
5453
Jay Foad39c79802011-01-12 09:06:06 +00005454QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00005455 if (BlockDescriptorType)
5456 return getTagDeclType(BlockDescriptorType);
5457
Alp Toker2dea15b2013-12-17 01:22:38 +00005458 RecordDecl *RD;
Mike Stumpd0153282009-10-20 02:12:22 +00005459 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00005460 RD = buildImplicitRecord("__block_descriptor");
5461 RD->startDefinition();
5462
Mike Stumpd0153282009-10-20 02:12:22 +00005463 QualType FieldTypes[] = {
5464 UnsignedLongTy,
5465 UnsignedLongTy,
5466 };
5467
Craig Topperd6d31ac2013-07-15 08:24:27 +00005468 static const char *const FieldNames[] = {
Mike Stumpd0153282009-10-20 02:12:22 +00005469 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005470 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00005471 };
5472
5473 for (size_t i = 0; i < 2; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00005474 FieldDecl *Field = FieldDecl::Create(
5475 *this, RD, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00005476 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
5477 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00005478 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00005479 RD->addDecl(Field);
Mike Stumpd0153282009-10-20 02:12:22 +00005480 }
5481
Alp Toker2dea15b2013-12-17 01:22:38 +00005482 RD->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00005483
Alp Toker2dea15b2013-12-17 01:22:38 +00005484 BlockDescriptorType = RD;
Mike Stumpd0153282009-10-20 02:12:22 +00005485
5486 return getTagDeclType(BlockDescriptorType);
5487}
5488
Jay Foad39c79802011-01-12 09:06:06 +00005489QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005490 if (BlockDescriptorExtendedType)
5491 return getTagDeclType(BlockDescriptorExtendedType);
5492
Alp Toker2dea15b2013-12-17 01:22:38 +00005493 RecordDecl *RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005494 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00005495 RD = buildImplicitRecord("__block_descriptor_withcopydispose");
5496 RD->startDefinition();
5497
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005498 QualType FieldTypes[] = {
5499 UnsignedLongTy,
5500 UnsignedLongTy,
5501 getPointerType(VoidPtrTy),
5502 getPointerType(VoidPtrTy)
5503 };
5504
Craig Topperd6d31ac2013-07-15 08:24:27 +00005505 static const char *const FieldNames[] = {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005506 "reserved",
5507 "Size",
5508 "CopyFuncPtr",
5509 "DestroyFuncPtr"
5510 };
5511
5512 for (size_t i = 0; i < 4; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00005513 FieldDecl *Field = FieldDecl::Create(
5514 *this, RD, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00005515 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
5516 /*BitWidth=*/nullptr,
Alp Toker2dea15b2013-12-17 01:22:38 +00005517 /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00005518 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00005519 RD->addDecl(Field);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005520 }
5521
Alp Toker2dea15b2013-12-17 01:22:38 +00005522 RD->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005523
Alp Toker2dea15b2013-12-17 01:22:38 +00005524 BlockDescriptorExtendedType = RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005525 return getTagDeclType(BlockDescriptorExtendedType);
5526}
5527
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00005528/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
5529/// requires copy/dispose. Note that this must match the logic
5530/// in buildByrefHelpers.
5531bool ASTContext::BlockRequiresCopying(QualType Ty,
5532 const VarDecl *D) {
5533 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
5534 const Expr *copyExpr = getBlockVarCopyInits(D);
5535 if (!copyExpr && record->hasTrivialDestructor()) return false;
5536
Mike Stump94967902009-10-21 18:16:27 +00005537 return true;
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00005538 }
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00005539
5540 if (!Ty->isObjCRetainableType()) return false;
5541
5542 Qualifiers qs = Ty.getQualifiers();
5543
5544 // If we have lifetime, that dominates.
5545 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00005546 switch (lifetime) {
5547 case Qualifiers::OCL_None: llvm_unreachable("impossible");
5548
5549 // These are just bits as far as the runtime is concerned.
5550 case Qualifiers::OCL_ExplicitNone:
5551 case Qualifiers::OCL_Autoreleasing:
5552 return false;
5553
5554 // Tell the runtime that this is ARC __weak, called by the
5555 // byref routines.
5556 case Qualifiers::OCL_Weak:
5557 // ARC __strong __block variables need to be retained.
5558 case Qualifiers::OCL_Strong:
5559 return true;
5560 }
5561 llvm_unreachable("fell out of lifetime switch!");
5562 }
5563 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
5564 Ty->isObjCObjectPointerType());
Mike Stump94967902009-10-21 18:16:27 +00005565}
5566
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00005567bool ASTContext::getByrefLifetime(QualType Ty,
5568 Qualifiers::ObjCLifetime &LifeTime,
5569 bool &HasByrefExtendedLayout) const {
5570
5571 if (!getLangOpts().ObjC1 ||
5572 getLangOpts().getGC() != LangOptions::NonGC)
5573 return false;
5574
5575 HasByrefExtendedLayout = false;
Fariborz Jahanianf762b722012-12-11 19:58:01 +00005576 if (Ty->isRecordType()) {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00005577 HasByrefExtendedLayout = true;
5578 LifeTime = Qualifiers::OCL_None;
John McCall460ce582015-10-22 18:38:17 +00005579 } else if ((LifeTime = Ty.getObjCLifetime())) {
5580 // Honor the ARC qualifiers.
5581 } else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) {
5582 // The MRR rule.
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00005583 LifeTime = Qualifiers::OCL_ExplicitNone;
John McCall460ce582015-10-22 18:38:17 +00005584 } else {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00005585 LifeTime = Qualifiers::OCL_None;
John McCall460ce582015-10-22 18:38:17 +00005586 }
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00005587 return true;
5588}
5589
Douglas Gregorbab8a962011-09-08 01:46:34 +00005590TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
5591 if (!ObjCInstanceTypeDecl)
Alp Toker56b5cc92013-12-15 10:36:26 +00005592 ObjCInstanceTypeDecl =
5593 buildImplicitTypedef(getObjCIdType(), "instancetype");
Douglas Gregorbab8a962011-09-08 01:46:34 +00005594 return ObjCInstanceTypeDecl;
5595}
5596
Anders Carlsson18acd442007-10-29 06:33:42 +00005597// This returns true if a type has been typedefed to BOOL:
5598// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00005599static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00005600 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00005601 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
5602 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00005603
Anders Carlssond8499822007-10-29 05:01:08 +00005604 return false;
5605}
5606
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005607/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005608/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00005609CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregora9d84932011-05-27 01:19:52 +00005610 if (!type->isIncompleteArrayType() && type->isIncompleteType())
5611 return CharUnits::Zero();
5612
Ken Dyck40775002010-01-11 17:06:35 +00005613 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00005614
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005615 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00005616 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00005617 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005618 // Treat arrays as pointers, since that's how they're passed in.
5619 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00005620 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00005621 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00005622}
5623
Hans Wennborg56fc62b2014-07-17 20:25:23 +00005624bool ASTContext::isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const {
David Majnemer3f021502015-10-08 04:53:31 +00005625 return getTargetInfo().getCXXABI().isMicrosoft() &&
5626 VD->isStaticDataMember() &&
David Majnemerfac52432015-10-19 23:22:49 +00005627 VD->getType()->isIntegralOrEnumerationType() &&
5628 !VD->getFirstDecl()->isOutOfLine() && VD->getFirstDecl()->hasInit();
Hans Wennborg56fc62b2014-07-17 20:25:23 +00005629}
5630
Richard Smithd9b90092016-07-02 01:32:16 +00005631ASTContext::InlineVariableDefinitionKind
5632ASTContext::getInlineVariableDefinitionKind(const VarDecl *VD) const {
5633 if (!VD->isInline())
5634 return InlineVariableDefinitionKind::None;
5635
5636 // In almost all cases, it's a weak definition.
5637 auto *First = VD->getFirstDecl();
5638 if (!First->isConstexpr() || First->isInlineSpecified() ||
5639 !VD->isStaticDataMember())
5640 return InlineVariableDefinitionKind::Weak;
5641
5642 // If there's a file-context declaration in this translation unit, it's a
5643 // non-discardable definition.
5644 for (auto *D : VD->redecls())
5645 if (D->getLexicalDeclContext()->isFileContext())
5646 return InlineVariableDefinitionKind::Strong;
5647
5648 // If we've not seen one yet, we don't know.
5649 return InlineVariableDefinitionKind::WeakUnknown;
5650}
5651
Ken Dyck40775002010-01-11 17:06:35 +00005652static inline
5653std::string charUnitsToString(const CharUnits &CU) {
5654 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005655}
5656
John McCall351762c2011-02-07 10:33:21 +00005657/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00005658/// declaration.
John McCall351762c2011-02-07 10:33:21 +00005659std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
5660 std::string S;
5661
David Chisnall950a9512009-11-17 19:33:30 +00005662 const BlockDecl *Decl = Expr->getBlockDecl();
5663 QualType BlockTy =
5664 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
5665 // Encode result type.
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00005666 if (getLangOpts().EncodeExtendedBlockSig)
Alp Toker314cc812014-01-25 16:55:45 +00005667 getObjCEncodingForMethodParameter(
5668 Decl::OBJC_TQ_None, BlockTy->getAs<FunctionType>()->getReturnType(), S,
5669 true /*Extended*/);
Fariborz Jahanian64223e62012-11-14 23:11:38 +00005670 else
Alp Toker314cc812014-01-25 16:55:45 +00005671 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getReturnType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00005672 // Compute size of all parameters.
5673 // Start with computing size of a pointer in number of bytes.
5674 // FIXME: There might(should) be a better way of doing this computation!
Ken Dyck40775002010-01-11 17:06:35 +00005675 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
5676 CharUnits ParmOffset = PtrSize;
David Majnemer59f77922016-06-24 04:05:48 +00005677 for (auto PI : Decl->parameters()) {
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +00005678 QualType PType = PI->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00005679 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahaniand4879412012-06-30 00:48:59 +00005680 if (sz.isZero())
5681 continue;
Ken Dyck40775002010-01-11 17:06:35 +00005682 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00005683 ParmOffset += sz;
5684 }
5685 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00005686 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00005687 // Block pointer and offset.
5688 S += "@?0";
David Chisnall950a9512009-11-17 19:33:30 +00005689
5690 // Argument types.
5691 ParmOffset = PtrSize;
David Majnemer59f77922016-06-24 04:05:48 +00005692 for (auto PVDecl : Decl->parameters()) {
David Chisnall950a9512009-11-17 19:33:30 +00005693 QualType PType = PVDecl->getOriginalType();
5694 if (const ArrayType *AT =
5695 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5696 // Use array's original type only if it has known number of
5697 // elements.
5698 if (!isa<ConstantArrayType>(AT))
5699 PType = PVDecl->getType();
5700 } else if (PType->isFunctionType())
5701 PType = PVDecl->getType();
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00005702 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian64223e62012-11-14 23:11:38 +00005703 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
5704 S, true /*Extended*/);
5705 else
5706 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00005707 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00005708 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00005709 }
John McCall351762c2011-02-07 10:33:21 +00005710
5711 return S;
David Chisnall950a9512009-11-17 19:33:30 +00005712}
5713
John McCall843dfcc2016-11-29 21:57:00 +00005714std::string
5715ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl) const {
5716 std::string S;
David Chisnall50e4eba2010-12-30 14:05:53 +00005717 // Encode result type.
Alp Toker314cc812014-01-25 16:55:45 +00005718 getObjCEncodingForType(Decl->getReturnType(), S);
David Chisnall50e4eba2010-12-30 14:05:53 +00005719 CharUnits ParmOffset;
5720 // Compute size of all parameters.
David Majnemer59f77922016-06-24 04:05:48 +00005721 for (auto PI : Decl->parameters()) {
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00005722 QualType PType = PI->getType();
David Chisnall50e4eba2010-12-30 14:05:53 +00005723 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00005724 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00005725 continue;
5726
John McCall843dfcc2016-11-29 21:57:00 +00005727 assert(sz.isPositive() &&
5728 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall50e4eba2010-12-30 14:05:53 +00005729 ParmOffset += sz;
5730 }
5731 S += charUnitsToString(ParmOffset);
5732 ParmOffset = CharUnits::Zero();
5733
5734 // Argument types.
David Majnemer59f77922016-06-24 04:05:48 +00005735 for (auto PVDecl : Decl->parameters()) {
David Chisnall50e4eba2010-12-30 14:05:53 +00005736 QualType PType = PVDecl->getOriginalType();
5737 if (const ArrayType *AT =
5738 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5739 // Use array's original type only if it has known number of
5740 // elements.
5741 if (!isa<ConstantArrayType>(AT))
5742 PType = PVDecl->getType();
5743 } else if (PType->isFunctionType())
5744 PType = PVDecl->getType();
5745 getObjCEncodingForType(PType, S);
5746 S += charUnitsToString(ParmOffset);
5747 ParmOffset += getObjCEncodingTypeSize(PType);
5748 }
Douglas Gregora9d84932011-05-27 01:19:52 +00005749
John McCall843dfcc2016-11-29 21:57:00 +00005750 return S;
David Chisnall50e4eba2010-12-30 14:05:53 +00005751}
5752
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005753/// getObjCEncodingForMethodParameter - Return the encoded type for a single
5754/// method parameter or return type. If Extended, include class names and
5755/// block object types.
5756void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
5757 QualType T, std::string& S,
5758 bool Extended) const {
5759 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
5760 getObjCEncodingForTypeQualifier(QT, S);
5761 // Encode parameter type.
Craig Topper36250ad2014-05-12 05:36:57 +00005762 getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005763 true /*OutermostType*/,
5764 false /*EncodingProperty*/,
5765 false /*StructField*/,
5766 Extended /*EncodeBlockParameters*/,
5767 Extended /*EncodeClassNames*/);
5768}
5769
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005770/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005771/// declaration.
John McCall843dfcc2016-11-29 21:57:00 +00005772std::string ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
5773 bool Extended) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00005774 // FIXME: This is not very efficient.
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005775 // Encode return type.
John McCall843dfcc2016-11-29 21:57:00 +00005776 std::string S;
Alp Toker314cc812014-01-25 16:55:45 +00005777 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
5778 Decl->getReturnType(), S, Extended);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005779 // Compute size of all parameters.
5780 // Start with computing size of a pointer in number of bytes.
5781 // FIXME: There might(should) be a better way of doing this computation!
Ken Dyck40775002010-01-11 17:06:35 +00005782 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005783 // The first two arguments (self and _cmd) are pointers; account for
5784 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00005785 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00005786 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00005787 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00005788 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00005789 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00005790 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00005791 continue;
5792
Ken Dyck40775002010-01-11 17:06:35 +00005793 assert (sz.isPositive() &&
5794 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005795 ParmOffset += sz;
5796 }
Ken Dyck40775002010-01-11 17:06:35 +00005797 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005798 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00005799 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00005800
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005801 // Argument types.
5802 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00005803 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00005804 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00005805 const ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00005806 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00005807 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00005808 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5809 // Use array's original type only if it has known number of
5810 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00005811 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00005812 PType = PVDecl->getType();
5813 } else if (PType->isFunctionType())
5814 PType = PVDecl->getType();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005815 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
5816 PType, S, Extended);
Ken Dyck40775002010-01-11 17:06:35 +00005817 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00005818 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005819 }
Douglas Gregora9d84932011-05-27 01:19:52 +00005820
John McCall843dfcc2016-11-29 21:57:00 +00005821 return S;
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005822}
5823
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005824ObjCPropertyImplDecl *
5825ASTContext::getObjCPropertyImplDeclForPropertyDecl(
5826 const ObjCPropertyDecl *PD,
5827 const Decl *Container) const {
5828 if (!Container)
Craig Topper36250ad2014-05-12 05:36:57 +00005829 return nullptr;
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005830 if (const ObjCCategoryImplDecl *CID =
5831 dyn_cast<ObjCCategoryImplDecl>(Container)) {
Aaron Ballmand85eff42014-03-14 15:02:45 +00005832 for (auto *PID : CID->property_impls())
5833 if (PID->getPropertyDecl() == PD)
5834 return PID;
Craig Topper36250ad2014-05-12 05:36:57 +00005835 } else {
5836 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
5837 for (auto *PID : OID->property_impls())
5838 if (PID->getPropertyDecl() == PD)
5839 return PID;
5840 }
5841 return nullptr;
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005842}
5843
Daniel Dunbar4932b362008-08-28 04:38:10 +00005844/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00005845/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00005846/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
5847/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00005848/// Property attributes are stored as a comma-delimited C string. The simple
5849/// attributes readonly and bycopy are encoded as single characters. The
5850/// parametrized attributes, getter=name, setter=name, and ivar=name, are
5851/// encoded as single characters, followed by an identifier. Property types
5852/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00005853/// these attributes are defined by the following enumeration:
5854/// @code
5855/// enum PropertyAttributes {
5856/// kPropertyReadOnly = 'R', // property is read-only.
5857/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
5858/// kPropertyByref = '&', // property is a reference to the value last assigned
5859/// kPropertyDynamic = 'D', // property is dynamic
5860/// kPropertyGetter = 'G', // followed by getter selector name
5861/// kPropertySetter = 'S', // followed by setter selector name
5862/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson8cf61852012-03-22 17:48:02 +00005863/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00005864/// kPropertyWeak = 'W' // 'weak' property
5865/// kPropertyStrong = 'P' // property GC'able
5866/// kPropertyNonAtomic = 'N' // property non-atomic
5867/// };
5868/// @endcode
John McCall843dfcc2016-11-29 21:57:00 +00005869std::string
5870ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
5871 const Decl *Container) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00005872 // Collect information from the property implementation decl(s).
5873 bool Dynamic = false;
Craig Topper36250ad2014-05-12 05:36:57 +00005874 ObjCPropertyImplDecl *SynthesizePID = nullptr;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005875
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005876 if (ObjCPropertyImplDecl *PropertyImpDecl =
5877 getObjCPropertyImplDeclForPropertyDecl(PD, Container)) {
5878 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
5879 Dynamic = true;
5880 else
5881 SynthesizePID = PropertyImpDecl;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005882 }
5883
5884 // FIXME: This is not very efficient.
John McCall843dfcc2016-11-29 21:57:00 +00005885 std::string S = "T";
Daniel Dunbar4932b362008-08-28 04:38:10 +00005886
5887 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005888 // GCC has some special rules regarding encoding of properties which
5889 // closely resembles encoding of ivars.
Joe Groff98ac7d22014-07-07 22:25:15 +00005890 getObjCEncodingForPropertyType(PD->getType(), S);
Daniel Dunbar4932b362008-08-28 04:38:10 +00005891
5892 if (PD->isReadOnly()) {
5893 S += ",R";
Nico Weber4e8626f2013-05-08 23:47:40 +00005894 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy)
5895 S += ",C";
5896 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain)
5897 S += ",&";
Fariborz Jahanian33079ee2014-04-02 22:49:42 +00005898 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak)
5899 S += ",W";
Daniel Dunbar4932b362008-08-28 04:38:10 +00005900 } else {
5901 switch (PD->getSetterKind()) {
5902 case ObjCPropertyDecl::Assign: break;
5903 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00005904 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian70a315c2011-08-12 20:47:08 +00005905 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005906 }
5907 }
5908
5909 // It really isn't clear at all what this means, since properties
5910 // are "dynamic by default".
5911 if (Dynamic)
5912 S += ",D";
5913
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005914 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
5915 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00005916
Daniel Dunbar4932b362008-08-28 04:38:10 +00005917 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
5918 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00005919 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005920 }
5921
5922 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
5923 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00005924 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005925 }
5926
5927 if (SynthesizePID) {
5928 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
5929 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00005930 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005931 }
5932
5933 // FIXME: OBJCGC: weak & strong
John McCall843dfcc2016-11-29 21:57:00 +00005934 return S;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005935}
5936
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005937/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00005938/// Another legacy compatibility encoding: 32-bit longs are encoded as
5939/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005940/// 'i' or 'I' instead if encoding a struct field, or a pointer!
5941///
5942void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00005943 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00005944 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00005945 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005946 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00005947 else
Jay Foad39c79802011-01-12 09:06:06 +00005948 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005949 PointeeTy = IntTy;
5950 }
5951 }
5952}
5953
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005954void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005955 const FieldDecl *Field,
5956 QualType *NotEncodedT) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005957 // We follow the behavior of gcc, expanding structures which are
5958 // directly pointed to, and expanding embedded structures. Note that
5959 // these rules are sufficient to prevent recursive encoding of the
5960 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00005961 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005962 true /* outermost type */, false, false,
5963 false, false, false, NotEncodedT);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005964}
5965
Joe Groff98ac7d22014-07-07 22:25:15 +00005966void ASTContext::getObjCEncodingForPropertyType(QualType T,
5967 std::string& S) const {
5968 // Encode result type.
5969 // GCC has some special rules regarding encoding of properties which
5970 // closely resembles encoding of ivars.
5971 getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
5972 true /* outermost type */,
5973 true /* encoding property */);
5974}
5975
John McCall393a78d2012-12-20 02:45:14 +00005976static char getObjCEncodingForPrimitiveKind(const ASTContext *C,
5977 BuiltinType::Kind kind) {
5978 switch (kind) {
David Chisnallb190a2c2010-06-04 01:10:52 +00005979 case BuiltinType::Void: return 'v';
5980 case BuiltinType::Bool: return 'B';
5981 case BuiltinType::Char_U:
5982 case BuiltinType::UChar: return 'C';
John McCall393a78d2012-12-20 02:45:14 +00005983 case BuiltinType::Char16:
David Chisnallb190a2c2010-06-04 01:10:52 +00005984 case BuiltinType::UShort: return 'S';
John McCall393a78d2012-12-20 02:45:14 +00005985 case BuiltinType::Char32:
David Chisnallb190a2c2010-06-04 01:10:52 +00005986 case BuiltinType::UInt: return 'I';
5987 case BuiltinType::ULong:
John McCall393a78d2012-12-20 02:45:14 +00005988 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00005989 case BuiltinType::UInt128: return 'T';
5990 case BuiltinType::ULongLong: return 'Q';
5991 case BuiltinType::Char_S:
5992 case BuiltinType::SChar: return 'c';
5993 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00005994 case BuiltinType::WChar_S:
5995 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00005996 case BuiltinType::Int: return 'i';
5997 case BuiltinType::Long:
John McCall393a78d2012-12-20 02:45:14 +00005998 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00005999 case BuiltinType::LongLong: return 'q';
6000 case BuiltinType::Int128: return 't';
6001 case BuiltinType::Float: return 'f';
6002 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00006003 case BuiltinType::LongDouble: return 'D';
John McCall393a78d2012-12-20 02:45:14 +00006004 case BuiltinType::NullPtr: return '*'; // like char*
6005
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00006006 case BuiltinType::Float16:
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00006007 case BuiltinType::Float128:
John McCall393a78d2012-12-20 02:45:14 +00006008 case BuiltinType::Half:
6009 // FIXME: potentially need @encodes for these!
6010 return ' ';
6011
6012 case BuiltinType::ObjCId:
6013 case BuiltinType::ObjCClass:
6014 case BuiltinType::ObjCSel:
6015 llvm_unreachable("@encoding ObjC primitive type");
6016
6017 // OpenCL and placeholder types don't need @encodings.
Alexey Bader954ba212016-04-08 13:40:33 +00006018#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6019 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00006020#include "clang/Basic/OpenCLImageTypes.def"
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00006021 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00006022 case BuiltinType::OCLClkEvent:
6023 case BuiltinType::OCLQueue:
Alexey Bader9c8453f2015-09-15 11:18:52 +00006024 case BuiltinType::OCLReserveID:
Guy Benyei61054192013-02-07 10:55:47 +00006025 case BuiltinType::OCLSampler:
John McCall393a78d2012-12-20 02:45:14 +00006026 case BuiltinType::Dependent:
6027#define BUILTIN_TYPE(KIND, ID)
6028#define PLACEHOLDER_TYPE(KIND, ID) \
6029 case BuiltinType::KIND:
6030#include "clang/AST/BuiltinTypes.def"
6031 llvm_unreachable("invalid builtin type for @encode");
David Chisnallb190a2c2010-06-04 01:10:52 +00006032 }
David Blaikie5a6a0202013-01-09 17:48:41 +00006033 llvm_unreachable("invalid BuiltinType::Kind value");
David Chisnallb190a2c2010-06-04 01:10:52 +00006034}
6035
Douglas Gregor8b7d4032011-09-08 17:18:35 +00006036static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
6037 EnumDecl *Enum = ET->getDecl();
6038
6039 // The encoding of an non-fixed enum type is always 'i', regardless of size.
6040 if (!Enum->isFixed())
6041 return 'i';
6042
6043 // The encoding of a fixed enum type matches its fixed underlying type.
John McCall393a78d2012-12-20 02:45:14 +00006044 const BuiltinType *BT = Enum->getIntegerType()->castAs<BuiltinType>();
6045 return getObjCEncodingForPrimitiveKind(C, BT->getKind());
Douglas Gregor8b7d4032011-09-08 17:18:35 +00006046}
6047
Jay Foad39c79802011-01-12 09:06:06 +00006048static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00006049 QualType T, const FieldDecl *FD) {
Richard Smithcaf33902011-10-10 18:28:20 +00006050 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00006051 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00006052 // The NeXT runtime encodes bit fields as b followed by the number of bits.
6053 // The GNU runtime requires more information; bitfields are encoded as b,
6054 // then the offset (in bits) of the first element, then the type of the
6055 // bitfield, then the size in bits. For example, in this structure:
6056 //
6057 // struct
6058 // {
6059 // int integer;
6060 // int flags:2;
6061 // };
6062 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
6063 // runtime, but b32i2 for the GNU runtime. The reason for this extra
6064 // information is not especially sensible, but we're stuck with it for
6065 // compatibility with GCC, although providing it breaks anything that
6066 // actually uses runtime introspection and wants to work on both runtimes...
John McCall5fb5df92012-06-20 06:18:46 +00006067 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
Akira Hatanaka4b1c4842017-06-27 04:34:04 +00006068 uint64_t Offset;
6069
6070 if (const auto *IVD = dyn_cast<ObjCIvarDecl>(FD)) {
6071 Offset = Ctx->lookupFieldBitOffset(IVD->getContainingInterface(), nullptr,
6072 IVD);
6073 } else {
6074 const RecordDecl *RD = FD->getParent();
6075 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
6076 Offset = RL.getFieldOffset(FD->getFieldIndex());
6077 }
6078
6079 S += llvm::utostr(Offset);
6080
Douglas Gregor8b7d4032011-09-08 17:18:35 +00006081 if (const EnumType *ET = T->getAs<EnumType>())
6082 S += ObjCEncodingForEnumType(Ctx, ET);
John McCall393a78d2012-12-20 02:45:14 +00006083 else {
6084 const BuiltinType *BT = T->castAs<BuiltinType>();
6085 S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind());
6086 }
David Chisnallb190a2c2010-06-04 01:10:52 +00006087 }
Richard Smithcaf33902011-10-10 18:28:20 +00006088 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian5c767722009-01-13 01:18:13 +00006089}
6090
Daniel Dunbar07d07852009-10-18 21:17:35 +00006091// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00006092void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
6093 bool ExpandPointedToStructures,
6094 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00006095 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00006096 bool OutermostType,
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006097 bool EncodingProperty,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006098 bool StructField,
6099 bool EncodeBlockParameters,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00006100 bool EncodeClassNames,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006101 bool EncodePointerToObjCTypedef,
6102 QualType *NotEncodedT) const {
John McCall393a78d2012-12-20 02:45:14 +00006103 CanQualType CT = getCanonicalType(T);
6104 switch (CT->getTypeClass()) {
6105 case Type::Builtin:
6106 case Type::Enum:
Chris Lattnere7cabb92009-07-13 00:10:46 +00006107 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00006108 return EncodeBitField(this, S, T, FD);
John McCall393a78d2012-12-20 02:45:14 +00006109 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CT))
6110 S += getObjCEncodingForPrimitiveKind(this, BT->getKind());
6111 else
6112 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
Chris Lattnere7cabb92009-07-13 00:10:46 +00006113 return;
Mike Stump11289f42009-09-09 15:08:12 +00006114
John McCall393a78d2012-12-20 02:45:14 +00006115 case Type::Complex: {
6116 const ComplexType *CT = T->castAs<ComplexType>();
Anders Carlsson39b2e132009-04-09 21:55:45 +00006117 S += 'j';
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006118 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, nullptr);
Chris Lattnere7cabb92009-07-13 00:10:46 +00006119 return;
6120 }
John McCall393a78d2012-12-20 02:45:14 +00006121
6122 case Type::Atomic: {
6123 const AtomicType *AT = T->castAs<AtomicType>();
6124 S += 'A';
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006125 getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, nullptr);
John McCall393a78d2012-12-20 02:45:14 +00006126 return;
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00006127 }
John McCall393a78d2012-12-20 02:45:14 +00006128
6129 // encoding for pointer or reference types.
6130 case Type::Pointer:
6131 case Type::LValueReference:
6132 case Type::RValueReference: {
6133 QualType PointeeTy;
6134 if (isa<PointerType>(CT)) {
6135 const PointerType *PT = T->castAs<PointerType>();
6136 if (PT->isObjCSelType()) {
6137 S += ':';
6138 return;
6139 }
6140 PointeeTy = PT->getPointeeType();
6141 } else {
6142 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
6143 }
6144
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006145 bool isReadOnly = false;
6146 // For historical/compatibility reasons, the read-only qualifier of the
6147 // pointee gets emitted _before_ the '^'. The read-only qualifier of
6148 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00006149 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00006150 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006151 if (OutermostType && T.isConstQualified()) {
6152 isReadOnly = true;
6153 S += 'r';
6154 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00006155 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006156 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006157 while (P->getAs<PointerType>())
6158 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006159 if (P.isConstQualified()) {
6160 isReadOnly = true;
6161 S += 'r';
6162 }
6163 }
6164 if (isReadOnly) {
6165 // Another legacy compatibility encoding. Some ObjC qualifier and type
6166 // combinations need to be rearranged.
6167 // Rewrite "in const" from "nr" to "rn"
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006168 if (StringRef(S).endswith("nr"))
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00006169 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006170 }
Mike Stump11289f42009-09-09 15:08:12 +00006171
Anders Carlssond8499822007-10-29 05:01:08 +00006172 if (PointeeTy->isCharType()) {
6173 // char pointer types should be encoded as '*' unless it is a
6174 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00006175 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00006176 S += '*';
6177 return;
6178 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006179 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00006180 // GCC binary compat: Need to convert "struct objc_class *" to "#".
6181 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
6182 S += '#';
6183 return;
6184 }
6185 // GCC binary compat: Need to convert "struct objc_object *" to "@".
6186 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
6187 S += '@';
6188 return;
6189 }
6190 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00006191 }
Anders Carlssond8499822007-10-29 05:01:08 +00006192 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006193 getLegacyIntegralTypeEncoding(PointeeTy);
6194
Mike Stump11289f42009-09-09 15:08:12 +00006195 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006196 nullptr, false, false, false, false, false, false,
6197 NotEncodedT);
Chris Lattnere7cabb92009-07-13 00:10:46 +00006198 return;
6199 }
John McCall393a78d2012-12-20 02:45:14 +00006200
6201 case Type::ConstantArray:
6202 case Type::IncompleteArray:
6203 case Type::VariableArray: {
6204 const ArrayType *AT = cast<ArrayType>(CT);
6205
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006206 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00006207 // Incomplete arrays are encoded as a pointer to the array element.
6208 S += '^';
6209
Mike Stump11289f42009-09-09 15:08:12 +00006210 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00006211 false, ExpandStructures, FD);
6212 } else {
6213 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00006214
Fariborz Jahanianf0dc11a2013-06-04 16:04:37 +00006215 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
6216 S += llvm::utostr(CAT->getSize().getZExtValue());
6217 else {
Anders Carlssond05f44b2009-02-22 01:38:57 +00006218 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006219 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
6220 "Unknown array type!");
Anders Carlssond05f44b2009-02-22 01:38:57 +00006221 S += '0';
6222 }
Mike Stump11289f42009-09-09 15:08:12 +00006223
6224 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006225 false, ExpandStructures, FD,
6226 false, false, false, false, false, false,
6227 NotEncodedT);
Anders Carlssond05f44b2009-02-22 01:38:57 +00006228 S += ']';
6229 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00006230 return;
6231 }
Mike Stump11289f42009-09-09 15:08:12 +00006232
John McCall393a78d2012-12-20 02:45:14 +00006233 case Type::FunctionNoProto:
6234 case Type::FunctionProto:
Anders Carlssondf4cc612007-10-30 00:06:20 +00006235 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00006236 return;
Mike Stump11289f42009-09-09 15:08:12 +00006237
John McCall393a78d2012-12-20 02:45:14 +00006238 case Type::Record: {
6239 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00006240 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00006241 // Anonymous structures print as '?'
6242 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
6243 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00006244 if (ClassTemplateSpecializationDecl *Spec
6245 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
6246 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
Benjamin Kramer9170e912013-02-22 15:46:01 +00006247 llvm::raw_string_ostream OS(S);
6248 TemplateSpecializationType::PrintTemplateArgumentList(OS,
David Majnemer6fbeee32016-07-07 04:43:07 +00006249 TemplateArgs.asArray(),
Douglas Gregorc0b07282011-09-27 22:38:19 +00006250 (*this).getPrintingPolicy());
Fariborz Jahanianc5158202010-05-07 00:28:49 +00006251 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00006252 } else {
6253 S += '?';
6254 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00006255 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00006256 S += '=';
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006257 if (!RDecl->isUnion()) {
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006258 getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006259 } else {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006260 for (const auto *Field : RDecl->fields()) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006261 if (FD) {
6262 S += '"';
6263 S += Field->getNameAsString();
6264 S += '"';
6265 }
Mike Stump11289f42009-09-09 15:08:12 +00006266
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006267 // Special case bit-fields.
6268 if (Field->isBitField()) {
6269 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006270 Field);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006271 } else {
6272 QualType qt = Field->getType();
6273 getLegacyIntegralTypeEncoding(qt);
6274 getObjCEncodingForTypeImpl(qt, S, false, true,
6275 FD, /*OutermostType*/false,
6276 /*EncodingProperty*/false,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006277 /*StructField*/true,
6278 false, false, false, NotEncodedT);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006279 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00006280 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00006281 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00006282 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00006283 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00006284 return;
6285 }
Mike Stump11289f42009-09-09 15:08:12 +00006286
John McCall393a78d2012-12-20 02:45:14 +00006287 case Type::BlockPointer: {
6288 const BlockPointerType *BT = T->castAs<BlockPointerType>();
Steve Naroff49140cb2009-02-02 18:24:29 +00006289 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006290 if (EncodeBlockParameters) {
John McCall393a78d2012-12-20 02:45:14 +00006291 const FunctionType *FT = BT->getPointeeType()->castAs<FunctionType>();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006292
6293 S += '<';
6294 // Block return type
Alp Toker314cc812014-01-25 16:55:45 +00006295 getObjCEncodingForTypeImpl(
6296 FT->getReturnType(), S, ExpandPointedToStructures, ExpandStructures,
6297 FD, false /* OutermostType */, EncodingProperty,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006298 false /* StructField */, EncodeBlockParameters, EncodeClassNames, false,
6299 NotEncodedT);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006300 // Block self
6301 S += "@?";
6302 // Block parameters
6303 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00006304 for (const auto &I : FPT->param_types())
6305 getObjCEncodingForTypeImpl(
6306 I, S, ExpandPointedToStructures, ExpandStructures, FD,
6307 false /* OutermostType */, EncodingProperty,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006308 false /* StructField */, EncodeBlockParameters, EncodeClassNames,
6309 false, NotEncodedT);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006310 }
6311 S += '>';
6312 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00006313 return;
6314 }
Mike Stump11289f42009-09-09 15:08:12 +00006315
Fariborz Jahanian33fa9622014-01-28 20:41:15 +00006316 case Type::ObjCObject: {
6317 // hack to match legacy encoding of *id and *Class
6318 QualType Ty = getObjCObjectPointerType(CT);
6319 if (Ty->isObjCIdType()) {
6320 S += "{objc_object=}";
6321 return;
6322 }
6323 else if (Ty->isObjCClassType()) {
6324 S += "{objc_class=}";
6325 return;
6326 }
Galina Kistanovaf87496d2017-06-03 06:31:42 +00006327 // TODO: Double check to make sure this intentially falls through.
6328 LLVM_FALLTHROUGH;
Fariborz Jahanian33fa9622014-01-28 20:41:15 +00006329 }
6330
John McCall393a78d2012-12-20 02:45:14 +00006331 case Type::ObjCInterface: {
6332 // Ignore protocol qualifiers when mangling at this level.
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00006333 // @encode(class_name)
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006334 ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00006335 S += '{';
Douglas Gregorb32684e2015-06-16 21:04:55 +00006336 S += OI->getObjCRuntimeNameAsString();
Akira Hatanakafd0fb202016-08-17 19:42:22 +00006337 if (ExpandStructures) {
6338 S += '=';
6339 SmallVector<const ObjCIvarDecl*, 32> Ivars;
6340 DeepCollectObjCIvars(OI, true, Ivars);
6341 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
6342 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
6343 if (Field->isBitField())
6344 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
6345 else
6346 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD,
6347 false, false, false, false, false,
6348 EncodePointerToObjCTypedef,
6349 NotEncodedT);
6350 }
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00006351 }
6352 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00006353 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00006354 }
Mike Stump11289f42009-09-09 15:08:12 +00006355
John McCall393a78d2012-12-20 02:45:14 +00006356 case Type::ObjCObjectPointer: {
6357 const ObjCObjectPointerType *OPT = T->castAs<ObjCObjectPointerType>();
Steve Naroff7cae42b2009-07-10 23:34:53 +00006358 if (OPT->isObjCIdType()) {
6359 S += '@';
6360 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00006361 }
Mike Stump11289f42009-09-09 15:08:12 +00006362
Steve Narofff0c86112009-10-28 22:03:49 +00006363 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
6364 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
6365 // Since this is a binary compatibility issue, need to consult with runtime
6366 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00006367 S += '#';
6368 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00006369 }
Mike Stump11289f42009-09-09 15:08:12 +00006370
Chris Lattnere7cabb92009-07-13 00:10:46 +00006371 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00006372 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00006373 ExpandPointedToStructures,
6374 ExpandStructures, FD);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006375 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00006376 // Note that we do extended encoding of protocol qualifer list
6377 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00006378 S += '"';
Aaron Ballman83731462014-03-17 16:14:00 +00006379 for (const auto *I : OPT->quals()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00006380 S += '<';
Douglas Gregorb32684e2015-06-16 21:04:55 +00006381 S += I->getObjCRuntimeNameAsString();
Steve Naroff7cae42b2009-07-10 23:34:53 +00006382 S += '>';
6383 }
6384 S += '"';
6385 }
6386 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00006387 }
Mike Stump11289f42009-09-09 15:08:12 +00006388
Chris Lattnere7cabb92009-07-13 00:10:46 +00006389 QualType PointeeTy = OPT->getPointeeType();
6390 if (!EncodingProperty &&
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00006391 isa<TypedefType>(PointeeTy.getTypePtr()) &&
6392 !EncodePointerToObjCTypedef) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00006393 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00006394 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00006395 // {...};
6396 S += '^';
Fariborz Jahanian88890e72013-07-12 16:19:11 +00006397 if (FD && OPT->getInterfaceDecl()) {
Fariborz Jahanianc682ef52013-07-12 16:41:56 +00006398 // Prevent recursive encoding of fields in some rare cases.
Fariborz Jahanian88890e72013-07-12 16:19:11 +00006399 ObjCInterfaceDecl *OI = OPT->getInterfaceDecl();
6400 SmallVector<const ObjCIvarDecl*, 32> Ivars;
6401 DeepCollectObjCIvars(OI, true, Ivars);
6402 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
6403 if (cast<FieldDecl>(Ivars[i]) == FD) {
6404 S += '{';
Douglas Gregorb32684e2015-06-16 21:04:55 +00006405 S += OI->getObjCRuntimeNameAsString();
Fariborz Jahanian88890e72013-07-12 16:19:11 +00006406 S += '}';
6407 return;
6408 }
6409 }
6410 }
Mike Stump11289f42009-09-09 15:08:12 +00006411 getObjCEncodingForTypeImpl(PointeeTy, S,
6412 false, ExpandPointedToStructures,
Craig Topper36250ad2014-05-12 05:36:57 +00006413 nullptr,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00006414 false, false, false, false, false,
6415 /*EncodePointerToObjCTypedef*/true);
Steve Naroff7cae42b2009-07-10 23:34:53 +00006416 return;
6417 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00006418
6419 S += '@';
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006420 if (OPT->getInterfaceDecl() &&
6421 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00006422 S += '"';
Douglas Gregorb32684e2015-06-16 21:04:55 +00006423 S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString();
Aaron Ballman83731462014-03-17 16:14:00 +00006424 for (const auto *I : OPT->quals()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00006425 S += '<';
Douglas Gregorb32684e2015-06-16 21:04:55 +00006426 S += I->getObjCRuntimeNameAsString();
Chris Lattnere7cabb92009-07-13 00:10:46 +00006427 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00006428 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00006429 S += '"';
6430 }
6431 return;
6432 }
Mike Stump11289f42009-09-09 15:08:12 +00006433
John McCalla9e6e8d2010-05-17 23:56:34 +00006434 // gcc just blithely ignores member pointers.
John McCall393a78d2012-12-20 02:45:14 +00006435 // FIXME: we shoul do better than that. 'M' is available.
6436 case Type::MemberPointer:
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006437 // This matches gcc's encoding, even though technically it is insufficient.
6438 //FIXME. We should do a better job than gcc.
John McCall393a78d2012-12-20 02:45:14 +00006439 case Type::Vector:
6440 case Type::ExtVector:
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006441 // Until we have a coherent encoding of these three types, issue warning.
6442 { if (NotEncodedT)
6443 *NotEncodedT = T;
6444 return;
6445 }
6446
6447 // We could see an undeduced auto type here during error recovery.
6448 // Just ignore it.
Richard Smith27d807c2013-04-30 13:56:41 +00006449 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00006450 case Type::DeducedTemplateSpecialization:
Richard Smith27d807c2013-04-30 13:56:41 +00006451 return;
6452
Xiuli Pan9c14e282016-01-09 12:53:17 +00006453 case Type::Pipe:
John McCall393a78d2012-12-20 02:45:14 +00006454#define ABSTRACT_TYPE(KIND, BASE)
6455#define TYPE(KIND, BASE)
6456#define DEPENDENT_TYPE(KIND, BASE) \
6457 case Type::KIND:
6458#define NON_CANONICAL_TYPE(KIND, BASE) \
6459 case Type::KIND:
6460#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
6461 case Type::KIND:
6462#include "clang/AST/TypeNodes.def"
6463 llvm_unreachable("@encode for dependent type!");
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00006464 }
John McCall393a78d2012-12-20 02:45:14 +00006465 llvm_unreachable("bad type kind!");
Anders Carlssond8499822007-10-29 05:01:08 +00006466}
6467
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006468void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
6469 std::string &S,
6470 const FieldDecl *FD,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006471 bool includeVBases,
6472 QualType *NotEncodedT) const {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006473 assert(RDecl && "Expected non-null RecordDecl");
6474 assert(!RDecl->isUnion() && "Should not be called for unions");
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00006475 if (!RDecl->getDefinition() || RDecl->getDefinition()->isInvalidDecl())
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006476 return;
6477
6478 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
6479 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
6480 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
6481
6482 if (CXXRec) {
Aaron Ballman574705e2014-03-13 15:41:46 +00006483 for (const auto &BI : CXXRec->bases()) {
6484 if (!BI.isVirtual()) {
6485 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00006486 if (base->isEmpty())
6487 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00006488 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006489 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
6490 std::make_pair(offs, base));
6491 }
6492 }
6493 }
6494
6495 unsigned i = 0;
Hans Wennborga302cd92014-08-21 16:06:57 +00006496 for (auto *Field : RDecl->fields()) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006497 uint64_t offs = layout.getFieldOffset(i);
6498 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
Hans Wennborga302cd92014-08-21 16:06:57 +00006499 std::make_pair(offs, Field));
6500 ++i;
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006501 }
6502
6503 if (CXXRec && includeVBases) {
Aaron Ballman445a9392014-03-13 16:15:17 +00006504 for (const auto &BI : CXXRec->vbases()) {
6505 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00006506 if (base->isEmpty())
6507 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00006508 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Eli Friedman1d24af82013-09-18 01:59:16 +00006509 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
6510 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
Argyrios Kyrtzidis81c0b5c2011-09-26 18:14:24 +00006511 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
6512 std::make_pair(offs, base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006513 }
6514 }
6515
6516 CharUnits size;
6517 if (CXXRec) {
6518 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
6519 } else {
6520 size = layout.getSize();
6521 }
6522
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006523#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006524 uint64_t CurOffs = 0;
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006525#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006526 std::multimap<uint64_t, NamedDecl *>::iterator
6527 CurLayObj = FieldOrBaseOffsets.begin();
6528
Douglas Gregorf5d6c742012-04-27 22:30:01 +00006529 if (CXXRec && CXXRec->isDynamicClass() &&
6530 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006531 if (FD) {
6532 S += "\"_vptr$";
6533 std::string recname = CXXRec->getNameAsString();
6534 if (recname.empty()) recname = "?";
6535 S += recname;
6536 S += '"';
6537 }
6538 S += "^^?";
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006539#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006540 CurOffs += getTypeSize(VoidPtrTy);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006541#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006542 }
6543
6544 if (!RDecl->hasFlexibleArrayMember()) {
6545 // Mark the end of the structure.
6546 uint64_t offs = toBits(size);
6547 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
Craig Topper36250ad2014-05-12 05:36:57 +00006548 std::make_pair(offs, nullptr));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006549 }
6550
6551 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006552#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006553 assert(CurOffs <= CurLayObj->first);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006554 if (CurOffs < CurLayObj->first) {
6555 uint64_t padding = CurLayObj->first - CurOffs;
6556 // FIXME: There doesn't seem to be a way to indicate in the encoding that
6557 // packing/alignment of members is different that normal, in which case
6558 // the encoding will be out-of-sync with the real layout.
6559 // If the runtime switches to just consider the size of types without
6560 // taking into account alignment, we could make padding explicit in the
6561 // encoding (e.g. using arrays of chars). The encoding strings would be
6562 // longer then though.
6563 CurOffs += padding;
6564 }
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006565#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006566
6567 NamedDecl *dcl = CurLayObj->second;
Craig Topper36250ad2014-05-12 05:36:57 +00006568 if (!dcl)
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006569 break; // reached end of structure.
6570
6571 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
6572 // We expand the bases without their virtual bases since those are going
6573 // in the initial structure. Note that this differs from gcc which
6574 // expands virtual bases each time one is encountered in the hierarchy,
6575 // making the encoding type bigger than it really is.
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006576 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
6577 NotEncodedT);
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00006578 assert(!base->isEmpty());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006579#ifndef NDEBUG
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00006580 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006581#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006582 } else {
6583 FieldDecl *field = cast<FieldDecl>(dcl);
6584 if (FD) {
6585 S += '"';
6586 S += field->getNameAsString();
6587 S += '"';
6588 }
6589
6590 if (field->isBitField()) {
6591 EncodeBitField(this, S, field->getType(), field);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006592#ifndef NDEBUG
Richard Smithcaf33902011-10-10 18:28:20 +00006593 CurOffs += field->getBitWidthValue(*this);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006594#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006595 } else {
6596 QualType qt = field->getType();
6597 getLegacyIntegralTypeEncoding(qt);
6598 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
6599 /*OutermostType*/false,
6600 /*EncodingProperty*/false,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006601 /*StructField*/true,
6602 false, false, false, NotEncodedT);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006603#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006604 CurOffs += getTypeSize(field->getType());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006605#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006606 }
6607 }
6608 }
6609}
6610
Mike Stump11289f42009-09-09 15:08:12 +00006611void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00006612 std::string& S) const {
6613 if (QT & Decl::OBJC_TQ_In)
6614 S += 'n';
6615 if (QT & Decl::OBJC_TQ_Inout)
6616 S += 'N';
6617 if (QT & Decl::OBJC_TQ_Out)
6618 S += 'o';
6619 if (QT & Decl::OBJC_TQ_Bycopy)
6620 S += 'O';
6621 if (QT & Decl::OBJC_TQ_Byref)
6622 S += 'R';
6623 if (QT & Decl::OBJC_TQ_Oneway)
6624 S += 'V';
6625}
6626
Douglas Gregor3ea72692011-08-12 05:46:01 +00006627TypedefDecl *ASTContext::getObjCIdDecl() const {
6628 if (!ObjCIdDecl) {
Douglas Gregore9d95f12015-07-07 03:57:35 +00006629 QualType T = getObjCObjectType(ObjCBuiltinIdTy, { }, { });
Douglas Gregor3ea72692011-08-12 05:46:01 +00006630 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00006631 ObjCIdDecl = buildImplicitTypedef(T, "id");
Douglas Gregor3ea72692011-08-12 05:46:01 +00006632 }
Douglas Gregor3ea72692011-08-12 05:46:01 +00006633 return ObjCIdDecl;
Steve Naroff66e9f332007-10-15 14:41:52 +00006634}
6635
Douglas Gregor52e02802011-08-12 06:17:30 +00006636TypedefDecl *ASTContext::getObjCSelDecl() const {
6637 if (!ObjCSelDecl) {
Alp Toker56b5cc92013-12-15 10:36:26 +00006638 QualType T = getPointerType(ObjCBuiltinSelTy);
6639 ObjCSelDecl = buildImplicitTypedef(T, "SEL");
Douglas Gregor52e02802011-08-12 06:17:30 +00006640 }
6641 return ObjCSelDecl;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00006642}
6643
Douglas Gregor0a586182011-08-12 05:59:41 +00006644TypedefDecl *ASTContext::getObjCClassDecl() const {
6645 if (!ObjCClassDecl) {
Douglas Gregore9d95f12015-07-07 03:57:35 +00006646 QualType T = getObjCObjectType(ObjCBuiltinClassTy, { }, { });
Douglas Gregor0a586182011-08-12 05:59:41 +00006647 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00006648 ObjCClassDecl = buildImplicitTypedef(T, "Class");
Douglas Gregor0a586182011-08-12 05:59:41 +00006649 }
Douglas Gregor0a586182011-08-12 05:59:41 +00006650 return ObjCClassDecl;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00006651}
6652
Douglas Gregord53ae832012-01-17 18:09:05 +00006653ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
6654 if (!ObjCProtocolClassDecl) {
6655 ObjCProtocolClassDecl
6656 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
6657 SourceLocation(),
6658 &Idents.get("Protocol"),
Douglas Gregor85f3f952015-07-07 03:57:15 +00006659 /*typeParamList=*/nullptr,
Craig Topper36250ad2014-05-12 05:36:57 +00006660 /*PrevDecl=*/nullptr,
Douglas Gregord53ae832012-01-17 18:09:05 +00006661 SourceLocation(), true);
6662 }
6663
6664 return ObjCProtocolClassDecl;
6665}
6666
Meador Inge5d3fb222012-06-16 03:34:49 +00006667//===----------------------------------------------------------------------===//
6668// __builtin_va_list Construction Functions
6669//===----------------------------------------------------------------------===//
6670
Charles Davisc7d5c942015-09-17 20:55:33 +00006671static TypedefDecl *CreateCharPtrNamedVaListDecl(const ASTContext *Context,
6672 StringRef Name) {
6673 // typedef char* __builtin[_ms]_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006674 QualType T = Context->getPointerType(Context->CharTy);
Charles Davisc7d5c942015-09-17 20:55:33 +00006675 return Context->buildImplicitTypedef(T, Name);
6676}
6677
6678static TypedefDecl *CreateMSVaListDecl(const ASTContext *Context) {
6679 return CreateCharPtrNamedVaListDecl(Context, "__builtin_ms_va_list");
6680}
6681
6682static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
6683 return CreateCharPtrNamedVaListDecl(Context, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006684}
6685
6686static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
6687 // typedef void* __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006688 QualType T = Context->getPointerType(Context->VoidTy);
6689 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006690}
6691
Tim Northover9bb857a2013-01-31 12:13:10 +00006692static TypedefDecl *
6693CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00006694 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00006695 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00006696 if (Context->getLangOpts().CPlusPlus) {
6697 // namespace std { struct __va_list {
6698 NamespaceDecl *NS;
6699 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
6700 Context->getTranslationUnitDecl(),
Craig Topper36250ad2014-05-12 05:36:57 +00006701 /*Inline*/ false, SourceLocation(),
Tim Northover9bb857a2013-01-31 12:13:10 +00006702 SourceLocation(), &Context->Idents.get("std"),
Craig Topper36250ad2014-05-12 05:36:57 +00006703 /*PrevDecl*/ nullptr);
Alp Toker56b5cc92013-12-15 10:36:26 +00006704 NS->setImplicit();
Tim Northover9bb857a2013-01-31 12:13:10 +00006705 VaListTagDecl->setDeclContext(NS);
Tim Northover9bb857a2013-01-31 12:13:10 +00006706 }
6707
6708 VaListTagDecl->startDefinition();
6709
6710 const size_t NumFields = 5;
6711 QualType FieldTypes[NumFields];
6712 const char *FieldNames[NumFields];
6713
6714 // void *__stack;
6715 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
6716 FieldNames[0] = "__stack";
6717
6718 // void *__gr_top;
6719 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
6720 FieldNames[1] = "__gr_top";
6721
6722 // void *__vr_top;
6723 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6724 FieldNames[2] = "__vr_top";
6725
6726 // int __gr_offs;
6727 FieldTypes[3] = Context->IntTy;
6728 FieldNames[3] = "__gr_offs";
6729
6730 // int __vr_offs;
6731 FieldTypes[4] = Context->IntTy;
6732 FieldNames[4] = "__vr_offs";
6733
6734 // Create fields
6735 for (unsigned i = 0; i < NumFields; ++i) {
6736 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6737 VaListTagDecl,
6738 SourceLocation(),
6739 SourceLocation(),
6740 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006741 FieldTypes[i], /*TInfo=*/nullptr,
6742 /*BitWidth=*/nullptr,
Tim Northover9bb857a2013-01-31 12:13:10 +00006743 /*Mutable=*/false,
6744 ICIS_NoInit);
6745 Field->setAccess(AS_public);
6746 VaListTagDecl->addDecl(Field);
6747 }
6748 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00006749 Context->VaListTagDecl = VaListTagDecl;
Tim Northover9bb857a2013-01-31 12:13:10 +00006750 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Tim Northover9bb857a2013-01-31 12:13:10 +00006751
6752 // } __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006753 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00006754}
6755
Meador Inge5d3fb222012-06-16 03:34:49 +00006756static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
6757 // typedef struct __va_list_tag {
6758 RecordDecl *VaListTagDecl;
6759
Alp Toker2dea15b2013-12-17 01:22:38 +00006760 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00006761 VaListTagDecl->startDefinition();
6762
6763 const size_t NumFields = 5;
6764 QualType FieldTypes[NumFields];
6765 const char *FieldNames[NumFields];
6766
6767 // unsigned char gpr;
6768 FieldTypes[0] = Context->UnsignedCharTy;
6769 FieldNames[0] = "gpr";
6770
6771 // unsigned char fpr;
6772 FieldTypes[1] = Context->UnsignedCharTy;
6773 FieldNames[1] = "fpr";
6774
6775 // unsigned short reserved;
6776 FieldTypes[2] = Context->UnsignedShortTy;
6777 FieldNames[2] = "reserved";
6778
6779 // void* overflow_arg_area;
6780 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6781 FieldNames[3] = "overflow_arg_area";
6782
6783 // void* reg_save_area;
6784 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
6785 FieldNames[4] = "reg_save_area";
6786
6787 // Create fields
6788 for (unsigned i = 0; i < NumFields; ++i) {
6789 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
6790 SourceLocation(),
6791 SourceLocation(),
6792 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006793 FieldTypes[i], /*TInfo=*/nullptr,
6794 /*BitWidth=*/nullptr,
Meador Inge5d3fb222012-06-16 03:34:49 +00006795 /*Mutable=*/false,
6796 ICIS_NoInit);
6797 Field->setAccess(AS_public);
6798 VaListTagDecl->addDecl(Field);
6799 }
6800 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00006801 Context->VaListTagDecl = VaListTagDecl;
Meador Inge5d3fb222012-06-16 03:34:49 +00006802 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6803
6804 // } __va_list_tag;
Alp Toker56b5cc92013-12-15 10:36:26 +00006805 TypedefDecl *VaListTagTypedefDecl =
6806 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
6807
Meador Inge5d3fb222012-06-16 03:34:49 +00006808 QualType VaListTagTypedefType =
6809 Context->getTypedefType(VaListTagTypedefDecl);
6810
6811 // typedef __va_list_tag __builtin_va_list[1];
6812 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6813 QualType VaListTagArrayType
6814 = Context->getConstantArrayType(VaListTagTypedefType,
6815 Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00006816 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006817}
6818
6819static TypedefDecl *
6820CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
Richard Smith9b88a4c2015-07-27 05:40:23 +00006821 // struct __va_list_tag {
Meador Inge5d3fb222012-06-16 03:34:49 +00006822 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00006823 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00006824 VaListTagDecl->startDefinition();
6825
6826 const size_t NumFields = 4;
6827 QualType FieldTypes[NumFields];
6828 const char *FieldNames[NumFields];
6829
6830 // unsigned gp_offset;
6831 FieldTypes[0] = Context->UnsignedIntTy;
6832 FieldNames[0] = "gp_offset";
6833
6834 // unsigned fp_offset;
6835 FieldTypes[1] = Context->UnsignedIntTy;
6836 FieldNames[1] = "fp_offset";
6837
6838 // void* overflow_arg_area;
6839 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6840 FieldNames[2] = "overflow_arg_area";
6841
6842 // void* reg_save_area;
6843 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6844 FieldNames[3] = "reg_save_area";
6845
6846 // Create fields
6847 for (unsigned i = 0; i < NumFields; ++i) {
6848 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6849 VaListTagDecl,
6850 SourceLocation(),
6851 SourceLocation(),
6852 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006853 FieldTypes[i], /*TInfo=*/nullptr,
6854 /*BitWidth=*/nullptr,
Meador Inge5d3fb222012-06-16 03:34:49 +00006855 /*Mutable=*/false,
6856 ICIS_NoInit);
6857 Field->setAccess(AS_public);
6858 VaListTagDecl->addDecl(Field);
6859 }
6860 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00006861 Context->VaListTagDecl = VaListTagDecl;
Meador Inge5d3fb222012-06-16 03:34:49 +00006862 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6863
Richard Smith9b88a4c2015-07-27 05:40:23 +00006864 // };
Alp Toker56b5cc92013-12-15 10:36:26 +00006865
Richard Smith9b88a4c2015-07-27 05:40:23 +00006866 // typedef struct __va_list_tag __builtin_va_list[1];
Meador Inge5d3fb222012-06-16 03:34:49 +00006867 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
Richard Smith9b88a4c2015-07-27 05:40:23 +00006868 QualType VaListTagArrayType =
6869 Context->getConstantArrayType(VaListTagType, Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00006870 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006871}
6872
6873static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
6874 // typedef int __builtin_va_list[4];
6875 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
Yaron Kerene0bcdd42016-10-08 06:45:10 +00006876 QualType IntArrayType =
6877 Context->getConstantArrayType(Context->IntTy, Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00006878 return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006879}
6880
Logan Chien57086ce2012-10-10 06:56:20 +00006881static TypedefDecl *
6882CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00006883 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00006884 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00006885 if (Context->getLangOpts().CPlusPlus) {
6886 // namespace std { struct __va_list {
6887 NamespaceDecl *NS;
6888 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
6889 Context->getTranslationUnitDecl(),
6890 /*Inline*/false, SourceLocation(),
6891 SourceLocation(), &Context->Idents.get("std"),
Craig Topper36250ad2014-05-12 05:36:57 +00006892 /*PrevDecl*/ nullptr);
Alp Toker56b5cc92013-12-15 10:36:26 +00006893 NS->setImplicit();
Logan Chien57086ce2012-10-10 06:56:20 +00006894 VaListDecl->setDeclContext(NS);
Logan Chien57086ce2012-10-10 06:56:20 +00006895 }
6896
6897 VaListDecl->startDefinition();
6898
6899 // void * __ap;
6900 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6901 VaListDecl,
6902 SourceLocation(),
6903 SourceLocation(),
6904 &Context->Idents.get("__ap"),
6905 Context->getPointerType(Context->VoidTy),
Craig Topper36250ad2014-05-12 05:36:57 +00006906 /*TInfo=*/nullptr,
6907 /*BitWidth=*/nullptr,
Logan Chien57086ce2012-10-10 06:56:20 +00006908 /*Mutable=*/false,
6909 ICIS_NoInit);
6910 Field->setAccess(AS_public);
6911 VaListDecl->addDecl(Field);
6912
6913 // };
6914 VaListDecl->completeDefinition();
Oleg Ranevskyyb88d2472016-03-30 21:30:30 +00006915 Context->VaListTagDecl = VaListDecl;
Logan Chien57086ce2012-10-10 06:56:20 +00006916
6917 // typedef struct __va_list __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006918 QualType T = Context->getRecordType(VaListDecl);
6919 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00006920}
6921
Ulrich Weigand47445072013-05-06 16:26:41 +00006922static TypedefDecl *
6923CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
Richard Smith9b88a4c2015-07-27 05:40:23 +00006924 // struct __va_list_tag {
Ulrich Weigand47445072013-05-06 16:26:41 +00006925 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00006926 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Ulrich Weigand47445072013-05-06 16:26:41 +00006927 VaListTagDecl->startDefinition();
6928
6929 const size_t NumFields = 4;
6930 QualType FieldTypes[NumFields];
6931 const char *FieldNames[NumFields];
6932
6933 // long __gpr;
6934 FieldTypes[0] = Context->LongTy;
6935 FieldNames[0] = "__gpr";
6936
6937 // long __fpr;
6938 FieldTypes[1] = Context->LongTy;
6939 FieldNames[1] = "__fpr";
6940
6941 // void *__overflow_arg_area;
6942 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6943 FieldNames[2] = "__overflow_arg_area";
6944
6945 // void *__reg_save_area;
6946 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6947 FieldNames[3] = "__reg_save_area";
6948
6949 // Create fields
6950 for (unsigned i = 0; i < NumFields; ++i) {
6951 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6952 VaListTagDecl,
6953 SourceLocation(),
6954 SourceLocation(),
6955 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006956 FieldTypes[i], /*TInfo=*/nullptr,
6957 /*BitWidth=*/nullptr,
Ulrich Weigand47445072013-05-06 16:26:41 +00006958 /*Mutable=*/false,
6959 ICIS_NoInit);
6960 Field->setAccess(AS_public);
6961 VaListTagDecl->addDecl(Field);
6962 }
6963 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00006964 Context->VaListTagDecl = VaListTagDecl;
Ulrich Weigand47445072013-05-06 16:26:41 +00006965 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Ulrich Weigand47445072013-05-06 16:26:41 +00006966
Richard Smith9b88a4c2015-07-27 05:40:23 +00006967 // };
Ulrich Weigand47445072013-05-06 16:26:41 +00006968
6969 // typedef __va_list_tag __builtin_va_list[1];
6970 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
Richard Smith9b88a4c2015-07-27 05:40:23 +00006971 QualType VaListTagArrayType =
6972 Context->getConstantArrayType(VaListTagType, Size, ArrayType::Normal, 0);
Ulrich Weigand47445072013-05-06 16:26:41 +00006973
Alp Toker56b5cc92013-12-15 10:36:26 +00006974 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Ulrich Weigand47445072013-05-06 16:26:41 +00006975}
6976
Meador Inge5d3fb222012-06-16 03:34:49 +00006977static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
6978 TargetInfo::BuiltinVaListKind Kind) {
6979 switch (Kind) {
6980 case TargetInfo::CharPtrBuiltinVaList:
6981 return CreateCharPtrBuiltinVaListDecl(Context);
6982 case TargetInfo::VoidPtrBuiltinVaList:
6983 return CreateVoidPtrBuiltinVaListDecl(Context);
Tim Northover9bb857a2013-01-31 12:13:10 +00006984 case TargetInfo::AArch64ABIBuiltinVaList:
6985 return CreateAArch64ABIBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00006986 case TargetInfo::PowerABIBuiltinVaList:
6987 return CreatePowerABIBuiltinVaListDecl(Context);
6988 case TargetInfo::X86_64ABIBuiltinVaList:
6989 return CreateX86_64ABIBuiltinVaListDecl(Context);
6990 case TargetInfo::PNaClABIBuiltinVaList:
6991 return CreatePNaClABIBuiltinVaListDecl(Context);
Logan Chien57086ce2012-10-10 06:56:20 +00006992 case TargetInfo::AAPCSABIBuiltinVaList:
6993 return CreateAAPCSABIBuiltinVaListDecl(Context);
Ulrich Weigand47445072013-05-06 16:26:41 +00006994 case TargetInfo::SystemZBuiltinVaList:
6995 return CreateSystemZBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00006996 }
6997
6998 llvm_unreachable("Unhandled __builtin_va_list type kind");
6999}
7000
7001TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00007002 if (!BuiltinVaListDecl) {
Meador Inge5d3fb222012-06-16 03:34:49 +00007003 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
Alp Toker56b5cc92013-12-15 10:36:26 +00007004 assert(BuiltinVaListDecl->isImplicit());
7005 }
Meador Inge5d3fb222012-06-16 03:34:49 +00007006
7007 return BuiltinVaListDecl;
7008}
7009
Richard Smith9b88a4c2015-07-27 05:40:23 +00007010Decl *ASTContext::getVaListTagDecl() const {
7011 // Force the creation of VaListTagDecl by building the __builtin_va_list
Meador Ingecfb60902012-07-01 15:57:25 +00007012 // declaration.
Richard Smith9b88a4c2015-07-27 05:40:23 +00007013 if (!VaListTagDecl)
7014 (void)getBuiltinVaListDecl();
Meador Ingecfb60902012-07-01 15:57:25 +00007015
Richard Smith9b88a4c2015-07-27 05:40:23 +00007016 return VaListTagDecl;
Meador Ingecfb60902012-07-01 15:57:25 +00007017}
7018
Charles Davisc7d5c942015-09-17 20:55:33 +00007019TypedefDecl *ASTContext::getBuiltinMSVaListDecl() const {
7020 if (!BuiltinMSVaListDecl)
7021 BuiltinMSVaListDecl = CreateMSVaListDecl(this);
7022
7023 return BuiltinMSVaListDecl;
7024}
7025
Ted Kremenek1b0ea822008-01-07 19:49:32 +00007026void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00007027 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00007028 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00007029
Ted Kremenek1b0ea822008-01-07 19:49:32 +00007030 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00007031}
7032
John McCalld28ae272009-12-02 08:04:21 +00007033/// \brief Retrieve the template name that corresponds to a non-empty
7034/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00007035TemplateName
7036ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
7037 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00007038 unsigned size = End - Begin;
7039 assert(size > 1 && "set is not overloaded!");
7040
7041 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
7042 size * sizeof(FunctionTemplateDecl*));
7043 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
7044
7045 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00007046 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00007047 NamedDecl *D = *I;
7048 assert(isa<FunctionTemplateDecl>(D) ||
7049 (isa<UsingShadowDecl>(D) &&
7050 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
7051 *Storage++ = D;
7052 }
7053
7054 return TemplateName(OT);
7055}
7056
Douglas Gregordc572a32009-03-30 22:58:21 +00007057/// \brief Retrieve the template name that represents a qualified
7058/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00007059TemplateName
7060ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
7061 bool TemplateKeyword,
7062 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00007063 assert(NNS && "Missing nested-name-specifier in qualified template name");
7064
Douglas Gregorc42075a2010-02-04 18:10:26 +00007065 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00007066 llvm::FoldingSetNodeID ID;
7067 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
7068
Craig Topper36250ad2014-05-12 05:36:57 +00007069 void *InsertPos = nullptr;
Douglas Gregordc572a32009-03-30 22:58:21 +00007070 QualifiedTemplateName *QTN =
7071 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7072 if (!QTN) {
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007073 QTN = new (*this, alignof(QualifiedTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00007074 QualifiedTemplateName(NNS, TemplateKeyword, Template);
Douglas Gregordc572a32009-03-30 22:58:21 +00007075 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
7076 }
7077
7078 return TemplateName(QTN);
7079}
7080
7081/// \brief Retrieve the template name that represents a dependent
7082/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00007083TemplateName
7084ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
7085 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00007086 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00007087 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00007088
7089 llvm::FoldingSetNodeID ID;
7090 DependentTemplateName::Profile(ID, NNS, Name);
7091
Craig Topper36250ad2014-05-12 05:36:57 +00007092 void *InsertPos = nullptr;
Douglas Gregordc572a32009-03-30 22:58:21 +00007093 DependentTemplateName *QTN =
7094 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7095
7096 if (QTN)
7097 return TemplateName(QTN);
7098
7099 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
7100 if (CanonNNS == NNS) {
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007101 QTN = new (*this, alignof(DependentTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00007102 DependentTemplateName(NNS, Name);
Douglas Gregordc572a32009-03-30 22:58:21 +00007103 } else {
7104 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007105 QTN = new (*this, alignof(DependentTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00007106 DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00007107 DependentTemplateName *CheckQTN =
7108 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7109 assert(!CheckQTN && "Dependent type name canonicalization broken");
7110 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00007111 }
7112
7113 DependentTemplateNames.InsertNode(QTN, InsertPos);
7114 return TemplateName(QTN);
7115}
7116
Douglas Gregor71395fa2009-11-04 00:56:37 +00007117/// \brief Retrieve the template name that represents a dependent
7118/// template name such as \c MetaFun::template operator+.
7119TemplateName
7120ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00007121 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00007122 assert((!NNS || NNS->isDependent()) &&
7123 "Nested name specifier must be dependent");
7124
7125 llvm::FoldingSetNodeID ID;
7126 DependentTemplateName::Profile(ID, NNS, Operator);
Craig Topper36250ad2014-05-12 05:36:57 +00007127
7128 void *InsertPos = nullptr;
Douglas Gregorc42075a2010-02-04 18:10:26 +00007129 DependentTemplateName *QTN
7130 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00007131
7132 if (QTN)
7133 return TemplateName(QTN);
7134
7135 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
7136 if (CanonNNS == NNS) {
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007137 QTN = new (*this, alignof(DependentTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00007138 DependentTemplateName(NNS, Operator);
Douglas Gregor71395fa2009-11-04 00:56:37 +00007139 } else {
7140 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007141 QTN = new (*this, alignof(DependentTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00007142 DependentTemplateName(NNS, Operator, Canon);
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007143
Douglas Gregorc42075a2010-02-04 18:10:26 +00007144 DependentTemplateName *CheckQTN
7145 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7146 assert(!CheckQTN && "Dependent template name canonicalization broken");
7147 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00007148 }
7149
7150 DependentTemplateNames.InsertNode(QTN, InsertPos);
7151 return TemplateName(QTN);
7152}
7153
Douglas Gregor5590be02011-01-15 06:45:20 +00007154TemplateName
John McCalld9dfe3a2011-06-30 08:33:18 +00007155ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
7156 TemplateName replacement) const {
7157 llvm::FoldingSetNodeID ID;
7158 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
Craig Topper36250ad2014-05-12 05:36:57 +00007159
7160 void *insertPos = nullptr;
John McCalld9dfe3a2011-06-30 08:33:18 +00007161 SubstTemplateTemplateParmStorage *subst
7162 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
7163
7164 if (!subst) {
7165 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
7166 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
7167 }
7168
7169 return TemplateName(subst);
7170}
7171
7172TemplateName
Douglas Gregor5590be02011-01-15 06:45:20 +00007173ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
7174 const TemplateArgument &ArgPack) const {
7175 ASTContext &Self = const_cast<ASTContext &>(*this);
7176 llvm::FoldingSetNodeID ID;
7177 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
Craig Topper36250ad2014-05-12 05:36:57 +00007178
7179 void *InsertPos = nullptr;
Douglas Gregor5590be02011-01-15 06:45:20 +00007180 SubstTemplateTemplateParmPackStorage *Subst
7181 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
7182
7183 if (!Subst) {
John McCalld9dfe3a2011-06-30 08:33:18 +00007184 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor5590be02011-01-15 06:45:20 +00007185 ArgPack.pack_size(),
7186 ArgPack.pack_begin());
7187 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
7188 }
7189
7190 return TemplateName(Subst);
7191}
7192
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00007193/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00007194/// TargetInfo, produce the corresponding type. The unsigned @p Type
7195/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00007196CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00007197 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00007198 case TargetInfo::NoInt: return CanQualType();
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00007199 case TargetInfo::SignedChar: return SignedCharTy;
7200 case TargetInfo::UnsignedChar: return UnsignedCharTy;
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00007201 case TargetInfo::SignedShort: return ShortTy;
7202 case TargetInfo::UnsignedShort: return UnsignedShortTy;
7203 case TargetInfo::SignedInt: return IntTy;
7204 case TargetInfo::UnsignedInt: return UnsignedIntTy;
7205 case TargetInfo::SignedLong: return LongTy;
7206 case TargetInfo::UnsignedLong: return UnsignedLongTy;
7207 case TargetInfo::SignedLongLong: return LongLongTy;
7208 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
7209 }
7210
David Blaikie83d382b2011-09-23 05:06:16 +00007211 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00007212}
Ted Kremenek77c51b22008-07-24 23:58:27 +00007213
7214//===----------------------------------------------------------------------===//
7215// Type Predicates.
7216//===----------------------------------------------------------------------===//
7217
Fariborz Jahanian96207692009-02-18 21:49:28 +00007218/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
7219/// garbage collection attribute.
7220///
John McCall553d45a2011-01-12 00:34:59 +00007221Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00007222 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCall553d45a2011-01-12 00:34:59 +00007223 return Qualifiers::GCNone;
7224
David Blaikiebbafb8a2012-03-11 07:00:24 +00007225 assert(getLangOpts().ObjC1);
John McCall553d45a2011-01-12 00:34:59 +00007226 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
7227
7228 // Default behaviour under objective-C's gc is for ObjC pointers
7229 // (or pointers to them) be treated as though they were declared
7230 // as __strong.
7231 if (GCAttrs == Qualifiers::GCNone) {
7232 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
7233 return Qualifiers::Strong;
7234 else if (Ty->isPointerType())
7235 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
7236 } else {
7237 // It's not valid to set GC attributes on anything that isn't a
7238 // pointer.
7239#ifndef NDEBUG
7240 QualType CT = Ty->getCanonicalTypeInternal();
7241 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
7242 CT = AT->getElementType();
7243 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
7244#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00007245 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00007246 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00007247}
7248
Chris Lattner49af6a42008-04-07 06:51:04 +00007249//===----------------------------------------------------------------------===//
7250// Type Compatibility Testing
7251//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00007252
Mike Stump11289f42009-09-09 15:08:12 +00007253/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00007254/// compatible.
7255static bool areCompatVectorTypes(const VectorType *LHS,
7256 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00007257 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00007258 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00007259 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00007260}
7261
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00007262bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
7263 QualType SecondVec) {
7264 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
7265 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
7266
7267 if (hasSameUnqualifiedType(FirstVec, SecondVec))
7268 return true;
7269
Bob Wilsone6aeebb2010-11-12 17:24:54 +00007270 // Treat Neon vector types and most AltiVec vector types as if they are the
7271 // equivalent GCC vector types.
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00007272 const VectorType *First = FirstVec->getAs<VectorType>();
7273 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00007274 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00007275 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00007276 First->getVectorKind() != VectorType::AltiVecPixel &&
7277 First->getVectorKind() != VectorType::AltiVecBool &&
7278 Second->getVectorKind() != VectorType::AltiVecPixel &&
7279 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00007280 return true;
7281
7282 return false;
7283}
7284
Steve Naroff8e6aee52009-07-23 01:01:38 +00007285//===----------------------------------------------------------------------===//
7286// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
7287//===----------------------------------------------------------------------===//
7288
7289/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
7290/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00007291bool
7292ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
7293 ObjCProtocolDecl *rProto) const {
Douglas Gregor33b24292012-01-01 18:09:12 +00007294 if (declaresSameEntity(lProto, rProto))
Steve Naroff8e6aee52009-07-23 01:01:38 +00007295 return true;
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00007296 for (auto *PI : rProto->protocols())
7297 if (ProtocolCompatibleWithProtocol(lProto, PI))
Steve Naroff8e6aee52009-07-23 01:01:38 +00007298 return true;
7299 return false;
7300}
7301
Dmitri Gribenko4364fcf2012-08-28 02:49:14 +00007302/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
7303/// Class<pr1, ...>.
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00007304bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
7305 QualType rhs) {
7306 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
7307 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
7308 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
7309
Aaron Ballman83731462014-03-17 16:14:00 +00007310 for (auto *lhsProto : lhsQID->quals()) {
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00007311 bool match = false;
Aaron Ballman83731462014-03-17 16:14:00 +00007312 for (auto *rhsProto : rhsOPT->quals()) {
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00007313 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
7314 match = true;
7315 break;
7316 }
7317 }
7318 if (!match)
7319 return false;
7320 }
7321 return true;
7322}
7323
Steve Naroff8e6aee52009-07-23 01:01:38 +00007324/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
7325/// ObjCQualifiedIDType.
7326bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
7327 bool compare) {
7328 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00007329 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00007330 lhs->isObjCIdType() || lhs->isObjCClassType())
7331 return true;
Mike Stump11289f42009-09-09 15:08:12 +00007332 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00007333 rhs->isObjCIdType() || rhs->isObjCClassType())
7334 return true;
7335
7336 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00007337 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00007338
Steve Naroff8e6aee52009-07-23 01:01:38 +00007339 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00007340
Steve Naroff8e6aee52009-07-23 01:01:38 +00007341 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00007342 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00007343 // make sure we check the class hierarchy.
7344 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
Aaron Ballman83731462014-03-17 16:14:00 +00007345 for (auto *I : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007346 // when comparing an id<P> on lhs with a static type on rhs,
7347 // see if static class implements all of id's protocols, directly or
7348 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00007349 if (!rhsID->ClassImplementsProtocol(I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00007350 return false;
7351 }
7352 }
7353 // If there are no qualifiers and no interface, we have an 'id'.
7354 return true;
7355 }
Mike Stump11289f42009-09-09 15:08:12 +00007356 // Both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00007357 for (auto *lhsProto : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007358 bool match = false;
7359
7360 // when comparing an id<P> on lhs with a static type on rhs,
7361 // see if static class implements all of id's protocols, directly or
7362 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00007363 for (auto *rhsProto : rhsOPT->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007364 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
7365 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
7366 match = true;
7367 break;
7368 }
7369 }
Mike Stump11289f42009-09-09 15:08:12 +00007370 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00007371 // make sure we check the class hierarchy.
7372 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
Aaron Ballman83731462014-03-17 16:14:00 +00007373 for (auto *I : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007374 // when comparing an id<P> on lhs with a static type on rhs,
7375 // see if static class implements all of id's protocols, directly or
7376 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00007377 if (rhsID->ClassImplementsProtocol(I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007378 match = true;
7379 break;
7380 }
7381 }
7382 }
7383 if (!match)
7384 return false;
7385 }
Mike Stump11289f42009-09-09 15:08:12 +00007386
Steve Naroff8e6aee52009-07-23 01:01:38 +00007387 return true;
7388 }
Mike Stump11289f42009-09-09 15:08:12 +00007389
Steve Naroff8e6aee52009-07-23 01:01:38 +00007390 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
7391 assert(rhsQID && "One of the LHS/RHS should be id<x>");
7392
Mike Stump11289f42009-09-09 15:08:12 +00007393 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00007394 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007395 // If both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00007396 for (auto *lhsProto : lhsOPT->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007397 bool match = false;
7398
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007399 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00007400 // see if static class implements all of id's protocols, directly or
7401 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007402 // First, lhs protocols in the qualifier list must be found, direct
7403 // or indirect in rhs's qualifier list or it is a mismatch.
Aaron Ballman83731462014-03-17 16:14:00 +00007404 for (auto *rhsProto : rhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007405 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
7406 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
7407 match = true;
7408 break;
7409 }
7410 }
7411 if (!match)
7412 return false;
7413 }
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007414
7415 // Static class's protocols, or its super class or category protocols
7416 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
7417 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
7418 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
7419 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
7420 // This is rather dubious but matches gcc's behavior. If lhs has
7421 // no type qualifier and its class has no static protocol(s)
7422 // assume that it is mismatch.
7423 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
7424 return false;
Aaron Ballman83731462014-03-17 16:14:00 +00007425 for (auto *lhsProto : LHSInheritedProtocols) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007426 bool match = false;
Aaron Ballman83731462014-03-17 16:14:00 +00007427 for (auto *rhsProto : rhsQID->quals()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007428 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
7429 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
7430 match = true;
7431 break;
7432 }
7433 }
7434 if (!match)
7435 return false;
7436 }
7437 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00007438 return true;
7439 }
7440 return false;
7441}
7442
Eli Friedman47f77112008-08-22 00:56:42 +00007443/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00007444/// compatible for assignment from RHS to LHS. This handles validation of any
7445/// protocol qualifiers on the LHS or RHS.
7446///
Steve Naroff7cae42b2009-07-10 23:34:53 +00007447bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
7448 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00007449 const ObjCObjectType* LHS = LHSOPT->getObjectType();
7450 const ObjCObjectType* RHS = RHSOPT->getObjectType();
7451
Steve Naroff1329fa02009-07-15 18:40:39 +00007452 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00007453 if (LHS->isObjCUnqualifiedIdOrClass() ||
7454 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00007455 return true;
7456
Douglas Gregorab209d82015-07-07 03:58:42 +00007457 // Function object that propagates a successful result or handles
7458 // __kindof types.
7459 auto finish = [&](bool succeeded) -> bool {
7460 if (succeeded)
7461 return true;
7462
7463 if (!RHS->isKindOfType())
7464 return false;
7465
7466 // Strip off __kindof and protocol qualifiers, then check whether
7467 // we can assign the other way.
7468 return canAssignObjCInterfaces(RHSOPT->stripObjCKindOfTypeAndQuals(*this),
7469 LHSOPT->stripObjCKindOfTypeAndQuals(*this));
7470 };
7471
7472 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) {
7473 return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
7474 QualType(RHSOPT,0),
7475 false));
7476 }
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00007477
Douglas Gregorab209d82015-07-07 03:58:42 +00007478 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) {
7479 return finish(ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
7480 QualType(RHSOPT,0)));
7481 }
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00007482
John McCall8b07ec22010-05-15 11:32:37 +00007483 // If we have 2 user-defined types, fall into that path.
Douglas Gregorab209d82015-07-07 03:58:42 +00007484 if (LHS->getInterface() && RHS->getInterface()) {
7485 return finish(canAssignObjCInterfaces(LHS, RHS));
7486 }
Mike Stump11289f42009-09-09 15:08:12 +00007487
Steve Naroff8e6aee52009-07-23 01:01:38 +00007488 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00007489}
7490
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007491/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattner57540c52011-04-15 05:22:18 +00007492/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007493/// arguments in block literals. When passed as arguments, passing 'A*' where
7494/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
7495/// not OK. For the return type, the opposite is not OK.
7496bool ASTContext::canAssignObjCInterfacesInBlockPointer(
7497 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007498 const ObjCObjectPointerType *RHSOPT,
7499 bool BlockReturnType) {
Douglas Gregorab209d82015-07-07 03:58:42 +00007500
7501 // Function object that propagates a successful result or handles
7502 // __kindof types.
7503 auto finish = [&](bool succeeded) -> bool {
7504 if (succeeded)
7505 return true;
7506
7507 const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT;
7508 if (!Expected->isKindOfType())
7509 return false;
7510
7511 // Strip off __kindof and protocol qualifiers, then check whether
7512 // we can assign the other way.
7513 return canAssignObjCInterfacesInBlockPointer(
7514 RHSOPT->stripObjCKindOfTypeAndQuals(*this),
7515 LHSOPT->stripObjCKindOfTypeAndQuals(*this),
7516 BlockReturnType);
7517 };
7518
Fariborz Jahanian440a6832010-04-06 17:23:39 +00007519 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007520 return true;
7521
7522 if (LHSOPT->isObjCBuiltinType()) {
Douglas Gregorab209d82015-07-07 03:58:42 +00007523 return finish(RHSOPT->isObjCBuiltinType() ||
7524 RHSOPT->isObjCQualifiedIdType());
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007525 }
7526
Fariborz Jahanian440a6832010-04-06 17:23:39 +00007527 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Douglas Gregorab209d82015-07-07 03:58:42 +00007528 return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
7529 QualType(RHSOPT,0),
7530 false));
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007531
7532 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
7533 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
7534 if (LHS && RHS) { // We have 2 user-defined types.
7535 if (LHS != RHS) {
7536 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Douglas Gregorab209d82015-07-07 03:58:42 +00007537 return finish(BlockReturnType);
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007538 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Douglas Gregorab209d82015-07-07 03:58:42 +00007539 return finish(!BlockReturnType);
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007540 }
7541 else
7542 return true;
7543 }
7544 return false;
7545}
7546
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007547/// Comparison routine for Objective-C protocols to be used with
7548/// llvm::array_pod_sort.
7549static int compareObjCProtocolsByName(ObjCProtocolDecl * const *lhs,
7550 ObjCProtocolDecl * const *rhs) {
7551 return (*lhs)->getName().compare((*rhs)->getName());
7552
7553}
7554
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007555/// getIntersectionOfProtocols - This routine finds the intersection of set
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007556/// of protocols inherited from two distinct objective-c pointer objects with
7557/// the given common base.
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007558/// It is used to build composite qualifier list of the composite type of
7559/// the conditional expression involving two objective-c pointer objects.
7560static
7561void getIntersectionOfProtocols(ASTContext &Context,
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007562 const ObjCInterfaceDecl *CommonBase,
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007563 const ObjCObjectPointerType *LHSOPT,
7564 const ObjCObjectPointerType *RHSOPT,
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007565 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007566
John McCall8b07ec22010-05-15 11:32:37 +00007567 const ObjCObjectType* LHS = LHSOPT->getObjectType();
7568 const ObjCObjectType* RHS = RHSOPT->getObjectType();
7569 assert(LHS->getInterface() && "LHS must have an interface base");
7570 assert(RHS->getInterface() && "RHS must have an interface base");
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007571
7572 // Add all of the protocols for the LHS.
7573 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSProtocolSet;
7574
7575 // Start with the protocol qualifiers.
7576 for (auto proto : LHS->quals()) {
7577 Context.CollectInheritedProtocols(proto, LHSProtocolSet);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007578 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007579
7580 // Also add the protocols associated with the LHS interface.
7581 Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet);
7582
7583 // Add all of the protocls for the RHS.
7584 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSProtocolSet;
7585
7586 // Start with the protocol qualifiers.
7587 for (auto proto : RHS->quals()) {
7588 Context.CollectInheritedProtocols(proto, RHSProtocolSet);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007589 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007590
7591 // Also add the protocols associated with the RHS interface.
7592 Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet);
7593
7594 // Compute the intersection of the collected protocol sets.
7595 for (auto proto : LHSProtocolSet) {
7596 if (RHSProtocolSet.count(proto))
7597 IntersectionSet.push_back(proto);
7598 }
7599
7600 // Compute the set of protocols that is implied by either the common type or
7601 // the protocols within the intersection.
7602 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ImpliedProtocols;
7603 Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols);
7604
7605 // Remove any implied protocols from the list of inherited protocols.
7606 if (!ImpliedProtocols.empty()) {
7607 IntersectionSet.erase(
7608 std::remove_if(IntersectionSet.begin(),
7609 IntersectionSet.end(),
7610 [&](ObjCProtocolDecl *proto) -> bool {
7611 return ImpliedProtocols.count(proto) > 0;
7612 }),
7613 IntersectionSet.end());
7614 }
7615
7616 // Sort the remaining protocols by name.
7617 llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(),
7618 compareObjCProtocolsByName);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007619}
7620
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007621/// Determine whether the first type is a subtype of the second.
7622static bool canAssignObjCObjectTypes(ASTContext &ctx, QualType lhs,
7623 QualType rhs) {
7624 // Common case: two object pointers.
7625 const ObjCObjectPointerType *lhsOPT = lhs->getAs<ObjCObjectPointerType>();
7626 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
7627 if (lhsOPT && rhsOPT)
7628 return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT);
7629
7630 // Two block pointers.
7631 const BlockPointerType *lhsBlock = lhs->getAs<BlockPointerType>();
7632 const BlockPointerType *rhsBlock = rhs->getAs<BlockPointerType>();
7633 if (lhsBlock && rhsBlock)
7634 return ctx.typesAreBlockPointerCompatible(lhs, rhs);
7635
7636 // If either is an unqualified 'id' and the other is a block, it's
7637 // acceptable.
7638 if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) ||
7639 (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock))
7640 return true;
7641
7642 return false;
7643}
7644
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007645// Check that the given Objective-C type argument lists are equivalent.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007646static bool sameObjCTypeArgs(ASTContext &ctx,
7647 const ObjCInterfaceDecl *iface,
7648 ArrayRef<QualType> lhsArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00007649 ArrayRef<QualType> rhsArgs,
7650 bool stripKindOf) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007651 if (lhsArgs.size() != rhsArgs.size())
7652 return false;
7653
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007654 ObjCTypeParamList *typeParams = iface->getTypeParamList();
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007655 for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) {
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007656 if (ctx.hasSameType(lhsArgs[i], rhsArgs[i]))
7657 continue;
7658
7659 switch (typeParams->begin()[i]->getVariance()) {
7660 case ObjCTypeParamVariance::Invariant:
Douglas Gregorab209d82015-07-07 03:58:42 +00007661 if (!stripKindOf ||
7662 !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx),
7663 rhsArgs[i].stripObjCKindOfType(ctx))) {
7664 return false;
7665 }
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007666 break;
7667
7668 case ObjCTypeParamVariance::Covariant:
7669 if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i]))
7670 return false;
7671 break;
7672
7673 case ObjCTypeParamVariance::Contravariant:
7674 if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i]))
7675 return false;
7676 break;
Douglas Gregorab209d82015-07-07 03:58:42 +00007677 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007678 }
7679
7680 return true;
7681}
7682
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00007683QualType ASTContext::areCommonBaseCompatible(
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007684 const ObjCObjectPointerType *Lptr,
7685 const ObjCObjectPointerType *Rptr) {
John McCall8b07ec22010-05-15 11:32:37 +00007686 const ObjCObjectType *LHS = Lptr->getObjectType();
7687 const ObjCObjectType *RHS = Rptr->getObjectType();
7688 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
7689 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007690
7691 if (!LDecl || !RDecl)
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00007692 return QualType();
Douglas Gregore83b9562015-07-07 03:57:53 +00007693
Manman Renc46f7d12016-05-06 19:35:02 +00007694 // When either LHS or RHS is a kindof type, we should return a kindof type.
7695 // For example, for common base of kindof(ASub1) and kindof(ASub2), we return
7696 // kindof(A).
7697 bool anyKindOf = LHS->isKindOfType() || RHS->isKindOfType();
7698
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007699 // Follow the left-hand side up the class hierarchy until we either hit a
7700 // root or find the RHS. Record the ancestors in case we don't find it.
7701 llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4>
7702 LHSAncestors;
7703 while (true) {
7704 // Record this ancestor. We'll need this if the common type isn't in the
7705 // path from the LHS to the root.
7706 LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS;
Douglas Gregore83b9562015-07-07 03:57:53 +00007707
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007708 if (declaresSameEntity(LHS->getInterface(), RDecl)) {
7709 // Get the type arguments.
7710 ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten();
7711 bool anyChanges = false;
7712 if (LHS->isSpecialized() && RHS->isSpecialized()) {
7713 // Both have type arguments, compare them.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007714 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
7715 LHS->getTypeArgs(), RHS->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00007716 /*stripKindOf=*/true))
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007717 return QualType();
7718 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
7719 // If only one has type arguments, the result will not have type
7720 // arguments.
7721 LHSTypeArgs = { };
7722 anyChanges = true;
7723 }
7724
7725 // Compute the intersection of protocols.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007726 SmallVector<ObjCProtocolDecl *, 8> Protocols;
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007727 getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr,
7728 Protocols);
John McCall8b07ec22010-05-15 11:32:37 +00007729 if (!Protocols.empty())
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007730 anyChanges = true;
7731
7732 // If anything in the LHS will have changed, build a new result type.
Manman Renc46f7d12016-05-06 19:35:02 +00007733 // If we need to return a kindof type but LHS is not a kindof type, we
7734 // build a new result type.
7735 if (anyChanges || LHS->isKindOfType() != anyKindOf) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007736 QualType Result = getObjCInterfaceType(LHS->getInterface());
Douglas Gregorab209d82015-07-07 03:58:42 +00007737 Result = getObjCObjectType(Result, LHSTypeArgs, Protocols,
Manman Renc46f7d12016-05-06 19:35:02 +00007738 anyKindOf || LHS->isKindOfType());
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007739 return getObjCObjectPointerType(Result);
7740 }
7741
7742 return getObjCObjectPointerType(QualType(LHS, 0));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007743 }
Douglas Gregore83b9562015-07-07 03:57:53 +00007744
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007745 // Find the superclass.
Douglas Gregore83b9562015-07-07 03:57:53 +00007746 QualType LHSSuperType = LHS->getSuperClassType();
7747 if (LHSSuperType.isNull())
7748 break;
7749
7750 LHS = LHSSuperType->castAs<ObjCObjectType>();
7751 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007752
7753 // We didn't find anything by following the LHS to its root; now check
7754 // the RHS against the cached set of ancestors.
7755 while (true) {
7756 auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl());
7757 if (KnownLHS != LHSAncestors.end()) {
7758 LHS = KnownLHS->second;
7759
7760 // Get the type arguments.
7761 ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten();
7762 bool anyChanges = false;
7763 if (LHS->isSpecialized() && RHS->isSpecialized()) {
7764 // Both have type arguments, compare them.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007765 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
7766 LHS->getTypeArgs(), RHS->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00007767 /*stripKindOf=*/true))
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007768 return QualType();
7769 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
7770 // If only one has type arguments, the result will not have type
7771 // arguments.
7772 RHSTypeArgs = { };
7773 anyChanges = true;
7774 }
7775
7776 // Compute the intersection of protocols.
7777 SmallVector<ObjCProtocolDecl *, 8> Protocols;
7778 getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr,
7779 Protocols);
7780 if (!Protocols.empty())
7781 anyChanges = true;
7782
Manman Renc46f7d12016-05-06 19:35:02 +00007783 // If we need to return a kindof type but RHS is not a kindof type, we
7784 // build a new result type.
7785 if (anyChanges || RHS->isKindOfType() != anyKindOf) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007786 QualType Result = getObjCInterfaceType(RHS->getInterface());
Douglas Gregorab209d82015-07-07 03:58:42 +00007787 Result = getObjCObjectType(Result, RHSTypeArgs, Protocols,
Manman Renc46f7d12016-05-06 19:35:02 +00007788 anyKindOf || RHS->isKindOfType());
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007789 return getObjCObjectPointerType(Result);
7790 }
7791
7792 return getObjCObjectPointerType(QualType(RHS, 0));
7793 }
7794
7795 // Find the superclass of the RHS.
7796 QualType RHSSuperType = RHS->getSuperClassType();
7797 if (RHSSuperType.isNull())
7798 break;
7799
7800 RHS = RHSSuperType->castAs<ObjCObjectType>();
7801 }
7802
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00007803 return QualType();
7804}
7805
John McCall8b07ec22010-05-15 11:32:37 +00007806bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
7807 const ObjCObjectType *RHS) {
7808 assert(LHS->getInterface() && "LHS is not an interface type");
7809 assert(RHS->getInterface() && "RHS is not an interface type");
7810
Chris Lattner49af6a42008-04-07 06:51:04 +00007811 // Verify that the base decls are compatible: the RHS must be a subclass of
7812 // the LHS.
Douglas Gregore83b9562015-07-07 03:57:53 +00007813 ObjCInterfaceDecl *LHSInterface = LHS->getInterface();
7814 bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface());
7815 if (!IsSuperClass)
Chris Lattner49af6a42008-04-07 06:51:04 +00007816 return false;
Mike Stump11289f42009-09-09 15:08:12 +00007817
Douglas Gregore83b9562015-07-07 03:57:53 +00007818 // If the LHS has protocol qualifiers, determine whether all of them are
7819 // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the
7820 // LHS).
7821 if (LHS->getNumProtocols() > 0) {
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00007822 // OK if conversion of LHS to SuperClass results in narrowing of types
7823 // ; i.e., SuperClass may implement at least one of the protocols
7824 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
7825 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
7826 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
7827 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
7828 // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
7829 // qualifiers.
7830 for (auto *RHSPI : RHS->quals())
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007831 CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols);
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00007832 // If there is no protocols associated with RHS, it is not a match.
7833 if (SuperClassInheritedProtocols.empty())
Steve Naroff114aecb2009-03-01 16:12:44 +00007834 return false;
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00007835
7836 for (const auto *LHSProto : LHS->quals()) {
7837 bool SuperImplementsProtocol = false;
7838 for (auto *SuperClassProto : SuperClassInheritedProtocols)
7839 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
7840 SuperImplementsProtocol = true;
7841 break;
7842 }
7843 if (!SuperImplementsProtocol)
7844 return false;
7845 }
Chris Lattner49af6a42008-04-07 06:51:04 +00007846 }
Douglas Gregore83b9562015-07-07 03:57:53 +00007847
7848 // If the LHS is specialized, we may need to check type arguments.
7849 if (LHS->isSpecialized()) {
7850 // Follow the superclass chain until we've matched the LHS class in the
7851 // hierarchy. This substitutes type arguments through.
7852 const ObjCObjectType *RHSSuper = RHS;
7853 while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface))
7854 RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>();
7855
7856 // If the RHS is specializd, compare type arguments.
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007857 if (RHSSuper->isSpecialized() &&
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007858 !sameObjCTypeArgs(*this, LHS->getInterface(),
7859 LHS->getTypeArgs(), RHSSuper->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00007860 /*stripKindOf=*/true)) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007861 return false;
Douglas Gregore83b9562015-07-07 03:57:53 +00007862 }
7863 }
7864
7865 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00007866}
7867
Steve Naroffb7605152009-02-12 17:52:19 +00007868bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
7869 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00007870 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
7871 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00007872
Steve Naroff7cae42b2009-07-10 23:34:53 +00007873 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00007874 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00007875
7876 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
7877 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00007878}
7879
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00007880bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
7881 return canAssignObjCInterfaces(
7882 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
7883 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
7884}
7885
Mike Stump11289f42009-09-09 15:08:12 +00007886/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00007887/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00007888/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00007889/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007890bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
7891 bool CompareUnqualified) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00007892 if (getLangOpts().CPlusPlus)
Douglas Gregor21e771e2010-02-03 21:02:30 +00007893 return hasSameType(LHS, RHS);
Joey Gouly5788b782016-11-18 14:10:54 +00007894
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007895 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00007896}
7897
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00007898bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanianc87c8792011-07-12 23:20:13 +00007899 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00007900}
7901
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007902bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
7903 return !mergeTypes(LHS, RHS, true).isNull();
7904}
7905
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00007906/// mergeTransparentUnionType - if T is a transparent union type and a member
7907/// of T is compatible with SubType, return the merged type, else return
7908/// QualType()
7909QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
7910 bool OfBlockPointer,
7911 bool Unqualified) {
7912 if (const RecordType *UT = T->getAsUnionType()) {
7913 RecordDecl *UD = UT->getDecl();
7914 if (UD->hasAttr<TransparentUnionAttr>()) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007915 for (const auto *I : UD->fields()) {
7916 QualType ET = I->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00007917 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
7918 if (!MT.isNull())
7919 return MT;
7920 }
7921 }
7922 }
7923
7924 return QualType();
7925}
7926
Alp Toker9cacbab2014-01-20 20:26:09 +00007927/// mergeFunctionParameterTypes - merge two types which appear as function
7928/// parameter types
7929QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs,
7930 bool OfBlockPointer,
7931 bool Unqualified) {
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00007932 // GNU extension: two types are compatible if they appear as a function
7933 // argument, one of the types is a transparent union type and the other
7934 // type is compatible with a union member
7935 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
7936 Unqualified);
7937 if (!lmerge.isNull())
7938 return lmerge;
7939
7940 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
7941 Unqualified);
7942 if (!rmerge.isNull())
7943 return rmerge;
7944
7945 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
7946}
7947
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007948QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007949 bool OfBlockPointer,
7950 bool Unqualified) {
John McCall9dd450b2009-09-21 23:43:11 +00007951 const FunctionType *lbase = lhs->getAs<FunctionType>();
7952 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007953 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
7954 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00007955 bool allLTypes = true;
7956 bool allRTypes = true;
7957
7958 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007959 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00007960 if (OfBlockPointer) {
Alp Toker314cc812014-01-25 16:55:45 +00007961 QualType RHS = rbase->getReturnType();
7962 QualType LHS = lbase->getReturnType();
Fariborz Jahanian17825972011-02-11 18:46:17 +00007963 bool UnqualifiedResult = Unqualified;
7964 if (!UnqualifiedResult)
7965 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007966 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahanian17825972011-02-11 18:46:17 +00007967 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007968 else
Alp Toker314cc812014-01-25 16:55:45 +00007969 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
John McCall8c6b56f2010-12-15 01:06:38 +00007970 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007971 if (retType.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007972
7973 if (Unqualified)
7974 retType = retType.getUnqualifiedType();
7975
Alp Toker314cc812014-01-25 16:55:45 +00007976 CanQualType LRetType = getCanonicalType(lbase->getReturnType());
7977 CanQualType RRetType = getCanonicalType(rbase->getReturnType());
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007978 if (Unqualified) {
7979 LRetType = LRetType.getUnqualifiedType();
7980 RRetType = RRetType.getUnqualifiedType();
7981 }
7982
7983 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00007984 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007985 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00007986 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00007987
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00007988 // FIXME: double check this
7989 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
7990 // rbase->getRegParmAttr() != 0 &&
7991 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00007992 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
7993 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00007994
Douglas Gregor8c940862010-01-18 17:14:39 +00007995 // Compatible functions must have compatible calling conventions
Reid Kleckner78af0702013-08-27 23:08:25 +00007996 if (lbaseInfo.getCC() != rbaseInfo.getCC())
Douglas Gregor8c940862010-01-18 17:14:39 +00007997 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00007998
John McCall8c6b56f2010-12-15 01:06:38 +00007999 // Regparm is part of the calling convention.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00008000 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
8001 return QualType();
John McCall8c6b56f2010-12-15 01:06:38 +00008002 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
8003 return QualType();
8004
John McCall31168b02011-06-15 23:02:42 +00008005 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
8006 return QualType();
Oren Ben Simhon318a6ea2017-04-27 12:01:00 +00008007 if (lbaseInfo.getNoCallerSavedRegs() != rbaseInfo.getNoCallerSavedRegs())
8008 return QualType();
John McCall31168b02011-06-15 23:02:42 +00008009
John McCall8c6b56f2010-12-15 01:06:38 +00008010 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
8011 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8c6b56f2010-12-15 01:06:38 +00008012
Rafael Espindola8778c282012-11-29 16:09:03 +00008013 if (lbaseInfo.getNoReturn() != NoReturn)
8014 allLTypes = false;
8015 if (rbaseInfo.getNoReturn() != NoReturn)
8016 allRTypes = false;
8017
John McCall31168b02011-06-15 23:02:42 +00008018 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00008019
Eli Friedman47f77112008-08-22 00:56:42 +00008020 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00008021 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
8022 "C++ shouldn't be here");
Alp Toker601b22c2014-01-21 23:35:24 +00008023 // Compatible functions must have the same number of parameters
8024 if (lproto->getNumParams() != rproto->getNumParams())
Eli Friedman47f77112008-08-22 00:56:42 +00008025 return QualType();
8026
8027 // Variadic and non-variadic functions aren't compatible
8028 if (lproto->isVariadic() != rproto->isVariadic())
8029 return QualType();
8030
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00008031 if (lproto->getTypeQuals() != rproto->getTypeQuals())
8032 return QualType();
8033
Akira Hatanaka98a49332017-09-22 00:41:05 +00008034 SmallVector<FunctionProtoType::ExtParameterInfo, 4> newParamInfos;
8035 bool canUseLeft, canUseRight;
8036 if (!mergeExtParameterInfo(lproto, rproto, canUseLeft, canUseRight,
8037 newParamInfos))
Fariborz Jahanian97676972011-09-28 21:52:05 +00008038 return QualType();
Alp Toker601b22c2014-01-21 23:35:24 +00008039
Akira Hatanaka98a49332017-09-22 00:41:05 +00008040 if (!canUseLeft)
8041 allLTypes = false;
8042 if (!canUseRight)
8043 allRTypes = false;
8044
Alp Toker601b22c2014-01-21 23:35:24 +00008045 // Check parameter type compatibility
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008046 SmallVector<QualType, 10> types;
Alp Toker601b22c2014-01-21 23:35:24 +00008047 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
8048 QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
8049 QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
8050 QualType paramType = mergeFunctionParameterTypes(
8051 lParamType, rParamType, OfBlockPointer, Unqualified);
8052 if (paramType.isNull())
8053 return QualType();
8054
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008055 if (Unqualified)
Alp Toker601b22c2014-01-21 23:35:24 +00008056 paramType = paramType.getUnqualifiedType();
8057
8058 types.push_back(paramType);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008059 if (Unqualified) {
Alp Toker601b22c2014-01-21 23:35:24 +00008060 lParamType = lParamType.getUnqualifiedType();
8061 rParamType = rParamType.getUnqualifiedType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008062 }
Alp Toker601b22c2014-01-21 23:35:24 +00008063
8064 if (getCanonicalType(paramType) != getCanonicalType(lParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00008065 allLTypes = false;
Alp Toker601b22c2014-01-21 23:35:24 +00008066 if (getCanonicalType(paramType) != getCanonicalType(rParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00008067 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00008068 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00008069
Eli Friedman47f77112008-08-22 00:56:42 +00008070 if (allLTypes) return lhs;
8071 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00008072
8073 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
8074 EPI.ExtInfo = einfo;
Akira Hatanaka98a49332017-09-22 00:41:05 +00008075 EPI.ExtParameterInfos =
8076 newParamInfos.empty() ? nullptr : newParamInfos.data();
Jordan Rose5c382722013-03-08 21:51:21 +00008077 return getFunctionType(retType, types, EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00008078 }
8079
8080 if (lproto) allRTypes = false;
8081 if (rproto) allLTypes = false;
8082
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008083 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00008084 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00008085 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00008086 if (proto->isVariadic()) return QualType();
8087 // Check that the types are compatible with the types that
8088 // would result from default argument promotions (C99 6.7.5.3p15).
8089 // The only types actually affected are promotable integer
8090 // types and floats, which would be passed as a different
8091 // type depending on whether the prototype is visible.
Alp Toker601b22c2014-01-21 23:35:24 +00008092 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
8093 QualType paramTy = proto->getParamType(i);
Alp Toker9cacbab2014-01-20 20:26:09 +00008094
Eli Friedman448ce402012-08-30 00:44:15 +00008095 // Look at the converted type of enum types, since that is the type used
Douglas Gregor2973d402010-02-03 19:27:29 +00008096 // to pass enum values.
Alp Toker601b22c2014-01-21 23:35:24 +00008097 if (const EnumType *Enum = paramTy->getAs<EnumType>()) {
8098 paramTy = Enum->getDecl()->getIntegerType();
8099 if (paramTy.isNull())
Eli Friedman448ce402012-08-30 00:44:15 +00008100 return QualType();
8101 }
Alp Toker601b22c2014-01-21 23:35:24 +00008102
8103 if (paramTy->isPromotableIntegerType() ||
8104 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
Eli Friedman47f77112008-08-22 00:56:42 +00008105 return QualType();
8106 }
8107
8108 if (allLTypes) return lhs;
8109 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00008110
8111 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
8112 EPI.ExtInfo = einfo;
Alp Toker9cacbab2014-01-20 20:26:09 +00008113 return getFunctionType(retType, proto->getParamTypes(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00008114 }
8115
8116 if (allLTypes) return lhs;
8117 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00008118 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00008119}
8120
John McCall433c2e62013-03-21 00:10:07 +00008121/// Given that we have an enum type and a non-enum type, try to merge them.
8122static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
8123 QualType other, bool isBlockReturnType) {
8124 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
8125 // a signed integer type, or an unsigned integer type.
8126 // Compatibility is based on the underlying type, not the promotion
8127 // type.
8128 QualType underlyingType = ET->getDecl()->getIntegerType();
8129 if (underlyingType.isNull()) return QualType();
8130 if (Context.hasSameType(underlyingType, other))
8131 return other;
8132
8133 // In block return types, we're more permissive and accept any
8134 // integral type of the same size.
8135 if (isBlockReturnType && other->isIntegerType() &&
8136 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
8137 return other;
8138
8139 return QualType();
8140}
8141
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008142QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008143 bool OfBlockPointer,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00008144 bool Unqualified, bool BlockReturnType) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00008145 // C++ [expr]: If an expression initially has the type "reference to T", the
8146 // type is adjusted to "T" prior to any further analysis, the expression
8147 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00008148 // expression is an lvalue unless the reference is an rvalue reference and
8149 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00008150 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
8151 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008152
8153 if (Unqualified) {
8154 LHS = LHS.getUnqualifiedType();
8155 RHS = RHS.getUnqualifiedType();
8156 }
Douglas Gregor21e771e2010-02-03 21:02:30 +00008157
Eli Friedman47f77112008-08-22 00:56:42 +00008158 QualType LHSCan = getCanonicalType(LHS),
8159 RHSCan = getCanonicalType(RHS);
8160
8161 // If two types are identical, they are compatible.
8162 if (LHSCan == RHSCan)
8163 return LHS;
8164
John McCall8ccfcb52009-09-24 19:53:00 +00008165 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00008166 Qualifiers LQuals = LHSCan.getLocalQualifiers();
8167 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00008168 if (LQuals != RQuals) {
8169 // If any of these qualifiers are different, we have a type
8170 // mismatch.
8171 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCall31168b02011-06-15 23:02:42 +00008172 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
Roger Ferrer Ibanezd93add32017-02-24 08:41:09 +00008173 LQuals.getObjCLifetime() != RQuals.getObjCLifetime() ||
8174 LQuals.hasUnaligned() != RQuals.hasUnaligned())
John McCall8ccfcb52009-09-24 19:53:00 +00008175 return QualType();
8176
8177 // Exactly one GC qualifier difference is allowed: __strong is
8178 // okay if the other type has no GC qualifier but is an Objective
8179 // C object pointer (i.e. implicitly strong by default). We fix
8180 // this by pretending that the unqualified type was actually
8181 // qualified __strong.
8182 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
8183 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
8184 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
8185
8186 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
8187 return QualType();
8188
8189 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
8190 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
8191 }
8192 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
8193 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
8194 }
Eli Friedman47f77112008-08-22 00:56:42 +00008195 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00008196 }
8197
8198 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00008199
Eli Friedmandcca6332009-06-01 01:22:52 +00008200 Type::TypeClass LHSClass = LHSCan->getTypeClass();
8201 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00008202
Chris Lattnerfd652912008-01-14 05:45:46 +00008203 // We want to consider the two function types to be the same for these
8204 // comparisons, just force one to the other.
8205 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
8206 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00008207
8208 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00008209 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
8210 LHSClass = Type::ConstantArray;
8211 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
8212 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00008213
John McCall8b07ec22010-05-15 11:32:37 +00008214 // ObjCInterfaces are just specialized ObjCObjects.
8215 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
8216 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
8217
Nate Begemance4d7fc2008-04-18 23:10:10 +00008218 // Canonicalize ExtVector -> Vector.
8219 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
8220 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00008221
Chris Lattner95554662008-04-07 05:43:21 +00008222 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00008223 if (LHSClass != RHSClass) {
John McCall433c2e62013-03-21 00:10:07 +00008224 // Note that we only have special rules for turning block enum
8225 // returns into block int returns, not vice-versa.
John McCall9dd450b2009-09-21 23:43:11 +00008226 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00008227 return mergeEnumWithInteger(*this, ETy, RHS, false);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00008228 }
John McCall9dd450b2009-09-21 23:43:11 +00008229 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00008230 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00008231 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00008232 // allow block pointer type to match an 'id' type.
Fariborz Jahanian194904e2012-01-26 17:08:50 +00008233 if (OfBlockPointer && !BlockReturnType) {
8234 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
8235 return LHS;
8236 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
8237 return RHS;
8238 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00008239
Eli Friedman47f77112008-08-22 00:56:42 +00008240 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00008241 }
Eli Friedman47f77112008-08-22 00:56:42 +00008242
Steve Naroffc6edcbd2008-01-09 22:43:08 +00008243 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00008244 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008245#define TYPE(Class, Base)
8246#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00008247#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008248#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
8249#define DEPENDENT_TYPE(Class, Base) case Type::Class:
8250#include "clang/AST/TypeNodes.def"
David Blaikie83d382b2011-09-23 05:06:16 +00008251 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008252
Richard Smith27d807c2013-04-30 13:56:41 +00008253 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00008254 case Type::DeducedTemplateSpecialization:
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00008255 case Type::LValueReference:
8256 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008257 case Type::MemberPointer:
David Blaikie83d382b2011-09-23 05:06:16 +00008258 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008259
John McCall8b07ec22010-05-15 11:32:37 +00008260 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008261 case Type::IncompleteArray:
8262 case Type::VariableArray:
8263 case Type::FunctionProto:
8264 case Type::ExtVector:
David Blaikie83d382b2011-09-23 05:06:16 +00008265 llvm_unreachable("Types are eliminated above");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008266
Chris Lattnerfd652912008-01-14 05:45:46 +00008267 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00008268 {
8269 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00008270 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
8271 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008272 if (Unqualified) {
8273 LHSPointee = LHSPointee.getUnqualifiedType();
8274 RHSPointee = RHSPointee.getUnqualifiedType();
8275 }
8276 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
8277 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00008278 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00008279 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00008280 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00008281 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00008282 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00008283 return getPointerType(ResultType);
8284 }
Steve Naroff68e167d2008-12-10 17:49:55 +00008285 case Type::BlockPointer:
8286 {
8287 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00008288 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
8289 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008290 if (Unqualified) {
8291 LHSPointee = LHSPointee.getUnqualifiedType();
8292 RHSPointee = RHSPointee.getUnqualifiedType();
8293 }
Anastasia Stulova81a25e352017-03-10 15:23:07 +00008294 if (getLangOpts().OpenCL) {
8295 Qualifiers LHSPteeQual = LHSPointee.getQualifiers();
8296 Qualifiers RHSPteeQual = RHSPointee.getQualifiers();
8297 // Blocks can't be an expression in a ternary operator (OpenCL v2.0
8298 // 6.12.5) thus the following check is asymmetric.
8299 if (!LHSPteeQual.isAddressSpaceSupersetOf(RHSPteeQual))
8300 return QualType();
8301 LHSPteeQual.removeAddressSpace();
8302 RHSPteeQual.removeAddressSpace();
8303 LHSPointee =
8304 QualType(LHSPointee.getTypePtr(), LHSPteeQual.getAsOpaqueValue());
8305 RHSPointee =
8306 QualType(RHSPointee.getTypePtr(), RHSPteeQual.getAsOpaqueValue());
8307 }
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008308 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
8309 Unqualified);
Steve Naroff68e167d2008-12-10 17:49:55 +00008310 if (ResultType.isNull()) return QualType();
8311 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
8312 return LHS;
8313 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
8314 return RHS;
8315 return getBlockPointerType(ResultType);
8316 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00008317 case Type::Atomic:
8318 {
8319 // Merge two pointer types, while trying to preserve typedef info
8320 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
8321 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
8322 if (Unqualified) {
8323 LHSValue = LHSValue.getUnqualifiedType();
8324 RHSValue = RHSValue.getUnqualifiedType();
8325 }
8326 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
8327 Unqualified);
8328 if (ResultType.isNull()) return QualType();
8329 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
8330 return LHS;
8331 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
8332 return RHS;
8333 return getAtomicType(ResultType);
8334 }
Chris Lattnerfd652912008-01-14 05:45:46 +00008335 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00008336 {
8337 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
8338 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
8339 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
8340 return QualType();
8341
8342 QualType LHSElem = getAsArrayType(LHS)->getElementType();
8343 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008344 if (Unqualified) {
8345 LHSElem = LHSElem.getUnqualifiedType();
8346 RHSElem = RHSElem.getUnqualifiedType();
8347 }
8348
8349 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00008350 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00008351 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
8352 return LHS;
8353 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
8354 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00008355 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
8356 ArrayType::ArraySizeModifier(), 0);
8357 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
8358 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00008359 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
8360 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00008361 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
8362 return LHS;
8363 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
8364 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00008365 if (LVAT) {
8366 // FIXME: This isn't correct! But tricky to implement because
8367 // the array's size has to be the size of LHS, but the type
8368 // has to be different.
8369 return LHS;
8370 }
8371 if (RVAT) {
8372 // FIXME: This isn't correct! But tricky to implement because
8373 // the array's size has to be the size of RHS, but the type
8374 // has to be different.
8375 return RHS;
8376 }
Eli Friedman3e62c212008-08-22 01:48:21 +00008377 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
8378 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00008379 return getIncompleteArrayType(ResultType,
8380 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00008381 }
Chris Lattnerfd652912008-01-14 05:45:46 +00008382 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008383 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008384 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008385 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00008386 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00008387 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00008388 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00008389 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00008390 case Type::Complex:
8391 // Distinct complex types are incompatible.
8392 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00008393 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00008394 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00008395 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
8396 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00008397 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00008398 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00008399 case Type::ObjCObject: {
8400 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00008401 // FIXME: This should be type compatibility, e.g. whether
8402 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00008403 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
8404 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
8405 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00008406 return LHS;
8407
Eli Friedman47f77112008-08-22 00:56:42 +00008408 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00008409 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00008410 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008411 if (OfBlockPointer) {
8412 if (canAssignObjCInterfacesInBlockPointer(
8413 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahanian90186f82011-03-14 16:07:00 +00008414 RHS->getAs<ObjCObjectPointerType>(),
8415 BlockReturnType))
David Blaikie8a40f702012-01-17 06:56:22 +00008416 return LHS;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008417 return QualType();
8418 }
John McCall9dd450b2009-09-21 23:43:11 +00008419 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
8420 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00008421 return LHS;
8422
Steve Naroffc68cfcf2008-12-10 22:14:21 +00008423 return QualType();
David Blaikie8a40f702012-01-17 06:56:22 +00008424 }
Xiuli Pan9c14e282016-01-09 12:53:17 +00008425 case Type::Pipe:
8426 {
Joey Goulye3c85de2016-12-01 11:30:49 +00008427 assert(LHS != RHS &&
8428 "Equivalent pipe types should have already been handled!");
8429 return QualType();
Xiuli Pan9c14e282016-01-09 12:53:17 +00008430 }
Steve Naroff32e44c02007-10-15 20:41:53 +00008431 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008432
David Blaikie8a40f702012-01-17 06:56:22 +00008433 llvm_unreachable("Invalid Type::Class!");
Steve Naroff32e44c02007-10-15 20:41:53 +00008434}
Ted Kremenekfc581a92007-10-31 17:10:13 +00008435
Akira Hatanaka98a49332017-09-22 00:41:05 +00008436bool ASTContext::mergeExtParameterInfo(
8437 const FunctionProtoType *FirstFnType, const FunctionProtoType *SecondFnType,
8438 bool &CanUseFirst, bool &CanUseSecond,
8439 SmallVectorImpl<FunctionProtoType::ExtParameterInfo> &NewParamInfos) {
8440 assert(NewParamInfos.empty() && "param info list not empty");
8441 CanUseFirst = CanUseSecond = true;
8442 bool FirstHasInfo = FirstFnType->hasExtParameterInfos();
8443 bool SecondHasInfo = SecondFnType->hasExtParameterInfos();
8444
John McCall18afab72016-03-01 00:49:02 +00008445 // Fast path: if the first type doesn't have ext parameter infos,
Akira Hatanaka98a49332017-09-22 00:41:05 +00008446 // we match if and only if the second type also doesn't have them.
8447 if (!FirstHasInfo && !SecondHasInfo)
8448 return true;
John McCall18afab72016-03-01 00:49:02 +00008449
Akira Hatanaka98a49332017-09-22 00:41:05 +00008450 bool NeedParamInfo = false;
8451 size_t E = FirstHasInfo ? FirstFnType->getExtParameterInfos().size()
8452 : SecondFnType->getExtParameterInfos().size();
John McCall18afab72016-03-01 00:49:02 +00008453
Akira Hatanaka98a49332017-09-22 00:41:05 +00008454 for (size_t I = 0; I < E; ++I) {
8455 FunctionProtoType::ExtParameterInfo FirstParam, SecondParam;
8456 if (FirstHasInfo)
8457 FirstParam = FirstFnType->getExtParameterInfo(I);
8458 if (SecondHasInfo)
8459 SecondParam = SecondFnType->getExtParameterInfo(I);
John McCall18afab72016-03-01 00:49:02 +00008460
Akira Hatanaka98a49332017-09-22 00:41:05 +00008461 // Cannot merge unless everything except the noescape flag matches.
8462 if (FirstParam.withIsNoEscape(false) != SecondParam.withIsNoEscape(false))
John McCall18afab72016-03-01 00:49:02 +00008463 return false;
Akira Hatanaka98a49332017-09-22 00:41:05 +00008464
8465 bool FirstNoEscape = FirstParam.isNoEscape();
8466 bool SecondNoEscape = SecondParam.isNoEscape();
8467 bool IsNoEscape = FirstNoEscape && SecondNoEscape;
8468 NewParamInfos.push_back(FirstParam.withIsNoEscape(IsNoEscape));
8469 if (NewParamInfos.back().getOpaqueValue())
8470 NeedParamInfo = true;
8471 if (FirstNoEscape != IsNoEscape)
8472 CanUseFirst = false;
8473 if (SecondNoEscape != IsNoEscape)
8474 CanUseSecond = false;
John McCall18afab72016-03-01 00:49:02 +00008475 }
Akira Hatanaka98a49332017-09-22 00:41:05 +00008476
8477 if (!NeedParamInfo)
8478 NewParamInfos.clear();
8479
Fariborz Jahanian97676972011-09-28 21:52:05 +00008480 return true;
8481}
8482
Chandler Carruth21c90602015-12-30 03:24:14 +00008483void ASTContext::ResetObjCLayout(const ObjCContainerDecl *CD) {
8484 ObjCLayouts[CD] = nullptr;
8485}
8486
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00008487/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
8488/// 'RHS' attributes and returns the merged version; including for function
8489/// return types.
8490QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
8491 QualType LHSCan = getCanonicalType(LHS),
8492 RHSCan = getCanonicalType(RHS);
8493 // If two types are identical, they are compatible.
8494 if (LHSCan == RHSCan)
8495 return LHS;
8496 if (RHSCan->isFunctionType()) {
8497 if (!LHSCan->isFunctionType())
8498 return QualType();
Alp Toker314cc812014-01-25 16:55:45 +00008499 QualType OldReturnType =
8500 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00008501 QualType NewReturnType =
Alp Toker314cc812014-01-25 16:55:45 +00008502 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00008503 QualType ResReturnType =
8504 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
8505 if (ResReturnType.isNull())
8506 return QualType();
8507 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
8508 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
8509 // In either case, use OldReturnType to build the new function type.
8510 const FunctionType *F = LHS->getAs<FunctionType>();
8511 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00008512 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8513 EPI.ExtInfo = getFunctionExtInfo(LHS);
Reid Kleckner896b32f2013-06-10 20:51:09 +00008514 QualType ResultType =
Alp Toker9cacbab2014-01-20 20:26:09 +00008515 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00008516 return ResultType;
8517 }
8518 }
8519 return QualType();
8520 }
8521
8522 // If the qualifiers are different, the types can still be merged.
8523 Qualifiers LQuals = LHSCan.getLocalQualifiers();
8524 Qualifiers RQuals = RHSCan.getLocalQualifiers();
8525 if (LQuals != RQuals) {
8526 // If any of these qualifiers are different, we have a type mismatch.
8527 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
8528 LQuals.getAddressSpace() != RQuals.getAddressSpace())
8529 return QualType();
8530
8531 // Exactly one GC qualifier difference is allowed: __strong is
8532 // okay if the other type has no GC qualifier but is an Objective
8533 // C object pointer (i.e. implicitly strong by default). We fix
8534 // this by pretending that the unqualified type was actually
8535 // qualified __strong.
8536 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
8537 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
8538 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
8539
8540 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
8541 return QualType();
8542
8543 if (GC_L == Qualifiers::Strong)
8544 return LHS;
8545 if (GC_R == Qualifiers::Strong)
8546 return RHS;
8547 return QualType();
8548 }
8549
8550 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
8551 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
8552 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
8553 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
8554 if (ResQT == LHSBaseQT)
8555 return LHS;
8556 if (ResQT == RHSBaseQT)
8557 return RHS;
8558 }
8559 return QualType();
8560}
8561
Chris Lattner4ba0cef2008-04-07 07:01:58 +00008562//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008563// Integer Predicates
8564//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00008565
Jay Foad39c79802011-01-12 09:06:06 +00008566unsigned ASTContext::getIntWidth(QualType T) const {
Richard Smithe9521062013-10-15 04:56:17 +00008567 if (const EnumType *ET = T->getAs<EnumType>())
Eli Friedmanee275c82009-12-10 22:29:29 +00008568 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00008569 if (T->isBooleanType())
8570 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00008571 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008572 return (unsigned)getTypeSize(T);
8573}
8574
Abramo Bagnara13640492012-09-09 10:21:24 +00008575QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00008576 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00008577
8578 // Turn <4 x signed int> -> <4 x unsigned int>
8579 if (const VectorType *VTy = T->getAs<VectorType>())
8580 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00008581 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00008582
8583 // For enums, we return the unsigned version of the base type.
8584 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008585 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00008586
8587 const BuiltinType *BTy = T->getAs<BuiltinType>();
8588 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008589 switch (BTy->getKind()) {
8590 case BuiltinType::Char_S:
8591 case BuiltinType::SChar:
8592 return UnsignedCharTy;
8593 case BuiltinType::Short:
8594 return UnsignedShortTy;
8595 case BuiltinType::Int:
8596 return UnsignedIntTy;
8597 case BuiltinType::Long:
8598 return UnsignedLongTy;
8599 case BuiltinType::LongLong:
8600 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00008601 case BuiltinType::Int128:
8602 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008603 default:
David Blaikie83d382b2011-09-23 05:06:16 +00008604 llvm_unreachable("Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008605 }
8606}
8607
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +00008608ASTMutationListener::~ASTMutationListener() { }
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00008609
Richard Smith1fa5d642013-05-11 05:45:24 +00008610void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
8611 QualType ReturnType) {}
Chris Lattnerecd79c62009-06-14 00:45:47 +00008612
8613//===----------------------------------------------------------------------===//
8614// Builtin Type Computation
8615//===----------------------------------------------------------------------===//
8616
8617/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00008618/// pointer over the consumed characters. This returns the resultant type. If
8619/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
8620/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
8621/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008622///
8623/// RequiresICE is filled in on return to indicate whether the value is required
8624/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00008625static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00008626 ASTContext::GetBuiltinTypeError &Error,
Chandler Carruth45bbe012017-03-24 09:11:57 +00008627 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00008628 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00008629 // Modifiers.
8630 int HowLong = 0;
8631 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008632 RequiresICE = false;
Chandler Carruth45bbe012017-03-24 09:11:57 +00008633
Chris Lattnerdc226c22010-10-01 22:42:38 +00008634 // Read the prefixed modifiers first.
Eric Christopher50daf5f2017-07-10 21:28:54 +00008635 bool Done = false;
8636 #ifndef NDEBUG
8637 bool IsSpecialLong = false;
8638 #endif
Chris Lattnerecd79c62009-06-14 00:45:47 +00008639 while (!Done) {
8640 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00008641 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00008642 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008643 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00008644 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008645 case 'S':
8646 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
8647 assert(!Signed && "Can't use 'S' modifier multiple times!");
8648 Signed = true;
8649 break;
8650 case 'U':
8651 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
Sean Silva2a995142015-01-16 21:44:26 +00008652 assert(!Unsigned && "Can't use 'U' modifier multiple times!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00008653 Unsigned = true;
8654 break;
8655 case 'L':
Bruno Cardoso Lopesafa47c92017-06-21 02:20:46 +00008656 assert(!IsSpecialLong && "Can't use 'L' with 'W' or 'N' modifiers");
Chris Lattnerecd79c62009-06-14 00:45:47 +00008657 assert(HowLong <= 2 && "Can't have LLLL modifier");
8658 ++HowLong;
8659 break;
Bruno Cardoso Lopesafa47c92017-06-21 02:20:46 +00008660 case 'N': {
8661 // 'N' behaves like 'L' for all non LP64 targets and 'int' otherwise.
8662 assert(!IsSpecialLong && "Can't use two 'N' or 'W' modifiers!");
8663 assert(HowLong == 0 && "Can't use both 'L' and 'N' modifiers!");
Eric Christopher50daf5f2017-07-10 21:28:54 +00008664 #ifndef NDEBUG
Bruno Cardoso Lopesafa47c92017-06-21 02:20:46 +00008665 IsSpecialLong = true;
Eric Christopher50daf5f2017-07-10 21:28:54 +00008666 #endif
Bruno Cardoso Lopesafa47c92017-06-21 02:20:46 +00008667 if (Context.getTargetInfo().getLongWidth() == 32)
8668 ++HowLong;
8669 break;
8670 }
Kevin Qinad64f6d2014-02-24 02:45:03 +00008671 case 'W':
8672 // This modifier represents int64 type.
Bruno Cardoso Lopesafa47c92017-06-21 02:20:46 +00008673 assert(!IsSpecialLong && "Can't use two 'N' or 'W' modifiers!");
Kevin Qinad64f6d2014-02-24 02:45:03 +00008674 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
Eric Christopher50daf5f2017-07-10 21:28:54 +00008675 #ifndef NDEBUG
Bruno Cardoso Lopesafa47c92017-06-21 02:20:46 +00008676 IsSpecialLong = true;
Eric Christopher50daf5f2017-07-10 21:28:54 +00008677 #endif
Kevin Qinad64f6d2014-02-24 02:45:03 +00008678 switch (Context.getTargetInfo().getInt64Type()) {
8679 default:
8680 llvm_unreachable("Unexpected integer type");
8681 case TargetInfo::SignedLong:
8682 HowLong = 1;
8683 break;
8684 case TargetInfo::SignedLongLong:
8685 HowLong = 2;
8686 break;
8687 }
Duncan P. N. Exon Smitheae8caa2017-06-14 21:26:31 +00008688 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008689 }
8690 }
8691
8692 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00008693
Chris Lattnerecd79c62009-06-14 00:45:47 +00008694 // Read the base type.
8695 switch (*Str++) {
David Blaikie83d382b2011-09-23 05:06:16 +00008696 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00008697 case 'v':
8698 assert(HowLong == 0 && !Signed && !Unsigned &&
8699 "Bad modifiers used with 'v'!");
8700 Type = Context.VoidTy;
8701 break;
Jack Carter24bef982013-08-15 15:16:57 +00008702 case 'h':
8703 assert(HowLong == 0 && !Signed && !Unsigned &&
Sean Silva2a995142015-01-16 21:44:26 +00008704 "Bad modifiers used with 'h'!");
Jack Carter24bef982013-08-15 15:16:57 +00008705 Type = Context.HalfTy;
8706 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008707 case 'f':
8708 assert(HowLong == 0 && !Signed && !Unsigned &&
8709 "Bad modifiers used with 'f'!");
8710 Type = Context.FloatTy;
8711 break;
8712 case 'd':
8713 assert(HowLong < 2 && !Signed && !Unsigned &&
8714 "Bad modifiers used with 'd'!");
8715 if (HowLong)
8716 Type = Context.LongDoubleTy;
8717 else
8718 Type = Context.DoubleTy;
8719 break;
8720 case 's':
8721 assert(HowLong == 0 && "Bad modifiers used with 's'!");
8722 if (Unsigned)
8723 Type = Context.UnsignedShortTy;
8724 else
8725 Type = Context.ShortTy;
8726 break;
8727 case 'i':
8728 if (HowLong == 3)
8729 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
8730 else if (HowLong == 2)
8731 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
8732 else if (HowLong == 1)
8733 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
8734 else
8735 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
8736 break;
8737 case 'c':
8738 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
8739 if (Signed)
8740 Type = Context.SignedCharTy;
8741 else if (Unsigned)
8742 Type = Context.UnsignedCharTy;
8743 else
8744 Type = Context.CharTy;
8745 break;
8746 case 'b': // boolean
8747 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
8748 Type = Context.BoolTy;
8749 break;
8750 case 'z': // size_t.
8751 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
8752 Type = Context.getSizeType();
8753 break;
Richard Smith8110c9d2016-11-29 19:45:17 +00008754 case 'w': // wchar_t.
8755 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'w'!");
8756 Type = Context.getWideCharType();
8757 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008758 case 'F':
8759 Type = Context.getCFConstantStringType();
8760 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00008761 case 'G':
8762 Type = Context.getObjCIdType();
8763 break;
8764 case 'H':
8765 Type = Context.getObjCSelType();
8766 break;
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00008767 case 'M':
8768 Type = Context.getObjCSuperType();
8769 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008770 case 'a':
8771 Type = Context.getBuiltinVaListType();
8772 assert(!Type.isNull() && "builtin va list type not initialized!");
8773 break;
8774 case 'A':
8775 // This is a "reference" to a va_list; however, what exactly
8776 // this means depends on how va_list is defined. There are two
8777 // different kinds of va_list: ones passed by value, and ones
8778 // passed by reference. An example of a by-value va_list is
8779 // x86, where va_list is a char*. An example of by-ref va_list
8780 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
8781 // we want this argument to be a char*&; for x86-64, we want
8782 // it to be a __va_list_tag*.
8783 Type = Context.getBuiltinVaListType();
8784 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008785 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00008786 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008787 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00008788 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008789 break;
8790 case 'V': {
8791 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008792 unsigned NumElements = strtoul(Str, &End, 10);
8793 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00008794 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00008795
Chandler Carruth45bbe012017-03-24 09:11:57 +00008796 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
8797 RequiresICE, false);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008798 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattnerdc226c22010-10-01 22:42:38 +00008799
8800 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00008801 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00008802 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008803 break;
8804 }
Douglas Gregorfed66992012-06-07 18:08:25 +00008805 case 'E': {
8806 char *End;
8807
8808 unsigned NumElements = strtoul(Str, &End, 10);
8809 assert(End != Str && "Missing vector size");
8810
8811 Str = End;
Chandler Carruth45bbe012017-03-24 09:11:57 +00008812
Douglas Gregorfed66992012-06-07 18:08:25 +00008813 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
Chandler Carruth45bbe012017-03-24 09:11:57 +00008814 false);
Douglas Gregorfed66992012-06-07 18:08:25 +00008815 Type = Context.getExtVectorType(ElementType, NumElements);
8816 break;
8817 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00008818 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008819 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
Chandler Carruth45bbe012017-03-24 09:11:57 +00008820 false);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008821 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00008822 Type = Context.getComplexType(ElementType);
8823 break;
Fariborz Jahanian73952fc2011-08-23 23:33:09 +00008824 }
8825 case 'Y' : {
8826 Type = Context.getPointerDiffType();
8827 break;
8828 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00008829 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00008830 Type = Context.getFILEType();
8831 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00008832 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008833 return QualType();
8834 }
Mike Stump2adb4da2009-07-28 23:47:15 +00008835 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00008836 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00008837 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00008838 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00008839 else
8840 Type = Context.getjmp_bufType();
8841
Mike Stump2adb4da2009-07-28 23:47:15 +00008842 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00008843 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00008844 return QualType();
8845 }
8846 break;
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00008847 case 'K':
8848 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
8849 Type = Context.getucontext_tType();
8850
8851 if (Type.isNull()) {
8852 Error = ASTContext::GE_Missing_ucontext;
8853 return QualType();
8854 }
8855 break;
Eli Friedman4e91899e2012-11-27 02:58:24 +00008856 case 'p':
8857 Type = Context.getProcessIDType();
8858 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00008859 }
Mike Stump11289f42009-09-09 15:08:12 +00008860
Chris Lattnerdc226c22010-10-01 22:42:38 +00008861 // If there are modifiers and if we're allowed to parse them, go for it.
8862 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008863 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00008864 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00008865 default: Done = true; --Str; break;
8866 case '*':
8867 case '&': {
8868 // Both pointers and references can have their pointee types
8869 // qualified with an address space.
8870 char *End;
8871 unsigned AddrSpace = strtoul(Str, &End, 10);
8872 if (End != Str && AddrSpace != 0) {
Alexander Richardson6d989432017-10-15 18:48:14 +00008873 Type = Context.getAddrSpaceQualType(Type,
8874 getLangASFromTargetAS(AddrSpace));
Chris Lattnerdc226c22010-10-01 22:42:38 +00008875 Str = End;
8876 }
8877 if (c == '*')
8878 Type = Context.getPointerType(Type);
8879 else
8880 Type = Context.getLValueReferenceType(Type);
8881 break;
8882 }
8883 // FIXME: There's no way to have a built-in with an rvalue ref arg.
8884 case 'C':
8885 Type = Type.withConst();
8886 break;
8887 case 'D':
8888 Type = Context.getVolatileType(Type);
8889 break;
Ted Kremenekf2a2f5f2012-01-20 21:40:12 +00008890 case 'R':
8891 Type = Type.withRestrict();
8892 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008893 }
8894 }
Chris Lattner84733392010-10-01 07:13:18 +00008895
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008896 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner84733392010-10-01 07:13:18 +00008897 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00008898
Chris Lattnerecd79c62009-06-14 00:45:47 +00008899 return Type;
8900}
8901
8902/// GetBuiltinType - Return the type for the specified builtin.
Chandler Carruth45bbe012017-03-24 09:11:57 +00008903QualType ASTContext::GetBuiltinType(unsigned Id,
8904 GetBuiltinTypeError &Error,
8905 unsigned *IntegerConstantArgs) const {
Eric Christopher02d5d862015-08-06 01:01:12 +00008906 const char *TypeStr = BuiltinInfo.getTypeString(Id);
Mike Stump11289f42009-09-09 15:08:12 +00008907
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008908 SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00008909
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008910 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008911 Error = GE_None;
Chandler Carruth45bbe012017-03-24 09:11:57 +00008912 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
8913 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008914 if (Error != GE_None)
8915 return QualType();
Chandler Carruth45bbe012017-03-24 09:11:57 +00008916
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008917 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
Chandler Carruth45bbe012017-03-24 09:11:57 +00008918
Chris Lattnerecd79c62009-06-14 00:45:47 +00008919 while (TypeStr[0] && TypeStr[0] != '.') {
Chandler Carruth45bbe012017-03-24 09:11:57 +00008920 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008921 if (Error != GE_None)
8922 return QualType();
8923
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008924 // If this argument is required to be an IntegerConstantExpression and the
8925 // caller cares, fill in the bitmask we return.
8926 if (RequiresICE && IntegerConstantArgs)
8927 *IntegerConstantArgs |= 1 << ArgTypes.size();
8928
Chris Lattnerecd79c62009-06-14 00:45:47 +00008929 // Do array -> pointer decay. The builtin should use the decayed type.
8930 if (Ty->isArrayType())
8931 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00008932
Chris Lattnerecd79c62009-06-14 00:45:47 +00008933 ArgTypes.push_back(Ty);
8934 }
8935
David Majnemerba3e5ec2015-03-13 18:26:17 +00008936 if (Id == Builtin::BI__GetExceptionInfo)
8937 return QualType();
8938
Chris Lattnerecd79c62009-06-14 00:45:47 +00008939 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
8940 "'.' should only occur at end of builtin type list!");
8941
Reid Kleckner78af0702013-08-27 23:08:25 +00008942 FunctionType::ExtInfo EI(CC_C);
John McCall991eb4b2010-12-21 00:44:39 +00008943 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
8944
8945 bool Variadic = (TypeStr[0] == '.');
8946
Richard Smith836de6b2016-12-19 23:59:34 +00008947 // We really shouldn't be making a no-proto type here.
8948 if (ArgTypes.empty() && Variadic && !getLangOpts().CPlusPlus)
John McCall991eb4b2010-12-21 00:44:39 +00008949 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00008950
John McCalldb40c7f2010-12-14 08:05:40 +00008951 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00008952 EPI.ExtInfo = EI;
8953 EPI.Variadic = Variadic;
Richard Smith391fb862016-10-18 07:13:55 +00008954 if (getLangOpts().CPlusPlus && BuiltinInfo.isNoThrow(Id))
8955 EPI.ExceptionSpec.Type =
8956 getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone;
John McCalldb40c7f2010-12-14 08:05:40 +00008957
Jordan Rose5c382722013-03-08 21:51:21 +00008958 return getFunctionType(ResType, ArgTypes, EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008959}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00008960
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008961static GVALinkage basicGVALinkageForFunction(const ASTContext &Context,
8962 const FunctionDecl *FD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00008963 if (!FD->isExternallyVisible())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008964 return GVA_Internal;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008965
Yaron Keren4cd211b2017-02-22 14:32:39 +00008966 GVALinkage External;
Rafael Espindola3ae00052013-05-13 00:12:11 +00008967 switch (FD->getTemplateSpecializationKind()) {
8968 case TSK_Undeclared:
8969 case TSK_ExplicitSpecialization:
8970 External = GVA_StrongExternal;
8971 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008972
Rafael Espindola3ae00052013-05-13 00:12:11 +00008973 case TSK_ExplicitInstantiationDefinition:
David Majnemer54e3ba52014-04-02 23:17:29 +00008974 return GVA_StrongODR;
Rafael Espindola3ae00052013-05-13 00:12:11 +00008975
David Majnemerc3d07332014-05-15 06:25:57 +00008976 // C++11 [temp.explicit]p10:
8977 // [ Note: The intent is that an inline function that is the subject of
8978 // an explicit instantiation declaration will still be implicitly
8979 // instantiated when used so that the body can be considered for
8980 // inlining, but that no out-of-line copy of the inline function would be
8981 // generated in the translation unit. -- end note ]
Rafael Espindola3ae00052013-05-13 00:12:11 +00008982 case TSK_ExplicitInstantiationDeclaration:
David Majnemer27d69db2014-04-28 22:17:59 +00008983 return GVA_AvailableExternally;
8984
Rafael Espindola3ae00052013-05-13 00:12:11 +00008985 case TSK_ImplicitInstantiation:
David Majnemer27d69db2014-04-28 22:17:59 +00008986 External = GVA_DiscardableODR;
Rafael Espindola3ae00052013-05-13 00:12:11 +00008987 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008988 }
8989
8990 if (!FD->isInlined())
8991 return External;
David Majnemer62f0ffd2013-08-01 17:26:42 +00008992
David Majnemer3f021502015-10-08 04:53:31 +00008993 if ((!Context.getLangOpts().CPlusPlus &&
8994 !Context.getTargetInfo().getCXXABI().isMicrosoft() &&
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008995 !FD->hasAttr<DLLExportAttr>()) ||
David Majnemer62f0ffd2013-08-01 17:26:42 +00008996 FD->hasAttr<GNUInlineAttr>()) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008997 // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
8998
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008999 // GNU or C99 inline semantics. Determine whether this symbol should be
9000 // externally visible.
9001 if (FD->isInlineDefinitionExternallyVisible())
9002 return External;
9003
9004 // C99 inline semantics, where the symbol is not externally visible.
David Majnemer27d69db2014-04-28 22:17:59 +00009005 return GVA_AvailableExternally;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009006 }
9007
David Majnemer54e3ba52014-04-02 23:17:29 +00009008 // Functions specified with extern and inline in -fms-compatibility mode
9009 // forcibly get emitted. While the body of the function cannot be later
9010 // replaced, the function definition cannot be discarded.
David Majnemer73768702015-03-20 00:02:27 +00009011 if (FD->isMSExternInline())
David Majnemer54e3ba52014-04-02 23:17:29 +00009012 return GVA_StrongODR;
9013
David Majnemer27d69db2014-04-28 22:17:59 +00009014 return GVA_DiscardableODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009015}
9016
Artem Belevichca2b9512016-05-02 20:30:03 +00009017static GVALinkage adjustGVALinkageForAttributes(const ASTContext &Context,
Richard Smitha4653622017-09-06 20:01:14 +00009018 const Decl *D, GVALinkage L) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009019 // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
9020 // dllexport/dllimport on inline functions.
9021 if (D->hasAttr<DLLImportAttr>()) {
9022 if (L == GVA_DiscardableODR || L == GVA_StrongODR)
9023 return GVA_AvailableExternally;
Artem Belevichca2b9512016-05-02 20:30:03 +00009024 } else if (D->hasAttr<DLLExportAttr>()) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009025 if (L == GVA_DiscardableODR)
9026 return GVA_StrongODR;
Artem Belevichca2b9512016-05-02 20:30:03 +00009027 } else if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice &&
9028 D->hasAttr<CUDAGlobalAttr>()) {
9029 // Device-side functions with __global__ attribute must always be
9030 // visible externally so they can be launched from host.
9031 if (L == GVA_DiscardableODR || L == GVA_Internal)
9032 return GVA_StrongODR;
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009033 }
9034 return L;
9035}
9036
Richard Smitha4653622017-09-06 20:01:14 +00009037/// Adjust the GVALinkage for a declaration based on what an external AST source
9038/// knows about whether there can be other definitions of this declaration.
9039static GVALinkage
9040adjustGVALinkageForExternalDefinitionKind(const ASTContext &Ctx, const Decl *D,
9041 GVALinkage L) {
9042 ExternalASTSource *Source = Ctx.getExternalSource();
9043 if (!Source)
9044 return L;
9045
9046 switch (Source->hasExternalDefinitions(D)) {
David Blaikie9ffe5a32017-01-30 05:00:26 +00009047 case ExternalASTSource::EK_Never:
Richard Smitha4653622017-09-06 20:01:14 +00009048 // Other translation units rely on us to provide the definition.
David Blaikie9ffe5a32017-01-30 05:00:26 +00009049 if (L == GVA_DiscardableODR)
9050 return GVA_StrongODR;
9051 break;
Richard Smitha4653622017-09-06 20:01:14 +00009052
David Blaikie9ffe5a32017-01-30 05:00:26 +00009053 case ExternalASTSource::EK_Always:
9054 return GVA_AvailableExternally;
Richard Smitha4653622017-09-06 20:01:14 +00009055
David Blaikie9ffe5a32017-01-30 05:00:26 +00009056 case ExternalASTSource::EK_ReplyHazy:
9057 break;
9058 }
9059 return L;
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009060}
9061
Richard Smitha4653622017-09-06 20:01:14 +00009062GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) const {
9063 return adjustGVALinkageForExternalDefinitionKind(*this, FD,
9064 adjustGVALinkageForAttributes(*this, FD,
9065 basicGVALinkageForFunction(*this, FD)));
9066}
9067
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009068static GVALinkage basicGVALinkageForVariable(const ASTContext &Context,
9069 const VarDecl *VD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00009070 if (!VD->isExternallyVisible())
9071 return GVA_Internal;
9072
David Majnemer27d69db2014-04-28 22:17:59 +00009073 if (VD->isStaticLocal()) {
David Majnemer27d69db2014-04-28 22:17:59 +00009074 const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
9075 while (LexicalContext && !isa<FunctionDecl>(LexicalContext))
9076 LexicalContext = LexicalContext->getLexicalParent();
9077
David Blaikieeb210012017-01-27 23:11:10 +00009078 // ObjC Blocks can create local variables that don't have a FunctionDecl
9079 // LexicalContext.
9080 if (!LexicalContext)
9081 return GVA_DiscardableODR;
David Majnemer27d69db2014-04-28 22:17:59 +00009082
David Blaikieeb210012017-01-27 23:11:10 +00009083 // Otherwise, let the static local variable inherit its linkage from the
9084 // nearest enclosing function.
9085 auto StaticLocalLinkage =
9086 Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext));
9087
9088 // Itanium ABI 5.2.2: "Each COMDAT group [for a static local variable] must
9089 // be emitted in any object with references to the symbol for the object it
9090 // contains, whether inline or out-of-line."
9091 // Similar behavior is observed with MSVC. An alternative ABI could use
9092 // StrongODR/AvailableExternally to match the function, but none are
9093 // known/supported currently.
9094 if (StaticLocalLinkage == GVA_StrongODR ||
9095 StaticLocalLinkage == GVA_AvailableExternally)
9096 return GVA_DiscardableODR;
9097 return StaticLocalLinkage;
David Majnemer27d69db2014-04-28 22:17:59 +00009098 }
9099
Hans Wennborg56fc62b2014-07-17 20:25:23 +00009100 // MSVC treats in-class initialized static data members as definitions.
9101 // By giving them non-strong linkage, out-of-line definitions won't
9102 // cause link errors.
9103 if (Context.isMSStaticDataMemberInlineDefinition(VD))
9104 return GVA_DiscardableODR;
9105
Richard Smithd9b90092016-07-02 01:32:16 +00009106 // Most non-template variables have strong linkage; inline variables are
9107 // linkonce_odr or (occasionally, for compatibility) weak_odr.
9108 GVALinkage StrongLinkage;
9109 switch (Context.getInlineVariableDefinitionKind(VD)) {
9110 case ASTContext::InlineVariableDefinitionKind::None:
9111 StrongLinkage = GVA_StrongExternal;
9112 break;
9113 case ASTContext::InlineVariableDefinitionKind::Weak:
9114 case ASTContext::InlineVariableDefinitionKind::WeakUnknown:
Richard Smith62f19e72016-06-25 00:15:56 +00009115 StrongLinkage = GVA_DiscardableODR;
Richard Smithd9b90092016-07-02 01:32:16 +00009116 break;
9117 case ASTContext::InlineVariableDefinitionKind::Strong:
9118 StrongLinkage = GVA_StrongODR;
9119 break;
9120 }
Richard Smith62f19e72016-06-25 00:15:56 +00009121
Richard Smith8809a0c2013-09-27 20:14:12 +00009122 switch (VD->getTemplateSpecializationKind()) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00009123 case TSK_Undeclared:
Richard Smith62f19e72016-06-25 00:15:56 +00009124 return StrongLinkage;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009125
David Majnemer6d1780c2015-07-17 23:36:49 +00009126 case TSK_ExplicitSpecialization:
David Majnemer3f021502015-10-08 04:53:31 +00009127 return Context.getTargetInfo().getCXXABI().isMicrosoft() &&
9128 VD->isStaticDataMember()
David Majnemer6d1780c2015-07-17 23:36:49 +00009129 ? GVA_StrongODR
Richard Smith62f19e72016-06-25 00:15:56 +00009130 : StrongLinkage;
David Majnemer6d1780c2015-07-17 23:36:49 +00009131
Rafael Espindola3ae00052013-05-13 00:12:11 +00009132 case TSK_ExplicitInstantiationDefinition:
David Majnemer54e3ba52014-04-02 23:17:29 +00009133 return GVA_StrongODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009134
David Majnemer27d69db2014-04-28 22:17:59 +00009135 case TSK_ExplicitInstantiationDeclaration:
9136 return GVA_AvailableExternally;
9137
Rafael Espindola3ae00052013-05-13 00:12:11 +00009138 case TSK_ImplicitInstantiation:
David Majnemer27d69db2014-04-28 22:17:59 +00009139 return GVA_DiscardableODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009140 }
Rafael Espindola27699c82013-05-13 14:05:53 +00009141
9142 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009143}
9144
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009145GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
Richard Smitha4653622017-09-06 20:01:14 +00009146 return adjustGVALinkageForExternalDefinitionKind(*this, VD,
9147 adjustGVALinkageForAttributes(*this, VD,
9148 basicGVALinkageForVariable(*this, VD)));
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009149}
9150
David Blaikiee6b7c282017-04-11 20:46:34 +00009151bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009152 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
9153 if (!VD->isFileVarDecl())
9154 return false;
Renato Golin9258aa52014-05-21 10:40:27 +00009155 // Global named register variables (GNU extension) are never emitted.
9156 if (VD->getStorageClass() == SC_Register)
9157 return false;
Richard Smith7747ce22015-08-19 20:49:38 +00009158 if (VD->getDescribedVarTemplate() ||
9159 isa<VarTemplatePartialSpecializationDecl>(VD))
9160 return false;
Richard Smith5205a8c2013-04-01 20:22:16 +00009161 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
9162 // We never need to emit an uninstantiated function template.
9163 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
9164 return false;
Nico Weber66220292016-03-02 17:28:48 +00009165 } else if (isa<PragmaCommentDecl>(D))
9166 return true;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00009167 else if (isa<OMPThreadPrivateDecl>(D) ||
9168 D->hasAttr<OMPDeclareTargetDeclAttr>())
9169 return true;
Nico Webercbbaeb12016-03-02 19:28:54 +00009170 else if (isa<PragmaDetectMismatchDecl>(D))
9171 return true;
Nico Weber66220292016-03-02 17:28:48 +00009172 else if (isa<OMPThreadPrivateDecl>(D))
Alexey Bataevc5b1d322016-03-04 09:22:22 +00009173 return !D->getDeclContext()->isDependentContext();
9174 else if (isa<OMPDeclareReductionDecl>(D))
9175 return !D->getDeclContext()->isDependentContext();
Richard Smithdc1f0422016-07-20 19:10:16 +00009176 else if (isa<ImportDecl>(D))
9177 return true;
Alexey Bataev97720002014-11-11 04:05:39 +00009178 else
Richard Smith5205a8c2013-04-01 20:22:16 +00009179 return false;
9180
9181 // If this is a member of a class template, we do not need to emit it.
9182 if (D->getDeclContext()->isDependentContext())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009183 return false;
9184
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00009185 // Weak references don't produce any output by themselves.
9186 if (D->hasAttr<WeakRefAttr>())
9187 return false;
9188
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009189 // Aliases and used decls are required.
9190 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
9191 return true;
9192
9193 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
9194 // Forward declarations aren't required.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00009195 if (!FD->doesThisDeclarationHaveABody())
Nick Lewycky26da4dd2011-07-18 05:26:13 +00009196 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009197
9198 // Constructors and destructors are required.
9199 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
9200 return true;
9201
John McCall6bd2a892013-01-25 22:31:03 +00009202 // The key function for a class is required. This rule only comes
9203 // into play when inline functions can be key functions, though.
9204 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
9205 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
9206 const CXXRecordDecl *RD = MD->getParent();
9207 if (MD->isOutOfLine() && RD->isDynamicClass()) {
9208 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
9209 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
9210 return true;
9211 }
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009212 }
9213 }
9214
David Blaikie9ffe5a32017-01-30 05:00:26 +00009215 GVALinkage Linkage = GetGVALinkageForFunction(FD);
9216
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009217 // static, static inline, always_inline, and extern inline functions can
9218 // always be deferred. Normal inline functions can be deferred in C99/C++.
9219 // Implicit template instantiations can also be deferred in C++.
David Blaikie9ffe5a32017-01-30 05:00:26 +00009220 return !isDiscardableGVALinkage(Linkage);
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009221 }
Douglas Gregor87d81242011-09-10 00:22:34 +00009222
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009223 const VarDecl *VD = cast<VarDecl>(D);
9224 assert(VD->isFileVarDecl() && "Expected file scoped var");
9225
Hans Wennborg56fc62b2014-07-17 20:25:23 +00009226 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
9227 !isMSStaticDataMemberInlineDefinition(VD))
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00009228 return false;
9229
Richard Smitha0e5e542012-11-12 21:38:00 +00009230 // Variables that can be needed in other TUs are required.
Richard Smitha4653622017-09-06 20:01:14 +00009231 auto Linkage = GetGVALinkageForVariable(VD);
9232 if (!isDiscardableGVALinkage(Linkage))
Richard Smitha0e5e542012-11-12 21:38:00 +00009233 return true;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009234
Richard Smitha4653622017-09-06 20:01:14 +00009235 // We never need to emit a variable that is available in another TU.
9236 if (Linkage == GVA_AvailableExternally)
9237 return false;
9238
Richard Smitha0e5e542012-11-12 21:38:00 +00009239 // Variables that have destruction with side-effects are required.
9240 if (VD->getType().isDestructedType())
9241 return true;
9242
9243 // Variables that have initialization with side-effects are required.
Richard Smith7747ce22015-08-19 20:49:38 +00009244 if (VD->getInit() && VD->getInit()->HasSideEffects(*this) &&
Richard Smith187ffb42017-01-20 01:19:46 +00009245 // We can get a value-dependent initializer during error recovery.
9246 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
Richard Smitha0e5e542012-11-12 21:38:00 +00009247 return true;
9248
Richard Smithda383632016-08-15 01:33:41 +00009249 // Likewise, variables with tuple-like bindings are required if their
9250 // bindings have side-effects.
9251 if (auto *DD = dyn_cast<DecompositionDecl>(VD))
9252 for (auto *BD : DD->bindings())
9253 if (auto *BindingVD = BD->getHoldingVar())
9254 if (DeclMustBeEmitted(BindingVD))
9255 return true;
9256
Richard Smitha0e5e542012-11-12 21:38:00 +00009257 return false;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009258}
Charles Davis53c59df2010-08-16 03:33:14 +00009259
Reid Kleckner78af0702013-08-27 23:08:25 +00009260CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic,
9261 bool IsCXXMethod) const {
Charles Davis99202b32010-11-09 18:04:24 +00009262 // Pass through to the C++ ABI object
Reid Kleckner78af0702013-08-27 23:08:25 +00009263 if (IsCXXMethod)
9264 return ABI->getDefaultMethodCallConv(IsVariadic);
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +00009265
Alexey Bataeva7547182016-05-18 09:06:38 +00009266 switch (LangOpts.getDefaultCallingConv()) {
9267 case LangOptions::DCC_None:
9268 break;
9269 case LangOptions::DCC_CDecl:
9270 return CC_C;
9271 case LangOptions::DCC_FastCall:
9272 if (getTargetInfo().hasFeature("sse2"))
9273 return CC_X86FastCall;
9274 break;
9275 case LangOptions::DCC_StdCall:
9276 if (!IsVariadic)
9277 return CC_X86StdCall;
9278 break;
9279 case LangOptions::DCC_VectorCall:
9280 // __vectorcall cannot be applied to variadic functions.
9281 if (!IsVariadic)
9282 return CC_X86VectorCall;
9283 break;
9284 }
Alexander Kornienko21de0ae2015-01-20 11:20:41 +00009285 return Target->getDefaultCallingConv(TargetInfo::CCMT_Unknown);
Charles Davis99202b32010-11-09 18:04:24 +00009286}
9287
Jay Foad39c79802011-01-12 09:06:06 +00009288bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +00009289 // Pass through to the C++ ABI object
9290 return ABI->isNearlyEmpty(RD);
9291}
9292
Reid Kleckner96f8f932014-02-05 17:27:08 +00009293VTableContextBase *ASTContext::getVTableContext() {
9294 if (!VTContext.get()) {
9295 if (Target->getCXXABI().isMicrosoft())
9296 VTContext.reset(new MicrosoftVTableContext(*this));
9297 else
9298 VTContext.reset(new ItaniumVTableContext(*this));
9299 }
9300 return VTContext.get();
9301}
9302
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00009303MangleContext *ASTContext::createMangleContext() {
John McCall359b8852013-01-25 22:30:49 +00009304 switch (Target->getCXXABI().getKind()) {
Tim Northover9bb857a2013-01-31 12:13:10 +00009305 case TargetCXXABI::GenericAArch64:
John McCall359b8852013-01-25 22:30:49 +00009306 case TargetCXXABI::GenericItanium:
9307 case TargetCXXABI::GenericARM:
Zoran Jovanovic26a12162015-02-18 15:21:35 +00009308 case TargetCXXABI::GenericMIPS:
John McCall359b8852013-01-25 22:30:49 +00009309 case TargetCXXABI::iOS:
Tim Northovera2ee4332014-03-29 15:09:45 +00009310 case TargetCXXABI::iOS64:
Dan Gohmanc2853072015-09-03 22:51:53 +00009311 case TargetCXXABI::WebAssembly:
Tim Northover756447a2015-10-30 16:30:36 +00009312 case TargetCXXABI::WatchOS:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00009313 return ItaniumMangleContext::create(*this, getDiagnostics());
John McCall359b8852013-01-25 22:30:49 +00009314 case TargetCXXABI::Microsoft:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00009315 return MicrosoftMangleContext::create(*this, getDiagnostics());
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00009316 }
David Blaikie83d382b2011-09-23 05:06:16 +00009317 llvm_unreachable("Unsupported ABI");
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00009318}
9319
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +00009320CXXABI::~CXXABI() {}
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00009321
9322size_t ASTContext::getSideTableAllocatedMemory() const {
Larisse Voufo39a1e502013-08-06 01:03:05 +00009323 return ASTRecordLayouts.getMemorySize() +
9324 llvm::capacity_in_bytes(ObjCLayouts) +
9325 llvm::capacity_in_bytes(KeyFunctions) +
9326 llvm::capacity_in_bytes(ObjCImpls) +
9327 llvm::capacity_in_bytes(BlockVarCopyInits) +
9328 llvm::capacity_in_bytes(DeclAttrs) +
9329 llvm::capacity_in_bytes(TemplateOrInstantiation) +
9330 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
9331 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
9332 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
9333 llvm::capacity_in_bytes(OverriddenMethods) +
9334 llvm::capacity_in_bytes(Types) +
9335 llvm::capacity_in_bytes(VariableArrayTypes) +
9336 llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00009337}
Ted Kremenek540017e2011-10-06 05:00:56 +00009338
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00009339/// getIntTypeForBitwidth -
9340/// sets integer QualTy according to specified details:
9341/// bitwidth, signed/unsigned.
9342/// Returns empty type if there is no appropriate target types.
9343QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth,
9344 unsigned Signed) const {
9345 TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed);
9346 CanQualType QualTy = getFromTargetType(Ty);
9347 if (!QualTy && DestWidth == 128)
9348 return Signed ? Int128Ty : UnsignedInt128Ty;
9349 return QualTy;
9350}
9351
9352/// getRealTypeForBitwidth -
9353/// sets floating point QualTy according to specified bitwidth.
9354/// Returns empty type if there is no appropriate target types.
9355QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth) const {
9356 TargetInfo::RealType Ty = getTargetInfo().getRealTypeByWidth(DestWidth);
9357 switch (Ty) {
9358 case TargetInfo::Float:
9359 return FloatTy;
9360 case TargetInfo::Double:
9361 return DoubleTy;
9362 case TargetInfo::LongDouble:
9363 return LongDoubleTy;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00009364 case TargetInfo::Float128:
9365 return Float128Ty;
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00009366 case TargetInfo::NoFloat:
9367 return QualType();
9368 }
9369
9370 llvm_unreachable("Unhandled TargetInfo::RealType value");
9371}
9372
Eli Friedman3b7d46c2013-07-10 00:30:46 +00009373void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
9374 if (Number > 1)
9375 MangleNumbers[ND] = Number;
David Blaikie095deba2012-11-14 01:52:05 +00009376}
9377
Eli Friedman3b7d46c2013-07-10 00:30:46 +00009378unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const {
Richard Smithe9b02d62016-03-21 22:33:02 +00009379 auto I = MangleNumbers.find(ND);
Eli Friedman3b7d46c2013-07-10 00:30:46 +00009380 return I != MangleNumbers.end() ? I->second : 1;
David Blaikie095deba2012-11-14 01:52:05 +00009381}
9382
David Majnemer2206bf52014-03-05 08:57:59 +00009383void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
9384 if (Number > 1)
9385 StaticLocalNumbers[VD] = Number;
9386}
9387
9388unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const {
Richard Smithe9b02d62016-03-21 22:33:02 +00009389 auto I = StaticLocalNumbers.find(VD);
David Majnemer2206bf52014-03-05 08:57:59 +00009390 return I != StaticLocalNumbers.end() ? I->second : 1;
9391}
9392
Eli Friedman3b7d46c2013-07-10 00:30:46 +00009393MangleNumberingContext &
9394ASTContext::getManglingNumberContext(const DeclContext *DC) {
Reid Klecknerd8110b62013-09-10 20:14:30 +00009395 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
Justin Lebar20ebffc2016-10-10 16:26:19 +00009396 std::unique_ptr<MangleNumberingContext> &MCtx = MangleNumberingContexts[DC];
Reid Klecknerd8110b62013-09-10 20:14:30 +00009397 if (!MCtx)
9398 MCtx = createMangleNumberingContext();
9399 return *MCtx;
9400}
9401
Justin Lebar20ebffc2016-10-10 16:26:19 +00009402std::unique_ptr<MangleNumberingContext>
9403ASTContext::createMangleNumberingContext() const {
Reid Klecknerd8110b62013-09-10 20:14:30 +00009404 return ABI->createMangleNumberingContext();
Douglas Gregor63798542012-02-20 19:44:39 +00009405}
9406
David Majnemere7a818f2015-03-06 18:53:55 +00009407const CXXConstructorDecl *
9408ASTContext::getCopyConstructorForExceptionObject(CXXRecordDecl *RD) {
9409 return ABI->getCopyConstructorForExceptionObject(
9410 cast<CXXRecordDecl>(RD->getFirstDecl()));
9411}
9412
9413void ASTContext::addCopyConstructorForExceptionObject(CXXRecordDecl *RD,
9414 CXXConstructorDecl *CD) {
9415 return ABI->addCopyConstructorForExceptionObject(
9416 cast<CXXRecordDecl>(RD->getFirstDecl()),
9417 cast<CXXConstructorDecl>(CD->getFirstDecl()));
9418}
9419
David Majnemer00350522015-08-31 18:48:39 +00009420void ASTContext::addTypedefNameForUnnamedTagDecl(TagDecl *TD,
9421 TypedefNameDecl *DD) {
9422 return ABI->addTypedefNameForUnnamedTagDecl(TD, DD);
9423}
9424
9425TypedefNameDecl *
9426ASTContext::getTypedefNameForUnnamedTagDecl(const TagDecl *TD) {
9427 return ABI->getTypedefNameForUnnamedTagDecl(TD);
9428}
9429
9430void ASTContext::addDeclaratorForUnnamedTagDecl(TagDecl *TD,
9431 DeclaratorDecl *DD) {
9432 return ABI->addDeclaratorForUnnamedTagDecl(TD, DD);
9433}
9434
9435DeclaratorDecl *ASTContext::getDeclaratorForUnnamedTagDecl(const TagDecl *TD) {
9436 return ABI->getDeclaratorForUnnamedTagDecl(TD);
9437}
9438
Ted Kremenek540017e2011-10-06 05:00:56 +00009439void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
9440 ParamIndices[D] = index;
9441}
9442
9443unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
9444 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
9445 assert(I != ParamIndices.end() &&
9446 "ParmIndices lacks entry set by ParmVarDecl");
9447 return I->second;
9448}
Fariborz Jahanian615de762013-05-28 17:37:39 +00009449
Richard Smithe6c01442013-06-05 00:46:14 +00009450APValue *
9451ASTContext::getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E,
9452 bool MayCreate) {
9453 assert(E && E->getStorageDuration() == SD_Static &&
9454 "don't need to cache the computed value for this temporary");
David Majnemer2dcef9e2015-08-13 23:50:15 +00009455 if (MayCreate) {
9456 APValue *&MTVI = MaterializedTemporaryValues[E];
9457 if (!MTVI)
9458 MTVI = new (*this) APValue;
9459 return MTVI;
9460 }
Richard Smithe6c01442013-06-05 00:46:14 +00009461
David Majnemer2dcef9e2015-08-13 23:50:15 +00009462 return MaterializedTemporaryValues.lookup(E);
Richard Smithe6c01442013-06-05 00:46:14 +00009463}
9464
Fariborz Jahanian615de762013-05-28 17:37:39 +00009465bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
9466 const llvm::Triple &T = getTargetInfo().getTriple();
9467 if (!T.isOSDarwin())
9468 return false;
9469
Bob Wilson2c82c3d2013-11-02 23:27:49 +00009470 if (!(T.isiOS() && T.isOSVersionLT(7)) &&
9471 !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
9472 return false;
9473
Fariborz Jahanian615de762013-05-28 17:37:39 +00009474 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
9475 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
9476 uint64_t Size = sizeChars.getQuantity();
9477 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
9478 unsigned Align = alignChars.getQuantity();
9479 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
9480 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
9481}
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009482
9483namespace {
9484
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009485ast_type_traits::DynTypedNode getSingleDynTypedNodeFromParentMap(
9486 ASTContext::ParentMapPointers::mapped_type U) {
Benjamin Kramerfbfa7a12015-10-22 11:26:35 +00009487 if (const auto *D = U.dyn_cast<const Decl *>())
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009488 return ast_type_traits::DynTypedNode::create(*D);
Benjamin Kramerfbfa7a12015-10-22 11:26:35 +00009489 if (const auto *S = U.dyn_cast<const Stmt *>())
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009490 return ast_type_traits::DynTypedNode::create(*S);
Benjamin Kramerfbfa7a12015-10-22 11:26:35 +00009491 return *U.get<ast_type_traits::DynTypedNode *>();
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009492}
9493
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009494/// Template specializations to abstract away from pointers and TypeLocs.
9495/// @{
9496template <typename T>
9497ast_type_traits::DynTypedNode createDynTypedNode(const T &Node) {
9498 return ast_type_traits::DynTypedNode::create(*Node);
9499}
9500template <>
9501ast_type_traits::DynTypedNode createDynTypedNode(const TypeLoc &Node) {
9502 return ast_type_traits::DynTypedNode::create(Node);
9503}
9504template <>
9505ast_type_traits::DynTypedNode
9506createDynTypedNode(const NestedNameSpecifierLoc &Node) {
9507 return ast_type_traits::DynTypedNode::create(Node);
9508}
9509/// @}
9510
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009511 /// \brief A \c RecursiveASTVisitor that builds a map from nodes to their
9512 /// parents as defined by the \c RecursiveASTVisitor.
9513 ///
9514 /// Note that the relationship described here is purely in terms of AST
9515 /// traversal - there are other relationships (for example declaration context)
9516 /// in the AST that are better modeled by special matchers.
9517 ///
Benjamin Kramere8c51fd2015-10-21 10:07:26 +00009518 /// FIXME: Currently only builds up the map using \c Stmt and \c Decl nodes.
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009519 class ParentMapASTVisitor : public RecursiveASTVisitor<ParentMapASTVisitor> {
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009520 public:
9521 /// \brief Builds and returns the translation unit's parent map.
9522 ///
9523 /// The caller takes ownership of the returned \c ParentMap.
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009524 static std::pair<ASTContext::ParentMapPointers *,
9525 ASTContext::ParentMapOtherNodes *>
9526 buildMap(TranslationUnitDecl &TU) {
9527 ParentMapASTVisitor Visitor(new ASTContext::ParentMapPointers,
9528 new ASTContext::ParentMapOtherNodes);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009529 Visitor.TraverseDecl(&TU);
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009530 return std::make_pair(Visitor.Parents, Visitor.OtherParents);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009531 }
9532
9533 private:
9534 typedef RecursiveASTVisitor<ParentMapASTVisitor> VisitorBase;
9535
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009536 ParentMapASTVisitor(ASTContext::ParentMapPointers *Parents,
9537 ASTContext::ParentMapOtherNodes *OtherParents)
9538 : Parents(Parents), OtherParents(OtherParents) {}
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009539
9540 bool shouldVisitTemplateInstantiations() const {
9541 return true;
9542 }
9543 bool shouldVisitImplicitCode() const {
9544 return true;
9545 }
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009546
Richard Smith85838722015-11-24 03:09:01 +00009547 template <typename T, typename MapNodeTy, typename BaseTraverseFn,
9548 typename MapTy>
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009549 bool TraverseNode(T Node, MapNodeTy MapNode,
Richard Smith85838722015-11-24 03:09:01 +00009550 BaseTraverseFn BaseTraverse, MapTy *Parents) {
Craig Topper36250ad2014-05-12 05:36:57 +00009551 if (!Node)
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009552 return true;
Manuel Klimek95403e62014-05-21 13:28:59 +00009553 if (ParentStack.size() > 0) {
Benjamin Kramere8c51fd2015-10-21 10:07:26 +00009554 // FIXME: Currently we add the same parent multiple times, but only
9555 // when no memoization data is available for the type.
9556 // For example when we visit all subexpressions of template
9557 // instantiations; this is suboptimal, but benign: the only way to
9558 // visit those is with hasAncestor / hasParent, and those do not create
9559 // new matches.
9560 // The plan is to enable DynTypedNode to be storable in a map or hash
9561 // map. The main problem there is to implement hash functions /
9562 // comparison operators for all types that DynTypedNode supports that
9563 // do not have pointer identity.
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009564 auto &NodeOrVector = (*Parents)[MapNode];
Manuel Klimek95403e62014-05-21 13:28:59 +00009565 if (NodeOrVector.isNull()) {
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009566 if (const auto *D = ParentStack.back().get<Decl>())
9567 NodeOrVector = D;
9568 else if (const auto *S = ParentStack.back().get<Stmt>())
9569 NodeOrVector = S;
9570 else
9571 NodeOrVector =
9572 new ast_type_traits::DynTypedNode(ParentStack.back());
Manuel Klimek95403e62014-05-21 13:28:59 +00009573 } else {
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009574 if (!NodeOrVector.template is<ASTContext::ParentVector *>()) {
9575 auto *Vector = new ASTContext::ParentVector(
9576 1, getSingleDynTypedNodeFromParentMap(NodeOrVector));
Gabor Horvath10a837a2017-04-19 15:11:10 +00009577 delete NodeOrVector
9578 .template dyn_cast<ast_type_traits::DynTypedNode *>();
Benjamin Kramer422b3ff2015-10-23 13:24:18 +00009579 NodeOrVector = Vector;
Samuel Benzaquen3ca0a7b2014-06-13 13:31:40 +00009580 }
Samuel Benzaquen3ca0a7b2014-06-13 13:31:40 +00009581
9582 auto *Vector =
9583 NodeOrVector.template get<ASTContext::ParentVector *>();
9584 // Skip duplicates for types that have memoization data.
9585 // We must check that the type has memoization data before calling
9586 // std::find() because DynTypedNode::operator== can't compare all
9587 // types.
9588 bool Found = ParentStack.back().getMemoizationData() &&
9589 std::find(Vector->begin(), Vector->end(),
9590 ParentStack.back()) != Vector->end();
9591 if (!Found)
9592 Vector->push_back(ParentStack.back());
Manuel Klimek95403e62014-05-21 13:28:59 +00009593 }
9594 }
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009595 ParentStack.push_back(createDynTypedNode(Node));
Richard Smith85838722015-11-24 03:09:01 +00009596 bool Result = BaseTraverse();
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009597 ParentStack.pop_back();
9598 return Result;
9599 }
9600
9601 bool TraverseDecl(Decl *DeclNode) {
Richard Smith85838722015-11-24 03:09:01 +00009602 return TraverseNode(DeclNode, DeclNode,
9603 [&] { return VisitorBase::TraverseDecl(DeclNode); },
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009604 Parents);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009605 }
9606
9607 bool TraverseStmt(Stmt *StmtNode) {
Richard Smith85838722015-11-24 03:09:01 +00009608 return TraverseNode(StmtNode, StmtNode,
9609 [&] { return VisitorBase::TraverseStmt(StmtNode); },
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009610 Parents);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009611 }
9612
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009613 bool TraverseTypeLoc(TypeLoc TypeLocNode) {
Richard Smith85838722015-11-24 03:09:01 +00009614 return TraverseNode(
9615 TypeLocNode, ast_type_traits::DynTypedNode::create(TypeLocNode),
9616 [&] { return VisitorBase::TraverseTypeLoc(TypeLocNode); },
9617 OtherParents);
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009618 }
9619
9620 bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNSLocNode) {
9621 return TraverseNode(
9622 NNSLocNode, ast_type_traits::DynTypedNode::create(NNSLocNode),
Richard Smith85838722015-11-24 03:09:01 +00009623 [&] {
9624 return VisitorBase::TraverseNestedNameSpecifierLoc(NNSLocNode);
9625 },
9626 OtherParents);
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009627 }
9628
9629 ASTContext::ParentMapPointers *Parents;
9630 ASTContext::ParentMapOtherNodes *OtherParents;
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009631 llvm::SmallVector<ast_type_traits::DynTypedNode, 16> ParentStack;
9632
9633 friend class RecursiveASTVisitor<ParentMapASTVisitor>;
9634 };
9635
Eugene Zelenkod4304d22015-11-04 21:37:17 +00009636} // anonymous namespace
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009637
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009638template <typename NodeTy, typename MapTy>
9639static ASTContext::DynTypedNodeList getDynNodeFromMap(const NodeTy &Node,
9640 const MapTy &Map) {
9641 auto I = Map.find(Node);
9642 if (I == Map.end()) {
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009643 return llvm::ArrayRef<ast_type_traits::DynTypedNode>();
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009644 }
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009645 if (auto *V = I->second.template dyn_cast<ASTContext::ParentVector *>()) {
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009646 return llvm::makeArrayRef(*V);
Manuel Klimek95403e62014-05-21 13:28:59 +00009647 }
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009648 return getSingleDynTypedNodeFromParentMap(I->second);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009649}
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00009650
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009651ASTContext::DynTypedNodeList
9652ASTContext::getParents(const ast_type_traits::DynTypedNode &Node) {
9653 if (!PointerParents) {
9654 // We always need to run over the whole translation unit, as
9655 // hasAncestor can escape any subtree.
9656 auto Maps = ParentMapASTVisitor::buildMap(*getTranslationUnitDecl());
9657 PointerParents.reset(Maps.first);
9658 OtherParents.reset(Maps.second);
9659 }
9660 if (Node.getNodeKind().hasPointerIdentity())
9661 return getDynNodeFromMap(Node.getMemoizationData(), *PointerParents);
9662 return getDynNodeFromMap(Node, *OtherParents);
9663}
9664
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00009665bool
9666ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
9667 const ObjCMethodDecl *MethodImpl) {
9668 // No point trying to match an unavailable/deprecated mothod.
9669 if (MethodDecl->hasAttr<UnavailableAttr>()
9670 || MethodDecl->hasAttr<DeprecatedAttr>())
9671 return false;
9672 if (MethodDecl->getObjCDeclQualifier() !=
9673 MethodImpl->getObjCDeclQualifier())
9674 return false;
Alp Toker314cc812014-01-25 16:55:45 +00009675 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00009676 return false;
9677
9678 if (MethodDecl->param_size() != MethodImpl->param_size())
9679 return false;
9680
9681 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
9682 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
9683 EF = MethodDecl->param_end();
9684 IM != EM && IF != EF; ++IM, ++IF) {
9685 const ParmVarDecl *DeclVar = (*IF);
9686 const ParmVarDecl *ImplVar = (*IM);
9687 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
9688 return false;
9689 if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
9690 return false;
9691 }
9692 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
9693
9694}
Richard Smith053f6c62014-05-16 23:01:30 +00009695
Yaxun Liu402804b2016-12-15 08:09:08 +00009696uint64_t ASTContext::getTargetNullPointerValue(QualType QT) const {
Alexander Richardson6d989432017-10-15 18:48:14 +00009697 LangAS AS;
Yaxun Liu402804b2016-12-15 08:09:08 +00009698 if (QT->getUnqualifiedDesugaredType()->isNullPtrType())
Alexander Richardson6d989432017-10-15 18:48:14 +00009699 AS = LangAS::Default;
Yaxun Liu402804b2016-12-15 08:09:08 +00009700 else
9701 AS = QT->getPointeeType().getAddressSpace();
9702
9703 return getTargetInfo().getNullPointerValue(AS);
9704}
9705
Alexander Richardson6d989432017-10-15 18:48:14 +00009706unsigned ASTContext::getTargetAddressSpace(LangAS AS) const {
9707 if (isTargetAddressSpace(AS))
9708 return toTargetAddressSpace(AS);
Yaxun Liub34ec822017-04-11 17:24:23 +00009709 else
Alexander Richardson6d989432017-10-15 18:48:14 +00009710 return (*AddrSpaceMap)[(unsigned)AS];
Yaxun Liub34ec822017-04-11 17:24:23 +00009711}
9712
Richard Smith053f6c62014-05-16 23:01:30 +00009713// Explicitly instantiate this in case a Redeclarable<T> is used from a TU that
9714// doesn't include ASTContext.h
9715template
9716clang::LazyGenerationalUpdatePtr<
9717 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType
9718clang::LazyGenerationalUpdatePtr<
9719 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue(
9720 const clang::ASTContext &Ctx, Decl *Value);