blob: 84161409efdc83d3ed4d41517ff5623b107e759f [file] [log] [blame]
Chris Lattnerddc135e2006-11-10 06:34:16 +00001//===--- ASTContext.cpp - Context to hold long-lived AST nodes ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerddc135e2006-11-10 06:34:16 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the ASTContext interface.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/ASTContext.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000015#include "CXXABI.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000016#include "clang/AST/ASTMutationListener.h"
17#include "clang/AST/Attr.h"
Ken Dyck8c89d592009-12-22 14:23:30 +000018#include "clang/AST/CharUnits.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000019#include "clang/AST/Comment.h"
Dmitri Gribenkoca7f80a2012-08-09 00:03:17 +000020#include "clang/AST/CommentCommandTraits.h"
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +000021#include "clang/AST/DeclCXX.h"
Chandler Carruthaa36b892015-12-30 03:40:23 +000022#include "clang/AST/DeclContextInternals.h"
Steve Naroff67391b82007-10-01 19:00:59 +000023#include "clang/AST/DeclObjC.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000024#include "clang/AST/DeclTemplate.h"
Daniel Dunbar221fa942008-08-11 04:54:23 +000025#include "clang/AST/Expr.h"
John McCall87fe5d52010-05-20 01:18:31 +000026#include "clang/AST/ExprCXX.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000027#include "clang/AST/ExternalASTSource.h"
Peter Collingbourne0ff0b372011-01-13 18:57:25 +000028#include "clang/AST/Mangle.h"
Reid Klecknerd8110b62013-09-10 20:14:30 +000029#include "clang/AST/MangleNumberingContext.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000030#include "clang/AST/RecordLayout.h"
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000031#include "clang/AST/RecursiveASTVisitor.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000032#include "clang/AST/TypeLoc.h"
Reid Kleckner96f8f932014-02-05 17:27:08 +000033#include "clang/AST/VTableBuilder.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000034#include "clang/Basic/Builtins.h"
Chris Lattnerd2868512009-03-28 03:45:20 +000035#include "clang/Basic/SourceManager.h"
Chris Lattner4dc8a6f2007-05-20 23:50:58 +000036#include "clang/Basic/TargetInfo.h"
Anders Carlssond8499822007-10-29 05:01:08 +000037#include "llvm/ADT/StringExtras.h"
Robert Lyttoneaf6f362013-11-12 10:09:34 +000038#include "llvm/ADT/Triple.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000039#include "llvm/Support/Capacity.h"
Nate Begemanb699c9b2009-01-18 06:42:49 +000040#include "llvm/Support/MathExtras.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000041#include "llvm/Support/raw_ostream.h"
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +000042#include <map>
Anders Carlssona4267a62009-07-18 21:19:52 +000043
Chris Lattnerddc135e2006-11-10 06:34:16 +000044using namespace clang;
45
Douglas Gregor9672f922010-07-03 00:47:00 +000046unsigned ASTContext::NumImplicitDefaultConstructors;
47unsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
Douglas Gregora6d69502010-07-02 23:41:54 +000048unsigned ASTContext::NumImplicitCopyConstructors;
49unsigned ASTContext::NumImplicitCopyConstructorsDeclared;
Alexis Huntfcaeae42011-05-25 20:50:04 +000050unsigned ASTContext::NumImplicitMoveConstructors;
51unsigned ASTContext::NumImplicitMoveConstructorsDeclared;
Douglas Gregor330b9cf2010-07-02 21:50:04 +000052unsigned ASTContext::NumImplicitCopyAssignmentOperators;
53unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Alexis Huntfcaeae42011-05-25 20:50:04 +000054unsigned ASTContext::NumImplicitMoveAssignmentOperators;
55unsigned ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
Douglas Gregor7454c562010-07-02 20:37:36 +000056unsigned ASTContext::NumImplicitDestructors;
57unsigned ASTContext::NumImplicitDestructorsDeclared;
58
Steve Naroff0af91202007-04-27 21:51:21 +000059enum FloatingRank {
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +000060 HalfRank, FloatRank, DoubleRank, LongDoubleRank, Float128Rank
Steve Naroff0af91202007-04-27 21:51:21 +000061};
62
Dmitri Gribenkof26054f2012-07-11 21:38:39 +000063RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const {
Dmitri Gribenkoaab83832012-06-20 00:34:58 +000064 if (!CommentsLoaded && ExternalSource) {
65 ExternalSource->ReadComments();
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +000066
67#ifndef NDEBUG
68 ArrayRef<RawComment *> RawComments = Comments.getComments();
69 assert(std::is_sorted(RawComments.begin(), RawComments.end(),
70 BeforeThanCompare<RawComment>(SourceMgr)));
71#endif
72
Dmitri Gribenkoaab83832012-06-20 00:34:58 +000073 CommentsLoaded = true;
74 }
75
76 assert(D);
77
Dmitri Gribenkodf17d642012-06-28 16:19:39 +000078 // User can not attach documentation to implicit declarations.
79 if (D->isImplicit())
Craig Topper36250ad2014-05-12 05:36:57 +000080 return nullptr;
Dmitri Gribenkodf17d642012-06-28 16:19:39 +000081
Dmitri Gribenkob2610882012-08-14 17:17:18 +000082 // User can not attach documentation to implicit instantiations.
83 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
84 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
Craig Topper36250ad2014-05-12 05:36:57 +000085 return nullptr;
Dmitri Gribenkob2610882012-08-14 17:17:18 +000086 }
87
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +000088 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
89 if (VD->isStaticDataMember() &&
90 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
Craig Topper36250ad2014-05-12 05:36:57 +000091 return nullptr;
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +000092 }
93
94 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
95 if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
Craig Topper36250ad2014-05-12 05:36:57 +000096 return nullptr;
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +000097 }
98
Dmitri Gribenko01b06512013-01-27 21:18:39 +000099 if (const ClassTemplateSpecializationDecl *CTSD =
100 dyn_cast<ClassTemplateSpecializationDecl>(D)) {
101 TemplateSpecializationKind TSK = CTSD->getSpecializationKind();
102 if (TSK == TSK_ImplicitInstantiation ||
103 TSK == TSK_Undeclared)
Craig Topper36250ad2014-05-12 05:36:57 +0000104 return nullptr;
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000105 }
106
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +0000107 if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
108 if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
Craig Topper36250ad2014-05-12 05:36:57 +0000109 return nullptr;
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +0000110 }
Fariborz Jahanian799a4032013-04-17 21:05:20 +0000111 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) {
112 // When tag declaration (but not definition!) is part of the
113 // decl-specifier-seq of some other declaration, it doesn't get comment
114 if (TD->isEmbeddedInDeclarator() && !TD->isCompleteDefinition())
Craig Topper36250ad2014-05-12 05:36:57 +0000115 return nullptr;
Fariborz Jahanian799a4032013-04-17 21:05:20 +0000116 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000117 // TODO: handle comments for function parameters properly.
118 if (isa<ParmVarDecl>(D))
Craig Topper36250ad2014-05-12 05:36:57 +0000119 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000120
Dmitri Gribenko34df2202012-07-31 22:37:06 +0000121 // TODO: we could look up template parameter documentation in the template
122 // documentation.
123 if (isa<TemplateTypeParmDecl>(D) ||
124 isa<NonTypeTemplateParmDecl>(D) ||
125 isa<TemplateTemplateParmDecl>(D))
Craig Topper36250ad2014-05-12 05:36:57 +0000126 return nullptr;
Dmitri Gribenko34df2202012-07-31 22:37:06 +0000127
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000128 ArrayRef<RawComment *> RawComments = Comments.getComments();
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000129
130 // If there are no comments anywhere, we won't find anything.
131 if (RawComments.empty())
Craig Topper36250ad2014-05-12 05:36:57 +0000132 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000133
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000134 // Find declaration location.
135 // For Objective-C declarations we generally don't expect to have multiple
136 // declarators, thus use declaration starting location as the "declaration
137 // location".
138 // For all other declarations multiple declarators are used quite frequently,
139 // so we use the location of the identifier as the "declaration location".
140 SourceLocation DeclLoc;
141 if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) ||
Dmitri Gribenko34df2202012-07-31 22:37:06 +0000142 isa<ObjCPropertyDecl>(D) ||
Dmitri Gribenko7f4b3772012-08-02 20:49:51 +0000143 isa<RedeclarableTemplateDecl>(D) ||
144 isa<ClassTemplateSpecializationDecl>(D))
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000145 DeclLoc = D->getLocStart();
Fariborz Jahanianb64e95f2013-07-24 22:58:51 +0000146 else {
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000147 DeclLoc = D->getLocation();
Dmitri Gribenkoef099dc2014-03-27 16:40:51 +0000148 if (DeclLoc.isMacroID()) {
149 if (isa<TypedefDecl>(D)) {
150 // If location of the typedef name is in a macro, it is because being
151 // declared via a macro. Try using declaration's starting location as
152 // the "declaration location".
153 DeclLoc = D->getLocStart();
154 } else if (const TagDecl *TD = dyn_cast<TagDecl>(D)) {
155 // If location of the tag decl is inside a macro, but the spelling of
156 // the tag name comes from a macro argument, it looks like a special
157 // macro like NS_ENUM is being used to define the tag decl. In that
158 // case, adjust the source location to the expansion loc so that we can
159 // attach the comment to the tag decl.
160 if (SourceMgr.isMacroArgExpansion(DeclLoc) &&
161 TD->isCompleteDefinition())
162 DeclLoc = SourceMgr.getExpansionLoc(DeclLoc);
163 }
164 }
Fariborz Jahanianb64e95f2013-07-24 22:58:51 +0000165 }
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000166
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000167 // If the declaration doesn't map directly to a location in a file, we
168 // can't find the comment.
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000169 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
Craig Topper36250ad2014-05-12 05:36:57 +0000170 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000171
172 // Find the comment that occurs just after this declaration.
Dmitri Gribenko82ea9472012-07-17 22:01:09 +0000173 ArrayRef<RawComment *>::iterator Comment;
174 {
175 // When searching for comments during parsing, the comment we are looking
176 // for is usually among the last two comments we parsed -- check them
177 // first.
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +0000178 RawComment CommentAtDeclLoc(
179 SourceMgr, SourceRange(DeclLoc), false,
180 LangOpts.CommentOpts.ParseAllComments);
Dmitri Gribenko82ea9472012-07-17 22:01:09 +0000181 BeforeThanCompare<RawComment> Compare(SourceMgr);
182 ArrayRef<RawComment *>::iterator MaybeBeforeDecl = RawComments.end() - 1;
183 bool Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
184 if (!Found && RawComments.size() >= 2) {
185 MaybeBeforeDecl--;
186 Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
187 }
188
189 if (Found) {
190 Comment = MaybeBeforeDecl + 1;
191 assert(Comment == std::lower_bound(RawComments.begin(), RawComments.end(),
192 &CommentAtDeclLoc, Compare));
193 } else {
194 // Slow path.
195 Comment = std::lower_bound(RawComments.begin(), RawComments.end(),
196 &CommentAtDeclLoc, Compare);
197 }
198 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000199
200 // Decompose the location for the declaration and find the beginning of the
201 // file buffer.
202 std::pair<FileID, unsigned> DeclLocDecomp = SourceMgr.getDecomposedLoc(DeclLoc);
203
204 // First check whether we have a trailing comment.
205 if (Comment != RawComments.end() &&
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000206 (*Comment)->isDocumentation() && (*Comment)->isTrailingComment() &&
Fariborz Jahanianfad28542013-08-06 23:29:00 +0000207 (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D) ||
Fariborz Jahanian3ab62222013-08-07 16:40:29 +0000208 isa<ObjCMethodDecl>(D) || isa<ObjCPropertyDecl>(D))) {
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000209 std::pair<FileID, unsigned> CommentBeginDecomp
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000210 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getBegin());
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000211 // Check that Doxygen trailing comment comes after the declaration, starts
212 // on the same line and in the same file as the declaration.
213 if (DeclLocDecomp.first == CommentBeginDecomp.first &&
214 SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second)
215 == SourceMgr.getLineNumber(CommentBeginDecomp.first,
216 CommentBeginDecomp.second)) {
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000217 return *Comment;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000218 }
219 }
220
221 // The comment just after the declaration was not a trailing comment.
222 // Let's look at the previous comment.
223 if (Comment == RawComments.begin())
Craig Topper36250ad2014-05-12 05:36:57 +0000224 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000225 --Comment;
226
227 // Check that we actually have a non-member Doxygen comment.
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000228 if (!(*Comment)->isDocumentation() || (*Comment)->isTrailingComment())
Craig Topper36250ad2014-05-12 05:36:57 +0000229 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000230
231 // Decompose the end of the comment.
232 std::pair<FileID, unsigned> CommentEndDecomp
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000233 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getEnd());
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000234
235 // If the comment and the declaration aren't in the same file, then they
236 // aren't related.
237 if (DeclLocDecomp.first != CommentEndDecomp.first)
Craig Topper36250ad2014-05-12 05:36:57 +0000238 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000239
240 // Get the corresponding buffer.
241 bool Invalid = false;
242 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
243 &Invalid).data();
244 if (Invalid)
Craig Topper36250ad2014-05-12 05:36:57 +0000245 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000246
247 // Extract text between the comment and declaration.
248 StringRef Text(Buffer + CommentEndDecomp.second,
249 DeclLocDecomp.second - CommentEndDecomp.second);
250
Dmitri Gribenko7e8729b2012-06-27 23:43:37 +0000251 // There should be no other declarations or preprocessor directives between
252 // comment and declaration.
Argyrios Kyrtzidisb534d3a2013-07-26 18:38:12 +0000253 if (Text.find_first_of(";{}#@") != StringRef::npos)
Craig Topper36250ad2014-05-12 05:36:57 +0000254 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000255
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000256 return *Comment;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000257}
258
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000259namespace {
260/// If we have a 'templated' declaration for a template, adjust 'D' to
261/// refer to the actual template.
Dmitri Gribenko90631802012-08-22 17:44:32 +0000262/// If we have an implicit instantiation, adjust 'D' to refer to template.
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000263const Decl *adjustDeclToTemplate(const Decl *D) {
Douglas Gregor35ceb272012-08-13 16:37:30 +0000264 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Dmitri Gribenko90631802012-08-22 17:44:32 +0000265 // Is this function declaration part of a function template?
Douglas Gregor35ceb272012-08-13 16:37:30 +0000266 if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
Dmitri Gribenko90631802012-08-22 17:44:32 +0000267 return FTD;
268
269 // Nothing to do if function is not an implicit instantiation.
270 if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
271 return D;
272
273 // Function is an implicit instantiation of a function template?
274 if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate())
275 return FTD;
276
277 // Function is instantiated from a member definition of a class template?
278 if (const FunctionDecl *MemberDecl =
279 FD->getInstantiatedFromMemberFunction())
280 return MemberDecl;
281
282 return D;
Douglas Gregor35ceb272012-08-13 16:37:30 +0000283 }
Dmitri Gribenko90631802012-08-22 17:44:32 +0000284 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
285 // Static data member is instantiated from a member definition of a class
286 // template?
287 if (VD->isStaticDataMember())
288 if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember())
289 return MemberDecl;
290
291 return D;
292 }
293 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
294 // Is this class declaration part of a class template?
295 if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate())
296 return CTD;
297
298 // Class is an implicit instantiation of a class template or partial
299 // specialization?
300 if (const ClassTemplateSpecializationDecl *CTSD =
301 dyn_cast<ClassTemplateSpecializationDecl>(CRD)) {
302 if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation)
303 return D;
304 llvm::PointerUnion<ClassTemplateDecl *,
305 ClassTemplatePartialSpecializationDecl *>
306 PU = CTSD->getSpecializedTemplateOrPartial();
307 return PU.is<ClassTemplateDecl*>() ?
308 static_cast<const Decl*>(PU.get<ClassTemplateDecl *>()) :
309 static_cast<const Decl*>(
310 PU.get<ClassTemplatePartialSpecializationDecl *>());
311 }
312
313 // Class is instantiated from a member definition of a class template?
314 if (const MemberSpecializationInfo *Info =
315 CRD->getMemberSpecializationInfo())
316 return Info->getInstantiatedFrom();
317
318 return D;
319 }
320 if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
321 // Enum is instantiated from a member definition of a class template?
322 if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum())
323 return MemberDecl;
324
325 return D;
326 }
327 // FIXME: Adjust alias templates?
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000328 return D;
329}
Eugene Zelenkod4304d22015-11-04 21:37:17 +0000330} // anonymous namespace
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000331
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000332const RawComment *ASTContext::getRawCommentForAnyRedecl(
333 const Decl *D,
334 const Decl **OriginalDecl) const {
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000335 D = adjustDeclToTemplate(D);
Douglas Gregor35ceb272012-08-13 16:37:30 +0000336
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000337 // Check whether we have cached a comment for this declaration already.
338 {
339 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
340 RedeclComments.find(D);
341 if (Pos != RedeclComments.end()) {
342 const RawCommentAndCacheFlags &Raw = Pos->second;
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000343 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
344 if (OriginalDecl)
345 *OriginalDecl = Raw.getOriginalDecl();
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000346 return Raw.getRaw();
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000347 }
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000348 }
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000349 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000350
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000351 // Search for comments attached to declarations in the redeclaration chain.
Craig Topper36250ad2014-05-12 05:36:57 +0000352 const RawComment *RC = nullptr;
353 const Decl *OriginalDeclForRC = nullptr;
Aaron Ballman86c93902014-03-06 23:45:36 +0000354 for (auto I : D->redecls()) {
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000355 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
Aaron Ballman86c93902014-03-06 23:45:36 +0000356 RedeclComments.find(I);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000357 if (Pos != RedeclComments.end()) {
358 const RawCommentAndCacheFlags &Raw = Pos->second;
359 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
360 RC = Raw.getRaw();
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000361 OriginalDeclForRC = Raw.getOriginalDecl();
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000362 break;
363 }
364 } else {
Aaron Ballman86c93902014-03-06 23:45:36 +0000365 RC = getRawCommentForDeclNoCache(I);
366 OriginalDeclForRC = I;
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000367 RawCommentAndCacheFlags Raw;
368 if (RC) {
Will Wilsonf9de5362015-10-27 17:01:10 +0000369 // Call order swapped to work around ICE in VS2015 RTM (Release Win32)
370 // https://connect.microsoft.com/VisualStudio/feedback/details/1741530
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000371 Raw.setKind(RawCommentAndCacheFlags::FromDecl);
Will Wilsonf9de5362015-10-27 17:01:10 +0000372 Raw.setRaw(RC);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000373 } else
374 Raw.setKind(RawCommentAndCacheFlags::NoCommentInDecl);
Aaron Ballman86c93902014-03-06 23:45:36 +0000375 Raw.setOriginalDecl(I);
376 RedeclComments[I] = Raw;
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000377 if (RC)
378 break;
379 }
380 }
381
Dmitri Gribenko5c8897d2012-06-28 16:25:36 +0000382 // If we found a comment, it should be a documentation comment.
383 assert(!RC || RC->isDocumentation());
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000384
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000385 if (OriginalDecl)
386 *OriginalDecl = OriginalDeclForRC;
387
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000388 // Update cache for every declaration in the redeclaration chain.
389 RawCommentAndCacheFlags Raw;
390 Raw.setRaw(RC);
391 Raw.setKind(RawCommentAndCacheFlags::FromRedecl);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000392 Raw.setOriginalDecl(OriginalDeclForRC);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000393
Aaron Ballman86c93902014-03-06 23:45:36 +0000394 for (auto I : D->redecls()) {
395 RawCommentAndCacheFlags &R = RedeclComments[I];
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000396 if (R.getKind() == RawCommentAndCacheFlags::NoCommentInDecl)
397 R = Raw;
398 }
399
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000400 return RC;
401}
402
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000403static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
404 SmallVectorImpl<const NamedDecl *> &Redeclared) {
405 const DeclContext *DC = ObjCMethod->getDeclContext();
406 if (const ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(DC)) {
407 const ObjCInterfaceDecl *ID = IMD->getClassInterface();
408 if (!ID)
409 return;
410 // Add redeclared method here.
Aaron Ballmanb4a53452014-03-13 21:57:01 +0000411 for (const auto *Ext : ID->known_extensions()) {
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000412 if (ObjCMethodDecl *RedeclaredMethod =
Douglas Gregor048fbfa2013-01-16 23:00:23 +0000413 Ext->getMethod(ObjCMethod->getSelector(),
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000414 ObjCMethod->isInstanceMethod()))
415 Redeclared.push_back(RedeclaredMethod);
416 }
417 }
418}
419
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000420comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC,
421 const Decl *D) const {
422 comments::DeclInfo *ThisDeclInfo = new (*this) comments::DeclInfo;
423 ThisDeclInfo->CommentDecl = D;
424 ThisDeclInfo->IsFilled = false;
425 ThisDeclInfo->fill();
426 ThisDeclInfo->CommentDecl = FC->getDecl();
Argyrios Kyrtzidis7daabbd2014-04-27 22:53:03 +0000427 if (!ThisDeclInfo->TemplateParameters)
428 ThisDeclInfo->TemplateParameters = FC->getDeclInfo()->TemplateParameters;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000429 comments::FullComment *CFC =
430 new (*this) comments::FullComment(FC->getBlocks(),
431 ThisDeclInfo);
432 return CFC;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000433}
434
Richard Smithb39b9d52013-05-21 05:24:00 +0000435comments::FullComment *ASTContext::getLocalCommentForDeclUncached(const Decl *D) const {
436 const RawComment *RC = getRawCommentForDeclNoCache(D);
Craig Topper36250ad2014-05-12 05:36:57 +0000437 return RC ? RC->parse(*this, nullptr, D) : nullptr;
Richard Smithb39b9d52013-05-21 05:24:00 +0000438}
439
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000440comments::FullComment *ASTContext::getCommentForDecl(
441 const Decl *D,
442 const Preprocessor *PP) const {
Fariborz Jahanian096f7c12013-05-13 17:27:00 +0000443 if (D->isInvalidDecl())
Craig Topper36250ad2014-05-12 05:36:57 +0000444 return nullptr;
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000445 D = adjustDeclToTemplate(D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000446
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000447 const Decl *Canonical = D->getCanonicalDecl();
448 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
449 ParsedComments.find(Canonical);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000450
451 if (Pos != ParsedComments.end()) {
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000452 if (Canonical != D) {
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000453 comments::FullComment *FC = Pos->second;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000454 comments::FullComment *CFC = cloneFullComment(FC, D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000455 return CFC;
456 }
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000457 return Pos->second;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000458 }
459
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000460 const Decl *OriginalDecl;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000461
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000462 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000463 if (!RC) {
464 if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +0000465 SmallVector<const NamedDecl*, 8> Overridden;
Fariborz Jahanian37494a12013-01-12 00:28:34 +0000466 const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D);
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000467 if (OMD && OMD->isPropertyAccessor())
468 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
469 if (comments::FullComment *FC = getCommentForDecl(PDecl, PP))
470 return cloneFullComment(FC, D);
Fariborz Jahanian37494a12013-01-12 00:28:34 +0000471 if (OMD)
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +0000472 addRedeclaredMethods(OMD, Overridden);
473 getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000474 for (unsigned i = 0, e = Overridden.size(); i < e; i++)
475 if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
476 return cloneFullComment(FC, D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000477 }
Fariborz Jahanian6384fbb2013-05-02 15:44:16 +0000478 else if (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000479 // Attach any tag type's documentation to its typedef if latter
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000480 // does not have one of its own.
Fariborz Jahanian40abf342013-01-25 22:48:32 +0000481 QualType QT = TD->getUnderlyingType();
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000482 if (const TagType *TT = QT->getAs<TagType>())
483 if (const Decl *TD = TT->getDecl())
484 if (comments::FullComment *FC = getCommentForDecl(TD, PP))
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000485 return cloneFullComment(FC, D);
Fariborz Jahanian40abf342013-01-25 22:48:32 +0000486 }
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000487 else if (const ObjCInterfaceDecl *IC = dyn_cast<ObjCInterfaceDecl>(D)) {
488 while (IC->getSuperClass()) {
489 IC = IC->getSuperClass();
490 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
491 return cloneFullComment(FC, D);
492 }
493 }
494 else if (const ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
495 if (const ObjCInterfaceDecl *IC = CD->getClassInterface())
496 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
497 return cloneFullComment(FC, D);
498 }
499 else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
500 if (!(RD = RD->getDefinition()))
Craig Topper36250ad2014-05-12 05:36:57 +0000501 return nullptr;
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000502 // Check non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +0000503 for (const auto &I : RD->bases()) {
504 if (I.isVirtual() || (I.getAccessSpecifier() != AS_public))
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000505 continue;
Aaron Ballman574705e2014-03-13 15:41:46 +0000506 QualType Ty = I.getType();
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000507 if (Ty.isNull())
508 continue;
509 if (const CXXRecordDecl *NonVirtualBase = Ty->getAsCXXRecordDecl()) {
510 if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
511 continue;
512
513 if (comments::FullComment *FC = getCommentForDecl((NonVirtualBase), PP))
514 return cloneFullComment(FC, D);
515 }
516 }
517 // Check virtual bases.
Aaron Ballman445a9392014-03-13 16:15:17 +0000518 for (const auto &I : RD->vbases()) {
519 if (I.getAccessSpecifier() != AS_public)
Fariborz Jahanian5a2e4a22013-04-26 23:34:36 +0000520 continue;
Aaron Ballman445a9392014-03-13 16:15:17 +0000521 QualType Ty = I.getType();
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000522 if (Ty.isNull())
523 continue;
524 if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
525 if (!(VirtualBase= VirtualBase->getDefinition()))
526 continue;
527 if (comments::FullComment *FC = getCommentForDecl((VirtualBase), PP))
528 return cloneFullComment(FC, D);
529 }
530 }
531 }
Craig Topper36250ad2014-05-12 05:36:57 +0000532 return nullptr;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000533 }
534
Dmitri Gribenkobfda9f72012-08-22 18:12:19 +0000535 // If the RawComment was attached to other redeclaration of this Decl, we
536 // should parse the comment in context of that other Decl. This is important
537 // because comments can contain references to parameter names which can be
538 // different across redeclarations.
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000539 if (D != OriginalDecl)
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000540 return getCommentForDecl(OriginalDecl, PP);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000541
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000542 comments::FullComment *FC = RC->parse(*this, PP, D);
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000543 ParsedComments[Canonical] = FC;
544 return FC;
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000545}
546
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000547void
548ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
549 TemplateTemplateParmDecl *Parm) {
550 ID.AddInteger(Parm->getDepth());
551 ID.AddInteger(Parm->getPosition());
Douglas Gregorf5500772011-01-05 15:48:55 +0000552 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000553
554 TemplateParameterList *Params = Parm->getTemplateParameters();
555 ID.AddInteger(Params->size());
556 for (TemplateParameterList::const_iterator P = Params->begin(),
557 PEnd = Params->end();
558 P != PEnd; ++P) {
559 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
560 ID.AddInteger(0);
561 ID.AddBoolean(TTP->isParameterPack());
562 continue;
563 }
564
565 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
566 ID.AddInteger(1);
Douglas Gregorf5500772011-01-05 15:48:55 +0000567 ID.AddBoolean(NTTP->isParameterPack());
Eli Friedman205a4292012-03-07 01:09:33 +0000568 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000569 if (NTTP->isExpandedParameterPack()) {
570 ID.AddBoolean(true);
571 ID.AddInteger(NTTP->getNumExpansionTypes());
Eli Friedman205a4292012-03-07 01:09:33 +0000572 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
573 QualType T = NTTP->getExpansionType(I);
574 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
575 }
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000576 } else
577 ID.AddBoolean(false);
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000578 continue;
579 }
580
581 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
582 ID.AddInteger(2);
583 Profile(ID, TTP);
584 }
585}
586
587TemplateTemplateParmDecl *
588ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad39c79802011-01-12 09:06:06 +0000589 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000590 // Check if we already have a canonical template template parameter.
591 llvm::FoldingSetNodeID ID;
592 CanonicalTemplateTemplateParm::Profile(ID, TTP);
Craig Topper36250ad2014-05-12 05:36:57 +0000593 void *InsertPos = nullptr;
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000594 CanonicalTemplateTemplateParm *Canonical
595 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
596 if (Canonical)
597 return Canonical->getParam();
598
599 // Build a canonical template parameter list.
600 TemplateParameterList *Params = TTP->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000601 SmallVector<NamedDecl *, 4> CanonParams;
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000602 CanonParams.reserve(Params->size());
603 for (TemplateParameterList::const_iterator P = Params->begin(),
604 PEnd = Params->end();
605 P != PEnd; ++P) {
606 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
607 CanonParams.push_back(
608 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnarab3185b02011-03-06 15:48:19 +0000609 SourceLocation(),
610 SourceLocation(),
611 TTP->getDepth(),
Craig Topper36250ad2014-05-12 05:36:57 +0000612 TTP->getIndex(), nullptr, false,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000613 TTP->isParameterPack()));
614 else if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000615 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
616 QualType T = getCanonicalType(NTTP->getType());
617 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
618 NonTypeTemplateParmDecl *Param;
619 if (NTTP->isExpandedParameterPack()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000620 SmallVector<QualType, 2> ExpandedTypes;
621 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000622 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
623 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
624 ExpandedTInfos.push_back(
625 getTrivialTypeSourceInfo(ExpandedTypes.back()));
626 }
627
628 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000629 SourceLocation(),
630 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000631 NTTP->getDepth(),
Craig Topper36250ad2014-05-12 05:36:57 +0000632 NTTP->getPosition(), nullptr,
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000633 T,
634 TInfo,
David Majnemerdfecf1a2016-07-06 04:19:16 +0000635 ExpandedTypes,
636 ExpandedTInfos);
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000637 } else {
638 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000639 SourceLocation(),
640 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000641 NTTP->getDepth(),
Craig Topper36250ad2014-05-12 05:36:57 +0000642 NTTP->getPosition(), nullptr,
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000643 T,
644 NTTP->isParameterPack(),
645 TInfo);
646 }
647 CanonParams.push_back(Param);
648
649 } else
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000650 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
651 cast<TemplateTemplateParmDecl>(*P)));
652 }
653
Hubert Tonge4a0c0e2016-07-30 22:33:34 +0000654 assert(!TTP->getRequiresClause() &&
655 "Unexpected requires-clause on template template-parameter");
George Burgess IVb7e4e482016-08-25 01:54:37 +0000656 Expr *const CanonRequiresClause = nullptr;
Hubert Tonge4a0c0e2016-07-30 22:33:34 +0000657
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000658 TemplateTemplateParmDecl *CanonTTP
659 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
660 SourceLocation(), TTP->getDepth(),
Douglas Gregorf5500772011-01-05 15:48:55 +0000661 TTP->getPosition(),
662 TTP->isParameterPack(),
Craig Topper36250ad2014-05-12 05:36:57 +0000663 nullptr,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000664 TemplateParameterList::Create(*this, SourceLocation(),
665 SourceLocation(),
David Majnemer902f8c62015-12-27 07:16:27 +0000666 CanonParams,
Hubert Tonge4a0c0e2016-07-30 22:33:34 +0000667 SourceLocation(),
668 CanonRequiresClause));
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000669
670 // Get the new insert position for the node we care about.
671 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +0000672 assert(!Canonical && "Shouldn't be in the map!");
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000673 (void)Canonical;
674
675 // Create the canonical template template parameter entry.
676 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
677 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
678 return CanonTTP;
679}
680
Charles Davis53c59df2010-08-16 03:33:14 +0000681CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
Craig Topper36250ad2014-05-12 05:36:57 +0000682 if (!LangOpts.CPlusPlus) return nullptr;
John McCall86353412010-08-21 22:46:04 +0000683
John McCall359b8852013-01-25 22:30:49 +0000684 switch (T.getCXXABI().getKind()) {
Joerg Sonnenbergerdaa13aa2014-05-13 11:20:16 +0000685 case TargetCXXABI::GenericARM: // Same as Itanium at this level
John McCall359b8852013-01-25 22:30:49 +0000686 case TargetCXXABI::iOS:
Tim Northovera2ee4332014-03-29 15:09:45 +0000687 case TargetCXXABI::iOS64:
Tim Northover756447a2015-10-30 16:30:36 +0000688 case TargetCXXABI::WatchOS:
Joerg Sonnenbergerdaa13aa2014-05-13 11:20:16 +0000689 case TargetCXXABI::GenericAArch64:
Zoran Jovanovic26a12162015-02-18 15:21:35 +0000690 case TargetCXXABI::GenericMIPS:
John McCall359b8852013-01-25 22:30:49 +0000691 case TargetCXXABI::GenericItanium:
Dan Gohmanc2853072015-09-03 22:51:53 +0000692 case TargetCXXABI::WebAssembly:
Charles Davis53c59df2010-08-16 03:33:14 +0000693 return CreateItaniumCXXABI(*this);
John McCall359b8852013-01-25 22:30:49 +0000694 case TargetCXXABI::Microsoft:
Charles Davis6bcb07a2010-08-19 02:18:14 +0000695 return CreateMicrosoftCXXABI(*this);
696 }
David Blaikie8a40f702012-01-17 06:56:22 +0000697 llvm_unreachable("Invalid CXXABI type!");
Charles Davis53c59df2010-08-16 03:33:14 +0000698}
699
Douglas Gregore8bbc122011-09-02 00:18:52 +0000700static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000701 const LangOptions &LOpts) {
702 if (LOpts.FakeAddressSpaceMap) {
703 // The fake address space map must have a distinct entry for each
704 // language-specific address space.
705 static const unsigned FakeAddrSpaceMap[] = {
706 1, // opencl_global
Egor Churaev28f00aa2016-12-23 16:11:25 +0000707 3, // opencl_local
708 2, // opencl_constant
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +0000709 4, // opencl_generic
710 5, // cuda_device
711 6, // cuda_constant
712 7 // cuda_shared
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000713 };
Douglas Gregore8bbc122011-09-02 00:18:52 +0000714 return &FakeAddrSpaceMap;
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000715 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000716 return &T.getAddressSpaceMap();
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000717 }
718}
719
David Tweed31d09b02013-09-13 12:04:22 +0000720static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI,
721 const LangOptions &LangOpts) {
722 switch (LangOpts.getAddressSpaceMapMangling()) {
David Tweed31d09b02013-09-13 12:04:22 +0000723 case LangOptions::ASMM_Target:
724 return TI.useAddressSpaceMapMangling();
725 case LangOptions::ASMM_On:
726 return true;
727 case LangOptions::ASMM_Off:
728 return false;
729 }
NAKAMURA Takumi5c81ca42013-09-13 17:12:09 +0000730 llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.");
David Tweed31d09b02013-09-13 12:04:22 +0000731}
732
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000733ASTContext::ASTContext(LangOptions &LOpts, SourceManager &SM,
Daniel Dunbar221fa942008-08-11 04:54:23 +0000734 IdentifierTable &idents, SelectorTable &sels,
Alp Toker08043432014-05-03 03:46:04 +0000735 Builtin::Context &builtins)
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000736 : FunctionProtoTypes(this_()), TemplateSpecializationTypes(this_()),
737 DependentTemplateSpecializationTypes(this_()),
738 SubstTemplateTemplateParmPacks(this_()),
739 GlobalNestedNameSpecifier(nullptr), Int128Decl(nullptr),
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +0000740 UInt128Decl(nullptr), BuiltinVaListDecl(nullptr),
741 BuiltinMSVaListDecl(nullptr), ObjCIdDecl(nullptr), ObjCSelDecl(nullptr),
742 ObjCClassDecl(nullptr), ObjCProtocolClassDecl(nullptr), BOOLDecl(nullptr),
Ben Langmuirf5416742016-02-04 00:55:24 +0000743 CFConstantStringTagDecl(nullptr), CFConstantStringTypeDecl(nullptr),
744 ObjCInstanceTypeDecl(nullptr), FILEDecl(nullptr), jmp_bufDecl(nullptr),
745 sigjmp_bufDecl(nullptr), ucontext_tDecl(nullptr),
746 BlockDescriptorType(nullptr), BlockDescriptorExtendedType(nullptr),
747 cudaConfigureCallDecl(nullptr), FirstLocalImport(), LastLocalImport(),
Eric Fiselier6ad68552016-07-01 01:24:09 +0000748 ExternCContext(nullptr), MakeIntegerSeqDecl(nullptr),
749 TypePackElementDecl(nullptr), SourceMgr(SM), LangOpts(LOpts),
Alexey Samsonova511cdd2015-02-04 17:40:08 +0000750 SanitizerBL(new SanitizerBlacklist(LangOpts.SanitizerBlacklistFiles, SM)),
Artem Belevichb5bc9232015-09-22 17:23:22 +0000751 AddrSpaceMap(nullptr), Target(nullptr), AuxTarget(nullptr),
752 PrintingPolicy(LOpts), Idents(idents), Selectors(sels),
753 BuiltinInfo(builtins), DeclarationNames(*this), ExternalSource(nullptr),
754 Listener(nullptr), Comments(SM), CommentsLoaded(false),
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000755 CommentCommandTraits(BumpAlloc, LOpts.CommentOpts), LastSDM(nullptr, 0) {
Daniel Dunbar221fa942008-08-11 04:54:23 +0000756 TUDecl = TranslationUnitDecl::Create(*this);
757}
758
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000759ASTContext::~ASTContext() {
Manuel Klimek95403e62014-05-21 13:28:59 +0000760 ReleaseParentMapEntries();
761
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000762 // Release the DenseMaps associated with DeclContext objects.
763 // FIXME: Is this the ideal solution?
764 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-03-02 23:58:15 +0000765
Manuel Klimeka7328992013-06-03 13:51:33 +0000766 // Call all of the deallocation functions on all of their targets.
Chandler Carruthff5a01a2015-12-30 03:00:23 +0000767 for (auto &Pair : Deallocations)
768 (Pair.first)(Pair.second);
Manuel Klimeka7328992013-06-03 13:51:33 +0000769
Ted Kremenek076baeb2010-06-08 23:00:58 +0000770 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor5b11d492010-07-25 17:53:33 +0000771 // because they can contain DenseMaps.
772 for (llvm::DenseMap<const ObjCContainerDecl*,
773 const ASTRecordLayout*>::iterator
774 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
775 // Increment in loop to prevent using deallocated memory.
776 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
777 R->Destroy(*this);
778
Ted Kremenek076baeb2010-06-08 23:00:58 +0000779 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
780 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
781 // Increment in loop to prevent using deallocated memory.
782 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
783 R->Destroy(*this);
784 }
Douglas Gregor561eceb2010-08-30 16:49:28 +0000785
786 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
787 AEnd = DeclAttrs.end();
788 A != AEnd; ++A)
789 A->second->~AttrVec();
Reid Klecknerd8110b62013-09-10 20:14:30 +0000790
David Majnemere694f3e2015-08-14 14:43:50 +0000791 for (std::pair<const MaterializeTemporaryExpr *, APValue *> &MTVPair :
792 MaterializedTemporaryValues)
793 MTVPair.second->~APValue();
794
Richard Smith423f46f2016-07-20 21:38:26 +0000795 for (const auto &Value : ModuleInitializers)
796 Value.second->~PerModuleInitializers();
Douglas Gregor561eceb2010-08-30 16:49:28 +0000797}
Douglas Gregorf21eb492009-03-26 23:50:42 +0000798
Manuel Klimek95403e62014-05-21 13:28:59 +0000799void ASTContext::ReleaseParentMapEntries() {
Benjamin Kramer94355ae2015-10-23 09:04:55 +0000800 if (!PointerParents) return;
801 for (const auto &Entry : *PointerParents) {
802 if (Entry.second.is<ast_type_traits::DynTypedNode *>()) {
803 delete Entry.second.get<ast_type_traits::DynTypedNode *>();
804 } else if (Entry.second.is<ParentVector *>()) {
805 delete Entry.second.get<ParentVector *>();
806 }
807 }
808 for (const auto &Entry : *OtherParents) {
Manuel Klimek95403e62014-05-21 13:28:59 +0000809 if (Entry.second.is<ast_type_traits::DynTypedNode *>()) {
810 delete Entry.second.get<ast_type_traits::DynTypedNode *>();
Benjamin Kramer8e4a1762015-10-22 11:21:40 +0000811 } else if (Entry.second.is<ParentVector *>()) {
Manuel Klimek95403e62014-05-21 13:28:59 +0000812 delete Entry.second.get<ParentVector *>();
813 }
814 }
815}
816
Douglas Gregor1a809332010-05-23 18:26:36 +0000817void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
Chandler Carruthff5a01a2015-12-30 03:00:23 +0000818 Deallocations.push_back({Callback, Data});
Douglas Gregor1a809332010-05-23 18:26:36 +0000819}
820
Mike Stump11289f42009-09-09 15:08:12 +0000821void
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000822ASTContext::setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source) {
Benjamin Kramerd6da1a02016-06-12 20:05:23 +0000823 ExternalSource = std::move(Source);
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000824}
825
Chris Lattner4eb445d2007-01-26 01:27:23 +0000826void ASTContext::PrintStats() const {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000827 llvm::errs() << "\n*** AST Context Stats:\n";
828 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000829
Douglas Gregora30d0462009-05-26 14:40:08 +0000830 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000831#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000832#define ABSTRACT_TYPE(Name, Parent)
833#include "clang/AST/TypeNodes.def"
834 0 // Extra
835 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000836
Chris Lattner4eb445d2007-01-26 01:27:23 +0000837 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
838 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000839 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000840 }
841
Douglas Gregora30d0462009-05-26 14:40:08 +0000842 unsigned Idx = 0;
843 unsigned TotalBytes = 0;
844#define TYPE(Name, Parent) \
845 if (counts[Idx]) \
Chandler Carruth3c147a72011-07-04 05:32:14 +0000846 llvm::errs() << " " << counts[Idx] << " " << #Name \
847 << " types\n"; \
Douglas Gregora30d0462009-05-26 14:40:08 +0000848 TotalBytes += counts[Idx] * sizeof(Name##Type); \
849 ++Idx;
850#define ABSTRACT_TYPE(Name, Parent)
851#include "clang/AST/TypeNodes.def"
Mike Stump11289f42009-09-09 15:08:12 +0000852
Chandler Carruth3c147a72011-07-04 05:32:14 +0000853 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
854
Douglas Gregor7454c562010-07-02 20:37:36 +0000855 // Implicit special member functions.
Chandler Carruth3c147a72011-07-04 05:32:14 +0000856 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
857 << NumImplicitDefaultConstructors
858 << " implicit default constructors created\n";
859 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
860 << NumImplicitCopyConstructors
861 << " implicit copy constructors created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000862 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000863 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
864 << NumImplicitMoveConstructors
865 << " implicit move constructors created\n";
866 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
867 << NumImplicitCopyAssignmentOperators
868 << " implicit copy assignment operators created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000869 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000870 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
871 << NumImplicitMoveAssignmentOperators
872 << " implicit move assignment operators created\n";
873 llvm::errs() << NumImplicitDestructorsDeclared << "/"
874 << NumImplicitDestructors
875 << " implicit destructors created\n";
876
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000877 if (ExternalSource) {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000878 llvm::errs() << "\n";
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000879 ExternalSource->PrintStats();
880 }
Chandler Carruth3c147a72011-07-04 05:32:14 +0000881
Douglas Gregor5b11d492010-07-25 17:53:33 +0000882 BumpAlloc.PrintStats();
Chris Lattner4eb445d2007-01-26 01:27:23 +0000883}
884
Richard Smith42413142015-05-15 20:05:43 +0000885void ASTContext::mergeDefinitionIntoModule(NamedDecl *ND, Module *M,
886 bool NotifyListeners) {
887 if (NotifyListeners)
888 if (auto *Listener = getASTMutationListener())
889 Listener->RedefinedHiddenDefinition(ND, M);
890
Benjamin Kramera72a70a2016-10-17 13:00:44 +0000891 if (getLangOpts().ModulesLocalVisibility)
892 MergedDefModules[ND].push_back(M);
893 else
Richard Smith42413142015-05-15 20:05:43 +0000894 ND->setHidden(false);
895}
896
897void ASTContext::deduplicateMergedDefinitonsFor(NamedDecl *ND) {
898 auto It = MergedDefModules.find(ND);
899 if (It == MergedDefModules.end())
900 return;
901
Benjamin Kramera72a70a2016-10-17 13:00:44 +0000902 auto &Merged = It->second;
Richard Smith42413142015-05-15 20:05:43 +0000903 llvm::DenseSet<Module*> Found;
904 for (Module *&M : Merged)
905 if (!Found.insert(M).second)
906 M = nullptr;
907 Merged.erase(std::remove(Merged.begin(), Merged.end(), nullptr), Merged.end());
908}
909
Richard Smithdc1f0422016-07-20 19:10:16 +0000910void ASTContext::PerModuleInitializers::resolve(ASTContext &Ctx) {
911 if (LazyInitializers.empty())
912 return;
913
914 auto *Source = Ctx.getExternalSource();
915 assert(Source && "lazy initializers but no external source");
916
917 auto LazyInits = std::move(LazyInitializers);
918 LazyInitializers.clear();
919
920 for (auto ID : LazyInits)
921 Initializers.push_back(Source->GetExternalDecl(ID));
922
923 assert(LazyInitializers.empty() &&
924 "GetExternalDecl for lazy module initializer added more inits");
925}
926
927void ASTContext::addModuleInitializer(Module *M, Decl *D) {
928 // One special case: if we add a module initializer that imports another
929 // module, and that module's only initializer is an ImportDecl, simplify.
930 if (auto *ID = dyn_cast<ImportDecl>(D)) {
931 auto It = ModuleInitializers.find(ID->getImportedModule());
932
933 // Maybe the ImportDecl does nothing at all. (Common case.)
934 if (It == ModuleInitializers.end())
935 return;
936
937 // Maybe the ImportDecl only imports another ImportDecl.
938 auto &Imported = *It->second;
939 if (Imported.Initializers.size() + Imported.LazyInitializers.size() == 1) {
940 Imported.resolve(*this);
941 auto *OnlyDecl = Imported.Initializers.front();
942 if (isa<ImportDecl>(OnlyDecl))
943 D = OnlyDecl;
944 }
945 }
946
947 auto *&Inits = ModuleInitializers[M];
948 if (!Inits)
949 Inits = new (*this) PerModuleInitializers;
950 Inits->Initializers.push_back(D);
951}
952
953void ASTContext::addLazyModuleInitializers(Module *M, ArrayRef<uint32_t> IDs) {
954 auto *&Inits = ModuleInitializers[M];
955 if (!Inits)
956 Inits = new (*this) PerModuleInitializers;
957 Inits->LazyInitializers.insert(Inits->LazyInitializers.end(),
958 IDs.begin(), IDs.end());
959}
960
961ArrayRef<Decl*> ASTContext::getModuleInitializers(Module *M) {
962 auto It = ModuleInitializers.find(M);
963 if (It == ModuleInitializers.end())
964 return None;
965
966 auto *Inits = It->second;
967 Inits->resolve(*this);
968 return Inits->Initializers;
969}
970
Richard Smithf19e1272015-03-07 00:04:49 +0000971ExternCContextDecl *ASTContext::getExternCContextDecl() const {
972 if (!ExternCContext)
973 ExternCContext = ExternCContextDecl::Create(*this, getTranslationUnitDecl());
974
975 return ExternCContext;
976}
977
David Majnemerd9b1a4f2015-11-04 03:40:30 +0000978BuiltinTemplateDecl *
979ASTContext::buildBuiltinTemplateDecl(BuiltinTemplateKind BTK,
980 const IdentifierInfo *II) const {
981 auto *BuiltinTemplate = BuiltinTemplateDecl::Create(*this, TUDecl, II, BTK);
982 BuiltinTemplate->setImplicit();
983 TUDecl->addDecl(BuiltinTemplate);
984
985 return BuiltinTemplate;
986}
987
988BuiltinTemplateDecl *
989ASTContext::getMakeIntegerSeqDecl() const {
990 if (!MakeIntegerSeqDecl)
991 MakeIntegerSeqDecl = buildBuiltinTemplateDecl(BTK__make_integer_seq,
992 getMakeIntegerSeqName());
993 return MakeIntegerSeqDecl;
994}
995
Eric Fiselier6ad68552016-07-01 01:24:09 +0000996BuiltinTemplateDecl *
997ASTContext::getTypePackElementDecl() const {
998 if (!TypePackElementDecl)
999 TypePackElementDecl = buildBuiltinTemplateDecl(BTK__type_pack_element,
1000 getTypePackElementName());
1001 return TypePackElementDecl;
1002}
1003
Alp Toker2dea15b2013-12-17 01:22:38 +00001004RecordDecl *ASTContext::buildImplicitRecord(StringRef Name,
1005 RecordDecl::TagKind TK) const {
Alp Toker56b5cc92013-12-15 10:36:26 +00001006 SourceLocation Loc;
1007 RecordDecl *NewDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00001008 if (getLangOpts().CPlusPlus)
1009 NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc,
1010 Loc, &Idents.get(Name));
Alp Toker56b5cc92013-12-15 10:36:26 +00001011 else
Alp Toker2dea15b2013-12-17 01:22:38 +00001012 NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
1013 &Idents.get(Name));
Alp Toker56b5cc92013-12-15 10:36:26 +00001014 NewDecl->setImplicit();
David Majnemerf8637362015-01-15 08:41:25 +00001015 NewDecl->addAttr(TypeVisibilityAttr::CreateImplicit(
1016 const_cast<ASTContext &>(*this), TypeVisibilityAttr::Default));
Alp Toker56b5cc92013-12-15 10:36:26 +00001017 return NewDecl;
1018}
1019
1020TypedefDecl *ASTContext::buildImplicitTypedef(QualType T,
1021 StringRef Name) const {
1022 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
1023 TypedefDecl *NewDecl = TypedefDecl::Create(
1024 const_cast<ASTContext &>(*this), getTranslationUnitDecl(),
1025 SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo);
1026 NewDecl->setImplicit();
1027 return NewDecl;
1028}
1029
Douglas Gregor801c99d2011-08-12 06:49:56 +00001030TypedefDecl *ASTContext::getInt128Decl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00001031 if (!Int128Decl)
1032 Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t");
Douglas Gregor801c99d2011-08-12 06:49:56 +00001033 return Int128Decl;
1034}
1035
1036TypedefDecl *ASTContext::getUInt128Decl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00001037 if (!UInt128Decl)
1038 UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t");
Douglas Gregor801c99d2011-08-12 06:49:56 +00001039 return UInt128Decl;
1040}
Chris Lattner4eb445d2007-01-26 01:27:23 +00001041
John McCall48f2d582009-10-23 23:03:21 +00001042void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
John McCall90d1c2d2009-09-24 23:30:46 +00001043 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +00001044 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +00001045 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +00001046}
1047
Artem Belevichb5bc9232015-09-22 17:23:22 +00001048void ASTContext::InitBuiltinTypes(const TargetInfo &Target,
1049 const TargetInfo *AuxTarget) {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001050 assert((!this->Target || this->Target == &Target) &&
1051 "Incorrect target reinitialization");
Chris Lattner970e54e2006-11-12 00:37:36 +00001052 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +00001053
Douglas Gregore8bbc122011-09-02 00:18:52 +00001054 this->Target = &Target;
Artem Belevichb5bc9232015-09-22 17:23:22 +00001055 this->AuxTarget = AuxTarget;
1056
Douglas Gregore8bbc122011-09-02 00:18:52 +00001057 ABI.reset(createCXXABI(Target));
1058 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
David Tweed31d09b02013-09-13 12:04:22 +00001059 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
Douglas Gregore8bbc122011-09-02 00:18:52 +00001060
Chris Lattner970e54e2006-11-12 00:37:36 +00001061 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +00001062 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +00001063
Chris Lattner970e54e2006-11-12 00:37:36 +00001064 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +00001065 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +00001066 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +00001067 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +00001068 InitBuiltinType(CharTy, BuiltinType::Char_S);
1069 else
1070 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +00001071 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +00001072 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
1073 InitBuiltinType(ShortTy, BuiltinType::Short);
1074 InitBuiltinType(IntTy, BuiltinType::Int);
1075 InitBuiltinType(LongTy, BuiltinType::Long);
1076 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +00001077
Chris Lattner970e54e2006-11-12 00:37:36 +00001078 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +00001079 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
1080 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
1081 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
1082 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
1083 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +00001084
Chris Lattner970e54e2006-11-12 00:37:36 +00001085 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +00001086 InitBuiltinType(FloatTy, BuiltinType::Float);
1087 InitBuiltinType(DoubleTy, BuiltinType::Double);
1088 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001089
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001090 // GNU extension, __float128 for IEEE quadruple precision
1091 InitBuiltinType(Float128Ty, BuiltinType::Float128);
1092
Chris Lattnerf122cef2009-04-30 02:43:43 +00001093 // GNU extension, 128-bit integers.
1094 InitBuiltinType(Int128Ty, BuiltinType::Int128);
1095 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
1096
Hans Wennborg0d81e012013-05-10 10:08:40 +00001097 // C++ 3.9.1p5
1098 if (TargetInfo::isTypeSigned(Target.getWCharType()))
1099 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
1100 else // -fshort-wchar makes wchar_t be unsigned.
1101 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
1102 if (LangOpts.CPlusPlus && LangOpts.WChar)
1103 WideCharTy = WCharTy;
1104 else {
1105 // C99 (or C++ using -fno-wchar).
1106 WideCharTy = getFromTargetType(Target.getWCharType());
1107 }
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001108
James Molloy36365542012-05-04 10:55:22 +00001109 WIntTy = getFromTargetType(Target.getWIntType());
1110
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001111 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1112 InitBuiltinType(Char16Ty, BuiltinType::Char16);
1113 else // C99
1114 Char16Ty = getFromTargetType(Target.getChar16Type());
1115
1116 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1117 InitBuiltinType(Char32Ty, BuiltinType::Char32);
1118 else // C99
1119 Char32Ty = getFromTargetType(Target.getChar32Type());
1120
Douglas Gregor4619e432008-12-05 23:32:09 +00001121 // Placeholder type for type-dependent expressions whose type is
1122 // completely unknown. No code should ever check a type against
1123 // DependentTy and users should never see it; however, it is here to
1124 // help diagnose failures to properly check for type-dependent
1125 // expressions.
1126 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001127
John McCall36e7fe32010-10-12 00:20:44 +00001128 // Placeholder type for functions.
1129 InitBuiltinType(OverloadTy, BuiltinType::Overload);
1130
John McCall0009fcc2011-04-26 20:42:42 +00001131 // Placeholder type for bound members.
1132 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
1133
John McCall526ab472011-10-25 17:37:35 +00001134 // Placeholder type for pseudo-objects.
1135 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
1136
John McCall31996342011-04-07 08:22:57 +00001137 // "any" type; useful for debugger-like clients.
1138 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
1139
John McCall8a6b59a2011-10-17 18:09:15 +00001140 // Placeholder type for unbridged ARC casts.
1141 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
1142
Eli Friedman34866c72012-08-31 00:14:07 +00001143 // Placeholder type for builtin functions.
1144 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
1145
Alexey Bataev1a3320e2015-08-25 14:24:04 +00001146 // Placeholder type for OMP array sections.
1147 if (LangOpts.OpenMP)
1148 InitBuiltinType(OMPArraySectionTy, BuiltinType::OMPArraySection);
1149
Chris Lattner970e54e2006-11-12 00:37:36 +00001150 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +00001151 FloatComplexTy = getComplexType(FloatTy);
1152 DoubleComplexTy = getComplexType(DoubleTy);
1153 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001154 Float128ComplexTy = getComplexType(Float128Ty);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001155
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001156 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +00001157 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
1158 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001159 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001160
Alexey Bader954ba212016-04-08 13:40:33 +00001161 if (LangOpts.OpenCL) {
1162#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1163 InitBuiltinType(SingletonId, BuiltinType::Id);
Alexey Baderb62f1442016-04-13 08:33:41 +00001164#include "clang/Basic/OpenCLImageTypes.def"
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001165
Guy Benyei61054192013-02-07 10:55:47 +00001166 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001167 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
Alexey Bader9c8453f2015-09-15 11:18:52 +00001168 InitBuiltinType(OCLClkEventTy, BuiltinType::OCLClkEvent);
1169 InitBuiltinType(OCLQueueTy, BuiltinType::OCLQueue);
1170 InitBuiltinType(OCLNDRangeTy, BuiltinType::OCLNDRange);
1171 InitBuiltinType(OCLReserveIDTy, BuiltinType::OCLReserveID);
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001172 }
Ted Kremeneke65b0862012-03-06 20:05:56 +00001173
1174 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian29898f42012-04-16 21:03:30 +00001175 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1176 SignedCharTy : BoolTy);
Ted Kremeneke65b0862012-03-06 20:05:56 +00001177
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001178 ObjCConstantStringType = QualType();
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00001179
1180 ObjCSuperType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +00001181
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00001182 // void * type
1183 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl576fd422009-05-10 18:38:11 +00001184
1185 // nullptr type (C++0x 2.14.7)
1186 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001187
1188 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1189 InitBuiltinType(HalfTy, BuiltinType::Half);
Meador Ingecfb60902012-07-01 15:57:25 +00001190
1191 // Builtin type used to help define __builtin_va_list.
Richard Smith9b88a4c2015-07-27 05:40:23 +00001192 VaListTagDecl = nullptr;
Chris Lattner970e54e2006-11-12 00:37:36 +00001193}
1194
David Blaikie9c902b52011-09-25 23:23:43 +00001195DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001196 return SourceMgr.getDiagnostics();
1197}
1198
Douglas Gregor561eceb2010-08-30 16:49:28 +00001199AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
1200 AttrVec *&Result = DeclAttrs[D];
1201 if (!Result) {
1202 void *Mem = Allocate(sizeof(AttrVec));
1203 Result = new (Mem) AttrVec;
1204 }
1205
1206 return *Result;
1207}
1208
1209/// \brief Erase the attributes corresponding to the given declaration.
1210void ASTContext::eraseDeclAttrs(const Decl *D) {
1211 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1212 if (Pos != DeclAttrs.end()) {
1213 Pos->second->~AttrVec();
1214 DeclAttrs.erase(Pos);
1215 }
1216}
1217
Larisse Voufo39a1e502013-08-06 01:03:05 +00001218// FIXME: Remove ?
Douglas Gregor86d142a2009-10-08 07:24:58 +00001219MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +00001220ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001221 assert(Var->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001222 return getTemplateOrSpecializationInfo(Var)
1223 .dyn_cast<MemberSpecializationInfo *>();
1224}
1225
1226ASTContext::TemplateOrSpecializationInfo
1227ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) {
1228 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1229 TemplateOrInstantiation.find(Var);
1230 if (Pos == TemplateOrInstantiation.end())
1231 return TemplateOrSpecializationInfo();
Mike Stump11289f42009-09-09 15:08:12 +00001232
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001233 return Pos->second;
1234}
1235
Mike Stump11289f42009-09-09 15:08:12 +00001236void
Douglas Gregor86d142a2009-10-08 07:24:58 +00001237ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +00001238 TemplateSpecializationKind TSK,
1239 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001240 assert(Inst->isStaticDataMember() && "Not a static data member");
1241 assert(Tmpl->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001242 setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo(
1243 Tmpl, TSK, PointOfInstantiation));
1244}
1245
1246void
1247ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst,
1248 TemplateOrSpecializationInfo TSI) {
1249 assert(!TemplateOrInstantiation[Inst] &&
1250 "Already noted what the variable was instantiated from");
1251 TemplateOrInstantiation[Inst] = TSI;
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001252}
1253
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001254FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
1255 const FunctionDecl *FD){
1256 assert(FD && "Specialization is 0");
1257 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet57928252011-08-14 14:28:49 +00001258 = ClassScopeSpecializationPattern.find(FD);
1259 if (Pos == ClassScopeSpecializationPattern.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001260 return nullptr;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001261
1262 return Pos->second;
1263}
1264
1265void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
1266 FunctionDecl *Pattern) {
1267 assert(FD && "Specialization is 0");
1268 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet57928252011-08-14 14:28:49 +00001269 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001270}
1271
John McCalle61f2ba2009-11-18 02:36:19 +00001272NamedDecl *
Richard Smithd8a9e372016-12-18 21:39:37 +00001273ASTContext::getInstantiatedFromUsingDecl(NamedDecl *UUD) {
1274 auto Pos = InstantiatedFromUsingDecl.find(UUD);
John McCallb96ec562009-12-04 22:46:56 +00001275 if (Pos == InstantiatedFromUsingDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001276 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001277
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001278 return Pos->second;
1279}
1280
1281void
Richard Smithd8a9e372016-12-18 21:39:37 +00001282ASTContext::setInstantiatedFromUsingDecl(NamedDecl *Inst, NamedDecl *Pattern) {
John McCallb96ec562009-12-04 22:46:56 +00001283 assert((isa<UsingDecl>(Pattern) ||
1284 isa<UnresolvedUsingValueDecl>(Pattern) ||
1285 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1286 "pattern decl is not a using decl");
Richard Smithd8a9e372016-12-18 21:39:37 +00001287 assert((isa<UsingDecl>(Inst) ||
1288 isa<UnresolvedUsingValueDecl>(Inst) ||
1289 isa<UnresolvedUsingTypenameDecl>(Inst)) &&
1290 "instantiation did not produce a using decl");
John McCallb96ec562009-12-04 22:46:56 +00001291 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1292 InstantiatedFromUsingDecl[Inst] = Pattern;
1293}
1294
1295UsingShadowDecl *
1296ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1297 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1298 = InstantiatedFromUsingShadowDecl.find(Inst);
1299 if (Pos == InstantiatedFromUsingShadowDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001300 return nullptr;
John McCallb96ec562009-12-04 22:46:56 +00001301
1302 return Pos->second;
1303}
1304
1305void
1306ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1307 UsingShadowDecl *Pattern) {
1308 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1309 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001310}
1311
Anders Carlsson5da84842009-09-01 04:26:58 +00001312FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1313 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1314 = InstantiatedFromUnnamedFieldDecl.find(Field);
1315 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001316 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001317
Anders Carlsson5da84842009-09-01 04:26:58 +00001318 return Pos->second;
1319}
1320
1321void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1322 FieldDecl *Tmpl) {
1323 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1324 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1325 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1326 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +00001327
Anders Carlsson5da84842009-09-01 04:26:58 +00001328 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1329}
1330
Douglas Gregor832940b2010-03-02 23:58:15 +00001331ASTContext::overridden_cxx_method_iterator
1332ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
Clement Courbet6ecaec82016-07-05 07:49:31 +00001333 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1334 OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001335 if (Pos == OverriddenMethods.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001336 return nullptr;
Douglas Gregor832940b2010-03-02 23:58:15 +00001337 return Pos->second.begin();
1338}
1339
1340ASTContext::overridden_cxx_method_iterator
1341ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
Clement Courbet6ecaec82016-07-05 07:49:31 +00001342 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1343 OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001344 if (Pos == OverriddenMethods.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001345 return nullptr;
Douglas Gregor832940b2010-03-02 23:58:15 +00001346 return Pos->second.end();
1347}
1348
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001349unsigned
1350ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
Clement Courbet6ecaec82016-07-05 07:49:31 +00001351 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1352 OverriddenMethods.find(Method->getCanonicalDecl());
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001353 if (Pos == OverriddenMethods.end())
1354 return 0;
Chandler Carruthb1bcd5d2016-06-11 04:45:38 +00001355 return Pos->second.size();
Clement Courbet8251ebf2016-06-10 11:54:43 +00001356}
1357
Clement Courbet6ecaec82016-07-05 07:49:31 +00001358ASTContext::overridden_method_range
1359ASTContext::overridden_methods(const CXXMethodDecl *Method) const {
1360 return overridden_method_range(overridden_methods_begin(Method),
1361 overridden_methods_end(Method));
1362}
1363
Douglas Gregor832940b2010-03-02 23:58:15 +00001364void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1365 const CXXMethodDecl *Overridden) {
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001366 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001367 OverriddenMethods[Method].push_back(Overridden);
1368}
1369
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +00001370void ASTContext::getOverriddenMethods(
1371 const NamedDecl *D,
1372 SmallVectorImpl<const NamedDecl *> &Overridden) const {
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001373 assert(D);
1374
1375 if (const CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidisc8e70082013-04-17 00:09:03 +00001376 Overridden.append(overridden_methods_begin(CXXMethod),
1377 overridden_methods_end(CXXMethod));
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001378 return;
1379 }
1380
1381 const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
1382 if (!Method)
1383 return;
1384
Argyrios Kyrtzidis353f6a42012-10-09 18:19:01 +00001385 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1386 Method->getOverriddenMethods(OverDecls);
Argyrios Kyrtzidisa7a10812012-10-09 20:08:43 +00001387 Overridden.append(OverDecls.begin(), OverDecls.end());
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001388}
1389
Douglas Gregor0f2a3602011-12-03 00:30:27 +00001390void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1391 assert(!Import->NextLocalImport && "Import declaration already in the chain");
1392 assert(!Import->isFromASTFile() && "Non-local import declaration");
1393 if (!FirstLocalImport) {
1394 FirstLocalImport = Import;
1395 LastLocalImport = Import;
1396 return;
1397 }
1398
1399 LastLocalImport->NextLocalImport = Import;
1400 LastLocalImport = Import;
1401}
1402
Chris Lattner53cfe802007-07-18 17:52:12 +00001403//===----------------------------------------------------------------------===//
1404// Type Sizing and Analysis
1405//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +00001406
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001407/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1408/// scalar floating point type.
1409const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +00001410 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001411 assert(BT && "Not a floating point type!");
1412 switch (BT->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001413 default: llvm_unreachable("Not a floating point type!");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001414 case BuiltinType::Half: return Target->getHalfFormat();
Douglas Gregore8bbc122011-09-02 00:18:52 +00001415 case BuiltinType::Float: return Target->getFloatFormat();
1416 case BuiltinType::Double: return Target->getDoubleFormat();
1417 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001418 case BuiltinType::Float128: return Target->getFloat128Format();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001419 }
1420}
1421
Rafael Espindola71eccb32013-08-08 19:53:46 +00001422CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001423 unsigned Align = Target->getCharWidth();
Eli Friedman19a546c2009-02-22 02:56:25 +00001424
John McCall94268702010-10-08 18:24:19 +00001425 bool UseAlignAttrOnly = false;
1426 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1427 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +00001428
John McCall94268702010-10-08 18:24:19 +00001429 // __attribute__((aligned)) can increase or decrease alignment
1430 // *except* on a struct or struct member, where it only increases
1431 // alignment unless 'packed' is also specified.
1432 //
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00001433 // It is an error for alignas to decrease alignment, so we can
John McCall94268702010-10-08 18:24:19 +00001434 // ignore that possibility; Sema should diagnose it.
1435 if (isa<FieldDecl>(D)) {
1436 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1437 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1438 } else {
1439 UseAlignAttrOnly = true;
1440 }
1441 }
Fariborz Jahanian9f107182011-05-05 21:19:14 +00001442 else if (isa<FieldDecl>(D))
1443 UseAlignAttrOnly =
1444 D->hasAttr<PackedAttr>() ||
1445 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall94268702010-10-08 18:24:19 +00001446
John McCall4e819612011-01-20 07:57:12 +00001447 // If we're using the align attribute only, just ignore everything
1448 // else about the declaration and its type.
John McCall94268702010-10-08 18:24:19 +00001449 if (UseAlignAttrOnly) {
John McCall4e819612011-01-20 07:57:12 +00001450 // do nothing
1451
John McCall94268702010-10-08 18:24:19 +00001452 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +00001453 QualType T = VD->getType();
Richard Smithf6d70302014-06-10 23:34:28 +00001454 if (const ReferenceType *RT = T->getAs<ReferenceType>()) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001455 if (ForAlignof)
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001456 T = RT->getPointeeType();
1457 else
1458 T = getPointerType(RT->getPointeeType());
1459 }
Richard Smithf6d70302014-06-10 23:34:28 +00001460 QualType BaseT = getBaseElementType(T);
Akira Hatanakad62f2c82017-01-06 17:56:15 +00001461 if (T->isFunctionType())
1462 Align = getTypeInfoImpl(T.getTypePtr()).Align;
1463 else if (!BaseT->isIncompleteType()) {
John McCall33ddac02011-01-19 10:06:00 +00001464 // Adjust alignments of declarations with array type by the
1465 // large-array alignment on the target.
Rafael Espindola88572752013-08-07 18:08:19 +00001466 if (const ArrayType *arrayType = getAsArrayType(T)) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001467 unsigned MinWidth = Target->getLargeArrayMinWidth();
1468 if (!ForAlignof && MinWidth) {
Rafael Espindola88572752013-08-07 18:08:19 +00001469 if (isa<VariableArrayType>(arrayType))
1470 Align = std::max(Align, Target->getLargeArrayAlign());
1471 else if (isa<ConstantArrayType>(arrayType) &&
1472 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
1473 Align = std::max(Align, Target->getLargeArrayAlign());
1474 }
John McCall33ddac02011-01-19 10:06:00 +00001475 }
Chad Rosier99ee7822011-07-26 07:03:04 +00001476 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Ulrich Weigandfa806422013-05-06 16:23:57 +00001477 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Ulrich Weigandb63f7792015-04-21 17:26:18 +00001478 if (VD->hasGlobalStorage() && !ForAlignof)
Ulrich Weigandfa806422013-05-06 16:23:57 +00001479 Align = std::max(Align, getTargetInfo().getMinGlobalAlign());
1480 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001481 }
John McCall4e819612011-01-20 07:57:12 +00001482
1483 // Fields can be subject to extra alignment constraints, like if
1484 // the field is packed, the struct is packed, or the struct has a
1485 // a max-field-alignment constraint (#pragma pack). So calculate
1486 // the actual alignment of the field within the struct, and then
1487 // (as we're expected to) constrain that by the alignment of the type.
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001488 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
1489 const RecordDecl *Parent = Field->getParent();
1490 // We can only produce a sensible answer if the record is valid.
1491 if (!Parent->isInvalidDecl()) {
1492 const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
John McCall4e819612011-01-20 07:57:12 +00001493
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001494 // Start with the record's overall alignment.
1495 unsigned FieldAlign = toBits(Layout.getAlignment());
John McCall4e819612011-01-20 07:57:12 +00001496
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001497 // Use the GCD of that and the offset within the record.
1498 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1499 if (Offset > 0) {
1500 // Alignment is always a power of 2, so the GCD will be a power of 2,
1501 // which means we get to do this crazy thing instead of Euclid's.
1502 uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1503 if (LowBitOfOffset < FieldAlign)
1504 FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1505 }
1506
1507 Align = std::min(Align, FieldAlign);
John McCall4e819612011-01-20 07:57:12 +00001508 }
Charles Davis3fc51072010-02-23 04:52:00 +00001509 }
Chris Lattner68061312009-01-24 21:53:27 +00001510 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001511
Ken Dyckcc56c542011-01-15 18:38:59 +00001512 return toCharUnitsFromBits(Align);
Chris Lattner68061312009-01-24 21:53:27 +00001513}
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001514
John McCallf1249922012-08-21 04:10:00 +00001515// getTypeInfoDataSizeInChars - Return the size of a type, in
1516// chars. If the type is a record, its data size is returned. This is
1517// the size of the memcpy that's performed when assigning this type
1518// using a trivial copy/move assignment operator.
1519std::pair<CharUnits, CharUnits>
1520ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1521 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1522
1523 // In C++, objects can sometimes be allocated into the tail padding
1524 // of a base-class subobject. We decide whether that's possible
1525 // during class layout, so here we can just trust the layout results.
1526 if (getLangOpts().CPlusPlus) {
1527 if (const RecordType *RT = T->getAs<RecordType>()) {
1528 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1529 sizeAndAlign.first = layout.getDataSize();
1530 }
1531 }
1532
1533 return sizeAndAlign;
1534}
1535
Richard Trieu04d2d942013-05-14 21:59:17 +00001536/// getConstantArrayInfoInChars - Performing the computation in CharUnits
1537/// instead of in bits prevents overflowing the uint64_t for some large arrays.
1538std::pair<CharUnits, CharUnits>
1539static getConstantArrayInfoInChars(const ASTContext &Context,
1540 const ConstantArrayType *CAT) {
1541 std::pair<CharUnits, CharUnits> EltInfo =
1542 Context.getTypeInfoInChars(CAT->getElementType());
1543 uint64_t Size = CAT->getSize().getZExtValue();
Richard Trieuc7509072013-05-14 23:41:50 +00001544 assert((Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity()) <=
1545 (uint64_t)(-1)/Size) &&
Richard Trieu04d2d942013-05-14 21:59:17 +00001546 "Overflow in array type char size evaluation");
1547 uint64_t Width = EltInfo.first.getQuantity() * Size;
1548 unsigned Align = EltInfo.second.getQuantity();
Warren Hunt5ae586a2013-11-01 23:59:41 +00001549 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1550 Context.getTargetInfo().getPointerWidth(0) == 64)
Rui Ueyama83aa9792016-01-14 21:00:27 +00001551 Width = llvm::alignTo(Width, Align);
Richard Trieu04d2d942013-05-14 21:59:17 +00001552 return std::make_pair(CharUnits::fromQuantity(Width),
1553 CharUnits::fromQuantity(Align));
1554}
1555
John McCall87fe5d52010-05-20 01:18:31 +00001556std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001557ASTContext::getTypeInfoInChars(const Type *T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001558 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(T))
1559 return getConstantArrayInfoInChars(*this, CAT);
David Majnemer34b57492014-07-30 01:30:47 +00001560 TypeInfo Info = getTypeInfo(T);
1561 return std::make_pair(toCharUnitsFromBits(Info.Width),
1562 toCharUnitsFromBits(Info.Align));
John McCall87fe5d52010-05-20 01:18:31 +00001563}
1564
1565std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001566ASTContext::getTypeInfoInChars(QualType T) const {
John McCall87fe5d52010-05-20 01:18:31 +00001567 return getTypeInfoInChars(T.getTypePtr());
1568}
1569
David Majnemer34b57492014-07-30 01:30:47 +00001570bool ASTContext::isAlignmentRequired(const Type *T) const {
1571 return getTypeInfo(T).AlignIsRequired;
1572}
Daniel Dunbarc6475872012-03-09 04:12:54 +00001573
David Majnemer34b57492014-07-30 01:30:47 +00001574bool ASTContext::isAlignmentRequired(QualType T) const {
1575 return isAlignmentRequired(T.getTypePtr());
1576}
1577
Richard Smithb2f0f052016-10-10 18:54:32 +00001578unsigned ASTContext::getTypeAlignIfKnown(QualType T) const {
1579 // An alignment on a typedef overrides anything else.
1580 if (auto *TT = T->getAs<TypedefType>())
1581 if (unsigned Align = TT->getDecl()->getMaxAlignment())
1582 return Align;
1583
1584 // If we have an (array of) complete type, we're done.
1585 T = getBaseElementType(T);
1586 if (!T->isIncompleteType())
1587 return getTypeAlign(T);
1588
1589 // If we had an array type, its element type might be a typedef
1590 // type with an alignment attribute.
1591 if (auto *TT = T->getAs<TypedefType>())
1592 if (unsigned Align = TT->getDecl()->getMaxAlignment())
1593 return Align;
1594
1595 // Otherwise, see if the declaration of the type had an attribute.
1596 if (auto *TT = T->getAs<TagType>())
1597 return TT->getDecl()->getMaxAlignment();
1598
1599 return 0;
1600}
1601
David Majnemer34b57492014-07-30 01:30:47 +00001602TypeInfo ASTContext::getTypeInfo(const Type *T) const {
David Majnemerf8d38642014-07-30 08:42:33 +00001603 TypeInfoMap::iterator I = MemoizedTypeInfo.find(T);
1604 if (I != MemoizedTypeInfo.end())
1605 return I->second;
1606
1607 // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup.
1608 TypeInfo TI = getTypeInfoImpl(T);
1609 MemoizedTypeInfo[T] = TI;
Rafael Espindolaeaa88c12014-07-30 04:40:23 +00001610 return TI;
Daniel Dunbarc6475872012-03-09 04:12:54 +00001611}
1612
1613/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1614/// method does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +00001615///
1616/// FIXME: Pointers into different addr spaces could have different sizes and
1617/// alignment requirements: getPointerInfo should take an AddrSpace, this
1618/// should take a QualType, &c.
David Majnemer34b57492014-07-30 01:30:47 +00001619TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
1620 uint64_t Width = 0;
1621 unsigned Align = 8;
1622 bool AlignIsRequired = false;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001623 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001624#define TYPE(Class, Base)
1625#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +00001626#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001627#define DEPENDENT_TYPE(Class, Base) case Type::Class:
David Blaikieab277d62013-07-13 21:08:03 +00001628#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
1629 case Type::Class: \
1630 assert(!T->isDependentType() && "should not see dependent types here"); \
1631 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001632#include "clang/AST/TypeNodes.def"
John McCall15547bb2011-06-28 16:49:23 +00001633 llvm_unreachable("Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001634
Chris Lattner355332d2007-07-13 22:27:08 +00001635 case Type::FunctionNoProto:
1636 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +00001637 // GCC extension: alignof(function) = 32 bits
1638 Width = 0;
1639 Align = 32;
1640 break;
1641
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001642 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +00001643 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +00001644 Width = 0;
1645 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1646 break;
1647
Steve Naroff5c131802007-08-30 01:06:46 +00001648 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001649 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +00001650
David Majnemer34b57492014-07-30 01:30:47 +00001651 TypeInfo EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001652 uint64_t Size = CAT->getSize().getZExtValue();
David Majnemer34b57492014-07-30 01:30:47 +00001653 assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
Daniel Dunbarc6475872012-03-09 04:12:54 +00001654 "Overflow in array type bit size evaluation");
David Majnemer34b57492014-07-30 01:30:47 +00001655 Width = EltInfo.Width * Size;
1656 Align = EltInfo.Align;
Warren Hunt5ae586a2013-11-01 23:59:41 +00001657 if (!getTargetInfo().getCXXABI().isMicrosoft() ||
1658 getTargetInfo().getPointerWidth(0) == 64)
Rui Ueyama83aa9792016-01-14 21:00:27 +00001659 Width = llvm::alignTo(Width, Align);
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001660 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +00001661 }
Nate Begemance4d7fc2008-04-18 23:10:10 +00001662 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001663 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +00001664 const VectorType *VT = cast<VectorType>(T);
David Majnemer34b57492014-07-30 01:30:47 +00001665 TypeInfo EltInfo = getTypeInfo(VT->getElementType());
1666 Width = EltInfo.Width * VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +00001667 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +00001668 // If the alignment is not a power of 2, round up to the next power of 2.
1669 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +00001670 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +00001671 Align = llvm::NextPowerOf2(Align);
Rui Ueyama83aa9792016-01-14 21:00:27 +00001672 Width = llvm::alignTo(Width, Align);
Chris Lattner63d2b362009-10-22 05:17:15 +00001673 }
Chad Rosiercc40ea72012-07-13 23:57:43 +00001674 // Adjust the alignment based on the target max.
1675 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1676 if (TargetVectorAlign && TargetVectorAlign < Align)
1677 Align = TargetVectorAlign;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001678 break;
1679 }
Chris Lattner647fb222007-07-18 18:26:58 +00001680
Chris Lattner7570e9c2008-03-08 08:52:55 +00001681 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +00001682 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001683 default: llvm_unreachable("Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +00001684 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +00001685 // GCC extension: alignof(void) = 8 bits.
1686 Width = 0;
1687 Align = 8;
1688 break;
1689
Chris Lattner6a4f7452007-12-19 19:23:28 +00001690 case BuiltinType::Bool:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001691 Width = Target->getBoolWidth();
1692 Align = Target->getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001693 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001694 case BuiltinType::Char_S:
1695 case BuiltinType::Char_U:
1696 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001697 case BuiltinType::SChar:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001698 Width = Target->getCharWidth();
1699 Align = Target->getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001700 break;
Chris Lattnerad3467e2010-12-25 23:25:43 +00001701 case BuiltinType::WChar_S:
1702 case BuiltinType::WChar_U:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001703 Width = Target->getWCharWidth();
1704 Align = Target->getWCharAlign();
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001705 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001706 case BuiltinType::Char16:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001707 Width = Target->getChar16Width();
1708 Align = Target->getChar16Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001709 break;
1710 case BuiltinType::Char32:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001711 Width = Target->getChar32Width();
1712 Align = Target->getChar32Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001713 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001714 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001715 case BuiltinType::Short:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001716 Width = Target->getShortWidth();
1717 Align = Target->getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001718 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001719 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001720 case BuiltinType::Int:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001721 Width = Target->getIntWidth();
1722 Align = Target->getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001723 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001724 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001725 case BuiltinType::Long:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001726 Width = Target->getLongWidth();
1727 Align = Target->getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001728 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001729 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001730 case BuiltinType::LongLong:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001731 Width = Target->getLongLongWidth();
1732 Align = Target->getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001733 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +00001734 case BuiltinType::Int128:
1735 case BuiltinType::UInt128:
1736 Width = 128;
1737 Align = 128; // int128_t is 128-bit aligned on all targets.
1738 break;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001739 case BuiltinType::Half:
1740 Width = Target->getHalfWidth();
1741 Align = Target->getHalfAlign();
1742 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +00001743 case BuiltinType::Float:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001744 Width = Target->getFloatWidth();
1745 Align = Target->getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001746 break;
1747 case BuiltinType::Double:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001748 Width = Target->getDoubleWidth();
1749 Align = Target->getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001750 break;
1751 case BuiltinType::LongDouble:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001752 Width = Target->getLongDoubleWidth();
1753 Align = Target->getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001754 break;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001755 case BuiltinType::Float128:
1756 Width = Target->getFloat128Width();
1757 Align = Target->getFloat128Align();
1758 break;
Sebastian Redl576fd422009-05-10 18:38:11 +00001759 case BuiltinType::NullPtr:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001760 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1761 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +00001762 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001763 case BuiltinType::ObjCId:
1764 case BuiltinType::ObjCClass:
1765 case BuiltinType::ObjCSel:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001766 Width = Target->getPointerWidth(0);
1767 Align = Target->getPointerAlign(0);
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001768 break;
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00001769 case BuiltinType::OCLSampler: {
1770 auto AS = getTargetAddressSpace(LangAS::opencl_constant);
1771 Width = Target->getPointerWidth(AS);
1772 Align = Target->getPointerAlign(AS);
Guy Benyei61054192013-02-07 10:55:47 +00001773 break;
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00001774 }
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001775 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00001776 case BuiltinType::OCLClkEvent:
1777 case BuiltinType::OCLQueue:
1778 case BuiltinType::OCLNDRange:
1779 case BuiltinType::OCLReserveID:
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001780 // Currently these types are pointers to opaque types.
1781 Width = Target->getPointerWidth(0);
1782 Align = Target->getPointerAlign(0);
1783 break;
Yaxun Liu99444cb2016-08-03 20:38:06 +00001784#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1785 case BuiltinType::Id:
1786#include "clang/Basic/OpenCLImageTypes.def"
1787 {
1788 auto AS = getTargetAddressSpace(Target->getOpenCLImageAddrSpace());
1789 Width = Target->getPointerWidth(AS);
1790 Align = Target->getPointerAlign(AS);
1791 }
Chris Lattner983a8bb2007-07-13 22:13:22 +00001792 }
Chris Lattner48f84b82007-07-15 23:46:53 +00001793 break;
Steve Narofffb4330f2009-06-17 22:40:22 +00001794 case Type::ObjCObjectPointer:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001795 Width = Target->getPointerWidth(0);
1796 Align = Target->getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +00001797 break;
Steve Naroff921a45c2008-09-24 15:05:44 +00001798 case Type::BlockPointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001799 unsigned AS = getTargetAddressSpace(
1800 cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001801 Width = Target->getPointerWidth(AS);
1802 Align = Target->getPointerAlign(AS);
Steve Naroff921a45c2008-09-24 15:05:44 +00001803 break;
1804 }
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001805 case Type::LValueReference:
1806 case Type::RValueReference: {
1807 // alignof and sizeof should never enter this code path here, so we go
1808 // the pointer route.
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001809 unsigned AS = getTargetAddressSpace(
1810 cast<ReferenceType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001811 Width = Target->getPointerWidth(AS);
1812 Align = Target->getPointerAlign(AS);
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001813 break;
1814 }
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001815 case Type::Pointer: {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001816 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001817 Width = Target->getPointerWidth(AS);
1818 Align = Target->getPointerAlign(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001819 break;
1820 }
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001821 case Type::MemberPointer: {
Charles Davis53c59df2010-08-16 03:33:14 +00001822 const MemberPointerType *MPT = cast<MemberPointerType>(T);
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001823 std::tie(Width, Align) = ABI->getMemberPointerWidthAndAlign(MPT);
Anders Carlsson32440a02009-05-17 02:06:04 +00001824 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001825 }
Chris Lattner647fb222007-07-18 18:26:58 +00001826 case Type::Complex: {
1827 // Complex types have the same alignment as their elements, but twice the
1828 // size.
David Majnemer34b57492014-07-30 01:30:47 +00001829 TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType());
1830 Width = EltInfo.Width * 2;
1831 Align = EltInfo.Align;
Chris Lattner647fb222007-07-18 18:26:58 +00001832 break;
1833 }
John McCall8b07ec22010-05-15 11:32:37 +00001834 case Type::ObjCObject:
1835 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Reid Kleckner0503a872013-12-05 01:23:43 +00001836 case Type::Adjusted:
Reid Kleckner8a365022013-06-24 17:51:48 +00001837 case Type::Decayed:
Reid Kleckner0503a872013-12-05 01:23:43 +00001838 return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +00001839 case Type::ObjCInterface: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001840 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +00001841 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001842 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001843 Align = toBits(Layout.getAlignment());
Devang Pateldbb72632008-06-04 21:54:36 +00001844 break;
1845 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001846 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001847 case Type::Enum: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001848 const TagType *TT = cast<TagType>(T);
1849
1850 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor7f971892011-04-20 17:29:44 +00001851 Width = 8;
1852 Align = 8;
Chris Lattner572100b2008-08-09 21:35:13 +00001853 break;
1854 }
Mike Stump11289f42009-09-09 15:08:12 +00001855
David Majnemer475b25e2015-01-21 10:54:38 +00001856 if (const EnumType *ET = dyn_cast<EnumType>(TT)) {
1857 const EnumDecl *ED = ET->getDecl();
1858 TypeInfo Info =
1859 getTypeInfo(ED->getIntegerType()->getUnqualifiedDesugaredType());
1860 if (unsigned AttrAlign = ED->getMaxAlignment()) {
1861 Info.Align = AttrAlign;
1862 Info.AlignIsRequired = true;
1863 }
1864 return Info;
1865 }
Chris Lattner8b23c252008-04-06 22:05:18 +00001866
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001867 const RecordType *RT = cast<RecordType>(TT);
David Majnemer5821ff72015-02-03 08:49:29 +00001868 const RecordDecl *RD = RT->getDecl();
1869 const ASTRecordLayout &Layout = getASTRecordLayout(RD);
Ken Dyckb0fcc592011-02-11 01:54:29 +00001870 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001871 Align = toBits(Layout.getAlignment());
David Majnemer5821ff72015-02-03 08:49:29 +00001872 AlignIsRequired = RD->hasAttr<AlignedAttr>();
Chris Lattner49a953a2007-07-23 22:46:22 +00001873 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001874 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001875
Chris Lattner63d2b362009-10-22 05:17:15 +00001876 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +00001877 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1878 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +00001879
Richard Smith600b5262017-01-26 20:40:47 +00001880 case Type::Auto:
1881 case Type::DeducedTemplateSpecialization: {
1882 const DeducedType *A = cast<DeducedType>(T);
Richard Smith27d807c2013-04-30 13:56:41 +00001883 assert(!A->getDeducedType().isNull() &&
1884 "cannot request the size of an undeduced or dependent auto type");
Matt Beaumont-Gay7a24210e2011-02-22 20:00:16 +00001885 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith30482bc2011-02-20 03:19:35 +00001886 }
1887
Abramo Bagnara924a8f32010-12-10 16:29:40 +00001888 case Type::Paren:
1889 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1890
Manman Rene6be26c2016-09-13 17:25:08 +00001891 case Type::ObjCTypeParam:
1892 return getTypeInfo(cast<ObjCTypeParamType>(T)->desugar().getTypePtr());
1893
Douglas Gregoref462e62009-04-30 17:32:17 +00001894 case Type::Typedef: {
Richard Smithdda56e42011-04-15 14:24:37 +00001895 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
David Majnemer34b57492014-07-30 01:30:47 +00001896 TypeInfo Info = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattner29eb47b2011-02-19 22:55:41 +00001897 // If the typedef has an aligned attribute on it, it overrides any computed
1898 // alignment we have. This violates the GCC documentation (which says that
1899 // attribute(aligned) can only round up) but matches its implementation.
David Majnemer34b57492014-07-30 01:30:47 +00001900 if (unsigned AttrAlign = Typedef->getMaxAlignment()) {
Chris Lattner29eb47b2011-02-19 22:55:41 +00001901 Align = AttrAlign;
David Majnemer34b57492014-07-30 01:30:47 +00001902 AlignIsRequired = true;
David Majnemer37bffb62014-08-04 05:11:01 +00001903 } else {
David Majnemer34b57492014-07-30 01:30:47 +00001904 Align = Info.Align;
David Majnemer37bffb62014-08-04 05:11:01 +00001905 AlignIsRequired = Info.AlignIsRequired;
1906 }
David Majnemer34b57492014-07-30 01:30:47 +00001907 Width = Info.Width;
Douglas Gregordc572a32009-03-30 22:58:21 +00001908 break;
Chris Lattner8b23c252008-04-06 22:05:18 +00001909 }
Douglas Gregoref462e62009-04-30 17:32:17 +00001910
Abramo Bagnara6150c882010-05-11 21:36:43 +00001911 case Type::Elaborated:
1912 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +00001913
John McCall81904512011-01-06 01:58:22 +00001914 case Type::Attributed:
1915 return getTypeInfo(
1916 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1917
Eli Friedman0dfb8892011-10-06 23:00:33 +00001918 case Type::Atomic: {
John McCalla8ec7eb2013-03-07 21:37:17 +00001919 // Start with the base type information.
David Majnemer34b57492014-07-30 01:30:47 +00001920 TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType());
1921 Width = Info.Width;
1922 Align = Info.Align;
John McCalla8ec7eb2013-03-07 21:37:17 +00001923
1924 // If the size of the type doesn't exceed the platform's max
1925 // atomic promotion width, make the size and alignment more
1926 // favorable to atomic operations:
1927 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth()) {
1928 // Round the size up to a power of 2.
1929 if (!llvm::isPowerOf2_64(Width))
1930 Width = llvm::NextPowerOf2(Width);
1931
1932 // Set the alignment equal to the size.
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001933 Align = static_cast<unsigned>(Width);
1934 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00001935 }
Xiuli Pan9c14e282016-01-09 12:53:17 +00001936 break;
1937
1938 case Type::Pipe: {
1939 TypeInfo Info = getTypeInfo(cast<PipeType>(T)->getElementType());
1940 Width = Info.Width;
1941 Align = Info.Align;
1942 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00001943
Douglas Gregoref462e62009-04-30 17:32:17 +00001944 }
Mike Stump11289f42009-09-09 15:08:12 +00001945
Eli Friedman4b72fdd2011-10-14 20:59:01 +00001946 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
David Majnemer34b57492014-07-30 01:30:47 +00001947 return TypeInfo(Width, Align, AlignIsRequired);
Chris Lattner983a8bb2007-07-13 22:13:22 +00001948}
1949
Alexey Bataev00396512015-07-02 03:40:19 +00001950unsigned ASTContext::getOpenMPDefaultSimdAlign(QualType T) const {
1951 unsigned SimdAlign = getTargetInfo().getSimdDefaultAlign();
1952 // Target ppc64 with QPX: simd default alignment for pointer to double is 32.
1953 if ((getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64 ||
1954 getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64le) &&
1955 getTargetInfo().getABI() == "elfv1-qpx" &&
1956 T->isSpecificBuiltinType(BuiltinType::Double))
1957 SimdAlign = 256;
1958 return SimdAlign;
1959}
1960
Ken Dyckcc56c542011-01-15 18:38:59 +00001961/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1962CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1963 return CharUnits::fromQuantity(BitSize / getCharWidth());
1964}
1965
Ken Dyckb0fcc592011-02-11 01:54:29 +00001966/// toBits - Convert a size in characters to a size in characters.
1967int64_t ASTContext::toBits(CharUnits CharSize) const {
1968 return CharSize.getQuantity() * getCharWidth();
1969}
1970
Ken Dyck8c89d592009-12-22 14:23:30 +00001971/// getTypeSizeInChars - Return the size of the specified type, in characters.
1972/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001973CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001974 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00001975}
Jay Foad39c79802011-01-12 09:06:06 +00001976CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001977 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00001978}
1979
Ken Dycka6046ab2010-01-26 17:25:18 +00001980/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +00001981/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00001982CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001983 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001984}
Jay Foad39c79802011-01-12 09:06:06 +00001985CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00001986 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00001987}
1988
Chris Lattnera3402cd2009-01-27 18:08:34 +00001989/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1990/// type for the current target in bits. This can be different than the ABI
1991/// alignment in cases where it is beneficial for performance to overalign
1992/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +00001993unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
David Majnemer34b57492014-07-30 01:30:47 +00001994 TypeInfo TI = getTypeInfo(T);
1995 unsigned ABIAlign = TI.Align;
Eli Friedman7ab09572009-05-25 21:27:19 +00001996
David Majnemere1544562015-04-24 01:25:05 +00001997 T = T->getBaseElementTypeUnsafe();
1998
1999 // The preferred alignment of member pointers is that of a pointer.
2000 if (T->isMemberPointerType())
2001 return getPreferredTypeAlign(getPointerDiffType().getTypePtr());
2002
Andrey Turetskiydb6655f2016-02-10 11:58:46 +00002003 if (!Target->allowsLargerPreferedTypeAlignment())
2004 return ABIAlign;
Robert Lyttoneaf6f362013-11-12 10:09:34 +00002005
Eli Friedman7ab09572009-05-25 21:27:19 +00002006 // Double and long long should be naturally aligned if possible.
David Majnemer1d4db8f2014-02-24 23:43:27 +00002007 if (const ComplexType *CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +00002008 T = CT->getElementType().getTypePtr();
David Majnemer475b25e2015-01-21 10:54:38 +00002009 if (const EnumType *ET = T->getAs<EnumType>())
2010 T = ET->getDecl()->getIntegerType().getTypePtr();
Eli Friedman7ab09572009-05-25 21:27:19 +00002011 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosierb57321a2012-03-21 20:20:47 +00002012 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
2013 T->isSpecificBuiltinType(BuiltinType::ULongLong))
David Majnemer8b6bd572014-02-24 23:34:17 +00002014 // Don't increase the alignment if an alignment attribute was specified on a
2015 // typedef declaration.
David Majnemer34b57492014-07-30 01:30:47 +00002016 if (!TI.AlignIsRequired)
David Majnemer8b6bd572014-02-24 23:34:17 +00002017 return std::max(ABIAlign, (unsigned)getTypeSize(T));
Eli Friedman7ab09572009-05-25 21:27:19 +00002018
Chris Lattnera3402cd2009-01-27 18:08:34 +00002019 return ABIAlign;
2020}
2021
Ulrich Weigandca3cb7f2015-04-21 17:29:35 +00002022/// getTargetDefaultAlignForAttributeAligned - Return the default alignment
2023/// for __attribute__((aligned)) on this target, to be used if no alignment
2024/// value is specified.
Eugene Zelenkod4304d22015-11-04 21:37:17 +00002025unsigned ASTContext::getTargetDefaultAlignForAttributeAligned() const {
Ulrich Weigandca3cb7f2015-04-21 17:29:35 +00002026 return getTargetInfo().getDefaultAlignForAttributeAligned();
2027}
2028
Ulrich Weigandfa806422013-05-06 16:23:57 +00002029/// getAlignOfGlobalVar - Return the alignment in bits that should be given
2030/// to a global variable of the specified type.
2031unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
2032 return std::max(getTypeAlign(T), getTargetInfo().getMinGlobalAlign());
2033}
2034
2035/// getAlignOfGlobalVarInChars - Return the alignment in characters that
2036/// should be given to a global variable of the specified type.
2037CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
2038 return toCharUnitsFromBits(getAlignOfGlobalVar(T));
2039}
2040
David Majnemer08ef2ba2015-06-23 20:34:18 +00002041CharUnits ASTContext::getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const {
2042 CharUnits Offset = CharUnits::Zero();
2043 const ASTRecordLayout *Layout = &getASTRecordLayout(RD);
2044 while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) {
2045 Offset += Layout->getBaseClassOffset(Base);
2046 Layout = &getASTRecordLayout(Base);
2047 }
2048 return Offset;
2049}
2050
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00002051/// DeepCollectObjCIvars -
2052/// This routine first collects all declared, but not synthesized, ivars in
2053/// super class and then collects all ivars, including those synthesized for
2054/// current class. This routine is used for implementation of current class
2055/// when all ivars, declared and synthesized are known.
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00002056///
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00002057void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
2058 bool leafClass,
Jordy Rosea91768e2011-07-22 02:08:32 +00002059 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00002060 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
2061 DeepCollectObjCIvars(SuperClass, false, Ivars);
2062 if (!leafClass) {
Aaron Ballman59abbd42014-03-13 21:09:43 +00002063 for (const auto *I : OI->ivars())
2064 Ivars.push_back(I);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00002065 } else {
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00002066 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Jordy Rosea91768e2011-07-22 02:08:32 +00002067 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00002068 Iv= Iv->getNextIvar())
2069 Ivars.push_back(Iv);
2070 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00002071}
2072
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002073/// CollectInheritedProtocols - Collect all protocols in current class and
2074/// those inherited by it.
2075void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00002076 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002077 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00002078 // We can use protocol_iterator here instead of
2079 // all_referenced_protocol_iterator since we are walking all categories.
Aaron Ballmana9f49e32014-03-13 20:55:22 +00002080 for (auto *Proto : OI->all_referenced_protocols()) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00002081 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00002082 }
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002083
2084 // Categories of this Interface.
Aaron Ballman3fe486a2014-03-13 21:23:55 +00002085 for (const auto *Cat : OI->visible_categories())
2086 CollectInheritedProtocols(Cat, Protocols);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002087
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002088 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
2089 while (SD) {
2090 CollectInheritedProtocols(SD, Protocols);
2091 SD = SD->getSuperClass();
2092 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00002093 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Aaron Ballman19a41762014-03-14 12:55:57 +00002094 for (auto *Proto : OC->protocols()) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00002095 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002096 }
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00002097 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00002098 // Insert the protocol.
2099 if (!Protocols.insert(
2100 const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second)
2101 return;
2102
2103 for (auto *Proto : OP->protocols())
2104 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002105 }
2106}
2107
Jay Foad39c79802011-01-12 09:06:06 +00002108unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00002109 unsigned count = 0;
2110 // Count ivars declared in class extension.
Aaron Ballmanb4a53452014-03-13 21:57:01 +00002111 for (const auto *Ext : OI->known_extensions())
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002112 count += Ext->ivar_size();
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002113
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00002114 // Count ivar defined in this class's implementation. This
2115 // includes synthesized ivars.
2116 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00002117 count += ImplDecl->ivar_size();
2118
Fariborz Jahanian7c809592009-06-04 01:19:09 +00002119 return count;
2120}
2121
Argyrios Kyrtzidis2e809ce2012-02-03 05:58:16 +00002122bool ASTContext::isSentinelNullExpr(const Expr *E) {
2123 if (!E)
2124 return false;
2125
2126 // nullptr_t is always treated as null.
2127 if (E->getType()->isNullPtrType()) return true;
2128
2129 if (E->getType()->isAnyPointerType() &&
2130 E->IgnoreParenCasts()->isNullPointerConstant(*this,
2131 Expr::NPC_ValueDependentIsNull))
2132 return true;
2133
2134 // Unfortunately, __null has type 'int'.
2135 if (isa<GNUNullExpr>(E)) return true;
2136
2137 return false;
2138}
2139
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002140/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
2141ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
2142 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2143 I = ObjCImpls.find(D);
2144 if (I != ObjCImpls.end())
2145 return cast<ObjCImplementationDecl>(I->second);
Craig Topper36250ad2014-05-12 05:36:57 +00002146 return nullptr;
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002147}
2148/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
2149ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
2150 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2151 I = ObjCImpls.find(D);
2152 if (I != ObjCImpls.end())
2153 return cast<ObjCCategoryImplDecl>(I->second);
Craig Topper36250ad2014-05-12 05:36:57 +00002154 return nullptr;
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002155}
2156
2157/// \brief Set the implementation of ObjCInterfaceDecl.
2158void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
2159 ObjCImplementationDecl *ImplD) {
2160 assert(IFaceD && ImplD && "Passed null params");
2161 ObjCImpls[IFaceD] = ImplD;
2162}
2163/// \brief Set the implementation of ObjCCategoryDecl.
2164void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
2165 ObjCCategoryImplDecl *ImplD) {
2166 assert(CatD && ImplD && "Passed null params");
2167 ObjCImpls[CatD] = ImplD;
2168}
2169
Chandler Carruth21c90602015-12-30 03:24:14 +00002170const ObjCMethodDecl *
2171ASTContext::getObjCMethodRedeclaration(const ObjCMethodDecl *MD) const {
2172 return ObjCMethodRedecls.lookup(MD);
2173}
2174
2175void ASTContext::setObjCMethodRedeclaration(const ObjCMethodDecl *MD,
2176 const ObjCMethodDecl *Redecl) {
2177 assert(!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration");
2178 ObjCMethodRedecls[MD] = Redecl;
2179}
2180
Dmitri Gribenko37527c22013-02-03 13:23:21 +00002181const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
2182 const NamedDecl *ND) const {
2183 if (const ObjCInterfaceDecl *ID =
2184 dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002185 return ID;
Dmitri Gribenko37527c22013-02-03 13:23:21 +00002186 if (const ObjCCategoryDecl *CD =
2187 dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002188 return CD->getClassInterface();
Dmitri Gribenko37527c22013-02-03 13:23:21 +00002189 if (const ObjCImplDecl *IMD =
2190 dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002191 return IMD->getClassInterface();
2192
Craig Topper36250ad2014-05-12 05:36:57 +00002193 return nullptr;
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002194}
2195
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002196/// \brief Get the copy initialization expression of VarDecl,or NULL if
2197/// none exists.
Fariborz Jahanian50198092010-12-02 17:02:11 +00002198Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002199 assert(VD && "Passed null params");
2200 assert(VD->hasAttr<BlocksAttr>() &&
2201 "getBlockVarCopyInits - not __block var");
Fariborz Jahanian50198092010-12-02 17:02:11 +00002202 llvm::DenseMap<const VarDecl*, Expr*>::iterator
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002203 I = BlockVarCopyInits.find(VD);
Craig Topper36250ad2014-05-12 05:36:57 +00002204 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : nullptr;
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002205}
2206
2207/// \brief Set the copy inialization expression of a block var decl.
2208void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
2209 assert(VD && Init && "Passed null params");
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002210 assert(VD->hasAttr<BlocksAttr>() &&
2211 "setBlockVarCopyInits - not __block var");
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002212 BlockVarCopyInits[VD] = Init;
2213}
2214
John McCallbcd03502009-12-07 02:54:59 +00002215TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00002216 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00002217 if (!DataSize)
2218 DataSize = TypeLoc::getFullDataSizeForType(T);
2219 else
2220 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00002221 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00002222
John McCallbcd03502009-12-07 02:54:59 +00002223 TypeSourceInfo *TInfo =
2224 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
2225 new (TInfo) TypeSourceInfo(T);
2226 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00002227}
2228
John McCallbcd03502009-12-07 02:54:59 +00002229TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002230 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00002231 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00002232 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00002233 return DI;
2234}
2235
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002236const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00002237ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Craig Topper36250ad2014-05-12 05:36:57 +00002238 return getObjCLayout(D, nullptr);
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002239}
2240
2241const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00002242ASTContext::getASTObjCImplementationLayout(
2243 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002244 return getObjCLayout(D->getClassInterface(), D);
2245}
2246
Chris Lattner983a8bb2007-07-13 22:13:22 +00002247//===----------------------------------------------------------------------===//
2248// Type creation/memoization methods
2249//===----------------------------------------------------------------------===//
2250
Jay Foad39c79802011-01-12 09:06:06 +00002251QualType
John McCall33ddac02011-01-19 10:06:00 +00002252ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
2253 unsigned fastQuals = quals.getFastQualifiers();
2254 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00002255
2256 // Check if we've already instantiated this type.
2257 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002258 ExtQuals::Profile(ID, baseType, quals);
Craig Topper36250ad2014-05-12 05:36:57 +00002259 void *insertPos = nullptr;
John McCall33ddac02011-01-19 10:06:00 +00002260 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
2261 assert(eq->getQualifiers() == quals);
2262 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002263 }
2264
John McCall33ddac02011-01-19 10:06:00 +00002265 // If the base type is not canonical, make the appropriate canonical type.
2266 QualType canon;
2267 if (!baseType->isCanonicalUnqualified()) {
2268 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall18ce25e2012-02-08 00:46:36 +00002269 canonSplit.Quals.addConsistentQualifiers(quals);
2270 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002271
2272 // Re-find the insert position.
2273 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
2274 }
2275
2276 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
2277 ExtQualNodes.InsertNode(eq, insertPos);
2278 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002279}
2280
Jay Foad39c79802011-01-12 09:06:06 +00002281QualType
2282ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002283 QualType CanT = getCanonicalType(T);
2284 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00002285 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00002286
John McCall8ccfcb52009-09-24 19:53:00 +00002287 // If we are composing extended qualifiers together, merge together
2288 // into one ExtQuals node.
2289 QualifierCollector Quals;
2290 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002291
John McCall8ccfcb52009-09-24 19:53:00 +00002292 // If this type already has an address space specified, it cannot get
2293 // another one.
2294 assert(!Quals.hasAddressSpace() &&
2295 "Type cannot be in multiple addr spaces!");
2296 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00002297
John McCall8ccfcb52009-09-24 19:53:00 +00002298 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00002299}
2300
Chris Lattnerd60183d2009-02-18 22:53:11 +00002301QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00002302 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002303 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00002304 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002305 return T;
Mike Stump11289f42009-09-09 15:08:12 +00002306
John McCall53fa7142010-12-24 02:08:15 +00002307 if (const PointerType *ptr = T->getAs<PointerType>()) {
2308 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00002309 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00002310 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
2311 return getPointerType(ResultType);
2312 }
2313 }
Mike Stump11289f42009-09-09 15:08:12 +00002314
John McCall8ccfcb52009-09-24 19:53:00 +00002315 // If we are composing extended qualifiers together, merge together
2316 // into one ExtQuals node.
2317 QualifierCollector Quals;
2318 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002319
John McCall8ccfcb52009-09-24 19:53:00 +00002320 // If this type already has an ObjCGC specified, it cannot get
2321 // another one.
2322 assert(!Quals.hasObjCGCAttr() &&
2323 "Type cannot have multiple ObjCGCs!");
2324 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00002325
John McCall8ccfcb52009-09-24 19:53:00 +00002326 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002327}
Chris Lattner983a8bb2007-07-13 22:13:22 +00002328
John McCall4f5019e2010-12-19 02:44:49 +00002329const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
2330 FunctionType::ExtInfo Info) {
2331 if (T->getExtInfo() == Info)
2332 return T;
2333
2334 QualType Result;
2335 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
Alp Toker314cc812014-01-25 16:55:45 +00002336 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
John McCall4f5019e2010-12-19 02:44:49 +00002337 } else {
2338 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
2339 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2340 EPI.ExtInfo = Info;
Alp Toker314cc812014-01-25 16:55:45 +00002341 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
John McCall4f5019e2010-12-19 02:44:49 +00002342 }
2343
2344 return cast<FunctionType>(Result.getTypePtr());
2345}
2346
Richard Smith2a7d4812013-05-04 07:00:32 +00002347void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
2348 QualType ResultType) {
Richard Smith1fa5d642013-05-11 05:45:24 +00002349 FD = FD->getMostRecentDecl();
2350 while (true) {
Richard Smith2a7d4812013-05-04 07:00:32 +00002351 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
2352 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
Alp Toker9cacbab2014-01-20 20:26:09 +00002353 FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI));
Richard Smith1fa5d642013-05-11 05:45:24 +00002354 if (FunctionDecl *Next = FD->getPreviousDecl())
2355 FD = Next;
2356 else
2357 break;
Richard Smith2a7d4812013-05-04 07:00:32 +00002358 }
Richard Smith1fa5d642013-05-11 05:45:24 +00002359 if (ASTMutationListener *L = getASTMutationListener())
2360 L->DeducedReturnType(FD, ResultType);
Richard Smith2a7d4812013-05-04 07:00:32 +00002361}
2362
Richard Smith0b3a4622014-11-13 20:01:57 +00002363/// Get a function type and produce the equivalent function type with the
2364/// specified exception specification. Type sugar that can be present on a
2365/// declaration of a function with an exception specification is permitted
2366/// and preserved. Other type sugar (for instance, typedefs) is not.
2367static QualType getFunctionTypeWithExceptionSpec(
2368 ASTContext &Context, QualType Orig,
2369 const FunctionProtoType::ExceptionSpecInfo &ESI) {
2370 // Might have some parens.
2371 if (auto *PT = dyn_cast<ParenType>(Orig))
2372 return Context.getParenType(
2373 getFunctionTypeWithExceptionSpec(Context, PT->getInnerType(), ESI));
2374
2375 // Might have a calling-convention attribute.
2376 if (auto *AT = dyn_cast<AttributedType>(Orig))
2377 return Context.getAttributedType(
2378 AT->getAttrKind(),
2379 getFunctionTypeWithExceptionSpec(Context, AT->getModifiedType(), ESI),
2380 getFunctionTypeWithExceptionSpec(Context, AT->getEquivalentType(),
2381 ESI));
2382
2383 // Anything else must be a function type. Rebuild it with the new exception
2384 // specification.
2385 const FunctionProtoType *Proto = cast<FunctionProtoType>(Orig);
2386 return Context.getFunctionType(
2387 Proto->getReturnType(), Proto->getParamTypes(),
2388 Proto->getExtProtoInfo().withExceptionSpec(ESI));
2389}
2390
Richard Smithdfe85e22016-12-15 02:35:39 +00002391bool ASTContext::hasSameFunctionTypeIgnoringExceptionSpec(QualType T,
2392 QualType U) {
2393 return hasSameType(T, U) ||
2394 (getLangOpts().CPlusPlus1z &&
2395 hasSameType(getFunctionTypeWithExceptionSpec(*this, T, EST_None),
2396 getFunctionTypeWithExceptionSpec(*this, U, EST_None)));
2397}
2398
Richard Smith0b3a4622014-11-13 20:01:57 +00002399void ASTContext::adjustExceptionSpec(
2400 FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI,
2401 bool AsWritten) {
2402 // Update the type.
2403 QualType Updated =
2404 getFunctionTypeWithExceptionSpec(*this, FD->getType(), ESI);
2405 FD->setType(Updated);
2406
2407 if (!AsWritten)
2408 return;
2409
2410 // Update the type in the type source information too.
2411 if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
2412 // If the type and the type-as-written differ, we may need to update
2413 // the type-as-written too.
2414 if (TSInfo->getType() != FD->getType())
2415 Updated = getFunctionTypeWithExceptionSpec(*this, TSInfo->getType(), ESI);
2416
2417 // FIXME: When we get proper type location information for exceptions,
2418 // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
2419 // up the TypeSourceInfo;
2420 assert(TypeLoc::getFullDataSizeForType(Updated) ==
2421 TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
2422 "TypeLoc size mismatch from updating exception specification");
2423 TSInfo->overrideType(Updated);
2424 }
2425}
2426
Chris Lattnerc6395932007-06-22 20:56:16 +00002427/// getComplexType - Return the uniqued reference to the type for a complex
2428/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00002429QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00002430 // Unique pointers, to guarantee there is only one pointer of a particular
2431 // structure.
2432 llvm::FoldingSetNodeID ID;
2433 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002434
Craig Topper36250ad2014-05-12 05:36:57 +00002435 void *InsertPos = nullptr;
Chris Lattnerc6395932007-06-22 20:56:16 +00002436 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
2437 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002438
Chris Lattnerc6395932007-06-22 20:56:16 +00002439 // If the pointee type isn't canonical, this won't be a canonical type either,
2440 // so fill in the canonical type field.
2441 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002442 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002443 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002444
Chris Lattnerc6395932007-06-22 20:56:16 +00002445 // Get the new insert position for the node we care about.
2446 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002447 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00002448 }
John McCall90d1c2d2009-09-24 23:30:46 +00002449 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00002450 Types.push_back(New);
2451 ComplexTypes.InsertNode(New, InsertPos);
2452 return QualType(New, 0);
2453}
2454
Chris Lattner970e54e2006-11-12 00:37:36 +00002455/// getPointerType - Return the uniqued reference to the type for a pointer to
2456/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002457QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00002458 // Unique pointers, to guarantee there is only one pointer of a particular
2459 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002460 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00002461 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002462
Craig Topper36250ad2014-05-12 05:36:57 +00002463 void *InsertPos = nullptr;
Chris Lattner67521df2007-01-27 01:29:36 +00002464 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002465 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002466
Chris Lattner7ccecb92006-11-12 08:50:50 +00002467 // If the pointee type isn't canonical, this won't be a canonical type either,
2468 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002469 QualType Canonical;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002470 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002471 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002472
Bob Wilsonc8541f22013-03-15 17:12:43 +00002473 // Get the new insert position for the node we care about.
2474 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002475 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002476 }
John McCall90d1c2d2009-09-24 23:30:46 +00002477 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00002478 Types.push_back(New);
2479 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002480 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00002481}
2482
Reid Kleckner0503a872013-12-05 01:23:43 +00002483QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const {
2484 llvm::FoldingSetNodeID ID;
2485 AdjustedType::Profile(ID, Orig, New);
Craig Topper36250ad2014-05-12 05:36:57 +00002486 void *InsertPos = nullptr;
Reid Kleckner0503a872013-12-05 01:23:43 +00002487 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2488 if (AT)
2489 return QualType(AT, 0);
2490
2491 QualType Canonical = getCanonicalType(New);
2492
2493 // Get the new insert position for the node we care about.
2494 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002495 assert(!AT && "Shouldn't be in the map!");
Reid Kleckner0503a872013-12-05 01:23:43 +00002496
2497 AT = new (*this, TypeAlignment)
2498 AdjustedType(Type::Adjusted, Orig, New, Canonical);
2499 Types.push_back(AT);
2500 AdjustedTypes.InsertNode(AT, InsertPos);
2501 return QualType(AT, 0);
2502}
2503
Reid Kleckner8a365022013-06-24 17:51:48 +00002504QualType ASTContext::getDecayedType(QualType T) const {
2505 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
2506
Reid Kleckner8a365022013-06-24 17:51:48 +00002507 QualType Decayed;
2508
2509 // C99 6.7.5.3p7:
2510 // A declaration of a parameter as "array of type" shall be
2511 // adjusted to "qualified pointer to type", where the type
2512 // qualifiers (if any) are those specified within the [ and ] of
2513 // the array type derivation.
2514 if (T->isArrayType())
2515 Decayed = getArrayDecayedType(T);
2516
2517 // C99 6.7.5.3p8:
2518 // A declaration of a parameter as "function returning type"
2519 // shall be adjusted to "pointer to function returning type", as
2520 // in 6.3.2.1.
2521 if (T->isFunctionType())
2522 Decayed = getPointerType(T);
2523
Reid Kleckner0503a872013-12-05 01:23:43 +00002524 llvm::FoldingSetNodeID ID;
2525 AdjustedType::Profile(ID, T, Decayed);
Craig Topper36250ad2014-05-12 05:36:57 +00002526 void *InsertPos = nullptr;
Reid Kleckner0503a872013-12-05 01:23:43 +00002527 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2528 if (AT)
2529 return QualType(AT, 0);
2530
Reid Kleckner8a365022013-06-24 17:51:48 +00002531 QualType Canonical = getCanonicalType(Decayed);
2532
2533 // Get the new insert position for the node we care about.
Reid Kleckner0503a872013-12-05 01:23:43 +00002534 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002535 assert(!AT && "Shouldn't be in the map!");
Reid Kleckner8a365022013-06-24 17:51:48 +00002536
Reid Kleckner0503a872013-12-05 01:23:43 +00002537 AT = new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical);
2538 Types.push_back(AT);
2539 AdjustedTypes.InsertNode(AT, InsertPos);
2540 return QualType(AT, 0);
Reid Kleckner8a365022013-06-24 17:51:48 +00002541}
2542
Mike Stump11289f42009-09-09 15:08:12 +00002543/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00002544/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00002545QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00002546 assert(T->isFunctionType() && "block of function types only");
2547 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00002548 // structure.
2549 llvm::FoldingSetNodeID ID;
2550 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002551
Craig Topper36250ad2014-05-12 05:36:57 +00002552 void *InsertPos = nullptr;
Steve Naroffec33ed92008-08-27 16:04:49 +00002553 if (BlockPointerType *PT =
2554 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2555 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002556
2557 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00002558 // type either so fill in the canonical type field.
2559 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002560 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00002561 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002562
Steve Naroffec33ed92008-08-27 16:04:49 +00002563 // Get the new insert position for the node we care about.
2564 BlockPointerType *NewIP =
2565 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002566 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00002567 }
John McCall90d1c2d2009-09-24 23:30:46 +00002568 BlockPointerType *New
2569 = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00002570 Types.push_back(New);
2571 BlockPointerTypes.InsertNode(New, InsertPos);
2572 return QualType(New, 0);
2573}
2574
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002575/// getLValueReferenceType - Return the uniqued reference to the type for an
2576/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002577QualType
2578ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Douglas Gregor291e8ee2011-05-21 22:16:50 +00002579 assert(getCanonicalType(T) != OverloadTy &&
2580 "Unresolved overloaded function type");
2581
Bill Wendling3708c182007-05-27 10:15:43 +00002582 // Unique pointers, to guarantee there is only one pointer of a particular
2583 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002584 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002585 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002586
Craig Topper36250ad2014-05-12 05:36:57 +00002587 void *InsertPos = nullptr;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002588 if (LValueReferenceType *RT =
2589 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00002590 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002591
John McCallfc93cf92009-10-22 22:37:11 +00002592 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2593
Bill Wendling3708c182007-05-27 10:15:43 +00002594 // If the referencee type isn't canonical, this won't be a canonical type
2595 // either, so fill in the canonical type field.
2596 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002597 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
2598 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2599 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002600
Bill Wendling3708c182007-05-27 10:15:43 +00002601 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002602 LValueReferenceType *NewIP =
2603 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002604 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00002605 }
2606
John McCall90d1c2d2009-09-24 23:30:46 +00002607 LValueReferenceType *New
John McCallfc93cf92009-10-22 22:37:11 +00002608 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
2609 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002610 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002611 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00002612
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002613 return QualType(New, 0);
2614}
2615
2616/// getRValueReferenceType - Return the uniqued reference to the type for an
2617/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002618QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002619 // Unique pointers, to guarantee there is only one pointer of a particular
2620 // structure.
2621 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002622 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002623
Craig Topper36250ad2014-05-12 05:36:57 +00002624 void *InsertPos = nullptr;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002625 if (RValueReferenceType *RT =
2626 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2627 return QualType(RT, 0);
2628
John McCallfc93cf92009-10-22 22:37:11 +00002629 const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2630
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002631 // If the referencee type isn't canonical, this won't be a canonical type
2632 // either, so fill in the canonical type field.
2633 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002634 if (InnerRef || !T.isCanonical()) {
2635 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2636 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002637
2638 // Get the new insert position for the node we care about.
2639 RValueReferenceType *NewIP =
2640 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002641 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002642 }
2643
John McCall90d1c2d2009-09-24 23:30:46 +00002644 RValueReferenceType *New
2645 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002646 Types.push_back(New);
2647 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00002648 return QualType(New, 0);
2649}
2650
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002651/// getMemberPointerType - Return the uniqued reference to the type for a
2652/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00002653QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002654 // Unique pointers, to guarantee there is only one pointer of a particular
2655 // structure.
2656 llvm::FoldingSetNodeID ID;
2657 MemberPointerType::Profile(ID, T, Cls);
2658
Craig Topper36250ad2014-05-12 05:36:57 +00002659 void *InsertPos = nullptr;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002660 if (MemberPointerType *PT =
2661 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2662 return QualType(PT, 0);
2663
2664 // If the pointee or class type isn't canonical, this won't be a canonical
2665 // type either, so fill in the canonical type field.
2666 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00002667 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002668 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
2669
2670 // Get the new insert position for the node we care about.
2671 MemberPointerType *NewIP =
2672 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002673 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002674 }
John McCall90d1c2d2009-09-24 23:30:46 +00002675 MemberPointerType *New
2676 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002677 Types.push_back(New);
2678 MemberPointerTypes.InsertNode(New, InsertPos);
2679 return QualType(New, 0);
2680}
2681
Mike Stump11289f42009-09-09 15:08:12 +00002682/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00002683/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00002684QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00002685 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002686 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002687 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00002688 assert((EltTy->isDependentType() ||
2689 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00002690 "Constant array of VLAs is illegal!");
2691
Chris Lattnere2df3f92009-05-13 04:12:56 +00002692 // Convert the array size into a canonical width matching the pointer size for
2693 // the target.
2694 llvm::APInt ArySize(ArySizeIn);
Jay Foad6d4db0c2010-12-07 08:25:34 +00002695 ArySize =
Douglas Gregore8bbc122011-09-02 00:18:52 +00002696 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
Mike Stump11289f42009-09-09 15:08:12 +00002697
Chris Lattner23b7eb62007-06-15 23:05:46 +00002698 llvm::FoldingSetNodeID ID;
Abramo Bagnara92141d22011-01-27 19:55:10 +00002699 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00002700
Craig Topper36250ad2014-05-12 05:36:57 +00002701 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002702 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002703 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002704 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002705
John McCall33ddac02011-01-19 10:06:00 +00002706 // If the element type isn't canonical or has qualifiers, this won't
2707 // be a canonical type either, so fill in the canonical type field.
2708 QualType Canon;
2709 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2710 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002711 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002712 ASM, IndexTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002713 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002714
Chris Lattner36f8e652007-01-27 08:31:04 +00002715 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00002716 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00002717 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002718 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00002719 }
Mike Stump11289f42009-09-09 15:08:12 +00002720
John McCall90d1c2d2009-09-24 23:30:46 +00002721 ConstantArrayType *New = new(*this,TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002722 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00002723 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00002724 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002725 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00002726}
2727
John McCall06549462011-01-18 08:40:38 +00002728/// getVariableArrayDecayedType - Turns the given type, which may be
2729/// variably-modified, into the corresponding type with all the known
2730/// sizes replaced with [*].
2731QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
2732 // Vastly most common case.
2733 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002734
John McCall06549462011-01-18 08:40:38 +00002735 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002736
John McCall06549462011-01-18 08:40:38 +00002737 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00002738 const Type *ty = split.Ty;
John McCall06549462011-01-18 08:40:38 +00002739 switch (ty->getTypeClass()) {
2740#define TYPE(Class, Base)
2741#define ABSTRACT_TYPE(Class, Base)
2742#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2743#include "clang/AST/TypeNodes.def"
2744 llvm_unreachable("didn't desugar past all non-canonical types?");
2745
2746 // These types should never be variably-modified.
2747 case Type::Builtin:
2748 case Type::Complex:
2749 case Type::Vector:
2750 case Type::ExtVector:
2751 case Type::DependentSizedExtVector:
2752 case Type::ObjCObject:
2753 case Type::ObjCInterface:
2754 case Type::ObjCObjectPointer:
2755 case Type::Record:
2756 case Type::Enum:
2757 case Type::UnresolvedUsing:
2758 case Type::TypeOfExpr:
2759 case Type::TypeOf:
2760 case Type::Decltype:
Alexis Hunte852b102011-05-24 22:41:36 +00002761 case Type::UnaryTransform:
John McCall06549462011-01-18 08:40:38 +00002762 case Type::DependentName:
2763 case Type::InjectedClassName:
2764 case Type::TemplateSpecialization:
2765 case Type::DependentTemplateSpecialization:
2766 case Type::TemplateTypeParm:
2767 case Type::SubstTemplateTypeParmPack:
Richard Smith30482bc2011-02-20 03:19:35 +00002768 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00002769 case Type::DeducedTemplateSpecialization:
John McCall06549462011-01-18 08:40:38 +00002770 case Type::PackExpansion:
2771 llvm_unreachable("type should never be variably-modified");
2772
2773 // These types can be variably-modified but should never need to
2774 // further decay.
2775 case Type::FunctionNoProto:
2776 case Type::FunctionProto:
2777 case Type::BlockPointer:
2778 case Type::MemberPointer:
Xiuli Pan9c14e282016-01-09 12:53:17 +00002779 case Type::Pipe:
John McCall06549462011-01-18 08:40:38 +00002780 return type;
2781
2782 // These types can be variably-modified. All these modifications
2783 // preserve structure except as noted by comments.
2784 // TODO: if we ever care about optimizing VLAs, there are no-op
2785 // optimizations available here.
2786 case Type::Pointer:
2787 result = getPointerType(getVariableArrayDecayedType(
2788 cast<PointerType>(ty)->getPointeeType()));
2789 break;
2790
2791 case Type::LValueReference: {
2792 const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
2793 result = getLValueReferenceType(
2794 getVariableArrayDecayedType(lv->getPointeeType()),
2795 lv->isSpelledAsLValue());
2796 break;
2797 }
2798
2799 case Type::RValueReference: {
2800 const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
2801 result = getRValueReferenceType(
2802 getVariableArrayDecayedType(lv->getPointeeType()));
2803 break;
2804 }
2805
Eli Friedman0dfb8892011-10-06 23:00:33 +00002806 case Type::Atomic: {
2807 const AtomicType *at = cast<AtomicType>(ty);
2808 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
2809 break;
2810 }
2811
John McCall06549462011-01-18 08:40:38 +00002812 case Type::ConstantArray: {
2813 const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
2814 result = getConstantArrayType(
2815 getVariableArrayDecayedType(cat->getElementType()),
2816 cat->getSize(),
2817 cat->getSizeModifier(),
2818 cat->getIndexTypeCVRQualifiers());
2819 break;
2820 }
2821
2822 case Type::DependentSizedArray: {
2823 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
2824 result = getDependentSizedArrayType(
2825 getVariableArrayDecayedType(dat->getElementType()),
2826 dat->getSizeExpr(),
2827 dat->getSizeModifier(),
2828 dat->getIndexTypeCVRQualifiers(),
2829 dat->getBracketsRange());
2830 break;
2831 }
2832
2833 // Turn incomplete types into [*] types.
2834 case Type::IncompleteArray: {
2835 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
2836 result = getVariableArrayType(
2837 getVariableArrayDecayedType(iat->getElementType()),
Craig Topper36250ad2014-05-12 05:36:57 +00002838 /*size*/ nullptr,
John McCall06549462011-01-18 08:40:38 +00002839 ArrayType::Normal,
2840 iat->getIndexTypeCVRQualifiers(),
2841 SourceRange());
2842 break;
2843 }
2844
2845 // Turn VLA types into [*] types.
2846 case Type::VariableArray: {
2847 const VariableArrayType *vat = cast<VariableArrayType>(ty);
2848 result = getVariableArrayType(
2849 getVariableArrayDecayedType(vat->getElementType()),
Craig Topper36250ad2014-05-12 05:36:57 +00002850 /*size*/ nullptr,
John McCall06549462011-01-18 08:40:38 +00002851 ArrayType::Star,
2852 vat->getIndexTypeCVRQualifiers(),
2853 vat->getBracketsRange());
2854 break;
2855 }
2856 }
2857
2858 // Apply the top-level qualifiers from the original.
John McCall18ce25e2012-02-08 00:46:36 +00002859 return getQualifiedType(result, split.Quals);
John McCall06549462011-01-18 08:40:38 +00002860}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00002861
Steve Naroffcadebd02007-08-30 18:14:25 +00002862/// getVariableArrayType - Returns a non-unique reference to the type for a
2863/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00002864QualType ASTContext::getVariableArrayType(QualType EltTy,
2865 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00002866 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002867 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00002868 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002869 // Since we don't unique expressions, it isn't possible to unique VLA's
2870 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00002871 QualType Canon;
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002872
John McCall33ddac02011-01-19 10:06:00 +00002873 // Be sure to pull qualifiers off the element type.
2874 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2875 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00002876 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00002877 IndexTypeQuals, Brackets);
John McCall18ce25e2012-02-08 00:46:36 +00002878 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00002879 }
2880
John McCall90d1c2d2009-09-24 23:30:46 +00002881 VariableArrayType *New = new(*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00002882 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00002883
2884 VariableArrayTypes.push_back(New);
2885 Types.push_back(New);
2886 return QualType(New, 0);
2887}
2888
Douglas Gregor4619e432008-12-05 23:32:09 +00002889/// getDependentSizedArrayType - Returns a non-unique reference to
2890/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00002891/// type.
John McCall33ddac02011-01-19 10:06:00 +00002892QualType ASTContext::getDependentSizedArrayType(QualType elementType,
2893 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00002894 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002895 unsigned elementTypeQuals,
2896 SourceRange brackets) const {
2897 assert((!numElements || numElements->isTypeDependent() ||
2898 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00002899 "Size must be type- or value-dependent!");
2900
John McCall33ddac02011-01-19 10:06:00 +00002901 // Dependently-sized array types that do not have a specified number
2902 // of elements will have their sizes deduced from a dependent
2903 // initializer. We do no canonicalization here at all, which is okay
2904 // because they can't be used in most locations.
2905 if (!numElements) {
2906 DependentSizedArrayType *newType
2907 = new (*this, TypeAlignment)
2908 DependentSizedArrayType(*this, elementType, QualType(),
2909 numElements, ASM, elementTypeQuals,
2910 brackets);
2911 Types.push_back(newType);
2912 return QualType(newType, 0);
2913 }
2914
2915 // Otherwise, we actually build a new type every time, but we
2916 // also build a canonical type.
2917
2918 SplitQualType canonElementType = getCanonicalType(elementType).split();
2919
Craig Topper36250ad2014-05-12 05:36:57 +00002920 void *insertPos = nullptr;
Douglas Gregorc42075a2010-02-04 18:10:26 +00002921 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002922 DependentSizedArrayType::Profile(ID, *this,
John McCall18ce25e2012-02-08 00:46:36 +00002923 QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002924 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002925
John McCall33ddac02011-01-19 10:06:00 +00002926 // Look for an existing type with these properties.
2927 DependentSizedArrayType *canonTy =
2928 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002929
John McCall33ddac02011-01-19 10:06:00 +00002930 // If we don't have one, build one.
2931 if (!canonTy) {
2932 canonTy = new (*this, TypeAlignment)
John McCall18ce25e2012-02-08 00:46:36 +00002933 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002934 QualType(), numElements, ASM, elementTypeQuals,
2935 brackets);
2936 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2937 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00002938 }
2939
John McCall33ddac02011-01-19 10:06:00 +00002940 // Apply qualifiers from the element type to the array.
2941 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall18ce25e2012-02-08 00:46:36 +00002942 canonElementType.Quals);
Mike Stump11289f42009-09-09 15:08:12 +00002943
David Majnemer16a74702015-07-24 05:54:19 +00002944 // If we didn't need extra canonicalization for the element type or the size
2945 // expression, then just use that as our result.
2946 if (QualType(canonElementType.Ty, 0) == elementType &&
2947 canonTy->getSizeExpr() == numElements)
John McCall33ddac02011-01-19 10:06:00 +00002948 return canon;
2949
2950 // Otherwise, we need to build a type which follows the spelling
2951 // of the element type.
2952 DependentSizedArrayType *sugaredType
2953 = new (*this, TypeAlignment)
2954 DependentSizedArrayType(*this, elementType, canon, numElements,
2955 ASM, elementTypeQuals, brackets);
2956 Types.push_back(sugaredType);
2957 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00002958}
2959
John McCall33ddac02011-01-19 10:06:00 +00002960QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00002961 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00002962 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00002963 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002964 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002965
Craig Topper36250ad2014-05-12 05:36:57 +00002966 void *insertPos = nullptr;
John McCall33ddac02011-01-19 10:06:00 +00002967 if (IncompleteArrayType *iat =
2968 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2969 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00002970
2971 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00002972 // either, so fill in the canonical type field. We also have to pull
2973 // qualifiers off the element type.
2974 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00002975
John McCall33ddac02011-01-19 10:06:00 +00002976 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2977 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall18ce25e2012-02-08 00:46:36 +00002978 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00002979 ASM, elementTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00002980 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002981
2982 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00002983 IncompleteArrayType *existing =
2984 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2985 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00002986 }
Eli Friedmanbd258282008-02-15 18:16:39 +00002987
John McCall33ddac02011-01-19 10:06:00 +00002988 IncompleteArrayType *newType = new (*this, TypeAlignment)
2989 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00002990
John McCall33ddac02011-01-19 10:06:00 +00002991 IncompleteArrayTypes.InsertNode(newType, insertPos);
2992 Types.push_back(newType);
2993 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00002994}
2995
Steve Naroff91fcddb2007-07-18 18:00:27 +00002996/// getVectorType - Return the unique reference to a vector type of
2997/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00002998QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00002999 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00003000 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00003001
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003002 // Check if we've already instantiated a vector of this type.
3003 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00003004 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00003005
Craig Topper36250ad2014-05-12 05:36:57 +00003006 void *InsertPos = nullptr;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003007 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
3008 return QualType(VTP, 0);
3009
3010 // If the element type isn't canonical, this won't be a canonical type either,
3011 // so fill in the canonical type field.
3012 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00003013 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00003014 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00003015
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003016 // Get the new insert position for the node we care about.
3017 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003018 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003019 }
John McCall90d1c2d2009-09-24 23:30:46 +00003020 VectorType *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00003021 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003022 VectorTypes.InsertNode(New, InsertPos);
3023 Types.push_back(New);
3024 return QualType(New, 0);
3025}
3026
Nate Begemance4d7fc2008-04-18 23:10:10 +00003027/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00003028/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00003029QualType
3030ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor39c02722011-06-15 16:02:29 +00003031 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump11289f42009-09-09 15:08:12 +00003032
Steve Naroff91fcddb2007-07-18 18:00:27 +00003033 // Check if we've already instantiated a vector of this type.
3034 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00003035 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00003036 VectorType::GenericVector);
Craig Topper36250ad2014-05-12 05:36:57 +00003037 void *InsertPos = nullptr;
Steve Naroff91fcddb2007-07-18 18:00:27 +00003038 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
3039 return QualType(VTP, 0);
3040
3041 // If the element type isn't canonical, this won't be a canonical type either,
3042 // so fill in the canonical type field.
3043 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00003044 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00003045 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00003046
Steve Naroff91fcddb2007-07-18 18:00:27 +00003047 // Get the new insert position for the node we care about.
3048 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003049 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00003050 }
John McCall90d1c2d2009-09-24 23:30:46 +00003051 ExtVectorType *New = new (*this, TypeAlignment)
3052 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00003053 VectorTypes.InsertNode(New, InsertPos);
3054 Types.push_back(New);
3055 return QualType(New, 0);
3056}
3057
Jay Foad39c79802011-01-12 09:06:06 +00003058QualType
3059ASTContext::getDependentSizedExtVectorType(QualType vecType,
3060 Expr *SizeExpr,
3061 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00003062 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00003063 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00003064 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00003065
Craig Topper36250ad2014-05-12 05:36:57 +00003066 void *InsertPos = nullptr;
Douglas Gregor352169a2009-07-31 03:54:25 +00003067 DependentSizedExtVectorType *Canon
3068 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3069 DependentSizedExtVectorType *New;
3070 if (Canon) {
3071 // We already have a canonical version of this array type; use it as
3072 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00003073 New = new (*this, TypeAlignment)
3074 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
3075 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00003076 } else {
3077 QualType CanonVecTy = getCanonicalType(vecType);
3078 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00003079 New = new (*this, TypeAlignment)
3080 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
3081 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003082
3083 DependentSizedExtVectorType *CanonCheck
3084 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3085 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
3086 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00003087 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
3088 } else {
3089 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
3090 SourceLocation());
John McCall90d1c2d2009-09-24 23:30:46 +00003091 New = new (*this, TypeAlignment)
3092 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00003093 }
3094 }
Mike Stump11289f42009-09-09 15:08:12 +00003095
Douglas Gregor758a8692009-06-17 21:51:59 +00003096 Types.push_back(New);
3097 return QualType(New, 0);
3098}
3099
John McCall18afab72016-03-01 00:49:02 +00003100/// \brief Determine whether \p T is canonical as the result type of a function.
3101static bool isCanonicalResultType(QualType T) {
3102 return T.isCanonical() &&
3103 (T.getObjCLifetime() == Qualifiers::OCL_None ||
3104 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
3105}
3106
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003107/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003108///
Jay Foad39c79802011-01-12 09:06:06 +00003109QualType
3110ASTContext::getFunctionNoProtoType(QualType ResultTy,
3111 const FunctionType::ExtInfo &Info) const {
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003112 // Unique functions, to guarantee there is only one function of a particular
3113 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00003114 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00003115 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00003116
Craig Topper36250ad2014-05-12 05:36:57 +00003117 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003118 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003119 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003120 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003121
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003122 QualType Canonical;
John McCall18afab72016-03-01 00:49:02 +00003123 if (!isCanonicalResultType(ResultTy)) {
3124 Canonical =
3125 getFunctionNoProtoType(getCanonicalFunctionResultType(ResultTy), Info);
Mike Stump11289f42009-09-09 15:08:12 +00003126
Chris Lattner47955de2007-01-27 08:37:20 +00003127 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003128 FunctionNoProtoType *NewIP =
3129 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003130 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00003131 }
Mike Stump11289f42009-09-09 15:08:12 +00003132
John McCall90d1c2d2009-09-24 23:30:46 +00003133 FunctionNoProtoType *New = new (*this, TypeAlignment)
John McCall18afab72016-03-01 00:49:02 +00003134 FunctionNoProtoType(ResultTy, Canonical, Info);
Chris Lattner47955de2007-01-27 08:37:20 +00003135 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003136 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003137 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003138}
3139
Douglas Gregora602a152015-10-01 20:20:47 +00003140CanQualType
3141ASTContext::getCanonicalFunctionResultType(QualType ResultType) const {
3142 CanQualType CanResultType = getCanonicalType(ResultType);
3143
3144 // Canonical result types do not have ARC lifetime qualifiers.
3145 if (CanResultType.getQualifiers().hasObjCLifetime()) {
3146 Qualifiers Qs = CanResultType.getQualifiers();
3147 Qs.removeObjCLifetime();
3148 return CanQualType::CreateUnsafe(
3149 getQualifiedType(CanResultType.getUnqualifiedType(), Qs));
3150 }
3151
3152 return CanResultType;
3153}
3154
Richard Smith3c4f8d22016-10-16 17:54:23 +00003155static bool isCanonicalExceptionSpecification(
3156 const FunctionProtoType::ExceptionSpecInfo &ESI, bool NoexceptInType) {
3157 if (ESI.Type == EST_None)
3158 return true;
3159 if (!NoexceptInType)
3160 return false;
3161
3162 // C++17 onwards: exception specification is part of the type, as a simple
3163 // boolean "can this function type throw".
3164 if (ESI.Type == EST_BasicNoexcept)
3165 return true;
3166
3167 // A dynamic exception specification is canonical if it only contains pack
Richard Smith2a2cda52016-10-18 19:29:18 +00003168 // expansions (so we can't tell whether it's non-throwing) and all its
3169 // contained types are canonical.
Richard Smith3c4f8d22016-10-16 17:54:23 +00003170 if (ESI.Type == EST_Dynamic) {
Richard Smithfda59e52016-10-26 01:05:54 +00003171 bool AnyPackExpansions = false;
3172 for (QualType ET : ESI.Exceptions) {
3173 if (!ET.isCanonical())
Richard Smith3c4f8d22016-10-16 17:54:23 +00003174 return false;
Richard Smithfda59e52016-10-26 01:05:54 +00003175 if (ET->getAs<PackExpansionType>())
3176 AnyPackExpansions = true;
3177 }
3178 return AnyPackExpansions;
Richard Smith3c4f8d22016-10-16 17:54:23 +00003179 }
3180
Richard Smith2a2cda52016-10-18 19:29:18 +00003181 // A noexcept(expr) specification is (possibly) canonical if expr is
3182 // value-dependent.
Richard Smith3c4f8d22016-10-16 17:54:23 +00003183 if (ESI.Type == EST_ComputedNoexcept)
3184 return ESI.NoexceptExpr && ESI.NoexceptExpr->isValueDependent();
3185
3186 return false;
3187}
3188
Richard Smith304b1242016-10-18 20:13:25 +00003189QualType ASTContext::getFunctionTypeInternal(
3190 QualType ResultTy, ArrayRef<QualType> ArgArray,
3191 const FunctionProtoType::ExtProtoInfo &EPI, bool OnlyWantCanonical) const {
Jordan Rose5c382722013-03-08 21:51:21 +00003192 size_t NumArgs = ArgArray.size();
3193
Richard Smith2a2cda52016-10-18 19:29:18 +00003194 // Unique functions, to guarantee there is only one function of a particular
3195 // structure.
3196 llvm::FoldingSetNodeID ID;
3197 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
3198 *this, true);
Richard Smith3c4f8d22016-10-16 17:54:23 +00003199
Richard Smith2a2cda52016-10-18 19:29:18 +00003200 QualType Canonical;
3201 bool Unique = false;
3202
3203 void *InsertPos = nullptr;
3204 if (FunctionProtoType *FPT =
3205 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) {
3206 QualType Existing = QualType(FPT, 0);
3207
3208 // If we find a pre-existing equivalent FunctionProtoType, we can just reuse
3209 // it so long as our exception specification doesn't contain a dependent
Richard Smith304b1242016-10-18 20:13:25 +00003210 // noexcept expression, or we're just looking for a canonical type.
3211 // Otherwise, we're going to need to create a type
Richard Smith2a2cda52016-10-18 19:29:18 +00003212 // sugar node to hold the concrete expression.
Richard Smith304b1242016-10-18 20:13:25 +00003213 if (OnlyWantCanonical || EPI.ExceptionSpec.Type != EST_ComputedNoexcept ||
Richard Smith2a2cda52016-10-18 19:29:18 +00003214 EPI.ExceptionSpec.NoexceptExpr == FPT->getNoexceptExpr())
3215 return Existing;
3216
3217 // We need a new type sugar node for this one, to hold the new noexcept
3218 // expression. We do no canonicalization here, but that's OK since we don't
3219 // expect to see the same noexcept expression much more than once.
3220 Canonical = getCanonicalType(Existing);
3221 Unique = true;
3222 }
3223
3224 bool NoexceptInType = getLangOpts().CPlusPlus1z;
Richard Smith3c4f8d22016-10-16 17:54:23 +00003225 bool IsCanonicalExceptionSpec =
3226 isCanonicalExceptionSpecification(EPI.ExceptionSpec, NoexceptInType);
3227
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003228 // Determine whether the type being created is already canonical or not.
Richard Smith2a2cda52016-10-18 19:29:18 +00003229 bool isCanonical = !Unique && IsCanonicalExceptionSpec &&
Richard Smith3c4f8d22016-10-16 17:54:23 +00003230 isCanonicalResultType(ResultTy) && !EPI.HasTrailingReturn;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003231 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00003232 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003233 isCanonical = false;
3234
Richard Smith304b1242016-10-18 20:13:25 +00003235 if (OnlyWantCanonical)
3236 assert(isCanonical &&
3237 "given non-canonical parameters constructing canonical type");
3238
Richard Smith2a2cda52016-10-18 19:29:18 +00003239 // If this type isn't canonical, get the canonical version of it if we don't
3240 // already have it. The exception spec is only partially part of the
3241 // canonical type, and only in C++17 onwards.
3242 if (!isCanonical && Canonical.isNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003243 SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003244 CanonicalArgs.reserve(NumArgs);
3245 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00003246 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003247
Benjamin Kramer3f515cd2016-10-26 12:51:45 +00003248 llvm::SmallVector<QualType, 8> ExceptionTypeStorage;
John McCalldb40c7f2010-12-14 08:05:40 +00003249 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smith5e580292012-02-10 09:58:53 +00003250 CanonicalEPI.HasTrailingReturn = false;
Richard Smith3c4f8d22016-10-16 17:54:23 +00003251
3252 if (IsCanonicalExceptionSpec) {
3253 // Exception spec is already OK.
3254 } else if (NoexceptInType) {
3255 switch (EPI.ExceptionSpec.Type) {
3256 case EST_Unparsed: case EST_Unevaluated: case EST_Uninstantiated:
3257 // We don't know yet. It shouldn't matter what we pick here; no-one
3258 // should ever look at this.
3259 LLVM_FALLTHROUGH;
Richard Smith2a2cda52016-10-18 19:29:18 +00003260 case EST_None: case EST_MSAny:
Richard Smith3c4f8d22016-10-16 17:54:23 +00003261 CanonicalEPI.ExceptionSpec.Type = EST_None;
3262 break;
3263
Richard Smith2a2cda52016-10-18 19:29:18 +00003264 // A dynamic exception specification is almost always "not noexcept",
3265 // with the exception that a pack expansion might expand to no types.
3266 case EST_Dynamic: {
3267 bool AnyPacks = false;
3268 for (QualType ET : EPI.ExceptionSpec.Exceptions) {
3269 if (ET->getAs<PackExpansionType>())
3270 AnyPacks = true;
3271 ExceptionTypeStorage.push_back(getCanonicalType(ET));
3272 }
3273 if (!AnyPacks)
3274 CanonicalEPI.ExceptionSpec.Type = EST_None;
3275 else {
3276 CanonicalEPI.ExceptionSpec.Type = EST_Dynamic;
3277 CanonicalEPI.ExceptionSpec.Exceptions = ExceptionTypeStorage;
3278 }
3279 break;
3280 }
3281
Richard Smith3c4f8d22016-10-16 17:54:23 +00003282 case EST_DynamicNone: case EST_BasicNoexcept:
3283 CanonicalEPI.ExceptionSpec.Type = EST_BasicNoexcept;
3284 break;
3285
3286 case EST_ComputedNoexcept:
3287 llvm::APSInt Value(1);
3288 auto *E = CanonicalEPI.ExceptionSpec.NoexceptExpr;
3289 if (!E || !E->isIntegerConstantExpr(Value, *this, nullptr,
3290 /*IsEvaluated*/false)) {
3291 // This noexcept specification is invalid.
3292 // FIXME: Should this be able to happen?
3293 CanonicalEPI.ExceptionSpec.Type = EST_None;
3294 break;
3295 }
3296
3297 CanonicalEPI.ExceptionSpec.Type =
3298 Value.getBoolValue() ? EST_BasicNoexcept : EST_None;
3299 break;
3300 }
Richard Smith3c4f8d22016-10-16 17:54:23 +00003301 } else {
3302 CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo();
3303 }
John McCalldb40c7f2010-12-14 08:05:40 +00003304
Douglas Gregora602a152015-10-01 20:20:47 +00003305 // Adjust the canonical function result type.
3306 CanQualType CanResultTy = getCanonicalFunctionResultType(ResultTy);
Richard Smith304b1242016-10-18 20:13:25 +00003307 Canonical =
3308 getFunctionTypeInternal(CanResultTy, CanonicalArgs, CanonicalEPI, true);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003309
Chris Lattnerfd4de792007-01-27 01:15:32 +00003310 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003311 FunctionProtoType *NewIP =
3312 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003313 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003314 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003315
John McCall31168b02011-06-15 23:02:42 +00003316 // FunctionProtoType objects are allocated with extra bytes after
3317 // them for three variable size arrays at the end:
3318 // - parameter types
3319 // - exception types
John McCall18afab72016-03-01 00:49:02 +00003320 // - extended parameter information
John McCall31168b02011-06-15 23:02:42 +00003321 // Instead of the exception types, there could be a noexcept
Richard Smithd3b5c9082012-07-27 04:22:15 +00003322 // expression, or information used to resolve the exception
3323 // specification.
John McCalldb40c7f2010-12-14 08:05:40 +00003324 size_t Size = sizeof(FunctionProtoType) +
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003325 NumArgs * sizeof(QualType);
John McCall18afab72016-03-01 00:49:02 +00003326
Richard Smith8acb4282014-07-31 21:57:55 +00003327 if (EPI.ExceptionSpec.Type == EST_Dynamic) {
3328 Size += EPI.ExceptionSpec.Exceptions.size() * sizeof(QualType);
3329 } else if (EPI.ExceptionSpec.Type == EST_ComputedNoexcept) {
Sebastian Redl31ad7542011-03-13 17:09:40 +00003330 Size += sizeof(Expr*);
Richard Smith8acb4282014-07-31 21:57:55 +00003331 } else if (EPI.ExceptionSpec.Type == EST_Uninstantiated) {
Richard Smithd3729422012-04-19 00:08:28 +00003332 Size += 2 * sizeof(FunctionDecl*);
Richard Smith8acb4282014-07-31 21:57:55 +00003333 } else if (EPI.ExceptionSpec.Type == EST_Unevaluated) {
Richard Smithd3b5c9082012-07-27 04:22:15 +00003334 Size += sizeof(FunctionDecl*);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003335 }
John McCall18afab72016-03-01 00:49:02 +00003336
3337 // Put the ExtParameterInfos last. If all were equal, it would make
3338 // more sense to put these before the exception specification, because
3339 // it's much easier to skip past them compared to the elaborate switch
3340 // required to skip the exception specification. However, all is not
3341 // equal; ExtParameterInfos are used to model very uncommon features,
3342 // and it's better not to burden the more common paths.
3343 if (EPI.ExtParameterInfos) {
3344 Size += NumArgs * sizeof(FunctionProtoType::ExtParameterInfo);
3345 }
John McCall31168b02011-06-15 23:02:42 +00003346
John McCalldb40c7f2010-12-14 08:05:40 +00003347 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
Roman Divacky65b88cd2011-03-01 17:40:53 +00003348 FunctionProtoType::ExtProtoInfo newEPI = EPI;
Jordan Rose5c382722013-03-08 21:51:21 +00003349 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003350 Types.push_back(FTP);
Richard Smith2a2cda52016-10-18 19:29:18 +00003351 if (!Unique)
3352 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003353 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003354}
Chris Lattneref51c202006-11-10 07:17:23 +00003355
Joey Goulye3c85de2016-12-01 11:30:49 +00003356QualType ASTContext::getPipeType(QualType T, bool ReadOnly) const {
Xiuli Pan9c14e282016-01-09 12:53:17 +00003357 llvm::FoldingSetNodeID ID;
Joey Goulye3c85de2016-12-01 11:30:49 +00003358 PipeType::Profile(ID, T, ReadOnly);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003359
3360 void *InsertPos = 0;
Joey Goulye3c85de2016-12-01 11:30:49 +00003361 if (PipeType *PT = PipeTypes.FindNodeOrInsertPos(ID, InsertPos))
Xiuli Pan9c14e282016-01-09 12:53:17 +00003362 return QualType(PT, 0);
3363
3364 // If the pipe element type isn't canonical, this won't be a canonical type
3365 // either, so fill in the canonical type field.
3366 QualType Canonical;
3367 if (!T.isCanonical()) {
Joey Goulye3c85de2016-12-01 11:30:49 +00003368 Canonical = getPipeType(getCanonicalType(T), ReadOnly);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003369
3370 // Get the new insert position for the node we care about.
Joey Goulye3c85de2016-12-01 11:30:49 +00003371 PipeType *NewIP = PipeTypes.FindNodeOrInsertPos(ID, InsertPos);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003372 assert(!NewIP && "Shouldn't be in the map!");
3373 (void)NewIP;
3374 }
Joey Goulye3c85de2016-12-01 11:30:49 +00003375 PipeType *New = new (*this, TypeAlignment) PipeType(T, Canonical, ReadOnly);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003376 Types.push_back(New);
Joey Goulye3c85de2016-12-01 11:30:49 +00003377 PipeTypes.InsertNode(New, InsertPos);
Joey Gouly5788b782016-11-18 14:10:54 +00003378 return QualType(New, 0);
3379}
3380
Joey Goulye3c85de2016-12-01 11:30:49 +00003381QualType ASTContext::getReadPipeType(QualType T) const {
3382 return getPipeType(T, true);
3383}
3384
Joey Gouly5788b782016-11-18 14:10:54 +00003385QualType ASTContext::getWritePipeType(QualType T) const {
Joey Goulye3c85de2016-12-01 11:30:49 +00003386 return getPipeType(T, false);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003387}
3388
John McCalle78aac42010-03-10 03:28:59 +00003389#ifndef NDEBUG
3390static bool NeedsInjectedClassNameType(const RecordDecl *D) {
3391 if (!isa<CXXRecordDecl>(D)) return false;
3392 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
3393 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
3394 return true;
3395 if (RD->getDescribedClassTemplate() &&
3396 !isa<ClassTemplateSpecializationDecl>(RD))
3397 return true;
3398 return false;
3399}
3400#endif
3401
3402/// getInjectedClassNameType - Return the unique reference to the
3403/// injected class name type for the specified templated declaration.
3404QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00003405 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00003406 assert(NeedsInjectedClassNameType(Decl));
3407 if (Decl->TypeForDecl) {
3408 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregorec9fd132012-01-14 16:38:05 +00003409 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCalle78aac42010-03-10 03:28:59 +00003410 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
3411 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3412 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
3413 } else {
John McCall424cec92011-01-19 06:33:43 +00003414 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00003415 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00003416 Decl->TypeForDecl = newType;
3417 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00003418 }
3419 return QualType(Decl->TypeForDecl, 0);
3420}
3421
Douglas Gregor83a586e2008-04-13 21:07:44 +00003422/// getTypeDeclType - Return the unique reference to the type for the
3423/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00003424QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00003425 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00003426 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00003427
Richard Smithdda56e42011-04-15 14:24:37 +00003428 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00003429 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00003430
John McCall96f0b5f2010-03-10 06:48:02 +00003431 assert(!isa<TemplateTypeParmDecl>(Decl) &&
3432 "Template type parameter types are always available.");
3433
John McCall81e38502010-02-16 03:57:14 +00003434 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00003435 assert(Record->isFirstDecl() && "struct/union has previous declaration");
John McCall96f0b5f2010-03-10 06:48:02 +00003436 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003437 return getRecordType(Record);
John McCall81e38502010-02-16 03:57:14 +00003438 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00003439 assert(Enum->isFirstDecl() && "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003440 return getEnumType(Enum);
John McCall81e38502010-02-16 03:57:14 +00003441 } else if (const UnresolvedUsingTypenameDecl *Using =
John McCallb96ec562009-12-04 22:46:56 +00003442 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00003443 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
3444 Decl->TypeForDecl = newType;
3445 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00003446 } else
John McCall96f0b5f2010-03-10 06:48:02 +00003447 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00003448
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00003449 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00003450}
3451
Chris Lattner32d920b2007-01-26 02:01:53 +00003452/// getTypedefType - Return the unique reference to the type for the
Richard Smithdda56e42011-04-15 14:24:37 +00003453/// specified typedef name decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003454QualType
Richard Smithdda56e42011-04-15 14:24:37 +00003455ASTContext::getTypedefType(const TypedefNameDecl *Decl,
3456 QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003457 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003458
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003459 if (Canonical.isNull())
3460 Canonical = getCanonicalType(Decl->getUnderlyingType());
John McCall424cec92011-01-19 06:33:43 +00003461 TypedefType *newType = new(*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00003462 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00003463 Decl->TypeForDecl = newType;
3464 Types.push_back(newType);
3465 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00003466}
3467
Jay Foad39c79802011-01-12 09:06:06 +00003468QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003469 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3470
Douglas Gregorec9fd132012-01-14 16:38:05 +00003471 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003472 if (PrevDecl->TypeForDecl)
3473 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3474
John McCall424cec92011-01-19 06:33:43 +00003475 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
3476 Decl->TypeForDecl = newType;
3477 Types.push_back(newType);
3478 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003479}
3480
Jay Foad39c79802011-01-12 09:06:06 +00003481QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003482 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3483
Douglas Gregorec9fd132012-01-14 16:38:05 +00003484 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003485 if (PrevDecl->TypeForDecl)
3486 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3487
John McCall424cec92011-01-19 06:33:43 +00003488 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
3489 Decl->TypeForDecl = newType;
3490 Types.push_back(newType);
3491 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003492}
3493
John McCall81904512011-01-06 01:58:22 +00003494QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
3495 QualType modifiedType,
3496 QualType equivalentType) {
3497 llvm::FoldingSetNodeID id;
3498 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
3499
Craig Topper36250ad2014-05-12 05:36:57 +00003500 void *insertPos = nullptr;
John McCall81904512011-01-06 01:58:22 +00003501 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
3502 if (type) return QualType(type, 0);
3503
3504 QualType canon = getCanonicalType(equivalentType);
3505 type = new (*this, TypeAlignment)
3506 AttributedType(canon, attrKind, modifiedType, equivalentType);
3507
3508 Types.push_back(type);
3509 AttributedTypes.InsertNode(type, insertPos);
3510
3511 return QualType(type, 0);
3512}
3513
John McCallcebee162009-10-18 09:09:24 +00003514/// \brief Retrieve a substitution-result type.
3515QualType
3516ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00003517 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00003518 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00003519 && "replacement types must always be canonical");
3520
3521 llvm::FoldingSetNodeID ID;
3522 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
Craig Topper36250ad2014-05-12 05:36:57 +00003523 void *InsertPos = nullptr;
John McCallcebee162009-10-18 09:09:24 +00003524 SubstTemplateTypeParmType *SubstParm
3525 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3526
3527 if (!SubstParm) {
3528 SubstParm = new (*this, TypeAlignment)
3529 SubstTemplateTypeParmType(Parm, Replacement);
3530 Types.push_back(SubstParm);
3531 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3532 }
3533
3534 return QualType(SubstParm, 0);
3535}
3536
Douglas Gregorada4b792011-01-14 02:55:32 +00003537/// \brief Retrieve a
3538QualType ASTContext::getSubstTemplateTypeParmPackType(
3539 const TemplateTypeParmType *Parm,
3540 const TemplateArgument &ArgPack) {
3541#ifndef NDEBUG
Aaron Ballman2a89e852014-07-15 21:32:31 +00003542 for (const auto &P : ArgPack.pack_elements()) {
3543 assert(P.getKind() == TemplateArgument::Type &&"Pack contains a non-type");
3544 assert(P.getAsType().isCanonical() && "Pack contains non-canonical type");
Douglas Gregorada4b792011-01-14 02:55:32 +00003545 }
3546#endif
3547
3548 llvm::FoldingSetNodeID ID;
3549 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
Craig Topper36250ad2014-05-12 05:36:57 +00003550 void *InsertPos = nullptr;
Douglas Gregorada4b792011-01-14 02:55:32 +00003551 if (SubstTemplateTypeParmPackType *SubstParm
3552 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
3553 return QualType(SubstParm, 0);
3554
3555 QualType Canon;
3556 if (!Parm->isCanonicalUnqualified()) {
3557 Canon = getCanonicalType(QualType(Parm, 0));
3558 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
3559 ArgPack);
3560 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
3561 }
3562
3563 SubstTemplateTypeParmPackType *SubstParm
3564 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
3565 ArgPack);
3566 Types.push_back(SubstParm);
3567 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3568 return QualType(SubstParm, 0);
3569}
3570
Douglas Gregoreff93e02009-02-05 23:33:38 +00003571/// \brief Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00003572/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00003573/// name.
Mike Stump11289f42009-09-09 15:08:12 +00003574QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00003575 bool ParameterPack,
Chandler Carruth08836322011-05-01 00:51:33 +00003576 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00003577 llvm::FoldingSetNodeID ID;
Chandler Carruth08836322011-05-01 00:51:33 +00003578 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Craig Topper36250ad2014-05-12 05:36:57 +00003579 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003580 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00003581 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3582
3583 if (TypeParm)
3584 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003585
Chandler Carruth08836322011-05-01 00:51:33 +00003586 if (TTPDecl) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00003587 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth08836322011-05-01 00:51:33 +00003588 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003589
3590 TemplateTypeParmType *TypeCheck
3591 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3592 assert(!TypeCheck && "Template type parameter canonical type broken");
3593 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00003594 } else
John McCall90d1c2d2009-09-24 23:30:46 +00003595 TypeParm = new (*this, TypeAlignment)
3596 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00003597
3598 Types.push_back(TypeParm);
3599 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
3600
3601 return QualType(TypeParm, 0);
3602}
3603
John McCalle78aac42010-03-10 03:28:59 +00003604TypeSourceInfo *
3605ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
3606 SourceLocation NameLoc,
3607 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003608 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003609 assert(!Name.getAsDependentTemplateName() &&
3610 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003611 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCalle78aac42010-03-10 03:28:59 +00003612
3613 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
David Blaikie6adc78e2013-02-18 22:06:02 +00003614 TemplateSpecializationTypeLoc TL =
3615 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003616 TL.setTemplateKeywordLoc(SourceLocation());
John McCalle78aac42010-03-10 03:28:59 +00003617 TL.setTemplateNameLoc(NameLoc);
3618 TL.setLAngleLoc(Args.getLAngleLoc());
3619 TL.setRAngleLoc(Args.getRAngleLoc());
3620 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
3621 TL.setArgLocInfo(i, Args[i].getLocInfo());
3622 return DI;
3623}
3624
Mike Stump11289f42009-09-09 15:08:12 +00003625QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00003626ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00003627 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003628 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003629 assert(!Template.getAsDependentTemplateName() &&
3630 "No dependent template names here!");
John McCall6b51f282009-11-23 01:53:49 +00003631
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003632 SmallVector<TemplateArgument, 4> ArgVec;
David Majnemer6fbeee32016-07-07 04:43:07 +00003633 ArgVec.reserve(Args.size());
3634 for (const TemplateArgumentLoc &Arg : Args.arguments())
3635 ArgVec.push_back(Arg.getArgument());
John McCall0ad16662009-10-29 08:12:44 +00003636
David Majnemer6fbeee32016-07-07 04:43:07 +00003637 return getTemplateSpecializationType(Template, ArgVec, Underlying);
John McCall0ad16662009-10-29 08:12:44 +00003638}
3639
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003640#ifndef NDEBUG
David Majnemer6fbeee32016-07-07 04:43:07 +00003641static bool hasAnyPackExpansions(ArrayRef<TemplateArgument> Args) {
3642 for (const TemplateArgument &Arg : Args)
3643 if (Arg.isPackExpansion())
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003644 return true;
3645
3646 return true;
3647}
3648#endif
3649
John McCall0ad16662009-10-29 08:12:44 +00003650QualType
3651ASTContext::getTemplateSpecializationType(TemplateName Template,
David Majnemer6fbeee32016-07-07 04:43:07 +00003652 ArrayRef<TemplateArgument> Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003653 QualType Underlying) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003654 assert(!Template.getAsDependentTemplateName() &&
3655 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00003656 // Look through qualified template names.
3657 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3658 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003659
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003660 bool IsTypeAlias =
Richard Smith3f1b5d02011-05-05 21:57:07 +00003661 Template.getAsTemplateDecl() &&
3662 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00003663 QualType CanonType;
3664 if (!Underlying.isNull())
3665 CanonType = getCanonicalType(Underlying);
3666 else {
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003667 // We can get here with an alias template when the specialization contains
3668 // a pack expansion that does not match up with a parameter pack.
David Majnemer6fbeee32016-07-07 04:43:07 +00003669 assert((!IsTypeAlias || hasAnyPackExpansions(Args)) &&
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003670 "Caller must compute aliased type");
3671 IsTypeAlias = false;
David Majnemer6fbeee32016-07-07 04:43:07 +00003672 CanonType = getCanonicalTemplateSpecializationType(Template, Args);
Richard Smith3f1b5d02011-05-05 21:57:07 +00003673 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00003674
Douglas Gregora8e02e72009-07-28 23:00:59 +00003675 // Allocate the (non-canonical) template specialization type, but don't
3676 // try to unique it: these types typically have location information that
3677 // we don't unique and don't want to lose.
Richard Smith3f1b5d02011-05-05 21:57:07 +00003678 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
David Majnemer6fbeee32016-07-07 04:43:07 +00003679 sizeof(TemplateArgument) * Args.size() +
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003680 (IsTypeAlias? sizeof(QualType) : 0),
John McCall90d1c2d2009-09-24 23:30:46 +00003681 TypeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +00003682 TemplateSpecializationType *Spec
David Majnemer6fbeee32016-07-07 04:43:07 +00003683 = new (Mem) TemplateSpecializationType(Template, Args, CanonType,
Douglas Gregor1f79ca82012-02-03 17:16:23 +00003684 IsTypeAlias ? Underlying : QualType());
Mike Stump11289f42009-09-09 15:08:12 +00003685
Douglas Gregor8bf42052009-02-09 18:46:07 +00003686 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00003687 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00003688}
3689
David Majnemer6fbeee32016-07-07 04:43:07 +00003690QualType ASTContext::getCanonicalTemplateSpecializationType(
3691 TemplateName Template, ArrayRef<TemplateArgument> Args) const {
Douglas Gregore16af532011-02-28 18:50:33 +00003692 assert(!Template.getAsDependentTemplateName() &&
3693 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003694
Douglas Gregore29139c2011-03-03 17:04:51 +00003695 // Look through qualified template names.
3696 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3697 Template = TemplateName(QTN->getTemplateDecl());
Douglas Gregore16af532011-02-28 18:50:33 +00003698
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003699 // Build the canonical template specialization type.
3700 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003701 SmallVector<TemplateArgument, 4> CanonArgs;
David Majnemer6fbeee32016-07-07 04:43:07 +00003702 unsigned NumArgs = Args.size();
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003703 CanonArgs.reserve(NumArgs);
David Majnemer6fbeee32016-07-07 04:43:07 +00003704 for (const TemplateArgument &Arg : Args)
3705 CanonArgs.push_back(getCanonicalTemplateArgument(Arg));
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003706
3707 // Determine whether this canonical template specialization type already
3708 // exists.
3709 llvm::FoldingSetNodeID ID;
3710 TemplateSpecializationType::Profile(ID, CanonTemplate,
David Majnemer6fbeee32016-07-07 04:43:07 +00003711 CanonArgs, *this);
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003712
Craig Topper36250ad2014-05-12 05:36:57 +00003713 void *InsertPos = nullptr;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003714 TemplateSpecializationType *Spec
3715 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3716
3717 if (!Spec) {
3718 // Allocate a new canonical template specialization type.
3719 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
3720 sizeof(TemplateArgument) * NumArgs),
3721 TypeAlignment);
3722 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
David Majnemer6fbeee32016-07-07 04:43:07 +00003723 CanonArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003724 QualType(), QualType());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003725 Types.push_back(Spec);
3726 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
3727 }
3728
3729 assert(Spec->isDependentType() &&
3730 "Non-dependent template-id type must have a canonical type");
3731 return QualType(Spec, 0);
3732}
3733
3734QualType
Abramo Bagnara6150c882010-05-11 21:36:43 +00003735ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
3736 NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00003737 QualType NamedType) const {
Douglas Gregor52537682009-03-19 00:18:19 +00003738 llvm::FoldingSetNodeID ID;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003739 ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
Douglas Gregor52537682009-03-19 00:18:19 +00003740
Craig Topper36250ad2014-05-12 05:36:57 +00003741 void *InsertPos = nullptr;
Abramo Bagnara6150c882010-05-11 21:36:43 +00003742 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003743 if (T)
3744 return QualType(T, 0);
3745
Douglas Gregorc42075a2010-02-04 18:10:26 +00003746 QualType Canon = NamedType;
3747 if (!Canon.isCanonical()) {
3748 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003749 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
3750 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00003751 (void)CheckT;
3752 }
3753
Benjamin Kramer8adeef92015-04-02 16:19:54 +00003754 T = new (*this, TypeAlignment) ElaboratedType(Keyword, NNS, NamedType, Canon);
Douglas Gregor52537682009-03-19 00:18:19 +00003755 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00003756 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00003757 return QualType(T, 0);
3758}
3759
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003760QualType
Jay Foad39c79802011-01-12 09:06:06 +00003761ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003762 llvm::FoldingSetNodeID ID;
3763 ParenType::Profile(ID, InnerType);
3764
Craig Topper36250ad2014-05-12 05:36:57 +00003765 void *InsertPos = nullptr;
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003766 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3767 if (T)
3768 return QualType(T, 0);
3769
3770 QualType Canon = InnerType;
3771 if (!Canon.isCanonical()) {
3772 Canon = getCanonicalType(InnerType);
3773 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3774 assert(!CheckT && "Paren canonical type broken");
3775 (void)CheckT;
3776 }
3777
Benjamin Kramer8adeef92015-04-02 16:19:54 +00003778 T = new (*this, TypeAlignment) ParenType(InnerType, Canon);
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003779 Types.push_back(T);
3780 ParenTypes.InsertNode(T, InsertPos);
3781 return QualType(T, 0);
3782}
3783
Douglas Gregor02085352010-03-31 20:19:30 +00003784QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
3785 NestedNameSpecifier *NNS,
3786 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003787 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00003788 if (Canon.isNull()) {
3789 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Richard Smith74f02342017-01-19 21:00:13 +00003790 if (CanonNNS != NNS)
3791 Canon = getDependentNameType(Keyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003792 }
3793
3794 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00003795 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00003796
Craig Topper36250ad2014-05-12 05:36:57 +00003797 void *InsertPos = nullptr;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003798 DependentNameType *T
3799 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00003800 if (T)
3801 return QualType(T, 0);
3802
Benjamin Kramer8adeef92015-04-02 16:19:54 +00003803 T = new (*this, TypeAlignment) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00003804 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00003805 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003806 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00003807}
3808
Mike Stump11289f42009-09-09 15:08:12 +00003809QualType
John McCallc392f372010-06-11 00:33:02 +00003810ASTContext::getDependentTemplateSpecializationType(
3811 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00003812 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00003813 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00003814 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00003815 // TODO: avoid this copy
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003816 SmallVector<TemplateArgument, 16> ArgCopy;
John McCallc392f372010-06-11 00:33:02 +00003817 for (unsigned I = 0, E = Args.size(); I != E; ++I)
3818 ArgCopy.push_back(Args[I].getArgument());
David Majnemer6fbeee32016-07-07 04:43:07 +00003819 return getDependentTemplateSpecializationType(Keyword, NNS, Name, ArgCopy);
John McCallc392f372010-06-11 00:33:02 +00003820}
3821
3822QualType
3823ASTContext::getDependentTemplateSpecializationType(
3824 ElaboratedTypeKeyword Keyword,
3825 NestedNameSpecifier *NNS,
3826 const IdentifierInfo *Name,
David Majnemer6fbeee32016-07-07 04:43:07 +00003827 ArrayRef<TemplateArgument> Args) const {
Douglas Gregor6e068012011-02-28 00:04:36 +00003828 assert((!NNS || NNS->isDependent()) &&
3829 "nested-name-specifier must be dependent");
Douglas Gregordce2b622009-04-01 00:28:59 +00003830
Douglas Gregorc42075a2010-02-04 18:10:26 +00003831 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00003832 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
David Majnemer6fbeee32016-07-07 04:43:07 +00003833 Name, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003834
Craig Topper36250ad2014-05-12 05:36:57 +00003835 void *InsertPos = nullptr;
John McCallc392f372010-06-11 00:33:02 +00003836 DependentTemplateSpecializationType *T
3837 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003838 if (T)
3839 return QualType(T, 0);
3840
John McCallc392f372010-06-11 00:33:02 +00003841 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003842
John McCallc392f372010-06-11 00:33:02 +00003843 ElaboratedTypeKeyword CanonKeyword = Keyword;
3844 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
3845
3846 bool AnyNonCanonArgs = false;
David Majnemer6fbeee32016-07-07 04:43:07 +00003847 unsigned NumArgs = Args.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003848 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCallc392f372010-06-11 00:33:02 +00003849 for (unsigned I = 0; I != NumArgs; ++I) {
3850 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
3851 if (!CanonArgs[I].structurallyEquals(Args[I]))
3852 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00003853 }
3854
John McCallc392f372010-06-11 00:33:02 +00003855 QualType Canon;
3856 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
3857 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
David Majnemer6fbeee32016-07-07 04:43:07 +00003858 Name,
3859 CanonArgs);
John McCallc392f372010-06-11 00:33:02 +00003860
3861 // Find the insert position again.
3862 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3863 }
3864
3865 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
3866 sizeof(TemplateArgument) * NumArgs),
3867 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00003868 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
David Majnemer6fbeee32016-07-07 04:43:07 +00003869 Name, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00003870 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00003871 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00003872 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00003873}
3874
Richard Smith32918772017-02-14 00:25:28 +00003875TemplateArgument ASTContext::getInjectedTemplateArg(NamedDecl *Param) {
3876 TemplateArgument Arg;
3877 if (auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
3878 QualType ArgType = getTypeDeclType(TTP);
3879 if (TTP->isParameterPack())
3880 ArgType = getPackExpansionType(ArgType, None);
3881
3882 Arg = TemplateArgument(ArgType);
3883 } else if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3884 Expr *E = new (*this) DeclRefExpr(
3885 NTTP, /*enclosing*/false,
3886 NTTP->getType().getNonLValueExprType(*this),
3887 Expr::getValueKindForType(NTTP->getType()), NTTP->getLocation());
3888
3889 if (NTTP->isParameterPack())
3890 E = new (*this) PackExpansionExpr(DependentTy, E, NTTP->getLocation(),
3891 None);
3892 Arg = TemplateArgument(E);
3893 } else {
3894 auto *TTP = cast<TemplateTemplateParmDecl>(Param);
3895 if (TTP->isParameterPack())
3896 Arg = TemplateArgument(TemplateName(TTP), Optional<unsigned>());
3897 else
3898 Arg = TemplateArgument(TemplateName(TTP));
3899 }
3900
3901 if (Param->isTemplateParameterPack())
3902 Arg = TemplateArgument::CreatePackCopy(*this, Arg);
3903
3904 return Arg;
3905}
3906
Richard Smith43e14d22016-12-23 02:10:11 +00003907void
3908ASTContext::getInjectedTemplateArgs(const TemplateParameterList *Params,
3909 SmallVectorImpl<TemplateArgument> &Args) {
3910 Args.reserve(Args.size() + Params->size());
3911
Richard Smith32918772017-02-14 00:25:28 +00003912 for (NamedDecl *Param : *Params)
3913 Args.push_back(getInjectedTemplateArg(Param));
Richard Smith43e14d22016-12-23 02:10:11 +00003914}
3915
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003916QualType ASTContext::getPackExpansionType(QualType Pattern,
David Blaikie05785d12013-02-20 22:23:23 +00003917 Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00003918 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003919 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003920
3921 assert(Pattern->containsUnexpandedParameterPack() &&
3922 "Pack expansions must expand one or more parameter packs");
Craig Topper36250ad2014-05-12 05:36:57 +00003923 void *InsertPos = nullptr;
Douglas Gregord2fa7662010-12-20 02:24:11 +00003924 PackExpansionType *T
3925 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3926 if (T)
3927 return QualType(T, 0);
3928
3929 QualType Canon;
3930 if (!Pattern.isCanonical()) {
Richard Smith68eea502012-07-16 00:20:35 +00003931 Canon = getCanonicalType(Pattern);
3932 // The canonical type might not contain an unexpanded parameter pack, if it
3933 // contains an alias template specialization which ignores one of its
3934 // parameters.
3935 if (Canon->containsUnexpandedParameterPack()) {
Richard Smith8b4e1e22014-07-10 01:20:17 +00003936 Canon = getPackExpansionType(Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003937
Richard Smith68eea502012-07-16 00:20:35 +00003938 // Find the insert position again, in case we inserted an element into
3939 // PackExpansionTypes and invalidated our insert position.
3940 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3941 }
Douglas Gregord2fa7662010-12-20 02:24:11 +00003942 }
3943
Benjamin Kramer8adeef92015-04-02 16:19:54 +00003944 T = new (*this, TypeAlignment)
3945 PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003946 Types.push_back(T);
3947 PackExpansionTypes.InsertNode(T, InsertPos);
Richard Smith8b4e1e22014-07-10 01:20:17 +00003948 return QualType(T, 0);
Douglas Gregord2fa7662010-12-20 02:24:11 +00003949}
3950
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003951/// CmpProtocolNames - Comparison predicate for sorting protocols
3952/// alphabetically.
Benjamin Kramer0eb262f2015-03-14 13:32:49 +00003953static int CmpProtocolNames(ObjCProtocolDecl *const *LHS,
3954 ObjCProtocolDecl *const *RHS) {
3955 return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName());
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003956}
3957
Craig Topper1f26d5b2016-01-03 19:43:23 +00003958static bool areSortedAndUniqued(ArrayRef<ObjCProtocolDecl *> Protocols) {
3959 if (Protocols.empty()) return true;
John McCallfc93cf92009-10-22 22:37:11 +00003960
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003961 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
3962 return false;
3963
Craig Topper1f26d5b2016-01-03 19:43:23 +00003964 for (unsigned i = 1; i != Protocols.size(); ++i)
Benjamin Kramer0eb262f2015-03-14 13:32:49 +00003965 if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 ||
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003966 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCallfc93cf92009-10-22 22:37:11 +00003967 return false;
3968 return true;
3969}
3970
Craig Topper6a8c1512015-10-22 01:56:18 +00003971static void
3972SortAndUniqueProtocols(SmallVectorImpl<ObjCProtocolDecl *> &Protocols) {
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003973 // Sort protocols, keyed by name.
Craig Topper6a8c1512015-10-22 01:56:18 +00003974 llvm::array_pod_sort(Protocols.begin(), Protocols.end(), CmpProtocolNames);
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003975
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00003976 // Canonicalize.
Craig Topper6a8c1512015-10-22 01:56:18 +00003977 for (ObjCProtocolDecl *&P : Protocols)
3978 P = P->getCanonicalDecl();
3979
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003980 // Remove duplicates.
Craig Topper6a8c1512015-10-22 01:56:18 +00003981 auto ProtocolsEnd = std::unique(Protocols.begin(), Protocols.end());
3982 Protocols.erase(ProtocolsEnd, Protocols.end());
Chris Lattnere0ea37a2008-04-07 04:56:42 +00003983}
3984
John McCall8b07ec22010-05-15 11:32:37 +00003985QualType ASTContext::getObjCObjectType(QualType BaseType,
3986 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00003987 unsigned NumProtocols) const {
Douglas Gregore9d95f12015-07-07 03:57:35 +00003988 return getObjCObjectType(BaseType, { },
Douglas Gregorab209d82015-07-07 03:58:42 +00003989 llvm::makeArrayRef(Protocols, NumProtocols),
3990 /*isKindOf=*/false);
Douglas Gregore9d95f12015-07-07 03:57:35 +00003991}
3992
3993QualType ASTContext::getObjCObjectType(
3994 QualType baseType,
3995 ArrayRef<QualType> typeArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00003996 ArrayRef<ObjCProtocolDecl *> protocols,
3997 bool isKindOf) const {
Douglas Gregore9d95f12015-07-07 03:57:35 +00003998 // If the base type is an interface and there aren't any protocols or
3999 // type arguments to add, then the interface type will do just fine.
Douglas Gregorab209d82015-07-07 03:58:42 +00004000 if (typeArgs.empty() && protocols.empty() && !isKindOf &&
4001 isa<ObjCInterfaceType>(baseType))
Douglas Gregore9d95f12015-07-07 03:57:35 +00004002 return baseType;
John McCall8b07ec22010-05-15 11:32:37 +00004003
4004 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00004005 llvm::FoldingSetNodeID ID;
Douglas Gregorab209d82015-07-07 03:58:42 +00004006 ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols, isKindOf);
Craig Topper36250ad2014-05-12 05:36:57 +00004007 void *InsertPos = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00004008 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
4009 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00004010
Douglas Gregore9d95f12015-07-07 03:57:35 +00004011 // Determine the type arguments to be used for canonicalization,
4012 // which may be explicitly specified here or written on the base
4013 // type.
4014 ArrayRef<QualType> effectiveTypeArgs = typeArgs;
4015 if (effectiveTypeArgs.empty()) {
4016 if (auto baseObject = baseType->getAs<ObjCObjectType>())
4017 effectiveTypeArgs = baseObject->getTypeArgs();
4018 }
John McCallfc93cf92009-10-22 22:37:11 +00004019
Douglas Gregore9d95f12015-07-07 03:57:35 +00004020 // Build the canonical type, which has the canonical base type and a
4021 // sorted-and-uniqued list of protocols and the type arguments
4022 // canonicalized.
4023 QualType canonical;
4024 bool typeArgsAreCanonical = std::all_of(effectiveTypeArgs.begin(),
4025 effectiveTypeArgs.end(),
4026 [&](QualType type) {
4027 return type.isCanonical();
4028 });
Craig Topper1f26d5b2016-01-03 19:43:23 +00004029 bool protocolsSorted = areSortedAndUniqued(protocols);
Douglas Gregore9d95f12015-07-07 03:57:35 +00004030 if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) {
4031 // Determine the canonical type arguments.
4032 ArrayRef<QualType> canonTypeArgs;
4033 SmallVector<QualType, 4> canonTypeArgsVec;
4034 if (!typeArgsAreCanonical) {
4035 canonTypeArgsVec.reserve(effectiveTypeArgs.size());
4036 for (auto typeArg : effectiveTypeArgs)
4037 canonTypeArgsVec.push_back(getCanonicalType(typeArg));
4038 canonTypeArgs = canonTypeArgsVec;
John McCallfc93cf92009-10-22 22:37:11 +00004039 } else {
Douglas Gregore9d95f12015-07-07 03:57:35 +00004040 canonTypeArgs = effectiveTypeArgs;
John McCallfc93cf92009-10-22 22:37:11 +00004041 }
4042
Douglas Gregore9d95f12015-07-07 03:57:35 +00004043 ArrayRef<ObjCProtocolDecl *> canonProtocols;
4044 SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec;
4045 if (!protocolsSorted) {
Craig Topper6a8c1512015-10-22 01:56:18 +00004046 canonProtocolsVec.append(protocols.begin(), protocols.end());
4047 SortAndUniqueProtocols(canonProtocolsVec);
4048 canonProtocols = canonProtocolsVec;
Douglas Gregore9d95f12015-07-07 03:57:35 +00004049 } else {
4050 canonProtocols = protocols;
4051 }
4052
4053 canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00004054 canonProtocols, isKindOf);
Douglas Gregore9d95f12015-07-07 03:57:35 +00004055
John McCallfc93cf92009-10-22 22:37:11 +00004056 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00004057 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
4058 }
4059
Douglas Gregore9d95f12015-07-07 03:57:35 +00004060 unsigned size = sizeof(ObjCObjectTypeImpl);
4061 size += typeArgs.size() * sizeof(QualType);
4062 size += protocols.size() * sizeof(ObjCProtocolDecl *);
4063 void *mem = Allocate(size, TypeAlignment);
John McCall8b07ec22010-05-15 11:32:37 +00004064 ObjCObjectTypeImpl *T =
Douglas Gregorab209d82015-07-07 03:58:42 +00004065 new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols,
4066 isKindOf);
John McCall8b07ec22010-05-15 11:32:37 +00004067
4068 Types.push_back(T);
4069 ObjCObjectTypes.InsertNode(T, InsertPos);
4070 return QualType(T, 0);
4071}
4072
Manman Ren3569eb52016-09-13 17:03:12 +00004073/// Apply Objective-C protocol qualifiers to the given type.
4074/// If this is for the canonical type of a type parameter, we can apply
4075/// protocol qualifiers on the ObjCObjectPointerType.
4076QualType
4077ASTContext::applyObjCProtocolQualifiers(QualType type,
4078 ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError,
4079 bool allowOnPointerType) const {
4080 hasError = false;
4081
Manman Renc5705ba2016-09-13 17:41:05 +00004082 if (const ObjCTypeParamType *objT =
4083 dyn_cast<ObjCTypeParamType>(type.getTypePtr())) {
4084 return getObjCTypeParamType(objT->getDecl(), protocols);
4085 }
4086
Manman Ren3569eb52016-09-13 17:03:12 +00004087 // Apply protocol qualifiers to ObjCObjectPointerType.
4088 if (allowOnPointerType) {
4089 if (const ObjCObjectPointerType *objPtr =
4090 dyn_cast<ObjCObjectPointerType>(type.getTypePtr())) {
4091 const ObjCObjectType *objT = objPtr->getObjectType();
4092 // Merge protocol lists and construct ObjCObjectType.
4093 SmallVector<ObjCProtocolDecl*, 8> protocolsVec;
4094 protocolsVec.append(objT->qual_begin(),
4095 objT->qual_end());
4096 protocolsVec.append(protocols.begin(), protocols.end());
4097 ArrayRef<ObjCProtocolDecl *> protocols = protocolsVec;
4098 type = getObjCObjectType(
4099 objT->getBaseType(),
4100 objT->getTypeArgsAsWritten(),
4101 protocols,
4102 objT->isKindOfTypeAsWritten());
4103 return getObjCObjectPointerType(type);
4104 }
4105 }
4106
4107 // Apply protocol qualifiers to ObjCObjectType.
4108 if (const ObjCObjectType *objT = dyn_cast<ObjCObjectType>(type.getTypePtr())){
4109 // FIXME: Check for protocols to which the class type is already
4110 // known to conform.
4111
4112 return getObjCObjectType(objT->getBaseType(),
4113 objT->getTypeArgsAsWritten(),
4114 protocols,
4115 objT->isKindOfTypeAsWritten());
4116 }
4117
4118 // If the canonical type is ObjCObjectType, ...
4119 if (type->isObjCObjectType()) {
4120 // Silently overwrite any existing protocol qualifiers.
4121 // TODO: determine whether that's the right thing to do.
4122
4123 // FIXME: Check for protocols to which the class type is already
4124 // known to conform.
4125 return getObjCObjectType(type, { }, protocols, false);
4126 }
4127
4128 // id<protocol-list>
4129 if (type->isObjCIdType()) {
4130 const ObjCObjectPointerType *objPtr = type->castAs<ObjCObjectPointerType>();
4131 type = getObjCObjectType(ObjCBuiltinIdTy, { }, protocols,
4132 objPtr->isKindOfType());
4133 return getObjCObjectPointerType(type);
4134 }
4135
4136 // Class<protocol-list>
4137 if (type->isObjCClassType()) {
4138 const ObjCObjectPointerType *objPtr = type->castAs<ObjCObjectPointerType>();
4139 type = getObjCObjectType(ObjCBuiltinClassTy, { }, protocols,
4140 objPtr->isKindOfType());
4141 return getObjCObjectPointerType(type);
4142 }
4143
4144 hasError = true;
4145 return type;
4146}
4147
Manman Rene6be26c2016-09-13 17:25:08 +00004148QualType
4149ASTContext::getObjCTypeParamType(const ObjCTypeParamDecl *Decl,
4150 ArrayRef<ObjCProtocolDecl *> protocols,
4151 QualType Canonical) const {
4152 // Look in the folding set for an existing type.
4153 llvm::FoldingSetNodeID ID;
4154 ObjCTypeParamType::Profile(ID, Decl, protocols);
4155 void *InsertPos = nullptr;
4156 if (ObjCTypeParamType *TypeParam =
4157 ObjCTypeParamTypes.FindNodeOrInsertPos(ID, InsertPos))
4158 return QualType(TypeParam, 0);
4159
4160 if (Canonical.isNull()) {
4161 // We canonicalize to the underlying type.
4162 Canonical = getCanonicalType(Decl->getUnderlyingType());
4163 if (!protocols.empty()) {
4164 // Apply the protocol qualifers.
4165 bool hasError;
4166 Canonical = applyObjCProtocolQualifiers(Canonical, protocols, hasError,
4167 true/*allowOnPointerType*/);
4168 assert(!hasError && "Error when apply protocol qualifier to bound type");
4169 }
4170 }
4171
4172 unsigned size = sizeof(ObjCTypeParamType);
4173 size += protocols.size() * sizeof(ObjCProtocolDecl *);
4174 void *mem = Allocate(size, TypeAlignment);
4175 ObjCTypeParamType *newType = new (mem)
4176 ObjCTypeParamType(Decl, Canonical, protocols);
4177
4178 Types.push_back(newType);
4179 ObjCTypeParamTypes.InsertNode(newType, InsertPos);
4180 return QualType(newType, 0);
4181}
4182
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004183/// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
4184/// protocol list adopt all protocols in QT's qualified-id protocol
4185/// list.
4186bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT,
4187 ObjCInterfaceDecl *IC) {
4188 if (!QT->isObjCQualifiedIdType())
4189 return false;
4190
4191 if (const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>()) {
4192 // If both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00004193 for (auto *Proto : OPT->quals()) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004194 if (!IC->ClassImplementsProtocol(Proto, false))
4195 return false;
4196 }
4197 return true;
4198 }
4199 return false;
4200}
4201
4202/// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
4203/// QT's qualified-id protocol list adopt all protocols in IDecl's list
4204/// of protocols.
4205bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
4206 ObjCInterfaceDecl *IDecl) {
4207 if (!QT->isObjCQualifiedIdType())
4208 return false;
4209 const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>();
4210 if (!OPT)
4211 return false;
4212 if (!IDecl->hasDefinition())
4213 return false;
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00004214 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols;
4215 CollectInheritedProtocols(IDecl, InheritedProtocols);
4216 if (InheritedProtocols.empty())
4217 return false;
Fariborz Jahanian48a01cb2014-04-04 23:53:45 +00004218 // Check that if every protocol in list of id<plist> conforms to a protcol
4219 // of IDecl's, then bridge casting is ok.
4220 bool Conforms = false;
4221 for (auto *Proto : OPT->quals()) {
4222 Conforms = false;
4223 for (auto *PI : InheritedProtocols) {
4224 if (ProtocolCompatibleWithProtocol(Proto, PI)) {
4225 Conforms = true;
4226 break;
4227 }
4228 }
4229 if (!Conforms)
4230 break;
4231 }
4232 if (Conforms)
4233 return true;
4234
Aaron Ballman83731462014-03-17 16:14:00 +00004235 for (auto *PI : InheritedProtocols) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004236 // If both the right and left sides have qualifiers.
4237 bool Adopts = false;
Aaron Ballman83731462014-03-17 16:14:00 +00004238 for (auto *Proto : OPT->quals()) {
Fariborz Jahanian48a01cb2014-04-04 23:53:45 +00004239 // return 'true' if 'PI' is in the inheritance hierarchy of Proto
Aaron Ballman83731462014-03-17 16:14:00 +00004240 if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004241 break;
4242 }
4243 if (!Adopts)
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00004244 return false;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004245 }
4246 return true;
4247}
4248
John McCall8b07ec22010-05-15 11:32:37 +00004249/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
4250/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00004251QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00004252 llvm::FoldingSetNodeID ID;
4253 ObjCObjectPointerType::Profile(ID, ObjectT);
4254
Craig Topper36250ad2014-05-12 05:36:57 +00004255 void *InsertPos = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00004256 if (ObjCObjectPointerType *QT =
4257 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
4258 return QualType(QT, 0);
4259
4260 // Find the canonical object type.
4261 QualType Canonical;
4262 if (!ObjectT.isCanonical()) {
4263 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
4264
4265 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00004266 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
4267 }
4268
Douglas Gregorf85bee62010-02-08 22:59:26 +00004269 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00004270 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
4271 ObjCObjectPointerType *QType =
4272 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00004273
Steve Narofffb4330f2009-06-17 22:40:22 +00004274 Types.push_back(QType);
4275 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00004276 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00004277}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004278
Douglas Gregor1c283312010-08-11 12:19:30 +00004279/// getObjCInterfaceType - Return the unique reference to the type for the
4280/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00004281QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
4282 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00004283 if (Decl->TypeForDecl)
4284 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00004285
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00004286 if (PrevDecl) {
4287 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
4288 Decl->TypeForDecl = PrevDecl->TypeForDecl;
4289 return QualType(PrevDecl->TypeForDecl, 0);
4290 }
4291
Douglas Gregor7671e532011-12-16 16:34:57 +00004292 // Prefer the definition, if there is one.
4293 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
4294 Decl = Def;
4295
Douglas Gregor1c283312010-08-11 12:19:30 +00004296 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
4297 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
4298 Decl->TypeForDecl = T;
4299 Types.push_back(T);
4300 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00004301}
4302
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004303/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
4304/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00004305/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00004306/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00004307/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00004308QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00004309 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004310 if (tofExpr->isTypeDependent()) {
4311 llvm::FoldingSetNodeID ID;
4312 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00004313
Craig Topper36250ad2014-05-12 05:36:57 +00004314 void *InsertPos = nullptr;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004315 DependentTypeOfExprType *Canon
4316 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
4317 if (Canon) {
4318 // We already have a "canonical" version of an identical, dependent
4319 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00004320 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004321 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00004322 } else {
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004323 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00004324 Canon
4325 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004326 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
4327 toe = Canon;
4328 }
4329 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00004330 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00004331 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00004332 }
Steve Naroffa773cd52007-08-01 18:02:17 +00004333 Types.push_back(toe);
4334 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00004335}
4336
Steve Naroffa773cd52007-08-01 18:02:17 +00004337/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
Richard Smith8eb1d322014-06-05 20:13:13 +00004338/// TypeOfType nodes. The only motivation to unique these nodes would be
Steve Naroffa773cd52007-08-01 18:02:17 +00004339/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Richard Smith8eb1d322014-06-05 20:13:13 +00004340/// an issue. This doesn't affect the type checker, since it operates
4341/// on canonical types (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00004342QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00004343 QualType Canonical = getCanonicalType(tofType);
John McCall90d1c2d2009-09-24 23:30:46 +00004344 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00004345 Types.push_back(tot);
4346 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00004347}
4348
Richard Smith8eb1d322014-06-05 20:13:13 +00004349/// \brief Unlike many "get<Type>" functions, we don't unique DecltypeType
4350/// nodes. This would never be helpful, since each such type has its own
4351/// expression, and would not give a significant memory saving, since there
4352/// is an Expr tree under each such type.
Douglas Gregor81495f32012-02-12 18:42:33 +00004353QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00004354 DecltypeType *dt;
Richard Smith8eb1d322014-06-05 20:13:13 +00004355
4356 // C++11 [temp.type]p2:
Douglas Gregor678d76c2011-07-01 01:22:09 +00004357 // If an expression e involves a template parameter, decltype(e) denotes a
Richard Smith8eb1d322014-06-05 20:13:13 +00004358 // unique dependent type. Two such decltype-specifiers refer to the same
4359 // type only if their expressions are equivalent (14.5.6.1).
Douglas Gregor678d76c2011-07-01 01:22:09 +00004360 if (e->isInstantiationDependent()) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00004361 llvm::FoldingSetNodeID ID;
4362 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00004363
Craig Topper36250ad2014-05-12 05:36:57 +00004364 void *InsertPos = nullptr;
Douglas Gregora21f6c32009-07-30 23:36:40 +00004365 DependentDecltypeType *Canon
4366 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
Richard Smith8eb1d322014-06-05 20:13:13 +00004367 if (!Canon) {
Yaron Keren633e14a2016-11-29 10:08:20 +00004368 // Build a new, canonical decltype(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00004369 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00004370 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
Douglas Gregora21f6c32009-07-30 23:36:40 +00004371 }
Richard Smith8eb1d322014-06-05 20:13:13 +00004372 dt = new (*this, TypeAlignment)
4373 DecltypeType(e, UnderlyingType, QualType((DecltypeType *)Canon, 0));
Douglas Gregora21f6c32009-07-30 23:36:40 +00004374 } else {
Richard Smith8eb1d322014-06-05 20:13:13 +00004375 dt = new (*this, TypeAlignment)
4376 DecltypeType(e, UnderlyingType, getCanonicalType(UnderlyingType));
Douglas Gregorabd68132009-07-08 00:03:05 +00004377 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00004378 Types.push_back(dt);
4379 return QualType(dt, 0);
4380}
4381
Alexis Hunte852b102011-05-24 22:41:36 +00004382/// getUnaryTransformationType - We don't unique these, since the memory
4383/// savings are minimal and these are rare.
4384QualType ASTContext::getUnaryTransformType(QualType BaseType,
4385 QualType UnderlyingType,
4386 UnaryTransformType::UTTKind Kind)
4387 const {
Vassil Vassilevbab6f962016-03-30 22:18:29 +00004388 UnaryTransformType *ut = nullptr;
4389
4390 if (BaseType->isDependentType()) {
4391 // Look in the folding set for an existing type.
4392 llvm::FoldingSetNodeID ID;
4393 DependentUnaryTransformType::Profile(ID, getCanonicalType(BaseType), Kind);
4394
4395 void *InsertPos = nullptr;
4396 DependentUnaryTransformType *Canon
4397 = DependentUnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos);
4398
4399 if (!Canon) {
4400 // Build a new, canonical __underlying_type(type) type.
4401 Canon = new (*this, TypeAlignment)
4402 DependentUnaryTransformType(*this, getCanonicalType(BaseType),
4403 Kind);
4404 DependentUnaryTransformTypes.InsertNode(Canon, InsertPos);
4405 }
4406 ut = new (*this, TypeAlignment) UnaryTransformType (BaseType,
4407 QualType(), Kind,
4408 QualType(Canon, 0));
4409 } else {
4410 QualType CanonType = getCanonicalType(UnderlyingType);
4411 ut = new (*this, TypeAlignment) UnaryTransformType (BaseType,
4412 UnderlyingType, Kind,
4413 CanonType);
4414 }
4415 Types.push_back(ut);
4416 return QualType(ut, 0);
Alexis Hunte852b102011-05-24 22:41:36 +00004417}
4418
Richard Smith2a7d4812013-05-04 07:00:32 +00004419/// getAutoType - Return the uniqued reference to the 'auto' type which has been
4420/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
4421/// canonical deduced-but-dependent 'auto' type.
Richard Smithe301ba22015-11-11 02:02:15 +00004422QualType ASTContext::getAutoType(QualType DeducedType, AutoTypeKeyword Keyword,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00004423 bool IsDependent) const {
Richard Smithe301ba22015-11-11 02:02:15 +00004424 if (DeducedType.isNull() && Keyword == AutoTypeKeyword::Auto && !IsDependent)
Richard Smith2a7d4812013-05-04 07:00:32 +00004425 return getAutoDeductType();
Manuel Klimek2fdbea22013-08-22 12:12:24 +00004426
Richard Smith2a7d4812013-05-04 07:00:32 +00004427 // Look in the folding set for an existing type.
Craig Topper36250ad2014-05-12 05:36:57 +00004428 void *InsertPos = nullptr;
Richard Smith2a7d4812013-05-04 07:00:32 +00004429 llvm::FoldingSetNodeID ID;
Richard Smithe301ba22015-11-11 02:02:15 +00004430 AutoType::Profile(ID, DeducedType, Keyword, IsDependent);
Richard Smith2a7d4812013-05-04 07:00:32 +00004431 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
4432 return QualType(AT, 0);
Richard Smithb2bc2e62011-02-21 20:05:19 +00004433
Richard Smith74aeef52013-04-26 16:15:35 +00004434 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType,
Richard Smithe301ba22015-11-11 02:02:15 +00004435 Keyword,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00004436 IsDependent);
Richard Smithb2bc2e62011-02-21 20:05:19 +00004437 Types.push_back(AT);
4438 if (InsertPos)
4439 AutoTypes.InsertNode(AT, InsertPos);
4440 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00004441}
4442
Richard Smith600b5262017-01-26 20:40:47 +00004443/// Return the uniqued reference to the deduced template specialization type
4444/// which has been deduced to the given type, or to the canonical undeduced
4445/// such type, or the canonical deduced-but-dependent such type.
4446QualType ASTContext::getDeducedTemplateSpecializationType(
4447 TemplateName Template, QualType DeducedType, bool IsDependent) const {
4448 // Look in the folding set for an existing type.
4449 void *InsertPos = nullptr;
4450 llvm::FoldingSetNodeID ID;
4451 DeducedTemplateSpecializationType::Profile(ID, Template, DeducedType,
4452 IsDependent);
4453 if (DeducedTemplateSpecializationType *DTST =
4454 DeducedTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos))
4455 return QualType(DTST, 0);
4456
4457 DeducedTemplateSpecializationType *DTST = new (*this, TypeAlignment)
4458 DeducedTemplateSpecializationType(Template, DeducedType, IsDependent);
4459 Types.push_back(DTST);
4460 if (InsertPos)
4461 DeducedTemplateSpecializationTypes.InsertNode(DTST, InsertPos);
4462 return QualType(DTST, 0);
4463}
4464
Eli Friedman0dfb8892011-10-06 23:00:33 +00004465/// getAtomicType - Return the uniqued reference to the atomic type for
4466/// the given value type.
4467QualType ASTContext::getAtomicType(QualType T) const {
4468 // Unique pointers, to guarantee there is only one pointer of a particular
4469 // structure.
4470 llvm::FoldingSetNodeID ID;
4471 AtomicType::Profile(ID, T);
4472
Craig Topper36250ad2014-05-12 05:36:57 +00004473 void *InsertPos = nullptr;
Eli Friedman0dfb8892011-10-06 23:00:33 +00004474 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
4475 return QualType(AT, 0);
4476
4477 // If the atomic value type isn't canonical, this won't be a canonical type
4478 // either, so fill in the canonical type field.
4479 QualType Canonical;
4480 if (!T.isCanonical()) {
4481 Canonical = getAtomicType(getCanonicalType(T));
4482
4483 // Get the new insert position for the node we care about.
4484 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00004485 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Eli Friedman0dfb8892011-10-06 23:00:33 +00004486 }
4487 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
4488 Types.push_back(New);
4489 AtomicTypes.InsertNode(New, InsertPos);
4490 return QualType(New, 0);
4491}
4492
Richard Smith02e85f32011-04-14 22:09:26 +00004493/// getAutoDeductType - Get type pattern for deducing against 'auto'.
4494QualType ASTContext::getAutoDeductType() const {
4495 if (AutoDeductTy.isNull())
Richard Smith2a7d4812013-05-04 07:00:32 +00004496 AutoDeductTy = QualType(
Richard Smithe301ba22015-11-11 02:02:15 +00004497 new (*this, TypeAlignment) AutoType(QualType(), AutoTypeKeyword::Auto,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00004498 /*dependent*/false),
Richard Smith2a7d4812013-05-04 07:00:32 +00004499 0);
Richard Smith02e85f32011-04-14 22:09:26 +00004500 return AutoDeductTy;
4501}
4502
4503/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
4504QualType ASTContext::getAutoRRefDeductType() const {
4505 if (AutoRRefDeductTy.isNull())
4506 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
4507 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
4508 return AutoRRefDeductTy;
4509}
4510
Chris Lattnerfb072462007-01-23 05:45:31 +00004511/// getTagDeclType - Return the unique reference to the type for the
4512/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00004513QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Ted Kremenek2b0ce112007-11-26 21:16:01 +00004514 assert (Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00004515 // FIXME: What is the design on getTagDeclType when it requires casting
4516 // away const? mutable?
4517 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00004518}
4519
Mike Stump11289f42009-09-09 15:08:12 +00004520/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
4521/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
4522/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00004523CanQualType ASTContext::getSizeType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00004524 return getFromTargetType(Target->getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00004525}
Chris Lattnerfb072462007-01-23 05:45:31 +00004526
Hans Wennborg27541db2011-10-27 08:29:09 +00004527/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
4528CanQualType ASTContext::getIntMaxType() const {
4529 return getFromTargetType(Target->getIntMaxType());
4530}
4531
4532/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
4533CanQualType ASTContext::getUIntMaxType() const {
4534 return getFromTargetType(Target->getUIntMaxType());
4535}
4536
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00004537/// getSignedWCharType - Return the type of "signed wchar_t".
4538/// Used when in C++, as a GCC extension.
4539QualType ASTContext::getSignedWCharType() const {
4540 // FIXME: derive from "Target" ?
4541 return WCharTy;
4542}
4543
4544/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
4545/// Used when in C++, as a GCC extension.
4546QualType ASTContext::getUnsignedWCharType() const {
4547 // FIXME: derive from "Target" ?
4548 return UnsignedIntTy;
4549}
4550
Enea Zaffanellaf11ceb62013-01-26 17:08:37 +00004551QualType ASTContext::getIntPtrType() const {
4552 return getFromTargetType(Target->getIntPtrType());
4553}
4554
4555QualType ASTContext::getUIntPtrType() const {
4556 return getCorrespondingUnsignedType(getIntPtrType());
4557}
4558
Hans Wennborg27541db2011-10-27 08:29:09 +00004559/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00004560/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
4561QualType ASTContext::getPointerDiffType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00004562 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00004563}
4564
Eli Friedman4e91899e2012-11-27 02:58:24 +00004565/// \brief Return the unique type for "pid_t" defined in
4566/// <sys/types.h>. We need this to compute the correct type for vfork().
4567QualType ASTContext::getProcessIDType() const {
4568 return getFromTargetType(Target->getProcessIDType());
4569}
4570
Chris Lattnera21ad802008-04-02 05:18:44 +00004571//===----------------------------------------------------------------------===//
4572// Type Operators
4573//===----------------------------------------------------------------------===//
4574
Jay Foad39c79802011-01-12 09:06:06 +00004575CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00004576 // Push qualifiers into arrays, and then discard any remaining
4577 // qualifiers.
4578 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00004579 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00004580 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00004581 QualType Result;
4582 if (isa<ArrayType>(Ty)) {
4583 Result = getArrayDecayedType(QualType(Ty,0));
4584 } else if (isa<FunctionType>(Ty)) {
4585 Result = getPointerType(QualType(Ty, 0));
4586 } else {
4587 Result = QualType(Ty, 0);
4588 }
4589
4590 return CanQualType::CreateUnsafe(Result);
4591}
4592
John McCall6c9dd522011-01-18 07:41:22 +00004593QualType ASTContext::getUnqualifiedArrayType(QualType type,
4594 Qualifiers &quals) {
4595 SplitQualType splitType = type.getSplitUnqualifiedType();
4596
4597 // FIXME: getSplitUnqualifiedType() actually walks all the way to
4598 // the unqualified desugared type and then drops it on the floor.
4599 // We then have to strip that sugar back off with
4600 // getUnqualifiedDesugaredType(), which is silly.
4601 const ArrayType *AT =
John McCall18ce25e2012-02-08 00:46:36 +00004602 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall6c9dd522011-01-18 07:41:22 +00004603
4604 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004605 if (!AT) {
John McCall18ce25e2012-02-08 00:46:36 +00004606 quals = splitType.Quals;
4607 return QualType(splitType.Ty, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00004608 }
4609
John McCall6c9dd522011-01-18 07:41:22 +00004610 // Otherwise, recurse on the array's element type.
4611 QualType elementType = AT->getElementType();
4612 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
4613
4614 // If that didn't change the element type, AT has no qualifiers, so we
4615 // can just use the results in splitType.
4616 if (elementType == unqualElementType) {
4617 assert(quals.empty()); // from the recursive call
John McCall18ce25e2012-02-08 00:46:36 +00004618 quals = splitType.Quals;
4619 return QualType(splitType.Ty, 0);
John McCall6c9dd522011-01-18 07:41:22 +00004620 }
4621
4622 // Otherwise, add in the qualifiers from the outermost type, then
4623 // build the type back up.
John McCall18ce25e2012-02-08 00:46:36 +00004624 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00004625
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004626 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00004627 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00004628 CAT->getSizeModifier(), 0);
4629 }
4630
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004631 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00004632 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00004633 }
4634
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004635 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00004636 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00004637 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004638 VAT->getSizeModifier(),
4639 VAT->getIndexTypeCVRQualifiers(),
4640 VAT->getBracketsRange());
4641 }
4642
4643 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00004644 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00004645 DSAT->getSizeModifier(), 0,
4646 SourceRange());
4647}
4648
Douglas Gregor1fc3d662010-06-09 03:53:18 +00004649/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
4650/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
4651/// they point to and return true. If T1 and T2 aren't pointer types
4652/// or pointer-to-member types, or if they are not similar at this
4653/// level, returns false and leaves T1 and T2 unchanged. Top-level
4654/// qualifiers on T1 and T2 are ignored. This function will typically
4655/// be called in a loop that successively "unwraps" pointer and
4656/// pointer-to-member types to compare them at each level.
4657bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
4658 const PointerType *T1PtrType = T1->getAs<PointerType>(),
4659 *T2PtrType = T2->getAs<PointerType>();
4660 if (T1PtrType && T2PtrType) {
4661 T1 = T1PtrType->getPointeeType();
4662 T2 = T2PtrType->getPointeeType();
4663 return true;
4664 }
4665
4666 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
4667 *T2MPType = T2->getAs<MemberPointerType>();
4668 if (T1MPType && T2MPType &&
4669 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
4670 QualType(T2MPType->getClass(), 0))) {
4671 T1 = T1MPType->getPointeeType();
4672 T2 = T2MPType->getPointeeType();
4673 return true;
4674 }
4675
David Blaikiebbafb8a2012-03-11 07:00:24 +00004676 if (getLangOpts().ObjC1) {
Douglas Gregor1fc3d662010-06-09 03:53:18 +00004677 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
4678 *T2OPType = T2->getAs<ObjCObjectPointerType>();
4679 if (T1OPType && T2OPType) {
4680 T1 = T1OPType->getPointeeType();
4681 T2 = T2OPType->getPointeeType();
4682 return true;
4683 }
4684 }
4685
4686 // FIXME: Block pointers, too?
4687
4688 return false;
4689}
4690
Jay Foad39c79802011-01-12 09:06:06 +00004691DeclarationNameInfo
4692ASTContext::getNameForTemplate(TemplateName Name,
4693 SourceLocation NameLoc) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00004694 switch (Name.getKind()) {
4695 case TemplateName::QualifiedTemplate:
4696 case TemplateName::Template:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004697 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCalld9dfe3a2011-06-30 08:33:18 +00004698 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
4699 NameLoc);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004700
John McCalld9dfe3a2011-06-30 08:33:18 +00004701 case TemplateName::OverloadedTemplate: {
4702 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
4703 // DNInfo work in progress: CHECKME: what about DNLoc?
4704 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
4705 }
4706
4707 case TemplateName::DependentTemplate: {
4708 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004709 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00004710 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004711 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
4712 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00004713 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004714 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
4715 // DNInfo work in progress: FIXME: source locations?
4716 DeclarationNameLoc DNLoc;
4717 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
4718 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
4719 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00004720 }
4721 }
4722
John McCalld9dfe3a2011-06-30 08:33:18 +00004723 case TemplateName::SubstTemplateTemplateParm: {
4724 SubstTemplateTemplateParmStorage *subst
4725 = Name.getAsSubstTemplateTemplateParm();
4726 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
4727 NameLoc);
4728 }
4729
4730 case TemplateName::SubstTemplateTemplateParmPack: {
4731 SubstTemplateTemplateParmPackStorage *subst
4732 = Name.getAsSubstTemplateTemplateParmPack();
4733 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
4734 NameLoc);
4735 }
4736 }
4737
4738 llvm_unreachable("bad template name kind!");
John McCall847e2a12009-11-24 18:42:40 +00004739}
4740
Jay Foad39c79802011-01-12 09:06:06 +00004741TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00004742 switch (Name.getKind()) {
4743 case TemplateName::QualifiedTemplate:
4744 case TemplateName::Template: {
4745 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004746 if (TemplateTemplateParmDecl *TTP
John McCalld9dfe3a2011-06-30 08:33:18 +00004747 = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004748 Template = getCanonicalTemplateTemplateParmDecl(TTP);
4749
4750 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00004751 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00004752 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00004753
John McCalld9dfe3a2011-06-30 08:33:18 +00004754 case TemplateName::OverloadedTemplate:
4755 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump11289f42009-09-09 15:08:12 +00004756
John McCalld9dfe3a2011-06-30 08:33:18 +00004757 case TemplateName::DependentTemplate: {
4758 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
4759 assert(DTN && "Non-dependent template names must refer to template decls.");
4760 return DTN->CanonicalTemplateName;
4761 }
4762
4763 case TemplateName::SubstTemplateTemplateParm: {
4764 SubstTemplateTemplateParmStorage *subst
4765 = Name.getAsSubstTemplateTemplateParm();
4766 return getCanonicalTemplateName(subst->getReplacement());
4767 }
4768
4769 case TemplateName::SubstTemplateTemplateParmPack: {
4770 SubstTemplateTemplateParmPackStorage *subst
4771 = Name.getAsSubstTemplateTemplateParmPack();
4772 TemplateTemplateParmDecl *canonParameter
4773 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
4774 TemplateArgument canonArgPack
4775 = getCanonicalTemplateArgument(subst->getArgumentPack());
4776 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
4777 }
4778 }
4779
4780 llvm_unreachable("bad template name!");
Douglas Gregor6bc50582009-05-07 06:41:52 +00004781}
4782
Douglas Gregoradee3e32009-11-11 23:06:43 +00004783bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
4784 X = getCanonicalTemplateName(X);
4785 Y = getCanonicalTemplateName(Y);
4786 return X.getAsVoidPointer() == Y.getAsVoidPointer();
4787}
4788
Mike Stump11289f42009-09-09 15:08:12 +00004789TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00004790ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00004791 switch (Arg.getKind()) {
4792 case TemplateArgument::Null:
4793 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00004794
Douglas Gregora8e02e72009-07-28 23:00:59 +00004795 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00004796 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00004797
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004798 case TemplateArgument::Declaration: {
Eli Friedmanb826a002012-09-26 02:36:12 +00004799 ValueDecl *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
David Blaikie952a9b12014-10-17 18:00:12 +00004800 return TemplateArgument(D, Arg.getParamTypeForDecl());
Douglas Gregor31f55dc2012-04-06 22:40:38 +00004801 }
Mike Stump11289f42009-09-09 15:08:12 +00004802
Eli Friedmanb826a002012-09-26 02:36:12 +00004803 case TemplateArgument::NullPtr:
4804 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
4805 /*isNullPtr*/true);
4806
Douglas Gregor9167f8b2009-11-11 01:00:40 +00004807 case TemplateArgument::Template:
4808 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004809
4810 case TemplateArgument::TemplateExpansion:
4811 return TemplateArgument(getCanonicalTemplateName(
4812 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00004813 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00004814
Douglas Gregora8e02e72009-07-28 23:00:59 +00004815 case TemplateArgument::Integral:
Benjamin Kramer6003ad52012-06-07 15:09:51 +00004816 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00004817
Douglas Gregora8e02e72009-07-28 23:00:59 +00004818 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00004819 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00004820
Douglas Gregora8e02e72009-07-28 23:00:59 +00004821 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00004822 if (Arg.pack_size() == 0)
4823 return Arg;
4824
Douglas Gregor1ccc8412010-11-07 23:05:16 +00004825 TemplateArgument *CanonArgs
4826 = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00004827 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004828 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00004829 AEnd = Arg.pack_end();
4830 A != AEnd; (void)++A, ++Idx)
4831 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00004832
Benjamin Kramercce63472015-08-05 09:40:22 +00004833 return TemplateArgument(llvm::makeArrayRef(CanonArgs, Arg.pack_size()));
Douglas Gregora8e02e72009-07-28 23:00:59 +00004834 }
4835 }
4836
4837 // Silence GCC warning
David Blaikie83d382b2011-09-23 05:06:16 +00004838 llvm_unreachable("Unhandled template argument kind");
Douglas Gregora8e02e72009-07-28 23:00:59 +00004839}
4840
Douglas Gregor333489b2009-03-27 23:10:48 +00004841NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00004842ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00004843 if (!NNS)
Craig Topper36250ad2014-05-12 05:36:57 +00004844 return nullptr;
Douglas Gregor333489b2009-03-27 23:10:48 +00004845
4846 switch (NNS->getKind()) {
4847 case NestedNameSpecifier::Identifier:
4848 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00004849 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00004850 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
4851 NNS->getAsIdentifier());
4852
4853 case NestedNameSpecifier::Namespace:
4854 // A namespace is canonical; build a nested-name-specifier with
4855 // this namespace and no prefix.
Craig Topper36250ad2014-05-12 05:36:57 +00004856 return NestedNameSpecifier::Create(*this, nullptr,
Douglas Gregor7b26ff92011-02-24 02:36:08 +00004857 NNS->getAsNamespace()->getOriginalNamespace());
4858
4859 case NestedNameSpecifier::NamespaceAlias:
4860 // A namespace is canonical; build a nested-name-specifier with
4861 // this namespace and no prefix.
Craig Topper36250ad2014-05-12 05:36:57 +00004862 return NestedNameSpecifier::Create(*this, nullptr,
Douglas Gregor7b26ff92011-02-24 02:36:08 +00004863 NNS->getAsNamespaceAlias()->getNamespace()
4864 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00004865
4866 case NestedNameSpecifier::TypeSpec:
4867 case NestedNameSpecifier::TypeSpecWithTemplate: {
4868 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Douglas Gregor3ade5702010-11-04 00:09:33 +00004869
4870 // If we have some kind of dependent-named type (e.g., "typename T::type"),
4871 // break it apart into its prefix and identifier, then reconsititute those
4872 // as the canonical nested-name-specifier. This is required to canonicalize
4873 // a dependent nested-name-specifier involving typedefs of dependent-name
4874 // types, e.g.,
4875 // typedef typename T::type T1;
4876 // typedef typename T1::type T2;
Eli Friedman5358a0a2012-03-03 04:09:56 +00004877 if (const DependentNameType *DNT = T->getAs<DependentNameType>())
4878 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor3ade5702010-11-04 00:09:33 +00004879 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor3ade5702010-11-04 00:09:33 +00004880
Eli Friedman5358a0a2012-03-03 04:09:56 +00004881 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
4882 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
4883 // first place?
Craig Topper36250ad2014-05-12 05:36:57 +00004884 return NestedNameSpecifier::Create(*this, nullptr, false,
4885 const_cast<Type *>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00004886 }
4887
4888 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +00004889 case NestedNameSpecifier::Super:
4890 // The global specifier and __super specifer are canonical and unique.
Douglas Gregor333489b2009-03-27 23:10:48 +00004891 return NNS;
4892 }
4893
David Blaikie8a40f702012-01-17 06:56:22 +00004894 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor333489b2009-03-27 23:10:48 +00004895}
4896
Jay Foad39c79802011-01-12 09:06:06 +00004897const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00004898 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004899 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00004900 // Handle the common positive case fast.
4901 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
4902 return AT;
4903 }
Mike Stump11289f42009-09-09 15:08:12 +00004904
John McCall8ccfcb52009-09-24 19:53:00 +00004905 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00004906 if (!isa<ArrayType>(T.getCanonicalType()))
Craig Topper36250ad2014-05-12 05:36:57 +00004907 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00004908
John McCall8ccfcb52009-09-24 19:53:00 +00004909 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00004910 // implements C99 6.7.3p8: "If the specification of an array type includes
4911 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00004912
Chris Lattner7adf0762008-08-04 07:31:14 +00004913 // If we get here, we either have type qualifiers on the type, or we have
4914 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00004915 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00004916
John McCall33ddac02011-01-19 10:06:00 +00004917 SplitQualType split = T.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00004918 Qualifiers qs = split.Quals;
Mike Stump11289f42009-09-09 15:08:12 +00004919
Chris Lattner7adf0762008-08-04 07:31:14 +00004920 // If we have a simple case, just return now.
John McCall18ce25e2012-02-08 00:46:36 +00004921 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
Craig Topper36250ad2014-05-12 05:36:57 +00004922 if (!ATy || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00004923 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00004924
Chris Lattner7adf0762008-08-04 07:31:14 +00004925 // Otherwise, we have an array and we have qualifiers on it. Push the
4926 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00004927 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00004928
Chris Lattner7adf0762008-08-04 07:31:14 +00004929 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
4930 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
4931 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004932 CAT->getIndexTypeCVRQualifiers()));
Chris Lattner7adf0762008-08-04 07:31:14 +00004933 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
4934 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
4935 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004936 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00004937
Mike Stump11289f42009-09-09 15:08:12 +00004938 if (const DependentSizedArrayType *DSAT
Douglas Gregor4619e432008-12-05 23:32:09 +00004939 = dyn_cast<DependentSizedArrayType>(ATy))
4940 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00004941 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00004942 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00004943 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004944 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00004945 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00004946
Chris Lattner7adf0762008-08-04 07:31:14 +00004947 const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00004948 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00004949 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00004950 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00004951 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00004952 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00004953}
4954
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00004955QualType ASTContext::getAdjustedParameterType(QualType T) const {
Reid Kleckner8a365022013-06-24 17:51:48 +00004956 if (T->isArrayType() || T->isFunctionType())
4957 return getDecayedType(T);
4958 return T;
Douglas Gregor84280642011-07-12 04:42:08 +00004959}
4960
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00004961QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00004962 T = getVariableArrayDecayedType(T);
4963 T = getAdjustedParameterType(T);
4964 return T.getUnqualifiedType();
4965}
4966
David Majnemerd09a51c2015-03-03 01:50:05 +00004967QualType ASTContext::getExceptionObjectType(QualType T) const {
4968 // C++ [except.throw]p3:
4969 // A throw-expression initializes a temporary object, called the exception
4970 // object, the type of which is determined by removing any top-level
4971 // cv-qualifiers from the static type of the operand of throw and adjusting
4972 // the type from "array of T" or "function returning T" to "pointer to T"
4973 // or "pointer to function returning T", [...]
4974 T = getVariableArrayDecayedType(T);
4975 if (T->isArrayType() || T->isFunctionType())
4976 T = getDecayedType(T);
4977 return T.getUnqualifiedType();
4978}
4979
Chris Lattnera21ad802008-04-02 05:18:44 +00004980/// getArrayDecayedType - Return the properly qualified result of decaying the
4981/// specified array type to a pointer. This operation is non-trivial when
4982/// handling typedefs etc. The canonical type of "T" must be an array type,
4983/// this returns a pointer to a properly qualified element of the array.
4984///
4985/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00004986QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00004987 // Get the element type with 'getAsArrayType' so that we don't lose any
4988 // typedefs in the element type of the array. This also handles propagation
4989 // of type qualifiers from the array type into the element type if present
4990 // (C99 6.7.3p8).
4991 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
4992 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00004993
Chris Lattner7adf0762008-08-04 07:31:14 +00004994 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00004995
4996 // int x[restrict 4] -> int *restrict
Jordan Rose303e2f12016-11-10 23:28:17 +00004997 QualType Result = getQualifiedType(PtrTy,
4998 PrettyArrayType->getIndexTypeQualifiers());
4999
5000 // int x[_Nullable] -> int * _Nullable
5001 if (auto Nullability = Ty->getNullability(*this)) {
5002 Result = const_cast<ASTContext *>(this)->getAttributedType(
5003 AttributedType::getNullabilityAttrKind(*Nullability), Result, Result);
5004 }
5005 return Result;
Chris Lattnera21ad802008-04-02 05:18:44 +00005006}
5007
John McCall33ddac02011-01-19 10:06:00 +00005008QualType ASTContext::getBaseElementType(const ArrayType *array) const {
5009 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00005010}
5011
John McCall33ddac02011-01-19 10:06:00 +00005012QualType ASTContext::getBaseElementType(QualType type) const {
5013 Qualifiers qs;
5014 while (true) {
5015 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00005016 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall33ddac02011-01-19 10:06:00 +00005017 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00005018
John McCall33ddac02011-01-19 10:06:00 +00005019 type = array->getElementType();
John McCall18ce25e2012-02-08 00:46:36 +00005020 qs.addConsistentQualifiers(split.Quals);
John McCall33ddac02011-01-19 10:06:00 +00005021 }
Mike Stump11289f42009-09-09 15:08:12 +00005022
John McCall33ddac02011-01-19 10:06:00 +00005023 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00005024}
5025
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00005026/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00005027uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00005028ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
5029 uint64_t ElementCount = 1;
5030 do {
5031 ElementCount *= CA->getSize().getZExtValue();
Richard Smith7808c6a2012-12-06 03:04:50 +00005032 CA = dyn_cast_or_null<ConstantArrayType>(
5033 CA->getElementType()->getAsArrayTypeUnsafe());
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00005034 } while (CA);
5035 return ElementCount;
5036}
5037
Steve Naroff0af91202007-04-27 21:51:21 +00005038/// getFloatingRank - Return a relative rank for floating point types.
5039/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00005040static FloatingRank getFloatingRank(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +00005041 if (const ComplexType *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00005042 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00005043
John McCall9dd450b2009-09-21 23:43:11 +00005044 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
5045 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00005046 default: llvm_unreachable("getFloatingRank(): not a floating type");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00005047 case BuiltinType::Half: return HalfRank;
Chris Lattnerc6395932007-06-22 20:56:16 +00005048 case BuiltinType::Float: return FloatRank;
5049 case BuiltinType::Double: return DoubleRank;
5050 case BuiltinType::LongDouble: return LongDoubleRank;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00005051 case BuiltinType::Float128: return Float128Rank;
Steve Naroffe4718892007-04-27 18:30:00 +00005052 }
5053}
5054
Mike Stump11289f42009-09-09 15:08:12 +00005055/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
5056/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00005057/// 'typeDomain' is a real floating point or complex type.
5058/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00005059QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
5060 QualType Domain) const {
5061 FloatingRank EltRank = getFloatingRank(Size);
5062 if (Domain->isComplexType()) {
5063 switch (EltRank) {
David Blaikief47fa302012-01-17 02:30:50 +00005064 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Naroff9091ef72007-08-27 01:27:54 +00005065 case FloatRank: return FloatComplexTy;
5066 case DoubleRank: return DoubleComplexTy;
5067 case LongDoubleRank: return LongDoubleComplexTy;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00005068 case Float128Rank: return Float128ComplexTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00005069 }
Steve Naroff0af91202007-04-27 21:51:21 +00005070 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00005071
5072 assert(Domain->isRealFloatingType() && "Unknown domain!");
5073 switch (EltRank) {
Joey Goulydd7f4562013-01-23 11:56:20 +00005074 case HalfRank: return HalfTy;
Chris Lattnerb9dfb032008-04-06 23:58:54 +00005075 case FloatRank: return FloatTy;
5076 case DoubleRank: return DoubleTy;
5077 case LongDoubleRank: return LongDoubleTy;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00005078 case Float128Rank: return Float128Ty;
Steve Naroff9091ef72007-08-27 01:27:54 +00005079 }
David Blaikief47fa302012-01-17 02:30:50 +00005080 llvm_unreachable("getFloatingRank(): illegal value for rank");
Steve Naroffe4718892007-04-27 18:30:00 +00005081}
5082
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005083/// getFloatingTypeOrder - Compare the rank of the two specified floating
5084/// point types, ignoring the domain of the type (i.e. 'double' ==
5085/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00005086/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00005087int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00005088 FloatingRank LHSR = getFloatingRank(LHS);
5089 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00005090
Chris Lattnerb90739d2008-04-06 23:38:49 +00005091 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00005092 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00005093 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00005094 return 1;
5095 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00005096}
5097
Chris Lattner76a00cf2008-04-06 22:59:24 +00005098/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
5099/// routine will assert if passed a built-in type that isn't an integer or enum,
5100/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00005101unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00005102 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00005103
Chris Lattner76a00cf2008-04-06 22:59:24 +00005104 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00005105 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005106 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005107 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005108 case BuiltinType::Char_S:
5109 case BuiltinType::Char_U:
5110 case BuiltinType::SChar:
5111 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005112 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005113 case BuiltinType::Short:
5114 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005115 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005116 case BuiltinType::Int:
5117 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005118 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005119 case BuiltinType::Long:
5120 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005121 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005122 case BuiltinType::LongLong:
5123 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005124 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00005125 case BuiltinType::Int128:
5126 case BuiltinType::UInt128:
5127 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00005128 }
5129}
5130
Eli Friedman629ffb92009-08-20 04:21:42 +00005131/// \brief Whether this is a promotable bitfield reference according
5132/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
5133///
5134/// \returns the type this bit-field will promote to, or NULL if no
5135/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00005136QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00005137 if (E->isTypeDependent() || E->isValueDependent())
5138 return QualType();
Richard Smith5b571672014-09-24 23:55:00 +00005139
5140 // FIXME: We should not do this unless E->refersToBitField() is true. This
5141 // matters in C where getSourceBitField() will find bit-fields for various
5142 // cases where the source expression is not a bit-field designator.
5143
John McCalld25db7e2013-05-06 21:39:12 +00005144 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
Eli Friedman629ffb92009-08-20 04:21:42 +00005145 if (!Field)
5146 return QualType();
5147
5148 QualType FT = Field->getType();
5149
Richard Smithcaf33902011-10-10 18:28:20 +00005150 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman629ffb92009-08-20 04:21:42 +00005151 uint64_t IntSize = getTypeSize(IntTy);
Richard Smith5b571672014-09-24 23:55:00 +00005152 // C++ [conv.prom]p5:
5153 // A prvalue for an integral bit-field can be converted to a prvalue of type
5154 // int if int can represent all the values of the bit-field; otherwise, it
5155 // can be converted to unsigned int if unsigned int can represent all the
5156 // values of the bit-field. If the bit-field is larger yet, no integral
5157 // promotion applies to it.
5158 // C11 6.3.1.1/2:
5159 // [For a bit-field of type _Bool, int, signed int, or unsigned int:]
5160 // If an int can represent all values of the original type (as restricted by
5161 // the width, for a bit-field), the value is converted to an int; otherwise,
5162 // it is converted to an unsigned int.
5163 //
5164 // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
5165 // We perform that promotion here to match GCC and C++.
Eli Friedman629ffb92009-08-20 04:21:42 +00005166 if (BitWidth < IntSize)
5167 return IntTy;
5168
5169 if (BitWidth == IntSize)
5170 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
5171
5172 // Types bigger than int are not subject to promotions, and therefore act
Richard Smith5b571672014-09-24 23:55:00 +00005173 // like the base type. GCC has some weird bugs in this area that we
5174 // deliberately do not follow (GCC follows a pre-standard resolution to
5175 // C's DR315 which treats bit-width as being part of the type, and this leaks
5176 // into their semantics in some cases).
Eli Friedman629ffb92009-08-20 04:21:42 +00005177 return QualType();
5178}
5179
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005180/// getPromotedIntegerType - Returns the type that Promotable will
5181/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
5182/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00005183QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005184 assert(!Promotable.isNull());
5185 assert(Promotable->isPromotableIntegerType());
John McCall56774992009-12-09 09:09:27 +00005186 if (const EnumType *ET = Promotable->getAs<EnumType>())
5187 return ET->getDecl()->getPromotionType();
Eli Friedman3f37c1c2011-10-26 07:22:48 +00005188
5189 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
5190 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
5191 // (3.9.1) can be converted to a prvalue of the first of the following
5192 // types that can represent all the values of its underlying type:
5193 // int, unsigned int, long int, unsigned long int, long long int, or
5194 // unsigned long long int [...]
5195 // FIXME: Is there some better way to compute this?
5196 if (BT->getKind() == BuiltinType::WChar_S ||
5197 BT->getKind() == BuiltinType::WChar_U ||
5198 BT->getKind() == BuiltinType::Char16 ||
5199 BT->getKind() == BuiltinType::Char32) {
5200 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
5201 uint64_t FromSize = getTypeSize(BT);
5202 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
5203 LongLongTy, UnsignedLongLongTy };
5204 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
5205 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
5206 if (FromSize < ToSize ||
5207 (FromSize == ToSize &&
5208 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
5209 return PromoteTypes[Idx];
5210 }
5211 llvm_unreachable("char type should fit into long long");
5212 }
5213 }
5214
5215 // At this point, we should have a signed or unsigned integer type.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005216 if (Promotable->isSignedIntegerType())
5217 return IntTy;
Eli Friedman6745c3b2012-11-15 01:21:59 +00005218 uint64_t PromotableSize = getIntWidth(Promotable);
5219 uint64_t IntSize = getIntWidth(IntTy);
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005220 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
5221 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
5222}
5223
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00005224/// \brief Recurses in pointer/array types until it finds an objc retainable
5225/// type and returns its ownership.
5226Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
5227 while (!T.isNull()) {
5228 if (T.getObjCLifetime() != Qualifiers::OCL_None)
5229 return T.getObjCLifetime();
5230 if (T->isArrayType())
5231 T = getBaseElementType(T);
5232 else if (const PointerType *PT = T->getAs<PointerType>())
5233 T = PT->getPointeeType();
5234 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis8e252532011-07-01 23:01:46 +00005235 T = RT->getPointeeType();
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00005236 else
5237 break;
5238 }
5239
5240 return Qualifiers::OCL_None;
5241}
5242
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00005243static const Type *getIntegerTypeForEnum(const EnumType *ET) {
5244 // Incomplete enum types are not treated as integer types.
5245 // FIXME: In C++, enum types are never integer types.
5246 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
5247 return ET->getDecl()->getIntegerType().getTypePtr();
Craig Topper36250ad2014-05-12 05:36:57 +00005248 return nullptr;
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00005249}
5250
Mike Stump11289f42009-09-09 15:08:12 +00005251/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005252/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00005253/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00005254int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00005255 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
5256 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00005257
5258 // Unwrap enums to their underlying type.
5259 if (const EnumType *ET = dyn_cast<EnumType>(LHSC))
5260 LHSC = getIntegerTypeForEnum(ET);
5261 if (const EnumType *ET = dyn_cast<EnumType>(RHSC))
5262 RHSC = getIntegerTypeForEnum(ET);
5263
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005264 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00005265
Chris Lattner76a00cf2008-04-06 22:59:24 +00005266 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
5267 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00005268
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005269 unsigned LHSRank = getIntegerRank(LHSC);
5270 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00005271
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005272 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
5273 if (LHSRank == RHSRank) return 0;
5274 return LHSRank > RHSRank ? 1 : -1;
5275 }
Mike Stump11289f42009-09-09 15:08:12 +00005276
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005277 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
5278 if (LHSUnsigned) {
5279 // If the unsigned [LHS] type is larger, return it.
5280 if (LHSRank >= RHSRank)
5281 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00005282
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005283 // If the signed type can represent all values of the unsigned type, it
5284 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00005285 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005286 return -1;
5287 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00005288
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005289 // If the unsigned [RHS] type is larger, return it.
5290 if (RHSRank >= LHSRank)
5291 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00005292
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005293 // If the signed type can represent all values of the unsigned type, it
5294 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00005295 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005296 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00005297}
Anders Carlsson98f07902007-08-17 05:31:46 +00005298
Ben Langmuirf5416742016-02-04 00:55:24 +00005299TypedefDecl *ASTContext::getCFConstantStringDecl() const {
Anders Carlsson98f07902007-08-17 05:31:46 +00005300 if (!CFConstantStringTypeDecl) {
Ben Langmuirf5416742016-02-04 00:55:24 +00005301 assert(!CFConstantStringTagDecl &&
5302 "tag and typedef should be initialized together");
5303 CFConstantStringTagDecl = buildImplicitRecord("__NSConstantString_tag");
5304 CFConstantStringTagDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00005305
Anders Carlsson9c1011c2007-11-19 00:25:30 +00005306 QualType FieldTypes[4];
Ben Langmuir4791a802016-02-25 16:36:26 +00005307 const char *FieldNames[4];
Mike Stump11289f42009-09-09 15:08:12 +00005308
Anders Carlsson98f07902007-08-17 05:31:46 +00005309 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00005310 FieldTypes[0] = getPointerType(IntTy.withConst());
Ben Langmuir4791a802016-02-25 16:36:26 +00005311 FieldNames[0] = "isa";
Anders Carlsson9c1011c2007-11-19 00:25:30 +00005312 // int flags;
5313 FieldTypes[1] = IntTy;
Ben Langmuir4791a802016-02-25 16:36:26 +00005314 FieldNames[1] = "flags";
Anders Carlsson98f07902007-08-17 05:31:46 +00005315 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00005316 FieldTypes[2] = getPointerType(CharTy.withConst());
Ben Langmuir4791a802016-02-25 16:36:26 +00005317 FieldNames[2] = "str";
Anders Carlsson98f07902007-08-17 05:31:46 +00005318 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00005319 FieldTypes[3] = LongTy;
Ben Langmuir4791a802016-02-25 16:36:26 +00005320 FieldNames[3] = "length";
Mike Stump11289f42009-09-09 15:08:12 +00005321
Anders Carlsson98f07902007-08-17 05:31:46 +00005322 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00005323 for (unsigned i = 0; i < 4; ++i) {
Ben Langmuirf5416742016-02-04 00:55:24 +00005324 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTagDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00005325 SourceLocation(),
Ben Langmuir4791a802016-02-25 16:36:26 +00005326 SourceLocation(),
5327 &Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00005328 FieldTypes[i], /*TInfo=*/nullptr,
5329 /*BitWidth=*/nullptr,
Richard Smith938f40b2011-06-11 17:19:42 +00005330 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00005331 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00005332 Field->setAccess(AS_public);
Ben Langmuirf5416742016-02-04 00:55:24 +00005333 CFConstantStringTagDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00005334 }
5335
Ben Langmuirf5416742016-02-04 00:55:24 +00005336 CFConstantStringTagDecl->completeDefinition();
5337 // This type is designed to be compatible with NSConstantString, but cannot
5338 // use the same name, since NSConstantString is an interface.
5339 auto tagType = getTagDeclType(CFConstantStringTagDecl);
5340 CFConstantStringTypeDecl =
5341 buildImplicitTypedef(tagType, "__NSConstantString");
Anders Carlsson98f07902007-08-17 05:31:46 +00005342 }
Mike Stump11289f42009-09-09 15:08:12 +00005343
Quentin Colombet043406b2016-02-03 22:41:00 +00005344 return CFConstantStringTypeDecl;
5345}
5346
Ben Langmuirf5416742016-02-04 00:55:24 +00005347RecordDecl *ASTContext::getCFConstantStringTagDecl() const {
5348 if (!CFConstantStringTagDecl)
5349 getCFConstantStringDecl(); // Build the tag and the typedef.
5350 return CFConstantStringTagDecl;
5351}
5352
Quentin Colombet043406b2016-02-03 22:41:00 +00005353// getCFConstantStringType - Return the type used for constant CFStrings.
5354QualType ASTContext::getCFConstantStringType() const {
Ben Langmuirf5416742016-02-04 00:55:24 +00005355 return getTypedefType(getCFConstantStringDecl());
Gabor Greif412af032007-09-11 15:32:40 +00005356}
Anders Carlsson87c149b2007-10-11 01:00:40 +00005357
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00005358QualType ASTContext::getObjCSuperType() const {
5359 if (ObjCSuperType.isNull()) {
Alp Toker2dea15b2013-12-17 01:22:38 +00005360 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00005361 TUDecl->addDecl(ObjCSuperTypeDecl);
5362 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
5363 }
5364 return ObjCSuperType;
5365}
5366
Douglas Gregor512b0772009-04-23 22:29:11 +00005367void ASTContext::setCFConstantStringType(QualType T) {
Ben Langmuirf5416742016-02-04 00:55:24 +00005368 const TypedefType *TD = T->getAs<TypedefType>();
5369 assert(TD && "Invalid CFConstantStringType");
5370 CFConstantStringTypeDecl = cast<TypedefDecl>(TD->getDecl());
5371 auto TagType =
5372 CFConstantStringTypeDecl->getUnderlyingType()->getAs<RecordType>();
5373 assert(TagType && "Invalid CFConstantStringType");
5374 CFConstantStringTagDecl = TagType->getDecl();
Douglas Gregor512b0772009-04-23 22:29:11 +00005375}
5376
Jay Foad39c79802011-01-12 09:06:06 +00005377QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00005378 if (BlockDescriptorType)
5379 return getTagDeclType(BlockDescriptorType);
5380
Alp Toker2dea15b2013-12-17 01:22:38 +00005381 RecordDecl *RD;
Mike Stumpd0153282009-10-20 02:12:22 +00005382 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00005383 RD = buildImplicitRecord("__block_descriptor");
5384 RD->startDefinition();
5385
Mike Stumpd0153282009-10-20 02:12:22 +00005386 QualType FieldTypes[] = {
5387 UnsignedLongTy,
5388 UnsignedLongTy,
5389 };
5390
Craig Topperd6d31ac2013-07-15 08:24:27 +00005391 static const char *const FieldNames[] = {
Mike Stumpd0153282009-10-20 02:12:22 +00005392 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005393 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00005394 };
5395
5396 for (size_t i = 0; i < 2; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00005397 FieldDecl *Field = FieldDecl::Create(
5398 *this, RD, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00005399 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
5400 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00005401 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00005402 RD->addDecl(Field);
Mike Stumpd0153282009-10-20 02:12:22 +00005403 }
5404
Alp Toker2dea15b2013-12-17 01:22:38 +00005405 RD->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00005406
Alp Toker2dea15b2013-12-17 01:22:38 +00005407 BlockDescriptorType = RD;
Mike Stumpd0153282009-10-20 02:12:22 +00005408
5409 return getTagDeclType(BlockDescriptorType);
5410}
5411
Jay Foad39c79802011-01-12 09:06:06 +00005412QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005413 if (BlockDescriptorExtendedType)
5414 return getTagDeclType(BlockDescriptorExtendedType);
5415
Alp Toker2dea15b2013-12-17 01:22:38 +00005416 RecordDecl *RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005417 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00005418 RD = buildImplicitRecord("__block_descriptor_withcopydispose");
5419 RD->startDefinition();
5420
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005421 QualType FieldTypes[] = {
5422 UnsignedLongTy,
5423 UnsignedLongTy,
5424 getPointerType(VoidPtrTy),
5425 getPointerType(VoidPtrTy)
5426 };
5427
Craig Topperd6d31ac2013-07-15 08:24:27 +00005428 static const char *const FieldNames[] = {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005429 "reserved",
5430 "Size",
5431 "CopyFuncPtr",
5432 "DestroyFuncPtr"
5433 };
5434
5435 for (size_t i = 0; i < 4; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00005436 FieldDecl *Field = FieldDecl::Create(
5437 *this, RD, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00005438 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
5439 /*BitWidth=*/nullptr,
Alp Toker2dea15b2013-12-17 01:22:38 +00005440 /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00005441 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00005442 RD->addDecl(Field);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005443 }
5444
Alp Toker2dea15b2013-12-17 01:22:38 +00005445 RD->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005446
Alp Toker2dea15b2013-12-17 01:22:38 +00005447 BlockDescriptorExtendedType = RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005448 return getTagDeclType(BlockDescriptorExtendedType);
5449}
5450
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00005451/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
5452/// requires copy/dispose. Note that this must match the logic
5453/// in buildByrefHelpers.
5454bool ASTContext::BlockRequiresCopying(QualType Ty,
5455 const VarDecl *D) {
5456 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
5457 const Expr *copyExpr = getBlockVarCopyInits(D);
5458 if (!copyExpr && record->hasTrivialDestructor()) return false;
5459
Mike Stump94967902009-10-21 18:16:27 +00005460 return true;
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00005461 }
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00005462
5463 if (!Ty->isObjCRetainableType()) return false;
5464
5465 Qualifiers qs = Ty.getQualifiers();
5466
5467 // If we have lifetime, that dominates.
5468 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00005469 switch (lifetime) {
5470 case Qualifiers::OCL_None: llvm_unreachable("impossible");
5471
5472 // These are just bits as far as the runtime is concerned.
5473 case Qualifiers::OCL_ExplicitNone:
5474 case Qualifiers::OCL_Autoreleasing:
5475 return false;
5476
5477 // Tell the runtime that this is ARC __weak, called by the
5478 // byref routines.
5479 case Qualifiers::OCL_Weak:
5480 // ARC __strong __block variables need to be retained.
5481 case Qualifiers::OCL_Strong:
5482 return true;
5483 }
5484 llvm_unreachable("fell out of lifetime switch!");
5485 }
5486 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
5487 Ty->isObjCObjectPointerType());
Mike Stump94967902009-10-21 18:16:27 +00005488}
5489
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00005490bool ASTContext::getByrefLifetime(QualType Ty,
5491 Qualifiers::ObjCLifetime &LifeTime,
5492 bool &HasByrefExtendedLayout) const {
5493
5494 if (!getLangOpts().ObjC1 ||
5495 getLangOpts().getGC() != LangOptions::NonGC)
5496 return false;
5497
5498 HasByrefExtendedLayout = false;
Fariborz Jahanianf762b722012-12-11 19:58:01 +00005499 if (Ty->isRecordType()) {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00005500 HasByrefExtendedLayout = true;
5501 LifeTime = Qualifiers::OCL_None;
John McCall460ce582015-10-22 18:38:17 +00005502 } else if ((LifeTime = Ty.getObjCLifetime())) {
5503 // Honor the ARC qualifiers.
5504 } else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) {
5505 // The MRR rule.
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00005506 LifeTime = Qualifiers::OCL_ExplicitNone;
John McCall460ce582015-10-22 18:38:17 +00005507 } else {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00005508 LifeTime = Qualifiers::OCL_None;
John McCall460ce582015-10-22 18:38:17 +00005509 }
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00005510 return true;
5511}
5512
Douglas Gregorbab8a962011-09-08 01:46:34 +00005513TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
5514 if (!ObjCInstanceTypeDecl)
Alp Toker56b5cc92013-12-15 10:36:26 +00005515 ObjCInstanceTypeDecl =
5516 buildImplicitTypedef(getObjCIdType(), "instancetype");
Douglas Gregorbab8a962011-09-08 01:46:34 +00005517 return ObjCInstanceTypeDecl;
5518}
5519
Anders Carlsson18acd442007-10-29 06:33:42 +00005520// This returns true if a type has been typedefed to BOOL:
5521// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00005522static bool isTypeTypedefedAsBOOL(QualType T) {
Anders Carlsson18acd442007-10-29 06:33:42 +00005523 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00005524 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
5525 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00005526
Anders Carlssond8499822007-10-29 05:01:08 +00005527 return false;
5528}
5529
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005530/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005531/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00005532CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregora9d84932011-05-27 01:19:52 +00005533 if (!type->isIncompleteArrayType() && type->isIncompleteType())
5534 return CharUnits::Zero();
5535
Ken Dyck40775002010-01-11 17:06:35 +00005536 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00005537
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005538 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00005539 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00005540 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005541 // Treat arrays as pointers, since that's how they're passed in.
5542 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00005543 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00005544 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00005545}
5546
Hans Wennborg56fc62b2014-07-17 20:25:23 +00005547bool ASTContext::isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const {
David Majnemer3f021502015-10-08 04:53:31 +00005548 return getTargetInfo().getCXXABI().isMicrosoft() &&
5549 VD->isStaticDataMember() &&
David Majnemerfac52432015-10-19 23:22:49 +00005550 VD->getType()->isIntegralOrEnumerationType() &&
5551 !VD->getFirstDecl()->isOutOfLine() && VD->getFirstDecl()->hasInit();
Hans Wennborg56fc62b2014-07-17 20:25:23 +00005552}
5553
Richard Smithd9b90092016-07-02 01:32:16 +00005554ASTContext::InlineVariableDefinitionKind
5555ASTContext::getInlineVariableDefinitionKind(const VarDecl *VD) const {
5556 if (!VD->isInline())
5557 return InlineVariableDefinitionKind::None;
5558
5559 // In almost all cases, it's a weak definition.
5560 auto *First = VD->getFirstDecl();
5561 if (!First->isConstexpr() || First->isInlineSpecified() ||
5562 !VD->isStaticDataMember())
5563 return InlineVariableDefinitionKind::Weak;
5564
5565 // If there's a file-context declaration in this translation unit, it's a
5566 // non-discardable definition.
5567 for (auto *D : VD->redecls())
5568 if (D->getLexicalDeclContext()->isFileContext())
5569 return InlineVariableDefinitionKind::Strong;
5570
5571 // If we've not seen one yet, we don't know.
5572 return InlineVariableDefinitionKind::WeakUnknown;
5573}
5574
Ken Dyck40775002010-01-11 17:06:35 +00005575static inline
5576std::string charUnitsToString(const CharUnits &CU) {
5577 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005578}
5579
John McCall351762c2011-02-07 10:33:21 +00005580/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00005581/// declaration.
John McCall351762c2011-02-07 10:33:21 +00005582std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
5583 std::string S;
5584
David Chisnall950a9512009-11-17 19:33:30 +00005585 const BlockDecl *Decl = Expr->getBlockDecl();
5586 QualType BlockTy =
5587 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
5588 // Encode result type.
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00005589 if (getLangOpts().EncodeExtendedBlockSig)
Alp Toker314cc812014-01-25 16:55:45 +00005590 getObjCEncodingForMethodParameter(
5591 Decl::OBJC_TQ_None, BlockTy->getAs<FunctionType>()->getReturnType(), S,
5592 true /*Extended*/);
Fariborz Jahanian64223e62012-11-14 23:11:38 +00005593 else
Alp Toker314cc812014-01-25 16:55:45 +00005594 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getReturnType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00005595 // Compute size of all parameters.
5596 // Start with computing size of a pointer in number of bytes.
5597 // FIXME: There might(should) be a better way of doing this computation!
5598 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00005599 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
5600 CharUnits ParmOffset = PtrSize;
David Majnemer59f77922016-06-24 04:05:48 +00005601 for (auto PI : Decl->parameters()) {
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +00005602 QualType PType = PI->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00005603 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahaniand4879412012-06-30 00:48:59 +00005604 if (sz.isZero())
5605 continue;
Ken Dyck40775002010-01-11 17:06:35 +00005606 assert (sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00005607 ParmOffset += sz;
5608 }
5609 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00005610 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00005611 // Block pointer and offset.
5612 S += "@?0";
David Chisnall950a9512009-11-17 19:33:30 +00005613
5614 // Argument types.
5615 ParmOffset = PtrSize;
David Majnemer59f77922016-06-24 04:05:48 +00005616 for (auto PVDecl : Decl->parameters()) {
David Chisnall950a9512009-11-17 19:33:30 +00005617 QualType PType = PVDecl->getOriginalType();
5618 if (const ArrayType *AT =
5619 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5620 // Use array's original type only if it has known number of
5621 // elements.
5622 if (!isa<ConstantArrayType>(AT))
5623 PType = PVDecl->getType();
5624 } else if (PType->isFunctionType())
5625 PType = PVDecl->getType();
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00005626 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian64223e62012-11-14 23:11:38 +00005627 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
5628 S, true /*Extended*/);
5629 else
5630 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00005631 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00005632 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00005633 }
John McCall351762c2011-02-07 10:33:21 +00005634
5635 return S;
David Chisnall950a9512009-11-17 19:33:30 +00005636}
5637
John McCall843dfcc2016-11-29 21:57:00 +00005638std::string
5639ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl) const {
5640 std::string S;
David Chisnall50e4eba2010-12-30 14:05:53 +00005641 // Encode result type.
Alp Toker314cc812014-01-25 16:55:45 +00005642 getObjCEncodingForType(Decl->getReturnType(), S);
David Chisnall50e4eba2010-12-30 14:05:53 +00005643 CharUnits ParmOffset;
5644 // Compute size of all parameters.
David Majnemer59f77922016-06-24 04:05:48 +00005645 for (auto PI : Decl->parameters()) {
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00005646 QualType PType = PI->getType();
David Chisnall50e4eba2010-12-30 14:05:53 +00005647 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00005648 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00005649 continue;
5650
John McCall843dfcc2016-11-29 21:57:00 +00005651 assert(sz.isPositive() &&
5652 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall50e4eba2010-12-30 14:05:53 +00005653 ParmOffset += sz;
5654 }
5655 S += charUnitsToString(ParmOffset);
5656 ParmOffset = CharUnits::Zero();
5657
5658 // Argument types.
David Majnemer59f77922016-06-24 04:05:48 +00005659 for (auto PVDecl : Decl->parameters()) {
David Chisnall50e4eba2010-12-30 14:05:53 +00005660 QualType PType = PVDecl->getOriginalType();
5661 if (const ArrayType *AT =
5662 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5663 // Use array's original type only if it has known number of
5664 // elements.
5665 if (!isa<ConstantArrayType>(AT))
5666 PType = PVDecl->getType();
5667 } else if (PType->isFunctionType())
5668 PType = PVDecl->getType();
5669 getObjCEncodingForType(PType, S);
5670 S += charUnitsToString(ParmOffset);
5671 ParmOffset += getObjCEncodingTypeSize(PType);
5672 }
Douglas Gregora9d84932011-05-27 01:19:52 +00005673
John McCall843dfcc2016-11-29 21:57:00 +00005674 return S;
David Chisnall50e4eba2010-12-30 14:05:53 +00005675}
5676
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005677/// getObjCEncodingForMethodParameter - Return the encoded type for a single
5678/// method parameter or return type. If Extended, include class names and
5679/// block object types.
5680void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
5681 QualType T, std::string& S,
5682 bool Extended) const {
5683 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
5684 getObjCEncodingForTypeQualifier(QT, S);
5685 // Encode parameter type.
Craig Topper36250ad2014-05-12 05:36:57 +00005686 getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005687 true /*OutermostType*/,
5688 false /*EncodingProperty*/,
5689 false /*StructField*/,
5690 Extended /*EncodeBlockParameters*/,
5691 Extended /*EncodeClassNames*/);
5692}
5693
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005694/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005695/// declaration.
John McCall843dfcc2016-11-29 21:57:00 +00005696std::string ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
5697 bool Extended) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00005698 // FIXME: This is not very efficient.
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005699 // Encode return type.
John McCall843dfcc2016-11-29 21:57:00 +00005700 std::string S;
Alp Toker314cc812014-01-25 16:55:45 +00005701 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
5702 Decl->getReturnType(), S, Extended);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005703 // Compute size of all parameters.
5704 // Start with computing size of a pointer in number of bytes.
5705 // FIXME: There might(should) be a better way of doing this computation!
5706 SourceLocation Loc;
Ken Dyck40775002010-01-11 17:06:35 +00005707 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005708 // The first two arguments (self and _cmd) are pointers; account for
5709 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00005710 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00005711 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00005712 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00005713 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00005714 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00005715 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00005716 continue;
5717
Ken Dyck40775002010-01-11 17:06:35 +00005718 assert (sz.isPositive() &&
5719 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005720 ParmOffset += sz;
5721 }
Ken Dyck40775002010-01-11 17:06:35 +00005722 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005723 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00005724 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00005725
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005726 // Argument types.
5727 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00005728 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00005729 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00005730 const ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00005731 QualType PType = PVDecl->getOriginalType();
Fariborz Jahaniana0befc02008-12-20 23:29:59 +00005732 if (const ArrayType *AT =
Steve Naroffe4e55d22009-04-14 00:03:58 +00005733 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5734 // Use array's original type only if it has known number of
5735 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00005736 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00005737 PType = PVDecl->getType();
5738 } else if (PType->isFunctionType())
5739 PType = PVDecl->getType();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00005740 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
5741 PType, S, Extended);
Ken Dyck40775002010-01-11 17:06:35 +00005742 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00005743 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005744 }
Douglas Gregora9d84932011-05-27 01:19:52 +00005745
John McCall843dfcc2016-11-29 21:57:00 +00005746 return S;
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00005747}
5748
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005749ObjCPropertyImplDecl *
5750ASTContext::getObjCPropertyImplDeclForPropertyDecl(
5751 const ObjCPropertyDecl *PD,
5752 const Decl *Container) const {
5753 if (!Container)
Craig Topper36250ad2014-05-12 05:36:57 +00005754 return nullptr;
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005755 if (const ObjCCategoryImplDecl *CID =
5756 dyn_cast<ObjCCategoryImplDecl>(Container)) {
Aaron Ballmand85eff42014-03-14 15:02:45 +00005757 for (auto *PID : CID->property_impls())
5758 if (PID->getPropertyDecl() == PD)
5759 return PID;
Craig Topper36250ad2014-05-12 05:36:57 +00005760 } else {
5761 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
5762 for (auto *PID : OID->property_impls())
5763 if (PID->getPropertyDecl() == PD)
5764 return PID;
5765 }
5766 return nullptr;
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005767}
5768
Daniel Dunbar4932b362008-08-28 04:38:10 +00005769/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00005770/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00005771/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
5772/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00005773/// Property attributes are stored as a comma-delimited C string. The simple
5774/// attributes readonly and bycopy are encoded as single characters. The
5775/// parametrized attributes, getter=name, setter=name, and ivar=name, are
5776/// encoded as single characters, followed by an identifier. Property types
5777/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00005778/// these attributes are defined by the following enumeration:
5779/// @code
5780/// enum PropertyAttributes {
5781/// kPropertyReadOnly = 'R', // property is read-only.
5782/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
5783/// kPropertyByref = '&', // property is a reference to the value last assigned
5784/// kPropertyDynamic = 'D', // property is dynamic
5785/// kPropertyGetter = 'G', // followed by getter selector name
5786/// kPropertySetter = 'S', // followed by setter selector name
5787/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson8cf61852012-03-22 17:48:02 +00005788/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00005789/// kPropertyWeak = 'W' // 'weak' property
5790/// kPropertyStrong = 'P' // property GC'able
5791/// kPropertyNonAtomic = 'N' // property non-atomic
5792/// };
5793/// @endcode
John McCall843dfcc2016-11-29 21:57:00 +00005794std::string
5795ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
5796 const Decl *Container) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00005797 // Collect information from the property implementation decl(s).
5798 bool Dynamic = false;
Craig Topper36250ad2014-05-12 05:36:57 +00005799 ObjCPropertyImplDecl *SynthesizePID = nullptr;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005800
Fariborz Jahaniandad96302014-01-22 19:02:20 +00005801 if (ObjCPropertyImplDecl *PropertyImpDecl =
5802 getObjCPropertyImplDeclForPropertyDecl(PD, Container)) {
5803 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
5804 Dynamic = true;
5805 else
5806 SynthesizePID = PropertyImpDecl;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005807 }
5808
5809 // FIXME: This is not very efficient.
John McCall843dfcc2016-11-29 21:57:00 +00005810 std::string S = "T";
Daniel Dunbar4932b362008-08-28 04:38:10 +00005811
5812 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005813 // GCC has some special rules regarding encoding of properties which
5814 // closely resembles encoding of ivars.
Joe Groff98ac7d22014-07-07 22:25:15 +00005815 getObjCEncodingForPropertyType(PD->getType(), S);
Daniel Dunbar4932b362008-08-28 04:38:10 +00005816
5817 if (PD->isReadOnly()) {
5818 S += ",R";
Nico Weber4e8626f2013-05-08 23:47:40 +00005819 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy)
5820 S += ",C";
5821 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain)
5822 S += ",&";
Fariborz Jahanian33079ee2014-04-02 22:49:42 +00005823 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak)
5824 S += ",W";
Daniel Dunbar4932b362008-08-28 04:38:10 +00005825 } else {
5826 switch (PD->getSetterKind()) {
5827 case ObjCPropertyDecl::Assign: break;
5828 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00005829 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian70a315c2011-08-12 20:47:08 +00005830 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005831 }
5832 }
5833
5834 // It really isn't clear at all what this means, since properties
5835 // are "dynamic by default".
5836 if (Dynamic)
5837 S += ",D";
5838
Fariborz Jahanian218c6302009-01-20 19:14:18 +00005839 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
5840 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00005841
Daniel Dunbar4932b362008-08-28 04:38:10 +00005842 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
5843 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00005844 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005845 }
5846
5847 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
5848 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00005849 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005850 }
5851
5852 if (SynthesizePID) {
5853 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
5854 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00005855 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00005856 }
5857
5858 // FIXME: OBJCGC: weak & strong
John McCall843dfcc2016-11-29 21:57:00 +00005859 return S;
Daniel Dunbar4932b362008-08-28 04:38:10 +00005860}
5861
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005862/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00005863/// Another legacy compatibility encoding: 32-bit longs are encoded as
5864/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005865/// 'i' or 'I' instead if encoding a struct field, or a pointer!
5866///
5867void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00005868 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
John McCall9dd450b2009-09-21 23:43:11 +00005869 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00005870 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005871 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00005872 else
Jay Foad39c79802011-01-12 09:06:06 +00005873 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00005874 PointeeTy = IntTy;
5875 }
5876 }
5877}
5878
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00005879void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005880 const FieldDecl *Field,
5881 QualType *NotEncodedT) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005882 // We follow the behavior of gcc, expanding structures which are
5883 // directly pointed to, and expanding embedded structures. Note that
5884 // these rules are sufficient to prevent recursive encoding of the
5885 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00005886 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00005887 true /* outermost type */, false, false,
5888 false, false, false, NotEncodedT);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00005889}
5890
Joe Groff98ac7d22014-07-07 22:25:15 +00005891void ASTContext::getObjCEncodingForPropertyType(QualType T,
5892 std::string& S) const {
5893 // Encode result type.
5894 // GCC has some special rules regarding encoding of properties which
5895 // closely resembles encoding of ivars.
5896 getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
5897 true /* outermost type */,
5898 true /* encoding property */);
5899}
5900
John McCall393a78d2012-12-20 02:45:14 +00005901static char getObjCEncodingForPrimitiveKind(const ASTContext *C,
5902 BuiltinType::Kind kind) {
5903 switch (kind) {
David Chisnallb190a2c2010-06-04 01:10:52 +00005904 case BuiltinType::Void: return 'v';
5905 case BuiltinType::Bool: return 'B';
5906 case BuiltinType::Char_U:
5907 case BuiltinType::UChar: return 'C';
John McCall393a78d2012-12-20 02:45:14 +00005908 case BuiltinType::Char16:
David Chisnallb190a2c2010-06-04 01:10:52 +00005909 case BuiltinType::UShort: return 'S';
John McCall393a78d2012-12-20 02:45:14 +00005910 case BuiltinType::Char32:
David Chisnallb190a2c2010-06-04 01:10:52 +00005911 case BuiltinType::UInt: return 'I';
5912 case BuiltinType::ULong:
John McCall393a78d2012-12-20 02:45:14 +00005913 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00005914 case BuiltinType::UInt128: return 'T';
5915 case BuiltinType::ULongLong: return 'Q';
5916 case BuiltinType::Char_S:
5917 case BuiltinType::SChar: return 'c';
5918 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00005919 case BuiltinType::WChar_S:
5920 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00005921 case BuiltinType::Int: return 'i';
5922 case BuiltinType::Long:
John McCall393a78d2012-12-20 02:45:14 +00005923 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00005924 case BuiltinType::LongLong: return 'q';
5925 case BuiltinType::Int128: return 't';
5926 case BuiltinType::Float: return 'f';
5927 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00005928 case BuiltinType::LongDouble: return 'D';
John McCall393a78d2012-12-20 02:45:14 +00005929 case BuiltinType::NullPtr: return '*'; // like char*
5930
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00005931 case BuiltinType::Float128:
John McCall393a78d2012-12-20 02:45:14 +00005932 case BuiltinType::Half:
5933 // FIXME: potentially need @encodes for these!
5934 return ' ';
5935
5936 case BuiltinType::ObjCId:
5937 case BuiltinType::ObjCClass:
5938 case BuiltinType::ObjCSel:
5939 llvm_unreachable("@encoding ObjC primitive type");
5940
5941 // OpenCL and placeholder types don't need @encodings.
Alexey Bader954ba212016-04-08 13:40:33 +00005942#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
5943 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00005944#include "clang/Basic/OpenCLImageTypes.def"
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005945 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00005946 case BuiltinType::OCLClkEvent:
5947 case BuiltinType::OCLQueue:
5948 case BuiltinType::OCLNDRange:
5949 case BuiltinType::OCLReserveID:
Guy Benyei61054192013-02-07 10:55:47 +00005950 case BuiltinType::OCLSampler:
John McCall393a78d2012-12-20 02:45:14 +00005951 case BuiltinType::Dependent:
5952#define BUILTIN_TYPE(KIND, ID)
5953#define PLACEHOLDER_TYPE(KIND, ID) \
5954 case BuiltinType::KIND:
5955#include "clang/AST/BuiltinTypes.def"
5956 llvm_unreachable("invalid builtin type for @encode");
David Chisnallb190a2c2010-06-04 01:10:52 +00005957 }
David Blaikie5a6a0202013-01-09 17:48:41 +00005958 llvm_unreachable("invalid BuiltinType::Kind value");
David Chisnallb190a2c2010-06-04 01:10:52 +00005959}
5960
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005961static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
5962 EnumDecl *Enum = ET->getDecl();
5963
5964 // The encoding of an non-fixed enum type is always 'i', regardless of size.
5965 if (!Enum->isFixed())
5966 return 'i';
5967
5968 // The encoding of a fixed enum type matches its fixed underlying type.
John McCall393a78d2012-12-20 02:45:14 +00005969 const BuiltinType *BT = Enum->getIntegerType()->castAs<BuiltinType>();
5970 return getObjCEncodingForPrimitiveKind(C, BT->getKind());
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005971}
5972
Jay Foad39c79802011-01-12 09:06:06 +00005973static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00005974 QualType T, const FieldDecl *FD) {
Richard Smithcaf33902011-10-10 18:28:20 +00005975 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00005976 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00005977 // The NeXT runtime encodes bit fields as b followed by the number of bits.
5978 // The GNU runtime requires more information; bitfields are encoded as b,
5979 // then the offset (in bits) of the first element, then the type of the
5980 // bitfield, then the size in bits. For example, in this structure:
5981 //
5982 // struct
5983 // {
5984 // int integer;
5985 // int flags:2;
5986 // };
5987 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
5988 // runtime, but b32i2 for the GNU runtime. The reason for this extra
5989 // information is not especially sensible, but we're stuck with it for
5990 // compatibility with GCC, although providing it breaks anything that
5991 // actually uses runtime introspection and wants to work on both runtimes...
John McCall5fb5df92012-06-20 06:18:46 +00005992 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
David Chisnallb190a2c2010-06-04 01:10:52 +00005993 const RecordDecl *RD = FD->getParent();
5994 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedmana3c122d2011-07-07 01:54:01 +00005995 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005996 if (const EnumType *ET = T->getAs<EnumType>())
5997 S += ObjCEncodingForEnumType(Ctx, ET);
John McCall393a78d2012-12-20 02:45:14 +00005998 else {
5999 const BuiltinType *BT = T->castAs<BuiltinType>();
6000 S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind());
6001 }
David Chisnallb190a2c2010-06-04 01:10:52 +00006002 }
Richard Smithcaf33902011-10-10 18:28:20 +00006003 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian5c767722009-01-13 01:18:13 +00006004}
6005
Daniel Dunbar07d07852009-10-18 21:17:35 +00006006// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00006007void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
6008 bool ExpandPointedToStructures,
6009 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00006010 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00006011 bool OutermostType,
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006012 bool EncodingProperty,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006013 bool StructField,
6014 bool EncodeBlockParameters,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00006015 bool EncodeClassNames,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006016 bool EncodePointerToObjCTypedef,
6017 QualType *NotEncodedT) const {
John McCall393a78d2012-12-20 02:45:14 +00006018 CanQualType CT = getCanonicalType(T);
6019 switch (CT->getTypeClass()) {
6020 case Type::Builtin:
6021 case Type::Enum:
Chris Lattnere7cabb92009-07-13 00:10:46 +00006022 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00006023 return EncodeBitField(this, S, T, FD);
John McCall393a78d2012-12-20 02:45:14 +00006024 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CT))
6025 S += getObjCEncodingForPrimitiveKind(this, BT->getKind());
6026 else
6027 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
Chris Lattnere7cabb92009-07-13 00:10:46 +00006028 return;
Mike Stump11289f42009-09-09 15:08:12 +00006029
John McCall393a78d2012-12-20 02:45:14 +00006030 case Type::Complex: {
6031 const ComplexType *CT = T->castAs<ComplexType>();
Anders Carlsson39b2e132009-04-09 21:55:45 +00006032 S += 'j';
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006033 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, nullptr);
Chris Lattnere7cabb92009-07-13 00:10:46 +00006034 return;
6035 }
John McCall393a78d2012-12-20 02:45:14 +00006036
6037 case Type::Atomic: {
6038 const AtomicType *AT = T->castAs<AtomicType>();
6039 S += 'A';
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006040 getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, nullptr);
John McCall393a78d2012-12-20 02:45:14 +00006041 return;
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00006042 }
John McCall393a78d2012-12-20 02:45:14 +00006043
6044 // encoding for pointer or reference types.
6045 case Type::Pointer:
6046 case Type::LValueReference:
6047 case Type::RValueReference: {
6048 QualType PointeeTy;
6049 if (isa<PointerType>(CT)) {
6050 const PointerType *PT = T->castAs<PointerType>();
6051 if (PT->isObjCSelType()) {
6052 S += ':';
6053 return;
6054 }
6055 PointeeTy = PT->getPointeeType();
6056 } else {
6057 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
6058 }
6059
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006060 bool isReadOnly = false;
6061 // For historical/compatibility reasons, the read-only qualifier of the
6062 // pointee gets emitted _before_ the '^'. The read-only qualifier of
6063 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00006064 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00006065 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006066 if (OutermostType && T.isConstQualified()) {
6067 isReadOnly = true;
6068 S += 'r';
6069 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00006070 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006071 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006072 while (P->getAs<PointerType>())
6073 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006074 if (P.isConstQualified()) {
6075 isReadOnly = true;
6076 S += 'r';
6077 }
6078 }
6079 if (isReadOnly) {
6080 // Another legacy compatibility encoding. Some ObjC qualifier and type
6081 // combinations need to be rearranged.
6082 // Rewrite "in const" from "nr" to "rn"
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006083 if (StringRef(S).endswith("nr"))
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00006084 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006085 }
Mike Stump11289f42009-09-09 15:08:12 +00006086
Anders Carlssond8499822007-10-29 05:01:08 +00006087 if (PointeeTy->isCharType()) {
6088 // char pointer types should be encoded as '*' unless it is a
6089 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00006090 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00006091 S += '*';
6092 return;
6093 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006094 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00006095 // GCC binary compat: Need to convert "struct objc_class *" to "#".
6096 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
6097 S += '#';
6098 return;
6099 }
6100 // GCC binary compat: Need to convert "struct objc_object *" to "@".
6101 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
6102 S += '@';
6103 return;
6104 }
6105 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00006106 }
Anders Carlssond8499822007-10-29 05:01:08 +00006107 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006108 getLegacyIntegralTypeEncoding(PointeeTy);
6109
Mike Stump11289f42009-09-09 15:08:12 +00006110 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006111 nullptr, false, false, false, false, false, false,
6112 NotEncodedT);
Chris Lattnere7cabb92009-07-13 00:10:46 +00006113 return;
6114 }
John McCall393a78d2012-12-20 02:45:14 +00006115
6116 case Type::ConstantArray:
6117 case Type::IncompleteArray:
6118 case Type::VariableArray: {
6119 const ArrayType *AT = cast<ArrayType>(CT);
6120
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006121 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00006122 // Incomplete arrays are encoded as a pointer to the array element.
6123 S += '^';
6124
Mike Stump11289f42009-09-09 15:08:12 +00006125 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00006126 false, ExpandStructures, FD);
6127 } else {
6128 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00006129
Fariborz Jahanianf0dc11a2013-06-04 16:04:37 +00006130 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
6131 S += llvm::utostr(CAT->getSize().getZExtValue());
6132 else {
Anders Carlssond05f44b2009-02-22 01:38:57 +00006133 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006134 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
6135 "Unknown array type!");
Anders Carlssond05f44b2009-02-22 01:38:57 +00006136 S += '0';
6137 }
Mike Stump11289f42009-09-09 15:08:12 +00006138
6139 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006140 false, ExpandStructures, FD,
6141 false, false, false, false, false, false,
6142 NotEncodedT);
Anders Carlssond05f44b2009-02-22 01:38:57 +00006143 S += ']';
6144 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00006145 return;
6146 }
Mike Stump11289f42009-09-09 15:08:12 +00006147
John McCall393a78d2012-12-20 02:45:14 +00006148 case Type::FunctionNoProto:
6149 case Type::FunctionProto:
Anders Carlssondf4cc612007-10-30 00:06:20 +00006150 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00006151 return;
Mike Stump11289f42009-09-09 15:08:12 +00006152
John McCall393a78d2012-12-20 02:45:14 +00006153 case Type::Record: {
6154 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00006155 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00006156 // Anonymous structures print as '?'
6157 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
6158 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00006159 if (ClassTemplateSpecializationDecl *Spec
6160 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
6161 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
Benjamin Kramer9170e912013-02-22 15:46:01 +00006162 llvm::raw_string_ostream OS(S);
6163 TemplateSpecializationType::PrintTemplateArgumentList(OS,
David Majnemer6fbeee32016-07-07 04:43:07 +00006164 TemplateArgs.asArray(),
Douglas Gregorc0b07282011-09-27 22:38:19 +00006165 (*this).getPrintingPolicy());
Fariborz Jahanianc5158202010-05-07 00:28:49 +00006166 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00006167 } else {
6168 S += '?';
6169 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00006170 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00006171 S += '=';
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006172 if (!RDecl->isUnion()) {
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006173 getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006174 } else {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006175 for (const auto *Field : RDecl->fields()) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006176 if (FD) {
6177 S += '"';
6178 S += Field->getNameAsString();
6179 S += '"';
6180 }
Mike Stump11289f42009-09-09 15:08:12 +00006181
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006182 // Special case bit-fields.
6183 if (Field->isBitField()) {
6184 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006185 Field);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006186 } else {
6187 QualType qt = Field->getType();
6188 getLegacyIntegralTypeEncoding(qt);
6189 getObjCEncodingForTypeImpl(qt, S, false, true,
6190 FD, /*OutermostType*/false,
6191 /*EncodingProperty*/false,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006192 /*StructField*/true,
6193 false, false, false, NotEncodedT);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006194 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00006195 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00006196 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00006197 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00006198 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00006199 return;
6200 }
Mike Stump11289f42009-09-09 15:08:12 +00006201
John McCall393a78d2012-12-20 02:45:14 +00006202 case Type::BlockPointer: {
6203 const BlockPointerType *BT = T->castAs<BlockPointerType>();
Steve Naroff49140cb2009-02-02 18:24:29 +00006204 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006205 if (EncodeBlockParameters) {
John McCall393a78d2012-12-20 02:45:14 +00006206 const FunctionType *FT = BT->getPointeeType()->castAs<FunctionType>();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006207
6208 S += '<';
6209 // Block return type
Alp Toker314cc812014-01-25 16:55:45 +00006210 getObjCEncodingForTypeImpl(
6211 FT->getReturnType(), S, ExpandPointedToStructures, ExpandStructures,
6212 FD, false /* OutermostType */, EncodingProperty,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006213 false /* StructField */, EncodeBlockParameters, EncodeClassNames, false,
6214 NotEncodedT);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006215 // Block self
6216 S += "@?";
6217 // Block parameters
6218 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00006219 for (const auto &I : FPT->param_types())
6220 getObjCEncodingForTypeImpl(
6221 I, S, ExpandPointedToStructures, ExpandStructures, FD,
6222 false /* OutermostType */, EncodingProperty,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006223 false /* StructField */, EncodeBlockParameters, EncodeClassNames,
6224 false, NotEncodedT);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006225 }
6226 S += '>';
6227 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00006228 return;
6229 }
Mike Stump11289f42009-09-09 15:08:12 +00006230
Fariborz Jahanian33fa9622014-01-28 20:41:15 +00006231 case Type::ObjCObject: {
6232 // hack to match legacy encoding of *id and *Class
6233 QualType Ty = getObjCObjectPointerType(CT);
6234 if (Ty->isObjCIdType()) {
6235 S += "{objc_object=}";
6236 return;
6237 }
6238 else if (Ty->isObjCClassType()) {
6239 S += "{objc_class=}";
6240 return;
6241 }
6242 }
6243
John McCall393a78d2012-12-20 02:45:14 +00006244 case Type::ObjCInterface: {
6245 // Ignore protocol qualifiers when mangling at this level.
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00006246 // @encode(class_name)
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006247 ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00006248 S += '{';
Douglas Gregorb32684e2015-06-16 21:04:55 +00006249 S += OI->getObjCRuntimeNameAsString();
Akira Hatanakafd0fb202016-08-17 19:42:22 +00006250 if (ExpandStructures) {
6251 S += '=';
6252 SmallVector<const ObjCIvarDecl*, 32> Ivars;
6253 DeepCollectObjCIvars(OI, true, Ivars);
6254 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
6255 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
6256 if (Field->isBitField())
6257 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
6258 else
6259 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD,
6260 false, false, false, false, false,
6261 EncodePointerToObjCTypedef,
6262 NotEncodedT);
6263 }
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00006264 }
6265 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00006266 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00006267 }
Mike Stump11289f42009-09-09 15:08:12 +00006268
John McCall393a78d2012-12-20 02:45:14 +00006269 case Type::ObjCObjectPointer: {
6270 const ObjCObjectPointerType *OPT = T->castAs<ObjCObjectPointerType>();
Steve Naroff7cae42b2009-07-10 23:34:53 +00006271 if (OPT->isObjCIdType()) {
6272 S += '@';
6273 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00006274 }
Mike Stump11289f42009-09-09 15:08:12 +00006275
Steve Narofff0c86112009-10-28 22:03:49 +00006276 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
6277 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
6278 // Since this is a binary compatibility issue, need to consult with runtime
6279 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00006280 S += '#';
6281 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00006282 }
Mike Stump11289f42009-09-09 15:08:12 +00006283
Chris Lattnere7cabb92009-07-13 00:10:46 +00006284 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00006285 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00006286 ExpandPointedToStructures,
6287 ExpandStructures, FD);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006288 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00006289 // Note that we do extended encoding of protocol qualifer list
6290 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00006291 S += '"';
Aaron Ballman83731462014-03-17 16:14:00 +00006292 for (const auto *I : OPT->quals()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00006293 S += '<';
Douglas Gregorb32684e2015-06-16 21:04:55 +00006294 S += I->getObjCRuntimeNameAsString();
Steve Naroff7cae42b2009-07-10 23:34:53 +00006295 S += '>';
6296 }
6297 S += '"';
6298 }
6299 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00006300 }
Mike Stump11289f42009-09-09 15:08:12 +00006301
Chris Lattnere7cabb92009-07-13 00:10:46 +00006302 QualType PointeeTy = OPT->getPointeeType();
6303 if (!EncodingProperty &&
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00006304 isa<TypedefType>(PointeeTy.getTypePtr()) &&
6305 !EncodePointerToObjCTypedef) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00006306 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00006307 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00006308 // {...};
6309 S += '^';
Fariborz Jahanian88890e72013-07-12 16:19:11 +00006310 if (FD && OPT->getInterfaceDecl()) {
Fariborz Jahanianc682ef52013-07-12 16:41:56 +00006311 // Prevent recursive encoding of fields in some rare cases.
Fariborz Jahanian88890e72013-07-12 16:19:11 +00006312 ObjCInterfaceDecl *OI = OPT->getInterfaceDecl();
6313 SmallVector<const ObjCIvarDecl*, 32> Ivars;
6314 DeepCollectObjCIvars(OI, true, Ivars);
6315 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
6316 if (cast<FieldDecl>(Ivars[i]) == FD) {
6317 S += '{';
Douglas Gregorb32684e2015-06-16 21:04:55 +00006318 S += OI->getObjCRuntimeNameAsString();
Fariborz Jahanian88890e72013-07-12 16:19:11 +00006319 S += '}';
6320 return;
6321 }
6322 }
6323 }
Mike Stump11289f42009-09-09 15:08:12 +00006324 getObjCEncodingForTypeImpl(PointeeTy, S,
6325 false, ExpandPointedToStructures,
Craig Topper36250ad2014-05-12 05:36:57 +00006326 nullptr,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00006327 false, false, false, false, false,
6328 /*EncodePointerToObjCTypedef*/true);
Steve Naroff7cae42b2009-07-10 23:34:53 +00006329 return;
6330 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00006331
6332 S += '@';
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006333 if (OPT->getInterfaceDecl() &&
6334 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00006335 S += '"';
Douglas Gregorb32684e2015-06-16 21:04:55 +00006336 S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString();
Aaron Ballman83731462014-03-17 16:14:00 +00006337 for (const auto *I : OPT->quals()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00006338 S += '<';
Douglas Gregorb32684e2015-06-16 21:04:55 +00006339 S += I->getObjCRuntimeNameAsString();
Chris Lattnere7cabb92009-07-13 00:10:46 +00006340 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00006341 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00006342 S += '"';
6343 }
6344 return;
6345 }
Mike Stump11289f42009-09-09 15:08:12 +00006346
John McCalla9e6e8d2010-05-17 23:56:34 +00006347 // gcc just blithely ignores member pointers.
John McCall393a78d2012-12-20 02:45:14 +00006348 // FIXME: we shoul do better than that. 'M' is available.
6349 case Type::MemberPointer:
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006350 // This matches gcc's encoding, even though technically it is insufficient.
6351 //FIXME. We should do a better job than gcc.
John McCall393a78d2012-12-20 02:45:14 +00006352 case Type::Vector:
6353 case Type::ExtVector:
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006354 // Until we have a coherent encoding of these three types, issue warning.
6355 { if (NotEncodedT)
6356 *NotEncodedT = T;
6357 return;
6358 }
6359
6360 // We could see an undeduced auto type here during error recovery.
6361 // Just ignore it.
Richard Smith27d807c2013-04-30 13:56:41 +00006362 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00006363 case Type::DeducedTemplateSpecialization:
Richard Smith27d807c2013-04-30 13:56:41 +00006364 return;
6365
Xiuli Pan9c14e282016-01-09 12:53:17 +00006366 case Type::Pipe:
John McCall393a78d2012-12-20 02:45:14 +00006367#define ABSTRACT_TYPE(KIND, BASE)
6368#define TYPE(KIND, BASE)
6369#define DEPENDENT_TYPE(KIND, BASE) \
6370 case Type::KIND:
6371#define NON_CANONICAL_TYPE(KIND, BASE) \
6372 case Type::KIND:
6373#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
6374 case Type::KIND:
6375#include "clang/AST/TypeNodes.def"
6376 llvm_unreachable("@encode for dependent type!");
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00006377 }
John McCall393a78d2012-12-20 02:45:14 +00006378 llvm_unreachable("bad type kind!");
Anders Carlssond8499822007-10-29 05:01:08 +00006379}
6380
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006381void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
6382 std::string &S,
6383 const FieldDecl *FD,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006384 bool includeVBases,
6385 QualType *NotEncodedT) const {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006386 assert(RDecl && "Expected non-null RecordDecl");
6387 assert(!RDecl->isUnion() && "Should not be called for unions");
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00006388 if (!RDecl->getDefinition() || RDecl->getDefinition()->isInvalidDecl())
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006389 return;
6390
6391 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
6392 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
6393 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
6394
6395 if (CXXRec) {
Aaron Ballman574705e2014-03-13 15:41:46 +00006396 for (const auto &BI : CXXRec->bases()) {
6397 if (!BI.isVirtual()) {
6398 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00006399 if (base->isEmpty())
6400 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00006401 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006402 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
6403 std::make_pair(offs, base));
6404 }
6405 }
6406 }
6407
6408 unsigned i = 0;
Hans Wennborga302cd92014-08-21 16:06:57 +00006409 for (auto *Field : RDecl->fields()) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006410 uint64_t offs = layout.getFieldOffset(i);
6411 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
Hans Wennborga302cd92014-08-21 16:06:57 +00006412 std::make_pair(offs, Field));
6413 ++i;
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006414 }
6415
6416 if (CXXRec && includeVBases) {
Aaron Ballman445a9392014-03-13 16:15:17 +00006417 for (const auto &BI : CXXRec->vbases()) {
6418 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00006419 if (base->isEmpty())
6420 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00006421 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Eli Friedman1d24af82013-09-18 01:59:16 +00006422 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
6423 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
Argyrios Kyrtzidis81c0b5c2011-09-26 18:14:24 +00006424 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
6425 std::make_pair(offs, base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006426 }
6427 }
6428
6429 CharUnits size;
6430 if (CXXRec) {
6431 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
6432 } else {
6433 size = layout.getSize();
6434 }
6435
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006436#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006437 uint64_t CurOffs = 0;
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006438#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006439 std::multimap<uint64_t, NamedDecl *>::iterator
6440 CurLayObj = FieldOrBaseOffsets.begin();
6441
Douglas Gregorf5d6c742012-04-27 22:30:01 +00006442 if (CXXRec && CXXRec->isDynamicClass() &&
6443 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006444 if (FD) {
6445 S += "\"_vptr$";
6446 std::string recname = CXXRec->getNameAsString();
6447 if (recname.empty()) recname = "?";
6448 S += recname;
6449 S += '"';
6450 }
6451 S += "^^?";
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006452#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006453 CurOffs += getTypeSize(VoidPtrTy);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006454#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006455 }
6456
6457 if (!RDecl->hasFlexibleArrayMember()) {
6458 // Mark the end of the structure.
6459 uint64_t offs = toBits(size);
6460 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
Craig Topper36250ad2014-05-12 05:36:57 +00006461 std::make_pair(offs, nullptr));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006462 }
6463
6464 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006465#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006466 assert(CurOffs <= CurLayObj->first);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006467 if (CurOffs < CurLayObj->first) {
6468 uint64_t padding = CurLayObj->first - CurOffs;
6469 // FIXME: There doesn't seem to be a way to indicate in the encoding that
6470 // packing/alignment of members is different that normal, in which case
6471 // the encoding will be out-of-sync with the real layout.
6472 // If the runtime switches to just consider the size of types without
6473 // taking into account alignment, we could make padding explicit in the
6474 // encoding (e.g. using arrays of chars). The encoding strings would be
6475 // longer then though.
6476 CurOffs += padding;
6477 }
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006478#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006479
6480 NamedDecl *dcl = CurLayObj->second;
Craig Topper36250ad2014-05-12 05:36:57 +00006481 if (!dcl)
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006482 break; // reached end of structure.
6483
6484 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
6485 // We expand the bases without their virtual bases since those are going
6486 // in the initial structure. Note that this differs from gcc which
6487 // expands virtual bases each time one is encountered in the hierarchy,
6488 // making the encoding type bigger than it really is.
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006489 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
6490 NotEncodedT);
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00006491 assert(!base->isEmpty());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006492#ifndef NDEBUG
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00006493 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006494#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006495 } else {
6496 FieldDecl *field = cast<FieldDecl>(dcl);
6497 if (FD) {
6498 S += '"';
6499 S += field->getNameAsString();
6500 S += '"';
6501 }
6502
6503 if (field->isBitField()) {
6504 EncodeBitField(this, S, field->getType(), field);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006505#ifndef NDEBUG
Richard Smithcaf33902011-10-10 18:28:20 +00006506 CurOffs += field->getBitWidthValue(*this);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006507#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006508 } else {
6509 QualType qt = field->getType();
6510 getLegacyIntegralTypeEncoding(qt);
6511 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
6512 /*OutermostType*/false,
6513 /*EncodingProperty*/false,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006514 /*StructField*/true,
6515 false, false, false, NotEncodedT);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006516#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006517 CurOffs += getTypeSize(field->getType());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006518#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006519 }
6520 }
6521 }
6522}
6523
Mike Stump11289f42009-09-09 15:08:12 +00006524void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00006525 std::string& S) const {
6526 if (QT & Decl::OBJC_TQ_In)
6527 S += 'n';
6528 if (QT & Decl::OBJC_TQ_Inout)
6529 S += 'N';
6530 if (QT & Decl::OBJC_TQ_Out)
6531 S += 'o';
6532 if (QT & Decl::OBJC_TQ_Bycopy)
6533 S += 'O';
6534 if (QT & Decl::OBJC_TQ_Byref)
6535 S += 'R';
6536 if (QT & Decl::OBJC_TQ_Oneway)
6537 S += 'V';
6538}
6539
Douglas Gregor3ea72692011-08-12 05:46:01 +00006540TypedefDecl *ASTContext::getObjCIdDecl() const {
6541 if (!ObjCIdDecl) {
Douglas Gregore9d95f12015-07-07 03:57:35 +00006542 QualType T = getObjCObjectType(ObjCBuiltinIdTy, { }, { });
Douglas Gregor3ea72692011-08-12 05:46:01 +00006543 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00006544 ObjCIdDecl = buildImplicitTypedef(T, "id");
Douglas Gregor3ea72692011-08-12 05:46:01 +00006545 }
Douglas Gregor3ea72692011-08-12 05:46:01 +00006546 return ObjCIdDecl;
Steve Naroff66e9f332007-10-15 14:41:52 +00006547}
6548
Douglas Gregor52e02802011-08-12 06:17:30 +00006549TypedefDecl *ASTContext::getObjCSelDecl() const {
6550 if (!ObjCSelDecl) {
Alp Toker56b5cc92013-12-15 10:36:26 +00006551 QualType T = getPointerType(ObjCBuiltinSelTy);
6552 ObjCSelDecl = buildImplicitTypedef(T, "SEL");
Douglas Gregor52e02802011-08-12 06:17:30 +00006553 }
6554 return ObjCSelDecl;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00006555}
6556
Douglas Gregor0a586182011-08-12 05:59:41 +00006557TypedefDecl *ASTContext::getObjCClassDecl() const {
6558 if (!ObjCClassDecl) {
Douglas Gregore9d95f12015-07-07 03:57:35 +00006559 QualType T = getObjCObjectType(ObjCBuiltinClassTy, { }, { });
Douglas Gregor0a586182011-08-12 05:59:41 +00006560 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00006561 ObjCClassDecl = buildImplicitTypedef(T, "Class");
Douglas Gregor0a586182011-08-12 05:59:41 +00006562 }
Douglas Gregor0a586182011-08-12 05:59:41 +00006563 return ObjCClassDecl;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00006564}
6565
Douglas Gregord53ae832012-01-17 18:09:05 +00006566ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
6567 if (!ObjCProtocolClassDecl) {
6568 ObjCProtocolClassDecl
6569 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
6570 SourceLocation(),
6571 &Idents.get("Protocol"),
Douglas Gregor85f3f952015-07-07 03:57:15 +00006572 /*typeParamList=*/nullptr,
Craig Topper36250ad2014-05-12 05:36:57 +00006573 /*PrevDecl=*/nullptr,
Douglas Gregord53ae832012-01-17 18:09:05 +00006574 SourceLocation(), true);
6575 }
6576
6577 return ObjCProtocolClassDecl;
6578}
6579
Meador Inge5d3fb222012-06-16 03:34:49 +00006580//===----------------------------------------------------------------------===//
6581// __builtin_va_list Construction Functions
6582//===----------------------------------------------------------------------===//
6583
Charles Davisc7d5c942015-09-17 20:55:33 +00006584static TypedefDecl *CreateCharPtrNamedVaListDecl(const ASTContext *Context,
6585 StringRef Name) {
6586 // typedef char* __builtin[_ms]_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006587 QualType T = Context->getPointerType(Context->CharTy);
Charles Davisc7d5c942015-09-17 20:55:33 +00006588 return Context->buildImplicitTypedef(T, Name);
6589}
6590
6591static TypedefDecl *CreateMSVaListDecl(const ASTContext *Context) {
6592 return CreateCharPtrNamedVaListDecl(Context, "__builtin_ms_va_list");
6593}
6594
6595static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
6596 return CreateCharPtrNamedVaListDecl(Context, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006597}
6598
6599static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
6600 // typedef void* __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006601 QualType T = Context->getPointerType(Context->VoidTy);
6602 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006603}
6604
Tim Northover9bb857a2013-01-31 12:13:10 +00006605static TypedefDecl *
6606CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00006607 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00006608 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00006609 if (Context->getLangOpts().CPlusPlus) {
6610 // namespace std { struct __va_list {
6611 NamespaceDecl *NS;
6612 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
6613 Context->getTranslationUnitDecl(),
Craig Topper36250ad2014-05-12 05:36:57 +00006614 /*Inline*/ false, SourceLocation(),
Tim Northover9bb857a2013-01-31 12:13:10 +00006615 SourceLocation(), &Context->Idents.get("std"),
Craig Topper36250ad2014-05-12 05:36:57 +00006616 /*PrevDecl*/ nullptr);
Alp Toker56b5cc92013-12-15 10:36:26 +00006617 NS->setImplicit();
Tim Northover9bb857a2013-01-31 12:13:10 +00006618 VaListTagDecl->setDeclContext(NS);
Tim Northover9bb857a2013-01-31 12:13:10 +00006619 }
6620
6621 VaListTagDecl->startDefinition();
6622
6623 const size_t NumFields = 5;
6624 QualType FieldTypes[NumFields];
6625 const char *FieldNames[NumFields];
6626
6627 // void *__stack;
6628 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
6629 FieldNames[0] = "__stack";
6630
6631 // void *__gr_top;
6632 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
6633 FieldNames[1] = "__gr_top";
6634
6635 // void *__vr_top;
6636 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6637 FieldNames[2] = "__vr_top";
6638
6639 // int __gr_offs;
6640 FieldTypes[3] = Context->IntTy;
6641 FieldNames[3] = "__gr_offs";
6642
6643 // int __vr_offs;
6644 FieldTypes[4] = Context->IntTy;
6645 FieldNames[4] = "__vr_offs";
6646
6647 // Create fields
6648 for (unsigned i = 0; i < NumFields; ++i) {
6649 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6650 VaListTagDecl,
6651 SourceLocation(),
6652 SourceLocation(),
6653 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006654 FieldTypes[i], /*TInfo=*/nullptr,
6655 /*BitWidth=*/nullptr,
Tim Northover9bb857a2013-01-31 12:13:10 +00006656 /*Mutable=*/false,
6657 ICIS_NoInit);
6658 Field->setAccess(AS_public);
6659 VaListTagDecl->addDecl(Field);
6660 }
6661 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00006662 Context->VaListTagDecl = VaListTagDecl;
Tim Northover9bb857a2013-01-31 12:13:10 +00006663 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Tim Northover9bb857a2013-01-31 12:13:10 +00006664
6665 // } __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006666 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00006667}
6668
Meador Inge5d3fb222012-06-16 03:34:49 +00006669static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
6670 // typedef struct __va_list_tag {
6671 RecordDecl *VaListTagDecl;
6672
Alp Toker2dea15b2013-12-17 01:22:38 +00006673 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00006674 VaListTagDecl->startDefinition();
6675
6676 const size_t NumFields = 5;
6677 QualType FieldTypes[NumFields];
6678 const char *FieldNames[NumFields];
6679
6680 // unsigned char gpr;
6681 FieldTypes[0] = Context->UnsignedCharTy;
6682 FieldNames[0] = "gpr";
6683
6684 // unsigned char fpr;
6685 FieldTypes[1] = Context->UnsignedCharTy;
6686 FieldNames[1] = "fpr";
6687
6688 // unsigned short reserved;
6689 FieldTypes[2] = Context->UnsignedShortTy;
6690 FieldNames[2] = "reserved";
6691
6692 // void* overflow_arg_area;
6693 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6694 FieldNames[3] = "overflow_arg_area";
6695
6696 // void* reg_save_area;
6697 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
6698 FieldNames[4] = "reg_save_area";
6699
6700 // Create fields
6701 for (unsigned i = 0; i < NumFields; ++i) {
6702 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
6703 SourceLocation(),
6704 SourceLocation(),
6705 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006706 FieldTypes[i], /*TInfo=*/nullptr,
6707 /*BitWidth=*/nullptr,
Meador Inge5d3fb222012-06-16 03:34:49 +00006708 /*Mutable=*/false,
6709 ICIS_NoInit);
6710 Field->setAccess(AS_public);
6711 VaListTagDecl->addDecl(Field);
6712 }
6713 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00006714 Context->VaListTagDecl = VaListTagDecl;
Meador Inge5d3fb222012-06-16 03:34:49 +00006715 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6716
6717 // } __va_list_tag;
Alp Toker56b5cc92013-12-15 10:36:26 +00006718 TypedefDecl *VaListTagTypedefDecl =
6719 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
6720
Meador Inge5d3fb222012-06-16 03:34:49 +00006721 QualType VaListTagTypedefType =
6722 Context->getTypedefType(VaListTagTypedefDecl);
6723
6724 // typedef __va_list_tag __builtin_va_list[1];
6725 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6726 QualType VaListTagArrayType
6727 = Context->getConstantArrayType(VaListTagTypedefType,
6728 Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00006729 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006730}
6731
6732static TypedefDecl *
6733CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
Richard Smith9b88a4c2015-07-27 05:40:23 +00006734 // struct __va_list_tag {
Meador Inge5d3fb222012-06-16 03:34:49 +00006735 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00006736 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00006737 VaListTagDecl->startDefinition();
6738
6739 const size_t NumFields = 4;
6740 QualType FieldTypes[NumFields];
6741 const char *FieldNames[NumFields];
6742
6743 // unsigned gp_offset;
6744 FieldTypes[0] = Context->UnsignedIntTy;
6745 FieldNames[0] = "gp_offset";
6746
6747 // unsigned fp_offset;
6748 FieldTypes[1] = Context->UnsignedIntTy;
6749 FieldNames[1] = "fp_offset";
6750
6751 // void* overflow_arg_area;
6752 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6753 FieldNames[2] = "overflow_arg_area";
6754
6755 // void* reg_save_area;
6756 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6757 FieldNames[3] = "reg_save_area";
6758
6759 // Create fields
6760 for (unsigned i = 0; i < NumFields; ++i) {
6761 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6762 VaListTagDecl,
6763 SourceLocation(),
6764 SourceLocation(),
6765 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006766 FieldTypes[i], /*TInfo=*/nullptr,
6767 /*BitWidth=*/nullptr,
Meador Inge5d3fb222012-06-16 03:34:49 +00006768 /*Mutable=*/false,
6769 ICIS_NoInit);
6770 Field->setAccess(AS_public);
6771 VaListTagDecl->addDecl(Field);
6772 }
6773 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00006774 Context->VaListTagDecl = VaListTagDecl;
Meador Inge5d3fb222012-06-16 03:34:49 +00006775 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6776
Richard Smith9b88a4c2015-07-27 05:40:23 +00006777 // };
Alp Toker56b5cc92013-12-15 10:36:26 +00006778
Richard Smith9b88a4c2015-07-27 05:40:23 +00006779 // typedef struct __va_list_tag __builtin_va_list[1];
Meador Inge5d3fb222012-06-16 03:34:49 +00006780 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
Richard Smith9b88a4c2015-07-27 05:40:23 +00006781 QualType VaListTagArrayType =
6782 Context->getConstantArrayType(VaListTagType, Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00006783 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006784}
6785
6786static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
6787 // typedef int __builtin_va_list[4];
6788 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
Yaron Kerene0bcdd42016-10-08 06:45:10 +00006789 QualType IntArrayType =
6790 Context->getConstantArrayType(Context->IntTy, Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00006791 return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006792}
6793
Logan Chien57086ce2012-10-10 06:56:20 +00006794static TypedefDecl *
6795CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00006796 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00006797 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00006798 if (Context->getLangOpts().CPlusPlus) {
6799 // namespace std { struct __va_list {
6800 NamespaceDecl *NS;
6801 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
6802 Context->getTranslationUnitDecl(),
6803 /*Inline*/false, SourceLocation(),
6804 SourceLocation(), &Context->Idents.get("std"),
Craig Topper36250ad2014-05-12 05:36:57 +00006805 /*PrevDecl*/ nullptr);
Alp Toker56b5cc92013-12-15 10:36:26 +00006806 NS->setImplicit();
Logan Chien57086ce2012-10-10 06:56:20 +00006807 VaListDecl->setDeclContext(NS);
Logan Chien57086ce2012-10-10 06:56:20 +00006808 }
6809
6810 VaListDecl->startDefinition();
6811
6812 // void * __ap;
6813 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6814 VaListDecl,
6815 SourceLocation(),
6816 SourceLocation(),
6817 &Context->Idents.get("__ap"),
6818 Context->getPointerType(Context->VoidTy),
Craig Topper36250ad2014-05-12 05:36:57 +00006819 /*TInfo=*/nullptr,
6820 /*BitWidth=*/nullptr,
Logan Chien57086ce2012-10-10 06:56:20 +00006821 /*Mutable=*/false,
6822 ICIS_NoInit);
6823 Field->setAccess(AS_public);
6824 VaListDecl->addDecl(Field);
6825
6826 // };
6827 VaListDecl->completeDefinition();
Oleg Ranevskyyb88d2472016-03-30 21:30:30 +00006828 Context->VaListTagDecl = VaListDecl;
Logan Chien57086ce2012-10-10 06:56:20 +00006829
6830 // typedef struct __va_list __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006831 QualType T = Context->getRecordType(VaListDecl);
6832 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00006833}
6834
Ulrich Weigand47445072013-05-06 16:26:41 +00006835static TypedefDecl *
6836CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
Richard Smith9b88a4c2015-07-27 05:40:23 +00006837 // struct __va_list_tag {
Ulrich Weigand47445072013-05-06 16:26:41 +00006838 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00006839 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Ulrich Weigand47445072013-05-06 16:26:41 +00006840 VaListTagDecl->startDefinition();
6841
6842 const size_t NumFields = 4;
6843 QualType FieldTypes[NumFields];
6844 const char *FieldNames[NumFields];
6845
6846 // long __gpr;
6847 FieldTypes[0] = Context->LongTy;
6848 FieldNames[0] = "__gpr";
6849
6850 // long __fpr;
6851 FieldTypes[1] = Context->LongTy;
6852 FieldNames[1] = "__fpr";
6853
6854 // void *__overflow_arg_area;
6855 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6856 FieldNames[2] = "__overflow_arg_area";
6857
6858 // void *__reg_save_area;
6859 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6860 FieldNames[3] = "__reg_save_area";
6861
6862 // Create fields
6863 for (unsigned i = 0; i < NumFields; ++i) {
6864 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6865 VaListTagDecl,
6866 SourceLocation(),
6867 SourceLocation(),
6868 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006869 FieldTypes[i], /*TInfo=*/nullptr,
6870 /*BitWidth=*/nullptr,
Ulrich Weigand47445072013-05-06 16:26:41 +00006871 /*Mutable=*/false,
6872 ICIS_NoInit);
6873 Field->setAccess(AS_public);
6874 VaListTagDecl->addDecl(Field);
6875 }
6876 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00006877 Context->VaListTagDecl = VaListTagDecl;
Ulrich Weigand47445072013-05-06 16:26:41 +00006878 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Ulrich Weigand47445072013-05-06 16:26:41 +00006879
Richard Smith9b88a4c2015-07-27 05:40:23 +00006880 // };
Ulrich Weigand47445072013-05-06 16:26:41 +00006881
6882 // typedef __va_list_tag __builtin_va_list[1];
6883 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
Richard Smith9b88a4c2015-07-27 05:40:23 +00006884 QualType VaListTagArrayType =
6885 Context->getConstantArrayType(VaListTagType, Size, ArrayType::Normal, 0);
Ulrich Weigand47445072013-05-06 16:26:41 +00006886
Alp Toker56b5cc92013-12-15 10:36:26 +00006887 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Ulrich Weigand47445072013-05-06 16:26:41 +00006888}
6889
Meador Inge5d3fb222012-06-16 03:34:49 +00006890static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
6891 TargetInfo::BuiltinVaListKind Kind) {
6892 switch (Kind) {
6893 case TargetInfo::CharPtrBuiltinVaList:
6894 return CreateCharPtrBuiltinVaListDecl(Context);
6895 case TargetInfo::VoidPtrBuiltinVaList:
6896 return CreateVoidPtrBuiltinVaListDecl(Context);
Tim Northover9bb857a2013-01-31 12:13:10 +00006897 case TargetInfo::AArch64ABIBuiltinVaList:
6898 return CreateAArch64ABIBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00006899 case TargetInfo::PowerABIBuiltinVaList:
6900 return CreatePowerABIBuiltinVaListDecl(Context);
6901 case TargetInfo::X86_64ABIBuiltinVaList:
6902 return CreateX86_64ABIBuiltinVaListDecl(Context);
6903 case TargetInfo::PNaClABIBuiltinVaList:
6904 return CreatePNaClABIBuiltinVaListDecl(Context);
Logan Chien57086ce2012-10-10 06:56:20 +00006905 case TargetInfo::AAPCSABIBuiltinVaList:
6906 return CreateAAPCSABIBuiltinVaListDecl(Context);
Ulrich Weigand47445072013-05-06 16:26:41 +00006907 case TargetInfo::SystemZBuiltinVaList:
6908 return CreateSystemZBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00006909 }
6910
6911 llvm_unreachable("Unhandled __builtin_va_list type kind");
6912}
6913
6914TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00006915 if (!BuiltinVaListDecl) {
Meador Inge5d3fb222012-06-16 03:34:49 +00006916 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
Alp Toker56b5cc92013-12-15 10:36:26 +00006917 assert(BuiltinVaListDecl->isImplicit());
6918 }
Meador Inge5d3fb222012-06-16 03:34:49 +00006919
6920 return BuiltinVaListDecl;
6921}
6922
Richard Smith9b88a4c2015-07-27 05:40:23 +00006923Decl *ASTContext::getVaListTagDecl() const {
6924 // Force the creation of VaListTagDecl by building the __builtin_va_list
Meador Ingecfb60902012-07-01 15:57:25 +00006925 // declaration.
Richard Smith9b88a4c2015-07-27 05:40:23 +00006926 if (!VaListTagDecl)
6927 (void)getBuiltinVaListDecl();
Meador Ingecfb60902012-07-01 15:57:25 +00006928
Richard Smith9b88a4c2015-07-27 05:40:23 +00006929 return VaListTagDecl;
Meador Ingecfb60902012-07-01 15:57:25 +00006930}
6931
Charles Davisc7d5c942015-09-17 20:55:33 +00006932TypedefDecl *ASTContext::getBuiltinMSVaListDecl() const {
6933 if (!BuiltinMSVaListDecl)
6934 BuiltinMSVaListDecl = CreateMSVaListDecl(this);
6935
6936 return BuiltinMSVaListDecl;
6937}
6938
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006939void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00006940 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00006941 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00006942
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006943 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00006944}
6945
John McCalld28ae272009-12-02 08:04:21 +00006946/// \brief Retrieve the template name that corresponds to a non-empty
6947/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00006948TemplateName
6949ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
6950 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00006951 unsigned size = End - Begin;
6952 assert(size > 1 && "set is not overloaded!");
6953
6954 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
6955 size * sizeof(FunctionTemplateDecl*));
6956 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
6957
6958 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00006959 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00006960 NamedDecl *D = *I;
6961 assert(isa<FunctionTemplateDecl>(D) ||
6962 (isa<UsingShadowDecl>(D) &&
6963 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
6964 *Storage++ = D;
6965 }
6966
6967 return TemplateName(OT);
6968}
6969
Douglas Gregordc572a32009-03-30 22:58:21 +00006970/// \brief Retrieve the template name that represents a qualified
6971/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00006972TemplateName
6973ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
6974 bool TemplateKeyword,
6975 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00006976 assert(NNS && "Missing nested-name-specifier in qualified template name");
6977
Douglas Gregorc42075a2010-02-04 18:10:26 +00006978 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00006979 llvm::FoldingSetNodeID ID;
6980 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
6981
Craig Topper36250ad2014-05-12 05:36:57 +00006982 void *InsertPos = nullptr;
Douglas Gregordc572a32009-03-30 22:58:21 +00006983 QualifiedTemplateName *QTN =
6984 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6985 if (!QTN) {
Benjamin Kramerc3f89252016-10-20 14:27:22 +00006986 QTN = new (*this, alignof(QualifiedTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00006987 QualifiedTemplateName(NNS, TemplateKeyword, Template);
Douglas Gregordc572a32009-03-30 22:58:21 +00006988 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
6989 }
6990
6991 return TemplateName(QTN);
6992}
6993
6994/// \brief Retrieve the template name that represents a dependent
6995/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00006996TemplateName
6997ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
6998 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00006999 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00007000 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00007001
7002 llvm::FoldingSetNodeID ID;
7003 DependentTemplateName::Profile(ID, NNS, Name);
7004
Craig Topper36250ad2014-05-12 05:36:57 +00007005 void *InsertPos = nullptr;
Douglas Gregordc572a32009-03-30 22:58:21 +00007006 DependentTemplateName *QTN =
7007 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7008
7009 if (QTN)
7010 return TemplateName(QTN);
7011
7012 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
7013 if (CanonNNS == NNS) {
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007014 QTN = new (*this, alignof(DependentTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00007015 DependentTemplateName(NNS, Name);
Douglas Gregordc572a32009-03-30 22:58:21 +00007016 } else {
7017 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007018 QTN = new (*this, alignof(DependentTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00007019 DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00007020 DependentTemplateName *CheckQTN =
7021 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7022 assert(!CheckQTN && "Dependent type name canonicalization broken");
7023 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00007024 }
7025
7026 DependentTemplateNames.InsertNode(QTN, InsertPos);
7027 return TemplateName(QTN);
7028}
7029
Douglas Gregor71395fa2009-11-04 00:56:37 +00007030/// \brief Retrieve the template name that represents a dependent
7031/// template name such as \c MetaFun::template operator+.
7032TemplateName
7033ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00007034 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00007035 assert((!NNS || NNS->isDependent()) &&
7036 "Nested name specifier must be dependent");
7037
7038 llvm::FoldingSetNodeID ID;
7039 DependentTemplateName::Profile(ID, NNS, Operator);
Craig Topper36250ad2014-05-12 05:36:57 +00007040
7041 void *InsertPos = nullptr;
Douglas Gregorc42075a2010-02-04 18:10:26 +00007042 DependentTemplateName *QTN
7043 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00007044
7045 if (QTN)
7046 return TemplateName(QTN);
7047
7048 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
7049 if (CanonNNS == NNS) {
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007050 QTN = new (*this, alignof(DependentTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00007051 DependentTemplateName(NNS, Operator);
Douglas Gregor71395fa2009-11-04 00:56:37 +00007052 } else {
7053 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007054 QTN = new (*this, alignof(DependentTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00007055 DependentTemplateName(NNS, Operator, Canon);
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007056
Douglas Gregorc42075a2010-02-04 18:10:26 +00007057 DependentTemplateName *CheckQTN
7058 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7059 assert(!CheckQTN && "Dependent template name canonicalization broken");
7060 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00007061 }
7062
7063 DependentTemplateNames.InsertNode(QTN, InsertPos);
7064 return TemplateName(QTN);
7065}
7066
Douglas Gregor5590be02011-01-15 06:45:20 +00007067TemplateName
John McCalld9dfe3a2011-06-30 08:33:18 +00007068ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
7069 TemplateName replacement) const {
7070 llvm::FoldingSetNodeID ID;
7071 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
Craig Topper36250ad2014-05-12 05:36:57 +00007072
7073 void *insertPos = nullptr;
John McCalld9dfe3a2011-06-30 08:33:18 +00007074 SubstTemplateTemplateParmStorage *subst
7075 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
7076
7077 if (!subst) {
7078 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
7079 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
7080 }
7081
7082 return TemplateName(subst);
7083}
7084
7085TemplateName
Douglas Gregor5590be02011-01-15 06:45:20 +00007086ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
7087 const TemplateArgument &ArgPack) const {
7088 ASTContext &Self = const_cast<ASTContext &>(*this);
7089 llvm::FoldingSetNodeID ID;
7090 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
Craig Topper36250ad2014-05-12 05:36:57 +00007091
7092 void *InsertPos = nullptr;
Douglas Gregor5590be02011-01-15 06:45:20 +00007093 SubstTemplateTemplateParmPackStorage *Subst
7094 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
7095
7096 if (!Subst) {
John McCalld9dfe3a2011-06-30 08:33:18 +00007097 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor5590be02011-01-15 06:45:20 +00007098 ArgPack.pack_size(),
7099 ArgPack.pack_begin());
7100 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
7101 }
7102
7103 return TemplateName(Subst);
7104}
7105
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00007106/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00007107/// TargetInfo, produce the corresponding type. The unsigned @p Type
7108/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00007109CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00007110 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00007111 case TargetInfo::NoInt: return CanQualType();
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00007112 case TargetInfo::SignedChar: return SignedCharTy;
7113 case TargetInfo::UnsignedChar: return UnsignedCharTy;
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00007114 case TargetInfo::SignedShort: return ShortTy;
7115 case TargetInfo::UnsignedShort: return UnsignedShortTy;
7116 case TargetInfo::SignedInt: return IntTy;
7117 case TargetInfo::UnsignedInt: return UnsignedIntTy;
7118 case TargetInfo::SignedLong: return LongTy;
7119 case TargetInfo::UnsignedLong: return UnsignedLongTy;
7120 case TargetInfo::SignedLongLong: return LongLongTy;
7121 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
7122 }
7123
David Blaikie83d382b2011-09-23 05:06:16 +00007124 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00007125}
Ted Kremenek77c51b22008-07-24 23:58:27 +00007126
7127//===----------------------------------------------------------------------===//
7128// Type Predicates.
7129//===----------------------------------------------------------------------===//
7130
Fariborz Jahanian96207692009-02-18 21:49:28 +00007131/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
7132/// garbage collection attribute.
7133///
John McCall553d45a2011-01-12 00:34:59 +00007134Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00007135 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCall553d45a2011-01-12 00:34:59 +00007136 return Qualifiers::GCNone;
7137
David Blaikiebbafb8a2012-03-11 07:00:24 +00007138 assert(getLangOpts().ObjC1);
John McCall553d45a2011-01-12 00:34:59 +00007139 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
7140
7141 // Default behaviour under objective-C's gc is for ObjC pointers
7142 // (or pointers to them) be treated as though they were declared
7143 // as __strong.
7144 if (GCAttrs == Qualifiers::GCNone) {
7145 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
7146 return Qualifiers::Strong;
7147 else if (Ty->isPointerType())
7148 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
7149 } else {
7150 // It's not valid to set GC attributes on anything that isn't a
7151 // pointer.
7152#ifndef NDEBUG
7153 QualType CT = Ty->getCanonicalTypeInternal();
7154 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
7155 CT = AT->getElementType();
7156 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
7157#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00007158 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00007159 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00007160}
7161
Chris Lattner49af6a42008-04-07 06:51:04 +00007162//===----------------------------------------------------------------------===//
7163// Type Compatibility Testing
7164//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00007165
Mike Stump11289f42009-09-09 15:08:12 +00007166/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00007167/// compatible.
7168static bool areCompatVectorTypes(const VectorType *LHS,
7169 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00007170 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00007171 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00007172 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00007173}
7174
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00007175bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
7176 QualType SecondVec) {
7177 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
7178 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
7179
7180 if (hasSameUnqualifiedType(FirstVec, SecondVec))
7181 return true;
7182
Bob Wilsone6aeebb2010-11-12 17:24:54 +00007183 // Treat Neon vector types and most AltiVec vector types as if they are the
7184 // equivalent GCC vector types.
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00007185 const VectorType *First = FirstVec->getAs<VectorType>();
7186 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00007187 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00007188 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00007189 First->getVectorKind() != VectorType::AltiVecPixel &&
7190 First->getVectorKind() != VectorType::AltiVecBool &&
7191 Second->getVectorKind() != VectorType::AltiVecPixel &&
7192 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00007193 return true;
7194
7195 return false;
7196}
7197
Steve Naroff8e6aee52009-07-23 01:01:38 +00007198//===----------------------------------------------------------------------===//
7199// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
7200//===----------------------------------------------------------------------===//
7201
7202/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
7203/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00007204bool
7205ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
7206 ObjCProtocolDecl *rProto) const {
Douglas Gregor33b24292012-01-01 18:09:12 +00007207 if (declaresSameEntity(lProto, rProto))
Steve Naroff8e6aee52009-07-23 01:01:38 +00007208 return true;
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00007209 for (auto *PI : rProto->protocols())
7210 if (ProtocolCompatibleWithProtocol(lProto, PI))
Steve Naroff8e6aee52009-07-23 01:01:38 +00007211 return true;
7212 return false;
7213}
7214
Dmitri Gribenko4364fcf2012-08-28 02:49:14 +00007215/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
7216/// Class<pr1, ...>.
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00007217bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
7218 QualType rhs) {
7219 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
7220 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
7221 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
7222
Aaron Ballman83731462014-03-17 16:14:00 +00007223 for (auto *lhsProto : lhsQID->quals()) {
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00007224 bool match = false;
Aaron Ballman83731462014-03-17 16:14:00 +00007225 for (auto *rhsProto : rhsOPT->quals()) {
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00007226 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
7227 match = true;
7228 break;
7229 }
7230 }
7231 if (!match)
7232 return false;
7233 }
7234 return true;
7235}
7236
Steve Naroff8e6aee52009-07-23 01:01:38 +00007237/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
7238/// ObjCQualifiedIDType.
7239bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
7240 bool compare) {
7241 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00007242 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00007243 lhs->isObjCIdType() || lhs->isObjCClassType())
7244 return true;
Mike Stump11289f42009-09-09 15:08:12 +00007245 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00007246 rhs->isObjCIdType() || rhs->isObjCClassType())
7247 return true;
7248
7249 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00007250 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00007251
Steve Naroff8e6aee52009-07-23 01:01:38 +00007252 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00007253
Steve Naroff8e6aee52009-07-23 01:01:38 +00007254 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00007255 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00007256 // make sure we check the class hierarchy.
7257 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
Aaron Ballman83731462014-03-17 16:14:00 +00007258 for (auto *I : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007259 // when comparing an id<P> on lhs with a static type on rhs,
7260 // see if static class implements all of id's protocols, directly or
7261 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00007262 if (!rhsID->ClassImplementsProtocol(I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00007263 return false;
7264 }
7265 }
7266 // If there are no qualifiers and no interface, we have an 'id'.
7267 return true;
7268 }
Mike Stump11289f42009-09-09 15:08:12 +00007269 // Both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00007270 for (auto *lhsProto : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007271 bool match = false;
7272
7273 // when comparing an id<P> on lhs with a static type on rhs,
7274 // see if static class implements all of id's protocols, directly or
7275 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00007276 for (auto *rhsProto : rhsOPT->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007277 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
7278 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
7279 match = true;
7280 break;
7281 }
7282 }
Mike Stump11289f42009-09-09 15:08:12 +00007283 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00007284 // make sure we check the class hierarchy.
7285 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
Aaron Ballman83731462014-03-17 16:14:00 +00007286 for (auto *I : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007287 // when comparing an id<P> on lhs with a static type on rhs,
7288 // see if static class implements all of id's protocols, directly or
7289 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00007290 if (rhsID->ClassImplementsProtocol(I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007291 match = true;
7292 break;
7293 }
7294 }
7295 }
7296 if (!match)
7297 return false;
7298 }
Mike Stump11289f42009-09-09 15:08:12 +00007299
Steve Naroff8e6aee52009-07-23 01:01:38 +00007300 return true;
7301 }
Mike Stump11289f42009-09-09 15:08:12 +00007302
Steve Naroff8e6aee52009-07-23 01:01:38 +00007303 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
7304 assert(rhsQID && "One of the LHS/RHS should be id<x>");
7305
Mike Stump11289f42009-09-09 15:08:12 +00007306 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00007307 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007308 // If both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00007309 for (auto *lhsProto : lhsOPT->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007310 bool match = false;
7311
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007312 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00007313 // see if static class implements all of id's protocols, directly or
7314 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007315 // First, lhs protocols in the qualifier list must be found, direct
7316 // or indirect in rhs's qualifier list or it is a mismatch.
Aaron Ballman83731462014-03-17 16:14:00 +00007317 for (auto *rhsProto : rhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007318 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
7319 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
7320 match = true;
7321 break;
7322 }
7323 }
7324 if (!match)
7325 return false;
7326 }
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007327
7328 // Static class's protocols, or its super class or category protocols
7329 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
7330 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
7331 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
7332 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
7333 // This is rather dubious but matches gcc's behavior. If lhs has
7334 // no type qualifier and its class has no static protocol(s)
7335 // assume that it is mismatch.
7336 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
7337 return false;
Aaron Ballman83731462014-03-17 16:14:00 +00007338 for (auto *lhsProto : LHSInheritedProtocols) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007339 bool match = false;
Aaron Ballman83731462014-03-17 16:14:00 +00007340 for (auto *rhsProto : rhsQID->quals()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007341 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
7342 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
7343 match = true;
7344 break;
7345 }
7346 }
7347 if (!match)
7348 return false;
7349 }
7350 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00007351 return true;
7352 }
7353 return false;
7354}
7355
Eli Friedman47f77112008-08-22 00:56:42 +00007356/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00007357/// compatible for assignment from RHS to LHS. This handles validation of any
7358/// protocol qualifiers on the LHS or RHS.
7359///
Steve Naroff7cae42b2009-07-10 23:34:53 +00007360bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
7361 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00007362 const ObjCObjectType* LHS = LHSOPT->getObjectType();
7363 const ObjCObjectType* RHS = RHSOPT->getObjectType();
7364
Steve Naroff1329fa02009-07-15 18:40:39 +00007365 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00007366 if (LHS->isObjCUnqualifiedIdOrClass() ||
7367 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00007368 return true;
7369
Douglas Gregorab209d82015-07-07 03:58:42 +00007370 // Function object that propagates a successful result or handles
7371 // __kindof types.
7372 auto finish = [&](bool succeeded) -> bool {
7373 if (succeeded)
7374 return true;
7375
7376 if (!RHS->isKindOfType())
7377 return false;
7378
7379 // Strip off __kindof and protocol qualifiers, then check whether
7380 // we can assign the other way.
7381 return canAssignObjCInterfaces(RHSOPT->stripObjCKindOfTypeAndQuals(*this),
7382 LHSOPT->stripObjCKindOfTypeAndQuals(*this));
7383 };
7384
7385 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) {
7386 return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
7387 QualType(RHSOPT,0),
7388 false));
7389 }
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00007390
Douglas Gregorab209d82015-07-07 03:58:42 +00007391 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) {
7392 return finish(ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
7393 QualType(RHSOPT,0)));
7394 }
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00007395
John McCall8b07ec22010-05-15 11:32:37 +00007396 // If we have 2 user-defined types, fall into that path.
Douglas Gregorab209d82015-07-07 03:58:42 +00007397 if (LHS->getInterface() && RHS->getInterface()) {
7398 return finish(canAssignObjCInterfaces(LHS, RHS));
7399 }
Mike Stump11289f42009-09-09 15:08:12 +00007400
Steve Naroff8e6aee52009-07-23 01:01:38 +00007401 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00007402}
7403
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007404/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattner57540c52011-04-15 05:22:18 +00007405/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007406/// arguments in block literals. When passed as arguments, passing 'A*' where
7407/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
7408/// not OK. For the return type, the opposite is not OK.
7409bool ASTContext::canAssignObjCInterfacesInBlockPointer(
7410 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007411 const ObjCObjectPointerType *RHSOPT,
7412 bool BlockReturnType) {
Douglas Gregorab209d82015-07-07 03:58:42 +00007413
7414 // Function object that propagates a successful result or handles
7415 // __kindof types.
7416 auto finish = [&](bool succeeded) -> bool {
7417 if (succeeded)
7418 return true;
7419
7420 const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT;
7421 if (!Expected->isKindOfType())
7422 return false;
7423
7424 // Strip off __kindof and protocol qualifiers, then check whether
7425 // we can assign the other way.
7426 return canAssignObjCInterfacesInBlockPointer(
7427 RHSOPT->stripObjCKindOfTypeAndQuals(*this),
7428 LHSOPT->stripObjCKindOfTypeAndQuals(*this),
7429 BlockReturnType);
7430 };
7431
Fariborz Jahanian440a6832010-04-06 17:23:39 +00007432 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007433 return true;
7434
7435 if (LHSOPT->isObjCBuiltinType()) {
Douglas Gregorab209d82015-07-07 03:58:42 +00007436 return finish(RHSOPT->isObjCBuiltinType() ||
7437 RHSOPT->isObjCQualifiedIdType());
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007438 }
7439
Fariborz Jahanian440a6832010-04-06 17:23:39 +00007440 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Douglas Gregorab209d82015-07-07 03:58:42 +00007441 return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
7442 QualType(RHSOPT,0),
7443 false));
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007444
7445 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
7446 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
7447 if (LHS && RHS) { // We have 2 user-defined types.
7448 if (LHS != RHS) {
7449 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Douglas Gregorab209d82015-07-07 03:58:42 +00007450 return finish(BlockReturnType);
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007451 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Douglas Gregorab209d82015-07-07 03:58:42 +00007452 return finish(!BlockReturnType);
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007453 }
7454 else
7455 return true;
7456 }
7457 return false;
7458}
7459
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007460/// Comparison routine for Objective-C protocols to be used with
7461/// llvm::array_pod_sort.
7462static int compareObjCProtocolsByName(ObjCProtocolDecl * const *lhs,
7463 ObjCProtocolDecl * const *rhs) {
7464 return (*lhs)->getName().compare((*rhs)->getName());
7465
7466}
7467
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007468/// getIntersectionOfProtocols - This routine finds the intersection of set
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007469/// of protocols inherited from two distinct objective-c pointer objects with
7470/// the given common base.
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007471/// It is used to build composite qualifier list of the composite type of
7472/// the conditional expression involving two objective-c pointer objects.
7473static
7474void getIntersectionOfProtocols(ASTContext &Context,
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007475 const ObjCInterfaceDecl *CommonBase,
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007476 const ObjCObjectPointerType *LHSOPT,
7477 const ObjCObjectPointerType *RHSOPT,
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007478 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007479
John McCall8b07ec22010-05-15 11:32:37 +00007480 const ObjCObjectType* LHS = LHSOPT->getObjectType();
7481 const ObjCObjectType* RHS = RHSOPT->getObjectType();
7482 assert(LHS->getInterface() && "LHS must have an interface base");
7483 assert(RHS->getInterface() && "RHS must have an interface base");
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007484
7485 // Add all of the protocols for the LHS.
7486 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSProtocolSet;
7487
7488 // Start with the protocol qualifiers.
7489 for (auto proto : LHS->quals()) {
7490 Context.CollectInheritedProtocols(proto, LHSProtocolSet);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007491 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007492
7493 // Also add the protocols associated with the LHS interface.
7494 Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet);
7495
7496 // Add all of the protocls for the RHS.
7497 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSProtocolSet;
7498
7499 // Start with the protocol qualifiers.
7500 for (auto proto : RHS->quals()) {
7501 Context.CollectInheritedProtocols(proto, RHSProtocolSet);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007502 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007503
7504 // Also add the protocols associated with the RHS interface.
7505 Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet);
7506
7507 // Compute the intersection of the collected protocol sets.
7508 for (auto proto : LHSProtocolSet) {
7509 if (RHSProtocolSet.count(proto))
7510 IntersectionSet.push_back(proto);
7511 }
7512
7513 // Compute the set of protocols that is implied by either the common type or
7514 // the protocols within the intersection.
7515 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ImpliedProtocols;
7516 Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols);
7517
7518 // Remove any implied protocols from the list of inherited protocols.
7519 if (!ImpliedProtocols.empty()) {
7520 IntersectionSet.erase(
7521 std::remove_if(IntersectionSet.begin(),
7522 IntersectionSet.end(),
7523 [&](ObjCProtocolDecl *proto) -> bool {
7524 return ImpliedProtocols.count(proto) > 0;
7525 }),
7526 IntersectionSet.end());
7527 }
7528
7529 // Sort the remaining protocols by name.
7530 llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(),
7531 compareObjCProtocolsByName);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007532}
7533
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007534/// Determine whether the first type is a subtype of the second.
7535static bool canAssignObjCObjectTypes(ASTContext &ctx, QualType lhs,
7536 QualType rhs) {
7537 // Common case: two object pointers.
7538 const ObjCObjectPointerType *lhsOPT = lhs->getAs<ObjCObjectPointerType>();
7539 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
7540 if (lhsOPT && rhsOPT)
7541 return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT);
7542
7543 // Two block pointers.
7544 const BlockPointerType *lhsBlock = lhs->getAs<BlockPointerType>();
7545 const BlockPointerType *rhsBlock = rhs->getAs<BlockPointerType>();
7546 if (lhsBlock && rhsBlock)
7547 return ctx.typesAreBlockPointerCompatible(lhs, rhs);
7548
7549 // If either is an unqualified 'id' and the other is a block, it's
7550 // acceptable.
7551 if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) ||
7552 (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock))
7553 return true;
7554
7555 return false;
7556}
7557
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007558// Check that the given Objective-C type argument lists are equivalent.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007559static bool sameObjCTypeArgs(ASTContext &ctx,
7560 const ObjCInterfaceDecl *iface,
7561 ArrayRef<QualType> lhsArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00007562 ArrayRef<QualType> rhsArgs,
7563 bool stripKindOf) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007564 if (lhsArgs.size() != rhsArgs.size())
7565 return false;
7566
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007567 ObjCTypeParamList *typeParams = iface->getTypeParamList();
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007568 for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) {
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007569 if (ctx.hasSameType(lhsArgs[i], rhsArgs[i]))
7570 continue;
7571
7572 switch (typeParams->begin()[i]->getVariance()) {
7573 case ObjCTypeParamVariance::Invariant:
Douglas Gregorab209d82015-07-07 03:58:42 +00007574 if (!stripKindOf ||
7575 !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx),
7576 rhsArgs[i].stripObjCKindOfType(ctx))) {
7577 return false;
7578 }
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007579 break;
7580
7581 case ObjCTypeParamVariance::Covariant:
7582 if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i]))
7583 return false;
7584 break;
7585
7586 case ObjCTypeParamVariance::Contravariant:
7587 if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i]))
7588 return false;
7589 break;
Douglas Gregorab209d82015-07-07 03:58:42 +00007590 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007591 }
7592
7593 return true;
7594}
7595
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00007596QualType ASTContext::areCommonBaseCompatible(
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007597 const ObjCObjectPointerType *Lptr,
7598 const ObjCObjectPointerType *Rptr) {
John McCall8b07ec22010-05-15 11:32:37 +00007599 const ObjCObjectType *LHS = Lptr->getObjectType();
7600 const ObjCObjectType *RHS = Rptr->getObjectType();
7601 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
7602 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007603
7604 if (!LDecl || !RDecl)
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00007605 return QualType();
Douglas Gregore83b9562015-07-07 03:57:53 +00007606
Manman Renc46f7d12016-05-06 19:35:02 +00007607 // When either LHS or RHS is a kindof type, we should return a kindof type.
7608 // For example, for common base of kindof(ASub1) and kindof(ASub2), we return
7609 // kindof(A).
7610 bool anyKindOf = LHS->isKindOfType() || RHS->isKindOfType();
7611
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007612 // Follow the left-hand side up the class hierarchy until we either hit a
7613 // root or find the RHS. Record the ancestors in case we don't find it.
7614 llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4>
7615 LHSAncestors;
7616 while (true) {
7617 // Record this ancestor. We'll need this if the common type isn't in the
7618 // path from the LHS to the root.
7619 LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS;
Douglas Gregore83b9562015-07-07 03:57:53 +00007620
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007621 if (declaresSameEntity(LHS->getInterface(), RDecl)) {
7622 // Get the type arguments.
7623 ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten();
7624 bool anyChanges = false;
7625 if (LHS->isSpecialized() && RHS->isSpecialized()) {
7626 // Both have type arguments, compare them.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007627 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
7628 LHS->getTypeArgs(), RHS->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00007629 /*stripKindOf=*/true))
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007630 return QualType();
7631 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
7632 // If only one has type arguments, the result will not have type
7633 // arguments.
7634 LHSTypeArgs = { };
7635 anyChanges = true;
7636 }
7637
7638 // Compute the intersection of protocols.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007639 SmallVector<ObjCProtocolDecl *, 8> Protocols;
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007640 getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr,
7641 Protocols);
John McCall8b07ec22010-05-15 11:32:37 +00007642 if (!Protocols.empty())
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007643 anyChanges = true;
7644
7645 // If anything in the LHS will have changed, build a new result type.
Manman Renc46f7d12016-05-06 19:35:02 +00007646 // If we need to return a kindof type but LHS is not a kindof type, we
7647 // build a new result type.
7648 if (anyChanges || LHS->isKindOfType() != anyKindOf) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007649 QualType Result = getObjCInterfaceType(LHS->getInterface());
Douglas Gregorab209d82015-07-07 03:58:42 +00007650 Result = getObjCObjectType(Result, LHSTypeArgs, Protocols,
Manman Renc46f7d12016-05-06 19:35:02 +00007651 anyKindOf || LHS->isKindOfType());
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007652 return getObjCObjectPointerType(Result);
7653 }
7654
7655 return getObjCObjectPointerType(QualType(LHS, 0));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007656 }
Douglas Gregore83b9562015-07-07 03:57:53 +00007657
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007658 // Find the superclass.
Douglas Gregore83b9562015-07-07 03:57:53 +00007659 QualType LHSSuperType = LHS->getSuperClassType();
7660 if (LHSSuperType.isNull())
7661 break;
7662
7663 LHS = LHSSuperType->castAs<ObjCObjectType>();
7664 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007665
7666 // We didn't find anything by following the LHS to its root; now check
7667 // the RHS against the cached set of ancestors.
7668 while (true) {
7669 auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl());
7670 if (KnownLHS != LHSAncestors.end()) {
7671 LHS = KnownLHS->second;
7672
7673 // Get the type arguments.
7674 ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten();
7675 bool anyChanges = false;
7676 if (LHS->isSpecialized() && RHS->isSpecialized()) {
7677 // Both have type arguments, compare them.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007678 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
7679 LHS->getTypeArgs(), RHS->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00007680 /*stripKindOf=*/true))
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007681 return QualType();
7682 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
7683 // If only one has type arguments, the result will not have type
7684 // arguments.
7685 RHSTypeArgs = { };
7686 anyChanges = true;
7687 }
7688
7689 // Compute the intersection of protocols.
7690 SmallVector<ObjCProtocolDecl *, 8> Protocols;
7691 getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr,
7692 Protocols);
7693 if (!Protocols.empty())
7694 anyChanges = true;
7695
Manman Renc46f7d12016-05-06 19:35:02 +00007696 // If we need to return a kindof type but RHS is not a kindof type, we
7697 // build a new result type.
7698 if (anyChanges || RHS->isKindOfType() != anyKindOf) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007699 QualType Result = getObjCInterfaceType(RHS->getInterface());
Douglas Gregorab209d82015-07-07 03:58:42 +00007700 Result = getObjCObjectType(Result, RHSTypeArgs, Protocols,
Manman Renc46f7d12016-05-06 19:35:02 +00007701 anyKindOf || RHS->isKindOfType());
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007702 return getObjCObjectPointerType(Result);
7703 }
7704
7705 return getObjCObjectPointerType(QualType(RHS, 0));
7706 }
7707
7708 // Find the superclass of the RHS.
7709 QualType RHSSuperType = RHS->getSuperClassType();
7710 if (RHSSuperType.isNull())
7711 break;
7712
7713 RHS = RHSSuperType->castAs<ObjCObjectType>();
7714 }
7715
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00007716 return QualType();
7717}
7718
John McCall8b07ec22010-05-15 11:32:37 +00007719bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
7720 const ObjCObjectType *RHS) {
7721 assert(LHS->getInterface() && "LHS is not an interface type");
7722 assert(RHS->getInterface() && "RHS is not an interface type");
7723
Chris Lattner49af6a42008-04-07 06:51:04 +00007724 // Verify that the base decls are compatible: the RHS must be a subclass of
7725 // the LHS.
Douglas Gregore83b9562015-07-07 03:57:53 +00007726 ObjCInterfaceDecl *LHSInterface = LHS->getInterface();
7727 bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface());
7728 if (!IsSuperClass)
Chris Lattner49af6a42008-04-07 06:51:04 +00007729 return false;
Mike Stump11289f42009-09-09 15:08:12 +00007730
Douglas Gregore83b9562015-07-07 03:57:53 +00007731 // If the LHS has protocol qualifiers, determine whether all of them are
7732 // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the
7733 // LHS).
7734 if (LHS->getNumProtocols() > 0) {
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00007735 // OK if conversion of LHS to SuperClass results in narrowing of types
7736 // ; i.e., SuperClass may implement at least one of the protocols
7737 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
7738 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
7739 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
7740 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
7741 // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
7742 // qualifiers.
7743 for (auto *RHSPI : RHS->quals())
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007744 CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols);
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00007745 // If there is no protocols associated with RHS, it is not a match.
7746 if (SuperClassInheritedProtocols.empty())
Steve Naroff114aecb2009-03-01 16:12:44 +00007747 return false;
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00007748
7749 for (const auto *LHSProto : LHS->quals()) {
7750 bool SuperImplementsProtocol = false;
7751 for (auto *SuperClassProto : SuperClassInheritedProtocols)
7752 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
7753 SuperImplementsProtocol = true;
7754 break;
7755 }
7756 if (!SuperImplementsProtocol)
7757 return false;
7758 }
Chris Lattner49af6a42008-04-07 06:51:04 +00007759 }
Douglas Gregore83b9562015-07-07 03:57:53 +00007760
7761 // If the LHS is specialized, we may need to check type arguments.
7762 if (LHS->isSpecialized()) {
7763 // Follow the superclass chain until we've matched the LHS class in the
7764 // hierarchy. This substitutes type arguments through.
7765 const ObjCObjectType *RHSSuper = RHS;
7766 while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface))
7767 RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>();
7768
7769 // If the RHS is specializd, compare type arguments.
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007770 if (RHSSuper->isSpecialized() &&
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007771 !sameObjCTypeArgs(*this, LHS->getInterface(),
7772 LHS->getTypeArgs(), RHSSuper->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00007773 /*stripKindOf=*/true)) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007774 return false;
Douglas Gregore83b9562015-07-07 03:57:53 +00007775 }
7776 }
7777
7778 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00007779}
7780
Steve Naroffb7605152009-02-12 17:52:19 +00007781bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
7782 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00007783 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
7784 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00007785
Steve Naroff7cae42b2009-07-10 23:34:53 +00007786 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00007787 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00007788
7789 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
7790 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00007791}
7792
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00007793bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
7794 return canAssignObjCInterfaces(
7795 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
7796 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
7797}
7798
Mike Stump11289f42009-09-09 15:08:12 +00007799/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00007800/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00007801/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00007802/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007803bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
7804 bool CompareUnqualified) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00007805 if (getLangOpts().CPlusPlus)
Douglas Gregor21e771e2010-02-03 21:02:30 +00007806 return hasSameType(LHS, RHS);
Joey Gouly5788b782016-11-18 14:10:54 +00007807
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007808 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00007809}
7810
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00007811bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanianc87c8792011-07-12 23:20:13 +00007812 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00007813}
7814
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007815bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
7816 return !mergeTypes(LHS, RHS, true).isNull();
7817}
7818
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00007819/// mergeTransparentUnionType - if T is a transparent union type and a member
7820/// of T is compatible with SubType, return the merged type, else return
7821/// QualType()
7822QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
7823 bool OfBlockPointer,
7824 bool Unqualified) {
7825 if (const RecordType *UT = T->getAsUnionType()) {
7826 RecordDecl *UD = UT->getDecl();
7827 if (UD->hasAttr<TransparentUnionAttr>()) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007828 for (const auto *I : UD->fields()) {
7829 QualType ET = I->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00007830 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
7831 if (!MT.isNull())
7832 return MT;
7833 }
7834 }
7835 }
7836
7837 return QualType();
7838}
7839
Alp Toker9cacbab2014-01-20 20:26:09 +00007840/// mergeFunctionParameterTypes - merge two types which appear as function
7841/// parameter types
7842QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs,
7843 bool OfBlockPointer,
7844 bool Unqualified) {
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00007845 // GNU extension: two types are compatible if they appear as a function
7846 // argument, one of the types is a transparent union type and the other
7847 // type is compatible with a union member
7848 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
7849 Unqualified);
7850 if (!lmerge.isNull())
7851 return lmerge;
7852
7853 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
7854 Unqualified);
7855 if (!rmerge.isNull())
7856 return rmerge;
7857
7858 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
7859}
7860
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007861QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007862 bool OfBlockPointer,
7863 bool Unqualified) {
John McCall9dd450b2009-09-21 23:43:11 +00007864 const FunctionType *lbase = lhs->getAs<FunctionType>();
7865 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007866 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
7867 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00007868 bool allLTypes = true;
7869 bool allRTypes = true;
7870
7871 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007872 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00007873 if (OfBlockPointer) {
Alp Toker314cc812014-01-25 16:55:45 +00007874 QualType RHS = rbase->getReturnType();
7875 QualType LHS = lbase->getReturnType();
Fariborz Jahanian17825972011-02-11 18:46:17 +00007876 bool UnqualifiedResult = Unqualified;
7877 if (!UnqualifiedResult)
7878 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007879 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahanian17825972011-02-11 18:46:17 +00007880 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007881 else
Alp Toker314cc812014-01-25 16:55:45 +00007882 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
John McCall8c6b56f2010-12-15 01:06:38 +00007883 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007884 if (retType.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007885
7886 if (Unqualified)
7887 retType = retType.getUnqualifiedType();
7888
Alp Toker314cc812014-01-25 16:55:45 +00007889 CanQualType LRetType = getCanonicalType(lbase->getReturnType());
7890 CanQualType RRetType = getCanonicalType(rbase->getReturnType());
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007891 if (Unqualified) {
7892 LRetType = LRetType.getUnqualifiedType();
7893 RRetType = RRetType.getUnqualifiedType();
7894 }
7895
7896 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00007897 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007898 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00007899 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00007900
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00007901 // FIXME: double check this
7902 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
7903 // rbase->getRegParmAttr() != 0 &&
7904 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00007905 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
7906 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00007907
Douglas Gregor8c940862010-01-18 17:14:39 +00007908 // Compatible functions must have compatible calling conventions
Reid Kleckner78af0702013-08-27 23:08:25 +00007909 if (lbaseInfo.getCC() != rbaseInfo.getCC())
Douglas Gregor8c940862010-01-18 17:14:39 +00007910 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00007911
John McCall8c6b56f2010-12-15 01:06:38 +00007912 // Regparm is part of the calling convention.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00007913 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
7914 return QualType();
John McCall8c6b56f2010-12-15 01:06:38 +00007915 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
7916 return QualType();
7917
John McCall31168b02011-06-15 23:02:42 +00007918 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
7919 return QualType();
7920
John McCall8c6b56f2010-12-15 01:06:38 +00007921 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
7922 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8c6b56f2010-12-15 01:06:38 +00007923
Rafael Espindola8778c282012-11-29 16:09:03 +00007924 if (lbaseInfo.getNoReturn() != NoReturn)
7925 allLTypes = false;
7926 if (rbaseInfo.getNoReturn() != NoReturn)
7927 allRTypes = false;
7928
John McCall31168b02011-06-15 23:02:42 +00007929 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00007930
Eli Friedman47f77112008-08-22 00:56:42 +00007931 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00007932 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
7933 "C++ shouldn't be here");
Alp Toker601b22c2014-01-21 23:35:24 +00007934 // Compatible functions must have the same number of parameters
7935 if (lproto->getNumParams() != rproto->getNumParams())
Eli Friedman47f77112008-08-22 00:56:42 +00007936 return QualType();
7937
7938 // Variadic and non-variadic functions aren't compatible
7939 if (lproto->isVariadic() != rproto->isVariadic())
7940 return QualType();
7941
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00007942 if (lproto->getTypeQuals() != rproto->getTypeQuals())
7943 return QualType();
7944
John McCall18afab72016-03-01 00:49:02 +00007945 if (!doFunctionTypesMatchOnExtParameterInfos(rproto, lproto))
Fariborz Jahanian97676972011-09-28 21:52:05 +00007946 return QualType();
Alp Toker601b22c2014-01-21 23:35:24 +00007947
7948 // Check parameter type compatibility
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007949 SmallVector<QualType, 10> types;
Alp Toker601b22c2014-01-21 23:35:24 +00007950 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
7951 QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
7952 QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
7953 QualType paramType = mergeFunctionParameterTypes(
7954 lParamType, rParamType, OfBlockPointer, Unqualified);
7955 if (paramType.isNull())
7956 return QualType();
7957
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007958 if (Unqualified)
Alp Toker601b22c2014-01-21 23:35:24 +00007959 paramType = paramType.getUnqualifiedType();
7960
7961 types.push_back(paramType);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007962 if (Unqualified) {
Alp Toker601b22c2014-01-21 23:35:24 +00007963 lParamType = lParamType.getUnqualifiedType();
7964 rParamType = rParamType.getUnqualifiedType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007965 }
Alp Toker601b22c2014-01-21 23:35:24 +00007966
7967 if (getCanonicalType(paramType) != getCanonicalType(lParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00007968 allLTypes = false;
Alp Toker601b22c2014-01-21 23:35:24 +00007969 if (getCanonicalType(paramType) != getCanonicalType(rParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00007970 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00007971 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00007972
Eli Friedman47f77112008-08-22 00:56:42 +00007973 if (allLTypes) return lhs;
7974 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00007975
7976 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
7977 EPI.ExtInfo = einfo;
Jordan Rose5c382722013-03-08 21:51:21 +00007978 return getFunctionType(retType, types, EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00007979 }
7980
7981 if (lproto) allRTypes = false;
7982 if (rproto) allLTypes = false;
7983
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007984 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00007985 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00007986 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00007987 if (proto->isVariadic()) return QualType();
7988 // Check that the types are compatible with the types that
7989 // would result from default argument promotions (C99 6.7.5.3p15).
7990 // The only types actually affected are promotable integer
7991 // types and floats, which would be passed as a different
7992 // type depending on whether the prototype is visible.
Alp Toker601b22c2014-01-21 23:35:24 +00007993 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
7994 QualType paramTy = proto->getParamType(i);
Alp Toker9cacbab2014-01-20 20:26:09 +00007995
Eli Friedman448ce402012-08-30 00:44:15 +00007996 // Look at the converted type of enum types, since that is the type used
Douglas Gregor2973d402010-02-03 19:27:29 +00007997 // to pass enum values.
Alp Toker601b22c2014-01-21 23:35:24 +00007998 if (const EnumType *Enum = paramTy->getAs<EnumType>()) {
7999 paramTy = Enum->getDecl()->getIntegerType();
8000 if (paramTy.isNull())
Eli Friedman448ce402012-08-30 00:44:15 +00008001 return QualType();
8002 }
Alp Toker601b22c2014-01-21 23:35:24 +00008003
8004 if (paramTy->isPromotableIntegerType() ||
8005 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
Eli Friedman47f77112008-08-22 00:56:42 +00008006 return QualType();
8007 }
8008
8009 if (allLTypes) return lhs;
8010 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00008011
8012 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
8013 EPI.ExtInfo = einfo;
Alp Toker9cacbab2014-01-20 20:26:09 +00008014 return getFunctionType(retType, proto->getParamTypes(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00008015 }
8016
8017 if (allLTypes) return lhs;
8018 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00008019 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00008020}
8021
John McCall433c2e62013-03-21 00:10:07 +00008022/// Given that we have an enum type and a non-enum type, try to merge them.
8023static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
8024 QualType other, bool isBlockReturnType) {
8025 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
8026 // a signed integer type, or an unsigned integer type.
8027 // Compatibility is based on the underlying type, not the promotion
8028 // type.
8029 QualType underlyingType = ET->getDecl()->getIntegerType();
8030 if (underlyingType.isNull()) return QualType();
8031 if (Context.hasSameType(underlyingType, other))
8032 return other;
8033
8034 // In block return types, we're more permissive and accept any
8035 // integral type of the same size.
8036 if (isBlockReturnType && other->isIntegerType() &&
8037 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
8038 return other;
8039
8040 return QualType();
8041}
8042
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008043QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008044 bool OfBlockPointer,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00008045 bool Unqualified, bool BlockReturnType) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00008046 // C++ [expr]: If an expression initially has the type "reference to T", the
8047 // type is adjusted to "T" prior to any further analysis, the expression
8048 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00008049 // expression is an lvalue unless the reference is an rvalue reference and
8050 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00008051 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
8052 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008053
8054 if (Unqualified) {
8055 LHS = LHS.getUnqualifiedType();
8056 RHS = RHS.getUnqualifiedType();
8057 }
Douglas Gregor21e771e2010-02-03 21:02:30 +00008058
Eli Friedman47f77112008-08-22 00:56:42 +00008059 QualType LHSCan = getCanonicalType(LHS),
8060 RHSCan = getCanonicalType(RHS);
8061
8062 // If two types are identical, they are compatible.
8063 if (LHSCan == RHSCan)
8064 return LHS;
8065
John McCall8ccfcb52009-09-24 19:53:00 +00008066 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00008067 Qualifiers LQuals = LHSCan.getLocalQualifiers();
8068 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00008069 if (LQuals != RQuals) {
Yaxun Liua1a87ad2016-04-12 19:43:36 +00008070 if (getLangOpts().OpenCL) {
Yaxun Liuab933942016-04-28 17:34:57 +00008071 if (LHSCan.getUnqualifiedType() != RHSCan.getUnqualifiedType() ||
Yaxun Liua1a87ad2016-04-12 19:43:36 +00008072 LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers())
8073 return QualType();
8074 if (LQuals.isAddressSpaceSupersetOf(RQuals))
8075 return LHS;
8076 if (RQuals.isAddressSpaceSupersetOf(LQuals))
8077 return RHS;
8078 }
John McCall8ccfcb52009-09-24 19:53:00 +00008079 // If any of these qualifiers are different, we have a type
8080 // mismatch.
8081 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCall31168b02011-06-15 23:02:42 +00008082 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
8083 LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
John McCall8ccfcb52009-09-24 19:53:00 +00008084 return QualType();
8085
8086 // Exactly one GC qualifier difference is allowed: __strong is
8087 // okay if the other type has no GC qualifier but is an Objective
8088 // C object pointer (i.e. implicitly strong by default). We fix
8089 // this by pretending that the unqualified type was actually
8090 // qualified __strong.
8091 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
8092 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
8093 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
8094
8095 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
8096 return QualType();
8097
8098 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
8099 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
8100 }
8101 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
8102 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
8103 }
Eli Friedman47f77112008-08-22 00:56:42 +00008104 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00008105 }
8106
8107 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00008108
Eli Friedmandcca6332009-06-01 01:22:52 +00008109 Type::TypeClass LHSClass = LHSCan->getTypeClass();
8110 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00008111
Chris Lattnerfd652912008-01-14 05:45:46 +00008112 // We want to consider the two function types to be the same for these
8113 // comparisons, just force one to the other.
8114 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
8115 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00008116
8117 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00008118 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
8119 LHSClass = Type::ConstantArray;
8120 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
8121 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00008122
John McCall8b07ec22010-05-15 11:32:37 +00008123 // ObjCInterfaces are just specialized ObjCObjects.
8124 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
8125 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
8126
Nate Begemance4d7fc2008-04-18 23:10:10 +00008127 // Canonicalize ExtVector -> Vector.
8128 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
8129 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00008130
Chris Lattner95554662008-04-07 05:43:21 +00008131 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00008132 if (LHSClass != RHSClass) {
John McCall433c2e62013-03-21 00:10:07 +00008133 // Note that we only have special rules for turning block enum
8134 // returns into block int returns, not vice-versa.
John McCall9dd450b2009-09-21 23:43:11 +00008135 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00008136 return mergeEnumWithInteger(*this, ETy, RHS, false);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00008137 }
John McCall9dd450b2009-09-21 23:43:11 +00008138 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00008139 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00008140 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00008141 // allow block pointer type to match an 'id' type.
Fariborz Jahanian194904e2012-01-26 17:08:50 +00008142 if (OfBlockPointer && !BlockReturnType) {
8143 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
8144 return LHS;
8145 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
8146 return RHS;
8147 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00008148
Eli Friedman47f77112008-08-22 00:56:42 +00008149 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00008150 }
Eli Friedman47f77112008-08-22 00:56:42 +00008151
Steve Naroffc6edcbd2008-01-09 22:43:08 +00008152 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00008153 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008154#define TYPE(Class, Base)
8155#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00008156#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008157#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
8158#define DEPENDENT_TYPE(Class, Base) case Type::Class:
8159#include "clang/AST/TypeNodes.def"
David Blaikie83d382b2011-09-23 05:06:16 +00008160 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008161
Richard Smith27d807c2013-04-30 13:56:41 +00008162 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00008163 case Type::DeducedTemplateSpecialization:
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00008164 case Type::LValueReference:
8165 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008166 case Type::MemberPointer:
David Blaikie83d382b2011-09-23 05:06:16 +00008167 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008168
John McCall8b07ec22010-05-15 11:32:37 +00008169 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008170 case Type::IncompleteArray:
8171 case Type::VariableArray:
8172 case Type::FunctionProto:
8173 case Type::ExtVector:
David Blaikie83d382b2011-09-23 05:06:16 +00008174 llvm_unreachable("Types are eliminated above");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008175
Chris Lattnerfd652912008-01-14 05:45:46 +00008176 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00008177 {
8178 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00008179 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
8180 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008181 if (Unqualified) {
8182 LHSPointee = LHSPointee.getUnqualifiedType();
8183 RHSPointee = RHSPointee.getUnqualifiedType();
8184 }
8185 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
8186 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00008187 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00008188 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00008189 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00008190 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00008191 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00008192 return getPointerType(ResultType);
8193 }
Steve Naroff68e167d2008-12-10 17:49:55 +00008194 case Type::BlockPointer:
8195 {
8196 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00008197 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
8198 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008199 if (Unqualified) {
8200 LHSPointee = LHSPointee.getUnqualifiedType();
8201 RHSPointee = RHSPointee.getUnqualifiedType();
8202 }
8203 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
8204 Unqualified);
Steve Naroff68e167d2008-12-10 17:49:55 +00008205 if (ResultType.isNull()) return QualType();
8206 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
8207 return LHS;
8208 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
8209 return RHS;
8210 return getBlockPointerType(ResultType);
8211 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00008212 case Type::Atomic:
8213 {
8214 // Merge two pointer types, while trying to preserve typedef info
8215 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
8216 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
8217 if (Unqualified) {
8218 LHSValue = LHSValue.getUnqualifiedType();
8219 RHSValue = RHSValue.getUnqualifiedType();
8220 }
8221 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
8222 Unqualified);
8223 if (ResultType.isNull()) return QualType();
8224 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
8225 return LHS;
8226 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
8227 return RHS;
8228 return getAtomicType(ResultType);
8229 }
Chris Lattnerfd652912008-01-14 05:45:46 +00008230 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00008231 {
8232 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
8233 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
8234 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
8235 return QualType();
8236
8237 QualType LHSElem = getAsArrayType(LHS)->getElementType();
8238 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008239 if (Unqualified) {
8240 LHSElem = LHSElem.getUnqualifiedType();
8241 RHSElem = RHSElem.getUnqualifiedType();
8242 }
8243
8244 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00008245 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00008246 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
8247 return LHS;
8248 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
8249 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00008250 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
8251 ArrayType::ArraySizeModifier(), 0);
8252 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
8253 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00008254 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
8255 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00008256 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
8257 return LHS;
8258 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
8259 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00008260 if (LVAT) {
8261 // FIXME: This isn't correct! But tricky to implement because
8262 // the array's size has to be the size of LHS, but the type
8263 // has to be different.
8264 return LHS;
8265 }
8266 if (RVAT) {
8267 // FIXME: This isn't correct! But tricky to implement because
8268 // the array's size has to be the size of RHS, but the type
8269 // has to be different.
8270 return RHS;
8271 }
Eli Friedman3e62c212008-08-22 01:48:21 +00008272 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
8273 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00008274 return getIncompleteArrayType(ResultType,
8275 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00008276 }
Chris Lattnerfd652912008-01-14 05:45:46 +00008277 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008278 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008279 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008280 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00008281 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00008282 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00008283 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00008284 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00008285 case Type::Complex:
8286 // Distinct complex types are incompatible.
8287 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00008288 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00008289 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00008290 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
8291 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00008292 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00008293 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00008294 case Type::ObjCObject: {
8295 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00008296 // FIXME: This should be type compatibility, e.g. whether
8297 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00008298 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
8299 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
8300 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00008301 return LHS;
8302
Eli Friedman47f77112008-08-22 00:56:42 +00008303 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00008304 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00008305 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008306 if (OfBlockPointer) {
8307 if (canAssignObjCInterfacesInBlockPointer(
8308 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahanian90186f82011-03-14 16:07:00 +00008309 RHS->getAs<ObjCObjectPointerType>(),
8310 BlockReturnType))
David Blaikie8a40f702012-01-17 06:56:22 +00008311 return LHS;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008312 return QualType();
8313 }
John McCall9dd450b2009-09-21 23:43:11 +00008314 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
8315 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00008316 return LHS;
8317
Steve Naroffc68cfcf2008-12-10 22:14:21 +00008318 return QualType();
David Blaikie8a40f702012-01-17 06:56:22 +00008319 }
Xiuli Pan9c14e282016-01-09 12:53:17 +00008320 case Type::Pipe:
8321 {
Joey Goulye3c85de2016-12-01 11:30:49 +00008322 assert(LHS != RHS &&
8323 "Equivalent pipe types should have already been handled!");
8324 return QualType();
Xiuli Pan9c14e282016-01-09 12:53:17 +00008325 }
Steve Naroff32e44c02007-10-15 20:41:53 +00008326 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008327
David Blaikie8a40f702012-01-17 06:56:22 +00008328 llvm_unreachable("Invalid Type::Class!");
Steve Naroff32e44c02007-10-15 20:41:53 +00008329}
Ted Kremenekfc581a92007-10-31 17:10:13 +00008330
John McCall18afab72016-03-01 00:49:02 +00008331bool ASTContext::doFunctionTypesMatchOnExtParameterInfos(
8332 const FunctionProtoType *firstFnType,
8333 const FunctionProtoType *secondFnType) {
8334 // Fast path: if the first type doesn't have ext parameter infos,
8335 // we match if and only if they second type also doesn't have them.
8336 if (!firstFnType->hasExtParameterInfos())
8337 return !secondFnType->hasExtParameterInfos();
8338
8339 // Otherwise, we can only match if the second type has them.
8340 if (!secondFnType->hasExtParameterInfos())
Fariborz Jahanian97676972011-09-28 21:52:05 +00008341 return false;
John McCall18afab72016-03-01 00:49:02 +00008342
8343 auto firstEPI = firstFnType->getExtParameterInfos();
8344 auto secondEPI = secondFnType->getExtParameterInfos();
8345 assert(firstEPI.size() == secondEPI.size());
8346
8347 for (size_t i = 0, n = firstEPI.size(); i != n; ++i) {
8348 if (firstEPI[i] != secondEPI[i])
8349 return false;
8350 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00008351 return true;
8352}
8353
Chandler Carruth21c90602015-12-30 03:24:14 +00008354void ASTContext::ResetObjCLayout(const ObjCContainerDecl *CD) {
8355 ObjCLayouts[CD] = nullptr;
8356}
8357
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00008358/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
8359/// 'RHS' attributes and returns the merged version; including for function
8360/// return types.
8361QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
8362 QualType LHSCan = getCanonicalType(LHS),
8363 RHSCan = getCanonicalType(RHS);
8364 // If two types are identical, they are compatible.
8365 if (LHSCan == RHSCan)
8366 return LHS;
8367 if (RHSCan->isFunctionType()) {
8368 if (!LHSCan->isFunctionType())
8369 return QualType();
Alp Toker314cc812014-01-25 16:55:45 +00008370 QualType OldReturnType =
8371 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00008372 QualType NewReturnType =
Alp Toker314cc812014-01-25 16:55:45 +00008373 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00008374 QualType ResReturnType =
8375 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
8376 if (ResReturnType.isNull())
8377 return QualType();
8378 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
8379 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
8380 // In either case, use OldReturnType to build the new function type.
8381 const FunctionType *F = LHS->getAs<FunctionType>();
8382 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00008383 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8384 EPI.ExtInfo = getFunctionExtInfo(LHS);
Reid Kleckner896b32f2013-06-10 20:51:09 +00008385 QualType ResultType =
Alp Toker9cacbab2014-01-20 20:26:09 +00008386 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00008387 return ResultType;
8388 }
8389 }
8390 return QualType();
8391 }
8392
8393 // If the qualifiers are different, the types can still be merged.
8394 Qualifiers LQuals = LHSCan.getLocalQualifiers();
8395 Qualifiers RQuals = RHSCan.getLocalQualifiers();
8396 if (LQuals != RQuals) {
8397 // If any of these qualifiers are different, we have a type mismatch.
8398 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
8399 LQuals.getAddressSpace() != RQuals.getAddressSpace())
8400 return QualType();
8401
8402 // Exactly one GC qualifier difference is allowed: __strong is
8403 // okay if the other type has no GC qualifier but is an Objective
8404 // C object pointer (i.e. implicitly strong by default). We fix
8405 // this by pretending that the unqualified type was actually
8406 // qualified __strong.
8407 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
8408 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
8409 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
8410
8411 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
8412 return QualType();
8413
8414 if (GC_L == Qualifiers::Strong)
8415 return LHS;
8416 if (GC_R == Qualifiers::Strong)
8417 return RHS;
8418 return QualType();
8419 }
8420
8421 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
8422 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
8423 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
8424 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
8425 if (ResQT == LHSBaseQT)
8426 return LHS;
8427 if (ResQT == RHSBaseQT)
8428 return RHS;
8429 }
8430 return QualType();
8431}
8432
Chris Lattner4ba0cef2008-04-07 07:01:58 +00008433//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008434// Integer Predicates
8435//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00008436
Jay Foad39c79802011-01-12 09:06:06 +00008437unsigned ASTContext::getIntWidth(QualType T) const {
Richard Smithe9521062013-10-15 04:56:17 +00008438 if (const EnumType *ET = T->getAs<EnumType>())
Eli Friedmanee275c82009-12-10 22:29:29 +00008439 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00008440 if (T->isBooleanType())
8441 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00008442 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008443 return (unsigned)getTypeSize(T);
8444}
8445
Abramo Bagnara13640492012-09-09 10:21:24 +00008446QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00008447 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00008448
8449 // Turn <4 x signed int> -> <4 x unsigned int>
8450 if (const VectorType *VTy = T->getAs<VectorType>())
8451 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00008452 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00008453
8454 // For enums, we return the unsigned version of the base type.
8455 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008456 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00008457
8458 const BuiltinType *BTy = T->getAs<BuiltinType>();
8459 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008460 switch (BTy->getKind()) {
8461 case BuiltinType::Char_S:
8462 case BuiltinType::SChar:
8463 return UnsignedCharTy;
8464 case BuiltinType::Short:
8465 return UnsignedShortTy;
8466 case BuiltinType::Int:
8467 return UnsignedIntTy;
8468 case BuiltinType::Long:
8469 return UnsignedLongTy;
8470 case BuiltinType::LongLong:
8471 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00008472 case BuiltinType::Int128:
8473 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008474 default:
David Blaikie83d382b2011-09-23 05:06:16 +00008475 llvm_unreachable("Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008476 }
8477}
8478
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +00008479ASTMutationListener::~ASTMutationListener() { }
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00008480
Richard Smith1fa5d642013-05-11 05:45:24 +00008481void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
8482 QualType ReturnType) {}
Chris Lattnerecd79c62009-06-14 00:45:47 +00008483
8484//===----------------------------------------------------------------------===//
8485// Builtin Type Computation
8486//===----------------------------------------------------------------------===//
8487
8488/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00008489/// pointer over the consumed characters. This returns the resultant type. If
8490/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
8491/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
8492/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008493///
8494/// RequiresICE is filled in on return to indicate whether the value is required
8495/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00008496static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00008497 ASTContext::GetBuiltinTypeError &Error,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008498 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00008499 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00008500 // Modifiers.
8501 int HowLong = 0;
8502 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008503 RequiresICE = false;
Chris Lattner84733392010-10-01 07:13:18 +00008504
Chris Lattnerdc226c22010-10-01 22:42:38 +00008505 // Read the prefixed modifiers first.
Chris Lattnerecd79c62009-06-14 00:45:47 +00008506 bool Done = false;
8507 while (!Done) {
8508 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00008509 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00008510 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008511 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00008512 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008513 case 'S':
8514 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
8515 assert(!Signed && "Can't use 'S' modifier multiple times!");
8516 Signed = true;
8517 break;
8518 case 'U':
8519 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
Sean Silva2a995142015-01-16 21:44:26 +00008520 assert(!Unsigned && "Can't use 'U' modifier multiple times!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00008521 Unsigned = true;
8522 break;
8523 case 'L':
8524 assert(HowLong <= 2 && "Can't have LLLL modifier");
8525 ++HowLong;
8526 break;
Kevin Qinad64f6d2014-02-24 02:45:03 +00008527 case 'W':
8528 // This modifier represents int64 type.
8529 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
8530 switch (Context.getTargetInfo().getInt64Type()) {
8531 default:
8532 llvm_unreachable("Unexpected integer type");
8533 case TargetInfo::SignedLong:
8534 HowLong = 1;
8535 break;
8536 case TargetInfo::SignedLongLong:
8537 HowLong = 2;
8538 break;
8539 }
Chris Lattnerecd79c62009-06-14 00:45:47 +00008540 }
8541 }
8542
8543 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00008544
Chris Lattnerecd79c62009-06-14 00:45:47 +00008545 // Read the base type.
8546 switch (*Str++) {
David Blaikie83d382b2011-09-23 05:06:16 +00008547 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00008548 case 'v':
8549 assert(HowLong == 0 && !Signed && !Unsigned &&
8550 "Bad modifiers used with 'v'!");
8551 Type = Context.VoidTy;
8552 break;
Jack Carter24bef982013-08-15 15:16:57 +00008553 case 'h':
8554 assert(HowLong == 0 && !Signed && !Unsigned &&
Sean Silva2a995142015-01-16 21:44:26 +00008555 "Bad modifiers used with 'h'!");
Jack Carter24bef982013-08-15 15:16:57 +00008556 Type = Context.HalfTy;
8557 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008558 case 'f':
8559 assert(HowLong == 0 && !Signed && !Unsigned &&
8560 "Bad modifiers used with 'f'!");
8561 Type = Context.FloatTy;
8562 break;
8563 case 'd':
8564 assert(HowLong < 2 && !Signed && !Unsigned &&
8565 "Bad modifiers used with 'd'!");
8566 if (HowLong)
8567 Type = Context.LongDoubleTy;
8568 else
8569 Type = Context.DoubleTy;
8570 break;
8571 case 's':
8572 assert(HowLong == 0 && "Bad modifiers used with 's'!");
8573 if (Unsigned)
8574 Type = Context.UnsignedShortTy;
8575 else
8576 Type = Context.ShortTy;
8577 break;
8578 case 'i':
8579 if (HowLong == 3)
8580 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
8581 else if (HowLong == 2)
8582 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
8583 else if (HowLong == 1)
8584 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
8585 else
8586 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
8587 break;
8588 case 'c':
8589 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
8590 if (Signed)
8591 Type = Context.SignedCharTy;
8592 else if (Unsigned)
8593 Type = Context.UnsignedCharTy;
8594 else
8595 Type = Context.CharTy;
8596 break;
8597 case 'b': // boolean
8598 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
8599 Type = Context.BoolTy;
8600 break;
8601 case 'z': // size_t.
8602 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
8603 Type = Context.getSizeType();
8604 break;
Richard Smith8110c9d2016-11-29 19:45:17 +00008605 case 'w': // wchar_t.
8606 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'w'!");
8607 Type = Context.getWideCharType();
8608 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008609 case 'F':
8610 Type = Context.getCFConstantStringType();
8611 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00008612 case 'G':
8613 Type = Context.getObjCIdType();
8614 break;
8615 case 'H':
8616 Type = Context.getObjCSelType();
8617 break;
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00008618 case 'M':
8619 Type = Context.getObjCSuperType();
8620 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008621 case 'a':
8622 Type = Context.getBuiltinVaListType();
8623 assert(!Type.isNull() && "builtin va list type not initialized!");
8624 break;
8625 case 'A':
8626 // This is a "reference" to a va_list; however, what exactly
8627 // this means depends on how va_list is defined. There are two
8628 // different kinds of va_list: ones passed by value, and ones
8629 // passed by reference. An example of a by-value va_list is
8630 // x86, where va_list is a char*. An example of by-ref va_list
8631 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
8632 // we want this argument to be a char*&; for x86-64, we want
8633 // it to be a __va_list_tag*.
8634 Type = Context.getBuiltinVaListType();
8635 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008636 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00008637 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008638 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00008639 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008640 break;
8641 case 'V': {
8642 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008643 unsigned NumElements = strtoul(Str, &End, 10);
8644 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00008645 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00008646
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008647 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
8648 RequiresICE, false);
8649 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattnerdc226c22010-10-01 22:42:38 +00008650
8651 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00008652 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00008653 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008654 break;
8655 }
Douglas Gregorfed66992012-06-07 18:08:25 +00008656 case 'E': {
8657 char *End;
8658
8659 unsigned NumElements = strtoul(Str, &End, 10);
8660 assert(End != Str && "Missing vector size");
8661
8662 Str = End;
8663
8664 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
8665 false);
8666 Type = Context.getExtVectorType(ElementType, NumElements);
8667 break;
8668 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00008669 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008670 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
8671 false);
8672 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00008673 Type = Context.getComplexType(ElementType);
8674 break;
Fariborz Jahanian73952fc2011-08-23 23:33:09 +00008675 }
8676 case 'Y' : {
8677 Type = Context.getPointerDiffType();
8678 break;
8679 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00008680 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00008681 Type = Context.getFILEType();
8682 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00008683 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008684 return QualType();
8685 }
Mike Stump2adb4da2009-07-28 23:47:15 +00008686 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00008687 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00008688 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00008689 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00008690 else
8691 Type = Context.getjmp_bufType();
8692
Mike Stump2adb4da2009-07-28 23:47:15 +00008693 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00008694 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00008695 return QualType();
8696 }
8697 break;
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00008698 case 'K':
8699 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
8700 Type = Context.getucontext_tType();
8701
8702 if (Type.isNull()) {
8703 Error = ASTContext::GE_Missing_ucontext;
8704 return QualType();
8705 }
8706 break;
Eli Friedman4e91899e2012-11-27 02:58:24 +00008707 case 'p':
8708 Type = Context.getProcessIDType();
8709 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00008710 }
Mike Stump11289f42009-09-09 15:08:12 +00008711
Chris Lattnerdc226c22010-10-01 22:42:38 +00008712 // If there are modifiers and if we're allowed to parse them, go for it.
8713 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008714 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00008715 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00008716 default: Done = true; --Str; break;
8717 case '*':
8718 case '&': {
8719 // Both pointers and references can have their pointee types
8720 // qualified with an address space.
8721 char *End;
8722 unsigned AddrSpace = strtoul(Str, &End, 10);
8723 if (End != Str && AddrSpace != 0) {
8724 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
8725 Str = End;
8726 }
8727 if (c == '*')
8728 Type = Context.getPointerType(Type);
8729 else
8730 Type = Context.getLValueReferenceType(Type);
8731 break;
8732 }
8733 // FIXME: There's no way to have a built-in with an rvalue ref arg.
8734 case 'C':
8735 Type = Type.withConst();
8736 break;
8737 case 'D':
8738 Type = Context.getVolatileType(Type);
8739 break;
Ted Kremenekf2a2f5f2012-01-20 21:40:12 +00008740 case 'R':
8741 Type = Type.withRestrict();
8742 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008743 }
8744 }
Chris Lattner84733392010-10-01 07:13:18 +00008745
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008746 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner84733392010-10-01 07:13:18 +00008747 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00008748
Chris Lattnerecd79c62009-06-14 00:45:47 +00008749 return Type;
8750}
8751
8752/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattnerdc226c22010-10-01 22:42:38 +00008753QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008754 GetBuiltinTypeError &Error,
Jay Foad39c79802011-01-12 09:06:06 +00008755 unsigned *IntegerConstantArgs) const {
Eric Christopher02d5d862015-08-06 01:01:12 +00008756 const char *TypeStr = BuiltinInfo.getTypeString(Id);
Mike Stump11289f42009-09-09 15:08:12 +00008757
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008758 SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00008759
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008760 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008761 Error = GE_None;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008762 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
8763 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008764 if (Error != GE_None)
8765 return QualType();
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008766
8767 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
8768
Chris Lattnerecd79c62009-06-14 00:45:47 +00008769 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008770 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008771 if (Error != GE_None)
8772 return QualType();
8773
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008774 // If this argument is required to be an IntegerConstantExpression and the
8775 // caller cares, fill in the bitmask we return.
8776 if (RequiresICE && IntegerConstantArgs)
8777 *IntegerConstantArgs |= 1 << ArgTypes.size();
8778
Chris Lattnerecd79c62009-06-14 00:45:47 +00008779 // Do array -> pointer decay. The builtin should use the decayed type.
8780 if (Ty->isArrayType())
8781 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00008782
Chris Lattnerecd79c62009-06-14 00:45:47 +00008783 ArgTypes.push_back(Ty);
8784 }
8785
David Majnemerba3e5ec2015-03-13 18:26:17 +00008786 if (Id == Builtin::BI__GetExceptionInfo)
8787 return QualType();
8788
Chris Lattnerecd79c62009-06-14 00:45:47 +00008789 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
8790 "'.' should only occur at end of builtin type list!");
8791
Reid Kleckner78af0702013-08-27 23:08:25 +00008792 FunctionType::ExtInfo EI(CC_C);
John McCall991eb4b2010-12-21 00:44:39 +00008793 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
8794
8795 bool Variadic = (TypeStr[0] == '.');
8796
Richard Smith836de6b2016-12-19 23:59:34 +00008797 // We really shouldn't be making a no-proto type here.
8798 if (ArgTypes.empty() && Variadic && !getLangOpts().CPlusPlus)
John McCall991eb4b2010-12-21 00:44:39 +00008799 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00008800
John McCalldb40c7f2010-12-14 08:05:40 +00008801 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00008802 EPI.ExtInfo = EI;
8803 EPI.Variadic = Variadic;
Richard Smith391fb862016-10-18 07:13:55 +00008804 if (getLangOpts().CPlusPlus && BuiltinInfo.isNoThrow(Id))
8805 EPI.ExceptionSpec.Type =
8806 getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone;
John McCalldb40c7f2010-12-14 08:05:40 +00008807
Jordan Rose5c382722013-03-08 21:51:21 +00008808 return getFunctionType(ResType, ArgTypes, EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008809}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00008810
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008811static GVALinkage basicGVALinkageForFunction(const ASTContext &Context,
8812 const FunctionDecl *FD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00008813 if (!FD->isExternallyVisible())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008814 return GVA_Internal;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008815
Rafael Espindola3ae00052013-05-13 00:12:11 +00008816 GVALinkage External = GVA_StrongExternal;
8817 switch (FD->getTemplateSpecializationKind()) {
8818 case TSK_Undeclared:
8819 case TSK_ExplicitSpecialization:
8820 External = GVA_StrongExternal;
8821 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008822
Rafael Espindola3ae00052013-05-13 00:12:11 +00008823 case TSK_ExplicitInstantiationDefinition:
David Majnemer54e3ba52014-04-02 23:17:29 +00008824 return GVA_StrongODR;
Rafael Espindola3ae00052013-05-13 00:12:11 +00008825
David Majnemerc3d07332014-05-15 06:25:57 +00008826 // C++11 [temp.explicit]p10:
8827 // [ Note: The intent is that an inline function that is the subject of
8828 // an explicit instantiation declaration will still be implicitly
8829 // instantiated when used so that the body can be considered for
8830 // inlining, but that no out-of-line copy of the inline function would be
8831 // generated in the translation unit. -- end note ]
Rafael Espindola3ae00052013-05-13 00:12:11 +00008832 case TSK_ExplicitInstantiationDeclaration:
David Majnemer27d69db2014-04-28 22:17:59 +00008833 return GVA_AvailableExternally;
8834
Rafael Espindola3ae00052013-05-13 00:12:11 +00008835 case TSK_ImplicitInstantiation:
David Majnemer27d69db2014-04-28 22:17:59 +00008836 External = GVA_DiscardableODR;
Rafael Espindola3ae00052013-05-13 00:12:11 +00008837 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008838 }
8839
8840 if (!FD->isInlined())
8841 return External;
David Majnemer62f0ffd2013-08-01 17:26:42 +00008842
David Majnemer3f021502015-10-08 04:53:31 +00008843 if ((!Context.getLangOpts().CPlusPlus &&
8844 !Context.getTargetInfo().getCXXABI().isMicrosoft() &&
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008845 !FD->hasAttr<DLLExportAttr>()) ||
David Majnemer62f0ffd2013-08-01 17:26:42 +00008846 FD->hasAttr<GNUInlineAttr>()) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008847 // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
8848
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008849 // GNU or C99 inline semantics. Determine whether this symbol should be
8850 // externally visible.
8851 if (FD->isInlineDefinitionExternallyVisible())
8852 return External;
8853
8854 // C99 inline semantics, where the symbol is not externally visible.
David Majnemer27d69db2014-04-28 22:17:59 +00008855 return GVA_AvailableExternally;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008856 }
8857
David Majnemer54e3ba52014-04-02 23:17:29 +00008858 // Functions specified with extern and inline in -fms-compatibility mode
8859 // forcibly get emitted. While the body of the function cannot be later
8860 // replaced, the function definition cannot be discarded.
David Majnemer73768702015-03-20 00:02:27 +00008861 if (FD->isMSExternInline())
David Majnemer54e3ba52014-04-02 23:17:29 +00008862 return GVA_StrongODR;
8863
David Majnemer27d69db2014-04-28 22:17:59 +00008864 return GVA_DiscardableODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008865}
8866
Artem Belevichca2b9512016-05-02 20:30:03 +00008867static GVALinkage adjustGVALinkageForAttributes(const ASTContext &Context,
8868 GVALinkage L, const Decl *D) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008869 // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
8870 // dllexport/dllimport on inline functions.
8871 if (D->hasAttr<DLLImportAttr>()) {
8872 if (L == GVA_DiscardableODR || L == GVA_StrongODR)
8873 return GVA_AvailableExternally;
Artem Belevichca2b9512016-05-02 20:30:03 +00008874 } else if (D->hasAttr<DLLExportAttr>()) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008875 if (L == GVA_DiscardableODR)
8876 return GVA_StrongODR;
Artem Belevichca2b9512016-05-02 20:30:03 +00008877 } else if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice &&
8878 D->hasAttr<CUDAGlobalAttr>()) {
8879 // Device-side functions with __global__ attribute must always be
8880 // visible externally so they can be launched from host.
8881 if (L == GVA_DiscardableODR || L == GVA_Internal)
8882 return GVA_StrongODR;
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008883 }
8884 return L;
8885}
8886
8887GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) const {
David Blaikie9ffe5a32017-01-30 05:00:26 +00008888 auto L = adjustGVALinkageForAttributes(
Artem Belevichca2b9512016-05-02 20:30:03 +00008889 *this, basicGVALinkageForFunction(*this, FD), FD);
David Blaikie9ffe5a32017-01-30 05:00:26 +00008890 auto EK = ExternalASTSource::EK_ReplyHazy;
8891 if (auto *Ext = getExternalSource())
8892 EK = Ext->hasExternalDefinitions(FD->getOwningModuleID());
8893 switch (EK) {
8894 case ExternalASTSource::EK_Never:
8895 if (L == GVA_DiscardableODR)
8896 return GVA_StrongODR;
8897 break;
8898 case ExternalASTSource::EK_Always:
8899 return GVA_AvailableExternally;
8900 case ExternalASTSource::EK_ReplyHazy:
8901 break;
8902 }
8903 return L;
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008904}
8905
8906static GVALinkage basicGVALinkageForVariable(const ASTContext &Context,
8907 const VarDecl *VD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00008908 if (!VD->isExternallyVisible())
8909 return GVA_Internal;
8910
David Majnemer27d69db2014-04-28 22:17:59 +00008911 if (VD->isStaticLocal()) {
David Majnemer27d69db2014-04-28 22:17:59 +00008912 const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
8913 while (LexicalContext && !isa<FunctionDecl>(LexicalContext))
8914 LexicalContext = LexicalContext->getLexicalParent();
8915
David Blaikieeb210012017-01-27 23:11:10 +00008916 // ObjC Blocks can create local variables that don't have a FunctionDecl
8917 // LexicalContext.
8918 if (!LexicalContext)
8919 return GVA_DiscardableODR;
David Majnemer27d69db2014-04-28 22:17:59 +00008920
David Blaikieeb210012017-01-27 23:11:10 +00008921 // Otherwise, let the static local variable inherit its linkage from the
8922 // nearest enclosing function.
8923 auto StaticLocalLinkage =
8924 Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext));
8925
8926 // Itanium ABI 5.2.2: "Each COMDAT group [for a static local variable] must
8927 // be emitted in any object with references to the symbol for the object it
8928 // contains, whether inline or out-of-line."
8929 // Similar behavior is observed with MSVC. An alternative ABI could use
8930 // StrongODR/AvailableExternally to match the function, but none are
8931 // known/supported currently.
8932 if (StaticLocalLinkage == GVA_StrongODR ||
8933 StaticLocalLinkage == GVA_AvailableExternally)
8934 return GVA_DiscardableODR;
8935 return StaticLocalLinkage;
David Majnemer27d69db2014-04-28 22:17:59 +00008936 }
8937
Hans Wennborg56fc62b2014-07-17 20:25:23 +00008938 // MSVC treats in-class initialized static data members as definitions.
8939 // By giving them non-strong linkage, out-of-line definitions won't
8940 // cause link errors.
8941 if (Context.isMSStaticDataMemberInlineDefinition(VD))
8942 return GVA_DiscardableODR;
8943
Richard Smithd9b90092016-07-02 01:32:16 +00008944 // Most non-template variables have strong linkage; inline variables are
8945 // linkonce_odr or (occasionally, for compatibility) weak_odr.
8946 GVALinkage StrongLinkage;
8947 switch (Context.getInlineVariableDefinitionKind(VD)) {
8948 case ASTContext::InlineVariableDefinitionKind::None:
8949 StrongLinkage = GVA_StrongExternal;
8950 break;
8951 case ASTContext::InlineVariableDefinitionKind::Weak:
8952 case ASTContext::InlineVariableDefinitionKind::WeakUnknown:
Richard Smith62f19e72016-06-25 00:15:56 +00008953 StrongLinkage = GVA_DiscardableODR;
Richard Smithd9b90092016-07-02 01:32:16 +00008954 break;
8955 case ASTContext::InlineVariableDefinitionKind::Strong:
8956 StrongLinkage = GVA_StrongODR;
8957 break;
8958 }
Richard Smith62f19e72016-06-25 00:15:56 +00008959
Richard Smith8809a0c2013-09-27 20:14:12 +00008960 switch (VD->getTemplateSpecializationKind()) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00008961 case TSK_Undeclared:
Richard Smith62f19e72016-06-25 00:15:56 +00008962 return StrongLinkage;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008963
David Majnemer6d1780c2015-07-17 23:36:49 +00008964 case TSK_ExplicitSpecialization:
David Majnemer3f021502015-10-08 04:53:31 +00008965 return Context.getTargetInfo().getCXXABI().isMicrosoft() &&
8966 VD->isStaticDataMember()
David Majnemer6d1780c2015-07-17 23:36:49 +00008967 ? GVA_StrongODR
Richard Smith62f19e72016-06-25 00:15:56 +00008968 : StrongLinkage;
David Majnemer6d1780c2015-07-17 23:36:49 +00008969
Rafael Espindola3ae00052013-05-13 00:12:11 +00008970 case TSK_ExplicitInstantiationDefinition:
David Majnemer54e3ba52014-04-02 23:17:29 +00008971 return GVA_StrongODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008972
David Majnemer27d69db2014-04-28 22:17:59 +00008973 case TSK_ExplicitInstantiationDeclaration:
8974 return GVA_AvailableExternally;
8975
Rafael Espindola3ae00052013-05-13 00:12:11 +00008976 case TSK_ImplicitInstantiation:
David Majnemer27d69db2014-04-28 22:17:59 +00008977 return GVA_DiscardableODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008978 }
Rafael Espindola27699c82013-05-13 14:05:53 +00008979
8980 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008981}
8982
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008983GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
Artem Belevichca2b9512016-05-02 20:30:03 +00008984 return adjustGVALinkageForAttributes(
8985 *this, basicGVALinkageForVariable(*this, VD), VD);
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008986}
8987
David Blaikie9ffe5a32017-01-30 05:00:26 +00008988bool ASTContext::DeclMustBeEmitted(const Decl *D, bool ForModularCodegen) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008989 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
8990 if (!VD->isFileVarDecl())
8991 return false;
Renato Golin9258aa52014-05-21 10:40:27 +00008992 // Global named register variables (GNU extension) are never emitted.
8993 if (VD->getStorageClass() == SC_Register)
8994 return false;
Richard Smith7747ce22015-08-19 20:49:38 +00008995 if (VD->getDescribedVarTemplate() ||
8996 isa<VarTemplatePartialSpecializationDecl>(VD))
8997 return false;
Richard Smith5205a8c2013-04-01 20:22:16 +00008998 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
8999 // We never need to emit an uninstantiated function template.
9000 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
9001 return false;
Nico Weber66220292016-03-02 17:28:48 +00009002 } else if (isa<PragmaCommentDecl>(D))
9003 return true;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00009004 else if (isa<OMPThreadPrivateDecl>(D) ||
9005 D->hasAttr<OMPDeclareTargetDeclAttr>())
9006 return true;
Nico Webercbbaeb12016-03-02 19:28:54 +00009007 else if (isa<PragmaDetectMismatchDecl>(D))
9008 return true;
Nico Weber66220292016-03-02 17:28:48 +00009009 else if (isa<OMPThreadPrivateDecl>(D))
Alexey Bataevc5b1d322016-03-04 09:22:22 +00009010 return !D->getDeclContext()->isDependentContext();
9011 else if (isa<OMPDeclareReductionDecl>(D))
9012 return !D->getDeclContext()->isDependentContext();
Richard Smithdc1f0422016-07-20 19:10:16 +00009013 else if (isa<ImportDecl>(D))
9014 return true;
Alexey Bataev97720002014-11-11 04:05:39 +00009015 else
Richard Smith5205a8c2013-04-01 20:22:16 +00009016 return false;
9017
9018 // If this is a member of a class template, we do not need to emit it.
9019 if (D->getDeclContext()->isDependentContext())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009020 return false;
9021
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00009022 // Weak references don't produce any output by themselves.
9023 if (D->hasAttr<WeakRefAttr>())
9024 return false;
9025
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009026 // Aliases and used decls are required.
9027 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
9028 return true;
9029
9030 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
9031 // Forward declarations aren't required.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00009032 if (!FD->doesThisDeclarationHaveABody())
Nick Lewycky26da4dd2011-07-18 05:26:13 +00009033 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009034
9035 // Constructors and destructors are required.
9036 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
9037 return true;
9038
John McCall6bd2a892013-01-25 22:31:03 +00009039 // The key function for a class is required. This rule only comes
9040 // into play when inline functions can be key functions, though.
9041 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
9042 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
9043 const CXXRecordDecl *RD = MD->getParent();
9044 if (MD->isOutOfLine() && RD->isDynamicClass()) {
9045 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
9046 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
9047 return true;
9048 }
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009049 }
9050 }
9051
David Blaikie9ffe5a32017-01-30 05:00:26 +00009052 GVALinkage Linkage = GetGVALinkageForFunction(FD);
9053
9054 if (Linkage == GVA_DiscardableODR && ForModularCodegen)
9055 return true;
9056
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009057 // static, static inline, always_inline, and extern inline functions can
9058 // always be deferred. Normal inline functions can be deferred in C99/C++.
9059 // Implicit template instantiations can also be deferred in C++.
David Blaikie9ffe5a32017-01-30 05:00:26 +00009060 return !isDiscardableGVALinkage(Linkage);
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009061 }
Douglas Gregor87d81242011-09-10 00:22:34 +00009062
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009063 const VarDecl *VD = cast<VarDecl>(D);
9064 assert(VD->isFileVarDecl() && "Expected file scoped var");
9065
Hans Wennborg56fc62b2014-07-17 20:25:23 +00009066 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
9067 !isMSStaticDataMemberInlineDefinition(VD))
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00009068 return false;
9069
Richard Smitha0e5e542012-11-12 21:38:00 +00009070 // Variables that can be needed in other TUs are required.
Justin Lebar606f01f2016-10-13 20:52:17 +00009071 if (!isDiscardableGVALinkage(GetGVALinkageForVariable(VD)))
Richard Smitha0e5e542012-11-12 21:38:00 +00009072 return true;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009073
Richard Smitha0e5e542012-11-12 21:38:00 +00009074 // Variables that have destruction with side-effects are required.
9075 if (VD->getType().isDestructedType())
9076 return true;
9077
9078 // Variables that have initialization with side-effects are required.
Richard Smith7747ce22015-08-19 20:49:38 +00009079 if (VD->getInit() && VD->getInit()->HasSideEffects(*this) &&
Richard Smith187ffb42017-01-20 01:19:46 +00009080 // We can get a value-dependent initializer during error recovery.
9081 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
Richard Smitha0e5e542012-11-12 21:38:00 +00009082 return true;
9083
Richard Smithda383632016-08-15 01:33:41 +00009084 // Likewise, variables with tuple-like bindings are required if their
9085 // bindings have side-effects.
9086 if (auto *DD = dyn_cast<DecompositionDecl>(VD))
9087 for (auto *BD : DD->bindings())
9088 if (auto *BindingVD = BD->getHoldingVar())
9089 if (DeclMustBeEmitted(BindingVD))
9090 return true;
9091
Richard Smitha0e5e542012-11-12 21:38:00 +00009092 return false;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009093}
Charles Davis53c59df2010-08-16 03:33:14 +00009094
Reid Kleckner78af0702013-08-27 23:08:25 +00009095CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic,
9096 bool IsCXXMethod) const {
Charles Davis99202b32010-11-09 18:04:24 +00009097 // Pass through to the C++ ABI object
Reid Kleckner78af0702013-08-27 23:08:25 +00009098 if (IsCXXMethod)
9099 return ABI->getDefaultMethodCallConv(IsVariadic);
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +00009100
Alexey Bataeva7547182016-05-18 09:06:38 +00009101 switch (LangOpts.getDefaultCallingConv()) {
9102 case LangOptions::DCC_None:
9103 break;
9104 case LangOptions::DCC_CDecl:
9105 return CC_C;
9106 case LangOptions::DCC_FastCall:
9107 if (getTargetInfo().hasFeature("sse2"))
9108 return CC_X86FastCall;
9109 break;
9110 case LangOptions::DCC_StdCall:
9111 if (!IsVariadic)
9112 return CC_X86StdCall;
9113 break;
9114 case LangOptions::DCC_VectorCall:
9115 // __vectorcall cannot be applied to variadic functions.
9116 if (!IsVariadic)
9117 return CC_X86VectorCall;
9118 break;
9119 }
Alexander Kornienko21de0ae2015-01-20 11:20:41 +00009120 return Target->getDefaultCallingConv(TargetInfo::CCMT_Unknown);
Charles Davis99202b32010-11-09 18:04:24 +00009121}
9122
Jay Foad39c79802011-01-12 09:06:06 +00009123bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +00009124 // Pass through to the C++ ABI object
9125 return ABI->isNearlyEmpty(RD);
9126}
9127
Reid Kleckner96f8f932014-02-05 17:27:08 +00009128VTableContextBase *ASTContext::getVTableContext() {
9129 if (!VTContext.get()) {
9130 if (Target->getCXXABI().isMicrosoft())
9131 VTContext.reset(new MicrosoftVTableContext(*this));
9132 else
9133 VTContext.reset(new ItaniumVTableContext(*this));
9134 }
9135 return VTContext.get();
9136}
9137
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00009138MangleContext *ASTContext::createMangleContext() {
John McCall359b8852013-01-25 22:30:49 +00009139 switch (Target->getCXXABI().getKind()) {
Tim Northover9bb857a2013-01-31 12:13:10 +00009140 case TargetCXXABI::GenericAArch64:
John McCall359b8852013-01-25 22:30:49 +00009141 case TargetCXXABI::GenericItanium:
9142 case TargetCXXABI::GenericARM:
Zoran Jovanovic26a12162015-02-18 15:21:35 +00009143 case TargetCXXABI::GenericMIPS:
John McCall359b8852013-01-25 22:30:49 +00009144 case TargetCXXABI::iOS:
Tim Northovera2ee4332014-03-29 15:09:45 +00009145 case TargetCXXABI::iOS64:
Dan Gohmanc2853072015-09-03 22:51:53 +00009146 case TargetCXXABI::WebAssembly:
Tim Northover756447a2015-10-30 16:30:36 +00009147 case TargetCXXABI::WatchOS:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00009148 return ItaniumMangleContext::create(*this, getDiagnostics());
John McCall359b8852013-01-25 22:30:49 +00009149 case TargetCXXABI::Microsoft:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00009150 return MicrosoftMangleContext::create(*this, getDiagnostics());
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00009151 }
David Blaikie83d382b2011-09-23 05:06:16 +00009152 llvm_unreachable("Unsupported ABI");
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00009153}
9154
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +00009155CXXABI::~CXXABI() {}
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00009156
9157size_t ASTContext::getSideTableAllocatedMemory() const {
Larisse Voufo39a1e502013-08-06 01:03:05 +00009158 return ASTRecordLayouts.getMemorySize() +
9159 llvm::capacity_in_bytes(ObjCLayouts) +
9160 llvm::capacity_in_bytes(KeyFunctions) +
9161 llvm::capacity_in_bytes(ObjCImpls) +
9162 llvm::capacity_in_bytes(BlockVarCopyInits) +
9163 llvm::capacity_in_bytes(DeclAttrs) +
9164 llvm::capacity_in_bytes(TemplateOrInstantiation) +
9165 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
9166 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
9167 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
9168 llvm::capacity_in_bytes(OverriddenMethods) +
9169 llvm::capacity_in_bytes(Types) +
9170 llvm::capacity_in_bytes(VariableArrayTypes) +
9171 llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00009172}
Ted Kremenek540017e2011-10-06 05:00:56 +00009173
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00009174/// getIntTypeForBitwidth -
9175/// sets integer QualTy according to specified details:
9176/// bitwidth, signed/unsigned.
9177/// Returns empty type if there is no appropriate target types.
9178QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth,
9179 unsigned Signed) const {
9180 TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed);
9181 CanQualType QualTy = getFromTargetType(Ty);
9182 if (!QualTy && DestWidth == 128)
9183 return Signed ? Int128Ty : UnsignedInt128Ty;
9184 return QualTy;
9185}
9186
9187/// getRealTypeForBitwidth -
9188/// sets floating point QualTy according to specified bitwidth.
9189/// Returns empty type if there is no appropriate target types.
9190QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth) const {
9191 TargetInfo::RealType Ty = getTargetInfo().getRealTypeByWidth(DestWidth);
9192 switch (Ty) {
9193 case TargetInfo::Float:
9194 return FloatTy;
9195 case TargetInfo::Double:
9196 return DoubleTy;
9197 case TargetInfo::LongDouble:
9198 return LongDoubleTy;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00009199 case TargetInfo::Float128:
9200 return Float128Ty;
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00009201 case TargetInfo::NoFloat:
9202 return QualType();
9203 }
9204
9205 llvm_unreachable("Unhandled TargetInfo::RealType value");
9206}
9207
Eli Friedman3b7d46c2013-07-10 00:30:46 +00009208void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
9209 if (Number > 1)
9210 MangleNumbers[ND] = Number;
David Blaikie095deba2012-11-14 01:52:05 +00009211}
9212
Eli Friedman3b7d46c2013-07-10 00:30:46 +00009213unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const {
Richard Smithe9b02d62016-03-21 22:33:02 +00009214 auto I = MangleNumbers.find(ND);
Eli Friedman3b7d46c2013-07-10 00:30:46 +00009215 return I != MangleNumbers.end() ? I->second : 1;
David Blaikie095deba2012-11-14 01:52:05 +00009216}
9217
David Majnemer2206bf52014-03-05 08:57:59 +00009218void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
9219 if (Number > 1)
9220 StaticLocalNumbers[VD] = Number;
9221}
9222
9223unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const {
Richard Smithe9b02d62016-03-21 22:33:02 +00009224 auto I = StaticLocalNumbers.find(VD);
David Majnemer2206bf52014-03-05 08:57:59 +00009225 return I != StaticLocalNumbers.end() ? I->second : 1;
9226}
9227
Eli Friedman3b7d46c2013-07-10 00:30:46 +00009228MangleNumberingContext &
9229ASTContext::getManglingNumberContext(const DeclContext *DC) {
Reid Klecknerd8110b62013-09-10 20:14:30 +00009230 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
Justin Lebar20ebffc2016-10-10 16:26:19 +00009231 std::unique_ptr<MangleNumberingContext> &MCtx = MangleNumberingContexts[DC];
Reid Klecknerd8110b62013-09-10 20:14:30 +00009232 if (!MCtx)
9233 MCtx = createMangleNumberingContext();
9234 return *MCtx;
9235}
9236
Justin Lebar20ebffc2016-10-10 16:26:19 +00009237std::unique_ptr<MangleNumberingContext>
9238ASTContext::createMangleNumberingContext() const {
Reid Klecknerd8110b62013-09-10 20:14:30 +00009239 return ABI->createMangleNumberingContext();
Douglas Gregor63798542012-02-20 19:44:39 +00009240}
9241
David Majnemere7a818f2015-03-06 18:53:55 +00009242const CXXConstructorDecl *
9243ASTContext::getCopyConstructorForExceptionObject(CXXRecordDecl *RD) {
9244 return ABI->getCopyConstructorForExceptionObject(
9245 cast<CXXRecordDecl>(RD->getFirstDecl()));
9246}
9247
9248void ASTContext::addCopyConstructorForExceptionObject(CXXRecordDecl *RD,
9249 CXXConstructorDecl *CD) {
9250 return ABI->addCopyConstructorForExceptionObject(
9251 cast<CXXRecordDecl>(RD->getFirstDecl()),
9252 cast<CXXConstructorDecl>(CD->getFirstDecl()));
9253}
9254
David Majnemer00350522015-08-31 18:48:39 +00009255void ASTContext::addTypedefNameForUnnamedTagDecl(TagDecl *TD,
9256 TypedefNameDecl *DD) {
9257 return ABI->addTypedefNameForUnnamedTagDecl(TD, DD);
9258}
9259
9260TypedefNameDecl *
9261ASTContext::getTypedefNameForUnnamedTagDecl(const TagDecl *TD) {
9262 return ABI->getTypedefNameForUnnamedTagDecl(TD);
9263}
9264
9265void ASTContext::addDeclaratorForUnnamedTagDecl(TagDecl *TD,
9266 DeclaratorDecl *DD) {
9267 return ABI->addDeclaratorForUnnamedTagDecl(TD, DD);
9268}
9269
9270DeclaratorDecl *ASTContext::getDeclaratorForUnnamedTagDecl(const TagDecl *TD) {
9271 return ABI->getDeclaratorForUnnamedTagDecl(TD);
9272}
9273
Ted Kremenek540017e2011-10-06 05:00:56 +00009274void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
9275 ParamIndices[D] = index;
9276}
9277
9278unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
9279 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
9280 assert(I != ParamIndices.end() &&
9281 "ParmIndices lacks entry set by ParmVarDecl");
9282 return I->second;
9283}
Fariborz Jahanian615de762013-05-28 17:37:39 +00009284
Richard Smithe6c01442013-06-05 00:46:14 +00009285APValue *
9286ASTContext::getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E,
9287 bool MayCreate) {
9288 assert(E && E->getStorageDuration() == SD_Static &&
9289 "don't need to cache the computed value for this temporary");
David Majnemer2dcef9e2015-08-13 23:50:15 +00009290 if (MayCreate) {
9291 APValue *&MTVI = MaterializedTemporaryValues[E];
9292 if (!MTVI)
9293 MTVI = new (*this) APValue;
9294 return MTVI;
9295 }
Richard Smithe6c01442013-06-05 00:46:14 +00009296
David Majnemer2dcef9e2015-08-13 23:50:15 +00009297 return MaterializedTemporaryValues.lookup(E);
Richard Smithe6c01442013-06-05 00:46:14 +00009298}
9299
Fariborz Jahanian615de762013-05-28 17:37:39 +00009300bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
9301 const llvm::Triple &T = getTargetInfo().getTriple();
9302 if (!T.isOSDarwin())
9303 return false;
9304
Bob Wilson2c82c3d2013-11-02 23:27:49 +00009305 if (!(T.isiOS() && T.isOSVersionLT(7)) &&
9306 !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
9307 return false;
9308
Fariborz Jahanian615de762013-05-28 17:37:39 +00009309 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
9310 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
9311 uint64_t Size = sizeChars.getQuantity();
9312 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
9313 unsigned Align = alignChars.getQuantity();
9314 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
9315 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
9316}
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009317
9318namespace {
9319
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009320ast_type_traits::DynTypedNode getSingleDynTypedNodeFromParentMap(
9321 ASTContext::ParentMapPointers::mapped_type U) {
Benjamin Kramerfbfa7a12015-10-22 11:26:35 +00009322 if (const auto *D = U.dyn_cast<const Decl *>())
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009323 return ast_type_traits::DynTypedNode::create(*D);
Benjamin Kramerfbfa7a12015-10-22 11:26:35 +00009324 if (const auto *S = U.dyn_cast<const Stmt *>())
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009325 return ast_type_traits::DynTypedNode::create(*S);
Benjamin Kramerfbfa7a12015-10-22 11:26:35 +00009326 return *U.get<ast_type_traits::DynTypedNode *>();
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009327}
9328
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009329/// Template specializations to abstract away from pointers and TypeLocs.
9330/// @{
9331template <typename T>
9332ast_type_traits::DynTypedNode createDynTypedNode(const T &Node) {
9333 return ast_type_traits::DynTypedNode::create(*Node);
9334}
9335template <>
9336ast_type_traits::DynTypedNode createDynTypedNode(const TypeLoc &Node) {
9337 return ast_type_traits::DynTypedNode::create(Node);
9338}
9339template <>
9340ast_type_traits::DynTypedNode
9341createDynTypedNode(const NestedNameSpecifierLoc &Node) {
9342 return ast_type_traits::DynTypedNode::create(Node);
9343}
9344/// @}
9345
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009346 /// \brief A \c RecursiveASTVisitor that builds a map from nodes to their
9347 /// parents as defined by the \c RecursiveASTVisitor.
9348 ///
9349 /// Note that the relationship described here is purely in terms of AST
9350 /// traversal - there are other relationships (for example declaration context)
9351 /// in the AST that are better modeled by special matchers.
9352 ///
Benjamin Kramere8c51fd2015-10-21 10:07:26 +00009353 /// FIXME: Currently only builds up the map using \c Stmt and \c Decl nodes.
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009354 class ParentMapASTVisitor : public RecursiveASTVisitor<ParentMapASTVisitor> {
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009355 public:
9356 /// \brief Builds and returns the translation unit's parent map.
9357 ///
9358 /// The caller takes ownership of the returned \c ParentMap.
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009359 static std::pair<ASTContext::ParentMapPointers *,
9360 ASTContext::ParentMapOtherNodes *>
9361 buildMap(TranslationUnitDecl &TU) {
9362 ParentMapASTVisitor Visitor(new ASTContext::ParentMapPointers,
9363 new ASTContext::ParentMapOtherNodes);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009364 Visitor.TraverseDecl(&TU);
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009365 return std::make_pair(Visitor.Parents, Visitor.OtherParents);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009366 }
9367
9368 private:
9369 typedef RecursiveASTVisitor<ParentMapASTVisitor> VisitorBase;
9370
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009371 ParentMapASTVisitor(ASTContext::ParentMapPointers *Parents,
9372 ASTContext::ParentMapOtherNodes *OtherParents)
9373 : Parents(Parents), OtherParents(OtherParents) {}
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009374
9375 bool shouldVisitTemplateInstantiations() const {
9376 return true;
9377 }
9378 bool shouldVisitImplicitCode() const {
9379 return true;
9380 }
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009381
Richard Smith85838722015-11-24 03:09:01 +00009382 template <typename T, typename MapNodeTy, typename BaseTraverseFn,
9383 typename MapTy>
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009384 bool TraverseNode(T Node, MapNodeTy MapNode,
Richard Smith85838722015-11-24 03:09:01 +00009385 BaseTraverseFn BaseTraverse, MapTy *Parents) {
Craig Topper36250ad2014-05-12 05:36:57 +00009386 if (!Node)
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009387 return true;
Manuel Klimek95403e62014-05-21 13:28:59 +00009388 if (ParentStack.size() > 0) {
Benjamin Kramere8c51fd2015-10-21 10:07:26 +00009389 // FIXME: Currently we add the same parent multiple times, but only
9390 // when no memoization data is available for the type.
9391 // For example when we visit all subexpressions of template
9392 // instantiations; this is suboptimal, but benign: the only way to
9393 // visit those is with hasAncestor / hasParent, and those do not create
9394 // new matches.
9395 // The plan is to enable DynTypedNode to be storable in a map or hash
9396 // map. The main problem there is to implement hash functions /
9397 // comparison operators for all types that DynTypedNode supports that
9398 // do not have pointer identity.
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009399 auto &NodeOrVector = (*Parents)[MapNode];
Manuel Klimek95403e62014-05-21 13:28:59 +00009400 if (NodeOrVector.isNull()) {
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009401 if (const auto *D = ParentStack.back().get<Decl>())
9402 NodeOrVector = D;
9403 else if (const auto *S = ParentStack.back().get<Stmt>())
9404 NodeOrVector = S;
9405 else
9406 NodeOrVector =
9407 new ast_type_traits::DynTypedNode(ParentStack.back());
Manuel Klimek95403e62014-05-21 13:28:59 +00009408 } else {
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009409 if (!NodeOrVector.template is<ASTContext::ParentVector *>()) {
9410 auto *Vector = new ASTContext::ParentVector(
9411 1, getSingleDynTypedNodeFromParentMap(NodeOrVector));
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009412 if (auto *Node =
9413 NodeOrVector
9414 .template dyn_cast<ast_type_traits::DynTypedNode *>())
9415 delete Node;
Benjamin Kramer422b3ff2015-10-23 13:24:18 +00009416 NodeOrVector = Vector;
Samuel Benzaquen3ca0a7b2014-06-13 13:31:40 +00009417 }
Samuel Benzaquen3ca0a7b2014-06-13 13:31:40 +00009418
9419 auto *Vector =
9420 NodeOrVector.template get<ASTContext::ParentVector *>();
9421 // Skip duplicates for types that have memoization data.
9422 // We must check that the type has memoization data before calling
9423 // std::find() because DynTypedNode::operator== can't compare all
9424 // types.
9425 bool Found = ParentStack.back().getMemoizationData() &&
9426 std::find(Vector->begin(), Vector->end(),
9427 ParentStack.back()) != Vector->end();
9428 if (!Found)
9429 Vector->push_back(ParentStack.back());
Manuel Klimek95403e62014-05-21 13:28:59 +00009430 }
9431 }
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009432 ParentStack.push_back(createDynTypedNode(Node));
Richard Smith85838722015-11-24 03:09:01 +00009433 bool Result = BaseTraverse();
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009434 ParentStack.pop_back();
9435 return Result;
9436 }
9437
9438 bool TraverseDecl(Decl *DeclNode) {
Richard Smith85838722015-11-24 03:09:01 +00009439 return TraverseNode(DeclNode, DeclNode,
9440 [&] { return VisitorBase::TraverseDecl(DeclNode); },
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009441 Parents);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009442 }
9443
9444 bool TraverseStmt(Stmt *StmtNode) {
Richard Smith85838722015-11-24 03:09:01 +00009445 return TraverseNode(StmtNode, StmtNode,
9446 [&] { return VisitorBase::TraverseStmt(StmtNode); },
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009447 Parents);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009448 }
9449
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009450 bool TraverseTypeLoc(TypeLoc TypeLocNode) {
Richard Smith85838722015-11-24 03:09:01 +00009451 return TraverseNode(
9452 TypeLocNode, ast_type_traits::DynTypedNode::create(TypeLocNode),
9453 [&] { return VisitorBase::TraverseTypeLoc(TypeLocNode); },
9454 OtherParents);
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009455 }
9456
9457 bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNSLocNode) {
9458 return TraverseNode(
9459 NNSLocNode, ast_type_traits::DynTypedNode::create(NNSLocNode),
Richard Smith85838722015-11-24 03:09:01 +00009460 [&] {
9461 return VisitorBase::TraverseNestedNameSpecifierLoc(NNSLocNode);
9462 },
9463 OtherParents);
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009464 }
9465
9466 ASTContext::ParentMapPointers *Parents;
9467 ASTContext::ParentMapOtherNodes *OtherParents;
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009468 llvm::SmallVector<ast_type_traits::DynTypedNode, 16> ParentStack;
9469
9470 friend class RecursiveASTVisitor<ParentMapASTVisitor>;
9471 };
9472
Eugene Zelenkod4304d22015-11-04 21:37:17 +00009473} // anonymous namespace
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009474
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009475template <typename NodeTy, typename MapTy>
9476static ASTContext::DynTypedNodeList getDynNodeFromMap(const NodeTy &Node,
9477 const MapTy &Map) {
9478 auto I = Map.find(Node);
9479 if (I == Map.end()) {
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009480 return llvm::ArrayRef<ast_type_traits::DynTypedNode>();
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009481 }
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009482 if (auto *V = I->second.template dyn_cast<ASTContext::ParentVector *>()) {
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009483 return llvm::makeArrayRef(*V);
Manuel Klimek95403e62014-05-21 13:28:59 +00009484 }
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009485 return getSingleDynTypedNodeFromParentMap(I->second);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009486}
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00009487
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009488ASTContext::DynTypedNodeList
9489ASTContext::getParents(const ast_type_traits::DynTypedNode &Node) {
9490 if (!PointerParents) {
9491 // We always need to run over the whole translation unit, as
9492 // hasAncestor can escape any subtree.
9493 auto Maps = ParentMapASTVisitor::buildMap(*getTranslationUnitDecl());
9494 PointerParents.reset(Maps.first);
9495 OtherParents.reset(Maps.second);
9496 }
9497 if (Node.getNodeKind().hasPointerIdentity())
9498 return getDynNodeFromMap(Node.getMemoizationData(), *PointerParents);
9499 return getDynNodeFromMap(Node, *OtherParents);
9500}
9501
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00009502bool
9503ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
9504 const ObjCMethodDecl *MethodImpl) {
9505 // No point trying to match an unavailable/deprecated mothod.
9506 if (MethodDecl->hasAttr<UnavailableAttr>()
9507 || MethodDecl->hasAttr<DeprecatedAttr>())
9508 return false;
9509 if (MethodDecl->getObjCDeclQualifier() !=
9510 MethodImpl->getObjCDeclQualifier())
9511 return false;
Alp Toker314cc812014-01-25 16:55:45 +00009512 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00009513 return false;
9514
9515 if (MethodDecl->param_size() != MethodImpl->param_size())
9516 return false;
9517
9518 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
9519 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
9520 EF = MethodDecl->param_end();
9521 IM != EM && IF != EF; ++IM, ++IF) {
9522 const ParmVarDecl *DeclVar = (*IF);
9523 const ParmVarDecl *ImplVar = (*IM);
9524 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
9525 return false;
9526 if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
9527 return false;
9528 }
9529 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
9530
9531}
Richard Smith053f6c62014-05-16 23:01:30 +00009532
Yaxun Liu402804b2016-12-15 08:09:08 +00009533uint64_t ASTContext::getTargetNullPointerValue(QualType QT) const {
9534 unsigned AS;
9535 if (QT->getUnqualifiedDesugaredType()->isNullPtrType())
9536 AS = 0;
9537 else
9538 AS = QT->getPointeeType().getAddressSpace();
9539
9540 return getTargetInfo().getNullPointerValue(AS);
9541}
9542
Richard Smith053f6c62014-05-16 23:01:30 +00009543// Explicitly instantiate this in case a Redeclarable<T> is used from a TU that
9544// doesn't include ASTContext.h
9545template
9546clang::LazyGenerationalUpdatePtr<
9547 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType
9548clang::LazyGenerationalUpdatePtr<
9549 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue(
9550 const clang::ASTContext &Ctx, Decl *Value);