blob: e8f98929de622e7437a7d20dea133b38bf0662d4 [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);
Alexey Bader9c8453f2015-09-15 11:18:52 +00001170 InitBuiltinType(OCLReserveIDTy, BuiltinType::OCLReserveID);
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001171 }
Ted Kremeneke65b0862012-03-06 20:05:56 +00001172
1173 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian29898f42012-04-16 21:03:30 +00001174 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1175 SignedCharTy : BoolTy);
Ted Kremeneke65b0862012-03-06 20:05:56 +00001176
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001177 ObjCConstantStringType = QualType();
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00001178
1179 ObjCSuperType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +00001180
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00001181 // void * type
1182 VoidPtrTy = getPointerType(VoidTy);
Sebastian Redl576fd422009-05-10 18:38:11 +00001183
1184 // nullptr type (C++0x 2.14.7)
1185 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001186
1187 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1188 InitBuiltinType(HalfTy, BuiltinType::Half);
Meador Ingecfb60902012-07-01 15:57:25 +00001189
1190 // Builtin type used to help define __builtin_va_list.
Richard Smith9b88a4c2015-07-27 05:40:23 +00001191 VaListTagDecl = nullptr;
Chris Lattner970e54e2006-11-12 00:37:36 +00001192}
1193
David Blaikie9c902b52011-09-25 23:23:43 +00001194DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001195 return SourceMgr.getDiagnostics();
1196}
1197
Douglas Gregor561eceb2010-08-30 16:49:28 +00001198AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
1199 AttrVec *&Result = DeclAttrs[D];
1200 if (!Result) {
1201 void *Mem = Allocate(sizeof(AttrVec));
1202 Result = new (Mem) AttrVec;
1203 }
1204
1205 return *Result;
1206}
1207
1208/// \brief Erase the attributes corresponding to the given declaration.
1209void ASTContext::eraseDeclAttrs(const Decl *D) {
1210 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1211 if (Pos != DeclAttrs.end()) {
1212 Pos->second->~AttrVec();
1213 DeclAttrs.erase(Pos);
1214 }
1215}
1216
Larisse Voufo39a1e502013-08-06 01:03:05 +00001217// FIXME: Remove ?
Douglas Gregor86d142a2009-10-08 07:24:58 +00001218MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +00001219ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001220 assert(Var->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001221 return getTemplateOrSpecializationInfo(Var)
1222 .dyn_cast<MemberSpecializationInfo *>();
1223}
1224
1225ASTContext::TemplateOrSpecializationInfo
1226ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) {
1227 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1228 TemplateOrInstantiation.find(Var);
1229 if (Pos == TemplateOrInstantiation.end())
1230 return TemplateOrSpecializationInfo();
Mike Stump11289f42009-09-09 15:08:12 +00001231
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001232 return Pos->second;
1233}
1234
Mike Stump11289f42009-09-09 15:08:12 +00001235void
Douglas Gregor86d142a2009-10-08 07:24:58 +00001236ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +00001237 TemplateSpecializationKind TSK,
1238 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001239 assert(Inst->isStaticDataMember() && "Not a static data member");
1240 assert(Tmpl->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001241 setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo(
1242 Tmpl, TSK, PointOfInstantiation));
1243}
1244
1245void
1246ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst,
1247 TemplateOrSpecializationInfo TSI) {
1248 assert(!TemplateOrInstantiation[Inst] &&
1249 "Already noted what the variable was instantiated from");
1250 TemplateOrInstantiation[Inst] = TSI;
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001251}
1252
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001253FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
1254 const FunctionDecl *FD){
1255 assert(FD && "Specialization is 0");
1256 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet57928252011-08-14 14:28:49 +00001257 = ClassScopeSpecializationPattern.find(FD);
1258 if (Pos == ClassScopeSpecializationPattern.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001259 return nullptr;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001260
1261 return Pos->second;
1262}
1263
1264void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
1265 FunctionDecl *Pattern) {
1266 assert(FD && "Specialization is 0");
1267 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet57928252011-08-14 14:28:49 +00001268 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001269}
1270
John McCalle61f2ba2009-11-18 02:36:19 +00001271NamedDecl *
Richard Smithd8a9e372016-12-18 21:39:37 +00001272ASTContext::getInstantiatedFromUsingDecl(NamedDecl *UUD) {
1273 auto Pos = InstantiatedFromUsingDecl.find(UUD);
John McCallb96ec562009-12-04 22:46:56 +00001274 if (Pos == InstantiatedFromUsingDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001275 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001276
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001277 return Pos->second;
1278}
1279
1280void
Richard Smithd8a9e372016-12-18 21:39:37 +00001281ASTContext::setInstantiatedFromUsingDecl(NamedDecl *Inst, NamedDecl *Pattern) {
John McCallb96ec562009-12-04 22:46:56 +00001282 assert((isa<UsingDecl>(Pattern) ||
1283 isa<UnresolvedUsingValueDecl>(Pattern) ||
1284 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1285 "pattern decl is not a using decl");
Richard Smithd8a9e372016-12-18 21:39:37 +00001286 assert((isa<UsingDecl>(Inst) ||
1287 isa<UnresolvedUsingValueDecl>(Inst) ||
1288 isa<UnresolvedUsingTypenameDecl>(Inst)) &&
1289 "instantiation did not produce a using decl");
John McCallb96ec562009-12-04 22:46:56 +00001290 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1291 InstantiatedFromUsingDecl[Inst] = Pattern;
1292}
1293
1294UsingShadowDecl *
1295ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1296 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1297 = InstantiatedFromUsingShadowDecl.find(Inst);
1298 if (Pos == InstantiatedFromUsingShadowDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001299 return nullptr;
John McCallb96ec562009-12-04 22:46:56 +00001300
1301 return Pos->second;
1302}
1303
1304void
1305ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1306 UsingShadowDecl *Pattern) {
1307 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1308 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001309}
1310
Anders Carlsson5da84842009-09-01 04:26:58 +00001311FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1312 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1313 = InstantiatedFromUnnamedFieldDecl.find(Field);
1314 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001315 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001316
Anders Carlsson5da84842009-09-01 04:26:58 +00001317 return Pos->second;
1318}
1319
1320void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1321 FieldDecl *Tmpl) {
1322 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1323 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1324 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1325 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +00001326
Anders Carlsson5da84842009-09-01 04:26:58 +00001327 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1328}
1329
Douglas Gregor832940b2010-03-02 23:58:15 +00001330ASTContext::overridden_cxx_method_iterator
1331ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
Clement Courbet6ecaec82016-07-05 07:49:31 +00001332 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1333 OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001334 if (Pos == OverriddenMethods.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001335 return nullptr;
Douglas Gregor832940b2010-03-02 23:58:15 +00001336 return Pos->second.begin();
1337}
1338
1339ASTContext::overridden_cxx_method_iterator
1340ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
Clement Courbet6ecaec82016-07-05 07:49:31 +00001341 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1342 OverriddenMethods.find(Method->getCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001343 if (Pos == OverriddenMethods.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001344 return nullptr;
Douglas Gregor832940b2010-03-02 23:58:15 +00001345 return Pos->second.end();
1346}
1347
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001348unsigned
1349ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
Clement Courbet6ecaec82016-07-05 07:49:31 +00001350 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1351 OverriddenMethods.find(Method->getCanonicalDecl());
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001352 if (Pos == OverriddenMethods.end())
1353 return 0;
Chandler Carruthb1bcd5d2016-06-11 04:45:38 +00001354 return Pos->second.size();
Clement Courbet8251ebf2016-06-10 11:54:43 +00001355}
1356
Clement Courbet6ecaec82016-07-05 07:49:31 +00001357ASTContext::overridden_method_range
1358ASTContext::overridden_methods(const CXXMethodDecl *Method) const {
1359 return overridden_method_range(overridden_methods_begin(Method),
1360 overridden_methods_end(Method));
1361}
1362
Douglas Gregor832940b2010-03-02 23:58:15 +00001363void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1364 const CXXMethodDecl *Overridden) {
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001365 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001366 OverriddenMethods[Method].push_back(Overridden);
1367}
1368
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +00001369void ASTContext::getOverriddenMethods(
1370 const NamedDecl *D,
1371 SmallVectorImpl<const NamedDecl *> &Overridden) const {
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001372 assert(D);
1373
1374 if (const CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidisc8e70082013-04-17 00:09:03 +00001375 Overridden.append(overridden_methods_begin(CXXMethod),
1376 overridden_methods_end(CXXMethod));
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001377 return;
1378 }
1379
1380 const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
1381 if (!Method)
1382 return;
1383
Argyrios Kyrtzidis353f6a42012-10-09 18:19:01 +00001384 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1385 Method->getOverriddenMethods(OverDecls);
Argyrios Kyrtzidisa7a10812012-10-09 20:08:43 +00001386 Overridden.append(OverDecls.begin(), OverDecls.end());
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001387}
1388
Douglas Gregor0f2a3602011-12-03 00:30:27 +00001389void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1390 assert(!Import->NextLocalImport && "Import declaration already in the chain");
1391 assert(!Import->isFromASTFile() && "Non-local import declaration");
1392 if (!FirstLocalImport) {
1393 FirstLocalImport = Import;
1394 LastLocalImport = Import;
1395 return;
1396 }
1397
1398 LastLocalImport->NextLocalImport = Import;
1399 LastLocalImport = Import;
1400}
1401
Chris Lattner53cfe802007-07-18 17:52:12 +00001402//===----------------------------------------------------------------------===//
1403// Type Sizing and Analysis
1404//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +00001405
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001406/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1407/// scalar floating point type.
1408const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
John McCall9dd450b2009-09-21 23:43:11 +00001409 const BuiltinType *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001410 assert(BT && "Not a floating point type!");
1411 switch (BT->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001412 default: llvm_unreachable("Not a floating point type!");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001413 case BuiltinType::Half: return Target->getHalfFormat();
Douglas Gregore8bbc122011-09-02 00:18:52 +00001414 case BuiltinType::Float: return Target->getFloatFormat();
1415 case BuiltinType::Double: return Target->getDoubleFormat();
1416 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001417 case BuiltinType::Float128: return Target->getFloat128Format();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001418 }
1419}
1420
Rafael Espindola71eccb32013-08-08 19:53:46 +00001421CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001422 unsigned Align = Target->getCharWidth();
Eli Friedman19a546c2009-02-22 02:56:25 +00001423
John McCall94268702010-10-08 18:24:19 +00001424 bool UseAlignAttrOnly = false;
1425 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1426 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +00001427
John McCall94268702010-10-08 18:24:19 +00001428 // __attribute__((aligned)) can increase or decrease alignment
1429 // *except* on a struct or struct member, where it only increases
1430 // alignment unless 'packed' is also specified.
1431 //
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00001432 // It is an error for alignas to decrease alignment, so we can
John McCall94268702010-10-08 18:24:19 +00001433 // ignore that possibility; Sema should diagnose it.
1434 if (isa<FieldDecl>(D)) {
1435 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1436 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1437 } else {
1438 UseAlignAttrOnly = true;
1439 }
1440 }
Fariborz Jahanian9f107182011-05-05 21:19:14 +00001441 else if (isa<FieldDecl>(D))
1442 UseAlignAttrOnly =
1443 D->hasAttr<PackedAttr>() ||
1444 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall94268702010-10-08 18:24:19 +00001445
John McCall4e819612011-01-20 07:57:12 +00001446 // If we're using the align attribute only, just ignore everything
1447 // else about the declaration and its type.
John McCall94268702010-10-08 18:24:19 +00001448 if (UseAlignAttrOnly) {
John McCall4e819612011-01-20 07:57:12 +00001449 // do nothing
1450
John McCall94268702010-10-08 18:24:19 +00001451 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +00001452 QualType T = VD->getType();
Richard Smithf6d70302014-06-10 23:34:28 +00001453 if (const ReferenceType *RT = T->getAs<ReferenceType>()) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001454 if (ForAlignof)
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001455 T = RT->getPointeeType();
1456 else
1457 T = getPointerType(RT->getPointeeType());
1458 }
Richard Smithf6d70302014-06-10 23:34:28 +00001459 QualType BaseT = getBaseElementType(T);
Akira Hatanakad62f2c82017-01-06 17:56:15 +00001460 if (T->isFunctionType())
1461 Align = getTypeInfoImpl(T.getTypePtr()).Align;
1462 else if (!BaseT->isIncompleteType()) {
John McCall33ddac02011-01-19 10:06:00 +00001463 // Adjust alignments of declarations with array type by the
1464 // large-array alignment on the target.
Rafael Espindola88572752013-08-07 18:08:19 +00001465 if (const ArrayType *arrayType = getAsArrayType(T)) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001466 unsigned MinWidth = Target->getLargeArrayMinWidth();
1467 if (!ForAlignof && MinWidth) {
Rafael Espindola88572752013-08-07 18:08:19 +00001468 if (isa<VariableArrayType>(arrayType))
1469 Align = std::max(Align, Target->getLargeArrayAlign());
1470 else if (isa<ConstantArrayType>(arrayType) &&
1471 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
1472 Align = std::max(Align, Target->getLargeArrayAlign());
1473 }
John McCall33ddac02011-01-19 10:06:00 +00001474 }
Chad Rosier99ee7822011-07-26 07:03:04 +00001475 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Roger Ferrer Ibanez3fa38a12017-03-08 14:00:44 +00001476 if (BaseT.getQualifiers().hasUnaligned())
1477 Align = Target->getCharWidth();
Ulrich Weigandfa806422013-05-06 16:23:57 +00001478 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Ulrich Weigandb63f7792015-04-21 17:26:18 +00001479 if (VD->hasGlobalStorage() && !ForAlignof)
Ulrich Weigandfa806422013-05-06 16:23:57 +00001480 Align = std::max(Align, getTargetInfo().getMinGlobalAlign());
1481 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001482 }
John McCall4e819612011-01-20 07:57:12 +00001483
1484 // Fields can be subject to extra alignment constraints, like if
1485 // the field is packed, the struct is packed, or the struct has a
1486 // a max-field-alignment constraint (#pragma pack). So calculate
1487 // the actual alignment of the field within the struct, and then
1488 // (as we're expected to) constrain that by the alignment of the type.
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001489 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
1490 const RecordDecl *Parent = Field->getParent();
1491 // We can only produce a sensible answer if the record is valid.
1492 if (!Parent->isInvalidDecl()) {
1493 const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
John McCall4e819612011-01-20 07:57:12 +00001494
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001495 // Start with the record's overall alignment.
1496 unsigned FieldAlign = toBits(Layout.getAlignment());
John McCall4e819612011-01-20 07:57:12 +00001497
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001498 // Use the GCD of that and the offset within the record.
1499 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1500 if (Offset > 0) {
1501 // Alignment is always a power of 2, so the GCD will be a power of 2,
1502 // which means we get to do this crazy thing instead of Euclid's.
1503 uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1504 if (LowBitOfOffset < FieldAlign)
1505 FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1506 }
1507
1508 Align = std::min(Align, FieldAlign);
John McCall4e819612011-01-20 07:57:12 +00001509 }
Charles Davis3fc51072010-02-23 04:52:00 +00001510 }
Chris Lattner68061312009-01-24 21:53:27 +00001511 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001512
Ken Dyckcc56c542011-01-15 18:38:59 +00001513 return toCharUnitsFromBits(Align);
Chris Lattner68061312009-01-24 21:53:27 +00001514}
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001515
John McCallf1249922012-08-21 04:10:00 +00001516// getTypeInfoDataSizeInChars - Return the size of a type, in
1517// chars. If the type is a record, its data size is returned. This is
1518// the size of the memcpy that's performed when assigning this type
1519// using a trivial copy/move assignment operator.
1520std::pair<CharUnits, CharUnits>
1521ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1522 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1523
1524 // In C++, objects can sometimes be allocated into the tail padding
1525 // of a base-class subobject. We decide whether that's possible
1526 // during class layout, so here we can just trust the layout results.
1527 if (getLangOpts().CPlusPlus) {
1528 if (const RecordType *RT = T->getAs<RecordType>()) {
1529 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1530 sizeAndAlign.first = layout.getDataSize();
1531 }
1532 }
1533
1534 return sizeAndAlign;
1535}
1536
Richard Trieu04d2d942013-05-14 21:59:17 +00001537/// getConstantArrayInfoInChars - Performing the computation in CharUnits
1538/// instead of in bits prevents overflowing the uint64_t for some large arrays.
1539std::pair<CharUnits, CharUnits>
1540static getConstantArrayInfoInChars(const ASTContext &Context,
1541 const ConstantArrayType *CAT) {
1542 std::pair<CharUnits, CharUnits> EltInfo =
1543 Context.getTypeInfoInChars(CAT->getElementType());
1544 uint64_t Size = CAT->getSize().getZExtValue();
Richard Trieuc7509072013-05-14 23:41:50 +00001545 assert((Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity()) <=
1546 (uint64_t)(-1)/Size) &&
Richard Trieu04d2d942013-05-14 21:59:17 +00001547 "Overflow in array type char size evaluation");
1548 uint64_t Width = EltInfo.first.getQuantity() * Size;
1549 unsigned Align = EltInfo.second.getQuantity();
Warren Hunt5ae586a2013-11-01 23:59:41 +00001550 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1551 Context.getTargetInfo().getPointerWidth(0) == 64)
Rui Ueyama83aa9792016-01-14 21:00:27 +00001552 Width = llvm::alignTo(Width, Align);
Richard Trieu04d2d942013-05-14 21:59:17 +00001553 return std::make_pair(CharUnits::fromQuantity(Width),
1554 CharUnits::fromQuantity(Align));
1555}
1556
John McCall87fe5d52010-05-20 01:18:31 +00001557std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001558ASTContext::getTypeInfoInChars(const Type *T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00001559 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(T))
1560 return getConstantArrayInfoInChars(*this, CAT);
David Majnemer34b57492014-07-30 01:30:47 +00001561 TypeInfo Info = getTypeInfo(T);
1562 return std::make_pair(toCharUnitsFromBits(Info.Width),
1563 toCharUnitsFromBits(Info.Align));
John McCall87fe5d52010-05-20 01:18:31 +00001564}
1565
1566std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001567ASTContext::getTypeInfoInChars(QualType T) const {
John McCall87fe5d52010-05-20 01:18:31 +00001568 return getTypeInfoInChars(T.getTypePtr());
1569}
1570
David Majnemer34b57492014-07-30 01:30:47 +00001571bool ASTContext::isAlignmentRequired(const Type *T) const {
1572 return getTypeInfo(T).AlignIsRequired;
1573}
Daniel Dunbarc6475872012-03-09 04:12:54 +00001574
David Majnemer34b57492014-07-30 01:30:47 +00001575bool ASTContext::isAlignmentRequired(QualType T) const {
1576 return isAlignmentRequired(T.getTypePtr());
1577}
1578
Richard Smithb2f0f052016-10-10 18:54:32 +00001579unsigned ASTContext::getTypeAlignIfKnown(QualType T) const {
1580 // An alignment on a typedef overrides anything else.
1581 if (auto *TT = T->getAs<TypedefType>())
1582 if (unsigned Align = TT->getDecl()->getMaxAlignment())
1583 return Align;
1584
1585 // If we have an (array of) complete type, we're done.
1586 T = getBaseElementType(T);
1587 if (!T->isIncompleteType())
1588 return getTypeAlign(T);
1589
1590 // If we had an array type, its element type might be a typedef
1591 // type with an alignment attribute.
1592 if (auto *TT = T->getAs<TypedefType>())
1593 if (unsigned Align = TT->getDecl()->getMaxAlignment())
1594 return Align;
1595
1596 // Otherwise, see if the declaration of the type had an attribute.
1597 if (auto *TT = T->getAs<TagType>())
1598 return TT->getDecl()->getMaxAlignment();
1599
1600 return 0;
1601}
1602
David Majnemer34b57492014-07-30 01:30:47 +00001603TypeInfo ASTContext::getTypeInfo(const Type *T) const {
David Majnemerf8d38642014-07-30 08:42:33 +00001604 TypeInfoMap::iterator I = MemoizedTypeInfo.find(T);
1605 if (I != MemoizedTypeInfo.end())
1606 return I->second;
1607
1608 // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup.
1609 TypeInfo TI = getTypeInfoImpl(T);
1610 MemoizedTypeInfo[T] = TI;
Rafael Espindolaeaa88c12014-07-30 04:40:23 +00001611 return TI;
Daniel Dunbarc6475872012-03-09 04:12:54 +00001612}
1613
1614/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1615/// method does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +00001616///
1617/// FIXME: Pointers into different addr spaces could have different sizes and
1618/// alignment requirements: getPointerInfo should take an AddrSpace, this
1619/// should take a QualType, &c.
David Majnemer34b57492014-07-30 01:30:47 +00001620TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
1621 uint64_t Width = 0;
1622 unsigned Align = 8;
1623 bool AlignIsRequired = false;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001624 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001625#define TYPE(Class, Base)
1626#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +00001627#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001628#define DEPENDENT_TYPE(Class, Base) case Type::Class:
David Blaikieab277d62013-07-13 21:08:03 +00001629#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
1630 case Type::Class: \
1631 assert(!T->isDependentType() && "should not see dependent types here"); \
1632 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001633#include "clang/AST/TypeNodes.def"
John McCall15547bb2011-06-28 16:49:23 +00001634 llvm_unreachable("Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001635
Chris Lattner355332d2007-07-13 22:27:08 +00001636 case Type::FunctionNoProto:
1637 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +00001638 // GCC extension: alignof(function) = 32 bits
1639 Width = 0;
1640 Align = 32;
1641 break;
1642
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001643 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +00001644 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +00001645 Width = 0;
1646 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1647 break;
1648
Steve Naroff5c131802007-08-30 01:06:46 +00001649 case Type::ConstantArray: {
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001650 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +00001651
David Majnemer34b57492014-07-30 01:30:47 +00001652 TypeInfo EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001653 uint64_t Size = CAT->getSize().getZExtValue();
David Majnemer34b57492014-07-30 01:30:47 +00001654 assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
Daniel Dunbarc6475872012-03-09 04:12:54 +00001655 "Overflow in array type bit size evaluation");
David Majnemer34b57492014-07-30 01:30:47 +00001656 Width = EltInfo.Width * Size;
1657 Align = EltInfo.Align;
Warren Hunt5ae586a2013-11-01 23:59:41 +00001658 if (!getTargetInfo().getCXXABI().isMicrosoft() ||
1659 getTargetInfo().getPointerWidth(0) == 64)
Rui Ueyama83aa9792016-01-14 21:00:27 +00001660 Width = llvm::alignTo(Width, Align);
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001661 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +00001662 }
Nate Begemance4d7fc2008-04-18 23:10:10 +00001663 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001664 case Type::Vector: {
Chris Lattner63d2b362009-10-22 05:17:15 +00001665 const VectorType *VT = cast<VectorType>(T);
David Majnemer34b57492014-07-30 01:30:47 +00001666 TypeInfo EltInfo = getTypeInfo(VT->getElementType());
1667 Width = EltInfo.Width * VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +00001668 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +00001669 // If the alignment is not a power of 2, round up to the next power of 2.
1670 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +00001671 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +00001672 Align = llvm::NextPowerOf2(Align);
Rui Ueyama83aa9792016-01-14 21:00:27 +00001673 Width = llvm::alignTo(Width, Align);
Chris Lattner63d2b362009-10-22 05:17:15 +00001674 }
Chad Rosiercc40ea72012-07-13 23:57:43 +00001675 // Adjust the alignment based on the target max.
1676 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1677 if (TargetVectorAlign && TargetVectorAlign < Align)
1678 Align = TargetVectorAlign;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001679 break;
1680 }
Chris Lattner647fb222007-07-18 18:26:58 +00001681
Chris Lattner7570e9c2008-03-08 08:52:55 +00001682 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +00001683 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001684 default: llvm_unreachable("Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +00001685 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +00001686 // GCC extension: alignof(void) = 8 bits.
1687 Width = 0;
1688 Align = 8;
1689 break;
1690
Chris Lattner6a4f7452007-12-19 19:23:28 +00001691 case BuiltinType::Bool:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001692 Width = Target->getBoolWidth();
1693 Align = Target->getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001694 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001695 case BuiltinType::Char_S:
1696 case BuiltinType::Char_U:
1697 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001698 case BuiltinType::SChar:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001699 Width = Target->getCharWidth();
1700 Align = Target->getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001701 break;
Chris Lattnerad3467e2010-12-25 23:25:43 +00001702 case BuiltinType::WChar_S:
1703 case BuiltinType::WChar_U:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001704 Width = Target->getWCharWidth();
1705 Align = Target->getWCharAlign();
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001706 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001707 case BuiltinType::Char16:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001708 Width = Target->getChar16Width();
1709 Align = Target->getChar16Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001710 break;
1711 case BuiltinType::Char32:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001712 Width = Target->getChar32Width();
1713 Align = Target->getChar32Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001714 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001715 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001716 case BuiltinType::Short:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001717 Width = Target->getShortWidth();
1718 Align = Target->getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001719 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001720 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001721 case BuiltinType::Int:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001722 Width = Target->getIntWidth();
1723 Align = Target->getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001724 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001725 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001726 case BuiltinType::Long:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001727 Width = Target->getLongWidth();
1728 Align = Target->getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001729 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001730 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001731 case BuiltinType::LongLong:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001732 Width = Target->getLongLongWidth();
1733 Align = Target->getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001734 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +00001735 case BuiltinType::Int128:
1736 case BuiltinType::UInt128:
1737 Width = 128;
1738 Align = 128; // int128_t is 128-bit aligned on all targets.
1739 break;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001740 case BuiltinType::Half:
1741 Width = Target->getHalfWidth();
1742 Align = Target->getHalfAlign();
1743 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +00001744 case BuiltinType::Float:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001745 Width = Target->getFloatWidth();
1746 Align = Target->getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001747 break;
1748 case BuiltinType::Double:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001749 Width = Target->getDoubleWidth();
1750 Align = Target->getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001751 break;
1752 case BuiltinType::LongDouble:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001753 Width = Target->getLongDoubleWidth();
1754 Align = Target->getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001755 break;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001756 case BuiltinType::Float128:
1757 Width = Target->getFloat128Width();
1758 Align = Target->getFloat128Align();
1759 break;
Sebastian Redl576fd422009-05-10 18:38:11 +00001760 case BuiltinType::NullPtr:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001761 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1762 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +00001763 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001764 case BuiltinType::ObjCId:
1765 case BuiltinType::ObjCClass:
1766 case BuiltinType::ObjCSel:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001767 Width = Target->getPointerWidth(0);
1768 Align = Target->getPointerAlign(0);
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001769 break;
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00001770 case BuiltinType::OCLSampler: {
1771 auto AS = getTargetAddressSpace(LangAS::opencl_constant);
1772 Width = Target->getPointerWidth(AS);
1773 Align = Target->getPointerAlign(AS);
Guy Benyei61054192013-02-07 10:55:47 +00001774 break;
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00001775 }
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001776 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00001777 case BuiltinType::OCLClkEvent:
1778 case BuiltinType::OCLQueue:
Alexey Bader9c8453f2015-09-15 11:18:52 +00001779 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:
Alexey Bader9c8453f2015-09-15 11:18:52 +00005948 case BuiltinType::OCLReserveID:
Guy Benyei61054192013-02-07 10:55:47 +00005949 case BuiltinType::OCLSampler:
John McCall393a78d2012-12-20 02:45:14 +00005950 case BuiltinType::Dependent:
5951#define BUILTIN_TYPE(KIND, ID)
5952#define PLACEHOLDER_TYPE(KIND, ID) \
5953 case BuiltinType::KIND:
5954#include "clang/AST/BuiltinTypes.def"
5955 llvm_unreachable("invalid builtin type for @encode");
David Chisnallb190a2c2010-06-04 01:10:52 +00005956 }
David Blaikie5a6a0202013-01-09 17:48:41 +00005957 llvm_unreachable("invalid BuiltinType::Kind value");
David Chisnallb190a2c2010-06-04 01:10:52 +00005958}
5959
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005960static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
5961 EnumDecl *Enum = ET->getDecl();
5962
5963 // The encoding of an non-fixed enum type is always 'i', regardless of size.
5964 if (!Enum->isFixed())
5965 return 'i';
5966
5967 // The encoding of a fixed enum type matches its fixed underlying type.
John McCall393a78d2012-12-20 02:45:14 +00005968 const BuiltinType *BT = Enum->getIntegerType()->castAs<BuiltinType>();
5969 return getObjCEncodingForPrimitiveKind(C, BT->getKind());
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005970}
5971
Jay Foad39c79802011-01-12 09:06:06 +00005972static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00005973 QualType T, const FieldDecl *FD) {
Richard Smithcaf33902011-10-10 18:28:20 +00005974 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00005975 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00005976 // The NeXT runtime encodes bit fields as b followed by the number of bits.
5977 // The GNU runtime requires more information; bitfields are encoded as b,
5978 // then the offset (in bits) of the first element, then the type of the
5979 // bitfield, then the size in bits. For example, in this structure:
5980 //
5981 // struct
5982 // {
5983 // int integer;
5984 // int flags:2;
5985 // };
5986 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
5987 // runtime, but b32i2 for the GNU runtime. The reason for this extra
5988 // information is not especially sensible, but we're stuck with it for
5989 // compatibility with GCC, although providing it breaks anything that
5990 // actually uses runtime introspection and wants to work on both runtimes...
John McCall5fb5df92012-06-20 06:18:46 +00005991 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
David Chisnallb190a2c2010-06-04 01:10:52 +00005992 const RecordDecl *RD = FD->getParent();
5993 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
Eli Friedmana3c122d2011-07-07 01:54:01 +00005994 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
Douglas Gregor8b7d4032011-09-08 17:18:35 +00005995 if (const EnumType *ET = T->getAs<EnumType>())
5996 S += ObjCEncodingForEnumType(Ctx, ET);
John McCall393a78d2012-12-20 02:45:14 +00005997 else {
5998 const BuiltinType *BT = T->castAs<BuiltinType>();
5999 S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind());
6000 }
David Chisnallb190a2c2010-06-04 01:10:52 +00006001 }
Richard Smithcaf33902011-10-10 18:28:20 +00006002 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian5c767722009-01-13 01:18:13 +00006003}
6004
Daniel Dunbar07d07852009-10-18 21:17:35 +00006005// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00006006void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
6007 bool ExpandPointedToStructures,
6008 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00006009 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00006010 bool OutermostType,
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006011 bool EncodingProperty,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006012 bool StructField,
6013 bool EncodeBlockParameters,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00006014 bool EncodeClassNames,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006015 bool EncodePointerToObjCTypedef,
6016 QualType *NotEncodedT) const {
John McCall393a78d2012-12-20 02:45:14 +00006017 CanQualType CT = getCanonicalType(T);
6018 switch (CT->getTypeClass()) {
6019 case Type::Builtin:
6020 case Type::Enum:
Chris Lattnere7cabb92009-07-13 00:10:46 +00006021 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00006022 return EncodeBitField(this, S, T, FD);
John McCall393a78d2012-12-20 02:45:14 +00006023 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CT))
6024 S += getObjCEncodingForPrimitiveKind(this, BT->getKind());
6025 else
6026 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
Chris Lattnere7cabb92009-07-13 00:10:46 +00006027 return;
Mike Stump11289f42009-09-09 15:08:12 +00006028
John McCall393a78d2012-12-20 02:45:14 +00006029 case Type::Complex: {
6030 const ComplexType *CT = T->castAs<ComplexType>();
Anders Carlsson39b2e132009-04-09 21:55:45 +00006031 S += 'j';
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006032 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, nullptr);
Chris Lattnere7cabb92009-07-13 00:10:46 +00006033 return;
6034 }
John McCall393a78d2012-12-20 02:45:14 +00006035
6036 case Type::Atomic: {
6037 const AtomicType *AT = T->castAs<AtomicType>();
6038 S += 'A';
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006039 getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, nullptr);
John McCall393a78d2012-12-20 02:45:14 +00006040 return;
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00006041 }
John McCall393a78d2012-12-20 02:45:14 +00006042
6043 // encoding for pointer or reference types.
6044 case Type::Pointer:
6045 case Type::LValueReference:
6046 case Type::RValueReference: {
6047 QualType PointeeTy;
6048 if (isa<PointerType>(CT)) {
6049 const PointerType *PT = T->castAs<PointerType>();
6050 if (PT->isObjCSelType()) {
6051 S += ':';
6052 return;
6053 }
6054 PointeeTy = PT->getPointeeType();
6055 } else {
6056 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
6057 }
6058
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006059 bool isReadOnly = false;
6060 // For historical/compatibility reasons, the read-only qualifier of the
6061 // pointee gets emitted _before_ the '^'. The read-only qualifier of
6062 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00006063 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00006064 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006065 if (OutermostType && T.isConstQualified()) {
6066 isReadOnly = true;
6067 S += 'r';
6068 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00006069 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006070 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006071 while (P->getAs<PointerType>())
6072 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006073 if (P.isConstQualified()) {
6074 isReadOnly = true;
6075 S += 'r';
6076 }
6077 }
6078 if (isReadOnly) {
6079 // Another legacy compatibility encoding. Some ObjC qualifier and type
6080 // combinations need to be rearranged.
6081 // Rewrite "in const" from "nr" to "rn"
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006082 if (StringRef(S).endswith("nr"))
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00006083 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006084 }
Mike Stump11289f42009-09-09 15:08:12 +00006085
Anders Carlssond8499822007-10-29 05:01:08 +00006086 if (PointeeTy->isCharType()) {
6087 // char pointer types should be encoded as '*' unless it is a
6088 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00006089 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00006090 S += '*';
6091 return;
6092 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006093 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00006094 // GCC binary compat: Need to convert "struct objc_class *" to "#".
6095 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
6096 S += '#';
6097 return;
6098 }
6099 // GCC binary compat: Need to convert "struct objc_object *" to "@".
6100 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
6101 S += '@';
6102 return;
6103 }
6104 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00006105 }
Anders Carlssond8499822007-10-29 05:01:08 +00006106 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006107 getLegacyIntegralTypeEncoding(PointeeTy);
6108
Mike Stump11289f42009-09-09 15:08:12 +00006109 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006110 nullptr, false, false, false, false, false, false,
6111 NotEncodedT);
Chris Lattnere7cabb92009-07-13 00:10:46 +00006112 return;
6113 }
John McCall393a78d2012-12-20 02:45:14 +00006114
6115 case Type::ConstantArray:
6116 case Type::IncompleteArray:
6117 case Type::VariableArray: {
6118 const ArrayType *AT = cast<ArrayType>(CT);
6119
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006120 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00006121 // Incomplete arrays are encoded as a pointer to the array element.
6122 S += '^';
6123
Mike Stump11289f42009-09-09 15:08:12 +00006124 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00006125 false, ExpandStructures, FD);
6126 } else {
6127 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00006128
Fariborz Jahanianf0dc11a2013-06-04 16:04:37 +00006129 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
6130 S += llvm::utostr(CAT->getSize().getZExtValue());
6131 else {
Anders Carlssond05f44b2009-02-22 01:38:57 +00006132 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006133 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
6134 "Unknown array type!");
Anders Carlssond05f44b2009-02-22 01:38:57 +00006135 S += '0';
6136 }
Mike Stump11289f42009-09-09 15:08:12 +00006137
6138 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006139 false, ExpandStructures, FD,
6140 false, false, false, false, false, false,
6141 NotEncodedT);
Anders Carlssond05f44b2009-02-22 01:38:57 +00006142 S += ']';
6143 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00006144 return;
6145 }
Mike Stump11289f42009-09-09 15:08:12 +00006146
John McCall393a78d2012-12-20 02:45:14 +00006147 case Type::FunctionNoProto:
6148 case Type::FunctionProto:
Anders Carlssondf4cc612007-10-30 00:06:20 +00006149 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00006150 return;
Mike Stump11289f42009-09-09 15:08:12 +00006151
John McCall393a78d2012-12-20 02:45:14 +00006152 case Type::Record: {
6153 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00006154 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00006155 // Anonymous structures print as '?'
6156 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
6157 S += II->getName();
Fariborz Jahanianc5158202010-05-07 00:28:49 +00006158 if (ClassTemplateSpecializationDecl *Spec
6159 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
6160 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
Benjamin Kramer9170e912013-02-22 15:46:01 +00006161 llvm::raw_string_ostream OS(S);
6162 TemplateSpecializationType::PrintTemplateArgumentList(OS,
David Majnemer6fbeee32016-07-07 04:43:07 +00006163 TemplateArgs.asArray(),
Douglas Gregorc0b07282011-09-27 22:38:19 +00006164 (*this).getPrintingPolicy());
Fariborz Jahanianc5158202010-05-07 00:28:49 +00006165 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00006166 } else {
6167 S += '?';
6168 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00006169 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00006170 S += '=';
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006171 if (!RDecl->isUnion()) {
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006172 getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006173 } else {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006174 for (const auto *Field : RDecl->fields()) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006175 if (FD) {
6176 S += '"';
6177 S += Field->getNameAsString();
6178 S += '"';
6179 }
Mike Stump11289f42009-09-09 15:08:12 +00006180
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006181 // Special case bit-fields.
6182 if (Field->isBitField()) {
6183 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006184 Field);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006185 } else {
6186 QualType qt = Field->getType();
6187 getLegacyIntegralTypeEncoding(qt);
6188 getObjCEncodingForTypeImpl(qt, S, false, true,
6189 FD, /*OutermostType*/false,
6190 /*EncodingProperty*/false,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006191 /*StructField*/true,
6192 false, false, false, NotEncodedT);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006193 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00006194 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00006195 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00006196 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00006197 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00006198 return;
6199 }
Mike Stump11289f42009-09-09 15:08:12 +00006200
John McCall393a78d2012-12-20 02:45:14 +00006201 case Type::BlockPointer: {
6202 const BlockPointerType *BT = T->castAs<BlockPointerType>();
Steve Naroff49140cb2009-02-02 18:24:29 +00006203 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006204 if (EncodeBlockParameters) {
John McCall393a78d2012-12-20 02:45:14 +00006205 const FunctionType *FT = BT->getPointeeType()->castAs<FunctionType>();
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006206
6207 S += '<';
6208 // Block return type
Alp Toker314cc812014-01-25 16:55:45 +00006209 getObjCEncodingForTypeImpl(
6210 FT->getReturnType(), S, ExpandPointedToStructures, ExpandStructures,
6211 FD, false /* OutermostType */, EncodingProperty,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006212 false /* StructField */, EncodeBlockParameters, EncodeClassNames, false,
6213 NotEncodedT);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006214 // Block self
6215 S += "@?";
6216 // Block parameters
6217 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00006218 for (const auto &I : FPT->param_types())
6219 getObjCEncodingForTypeImpl(
6220 I, S, ExpandPointedToStructures, ExpandStructures, FD,
6221 false /* OutermostType */, EncodingProperty,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006222 false /* StructField */, EncodeBlockParameters, EncodeClassNames,
6223 false, NotEncodedT);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006224 }
6225 S += '>';
6226 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00006227 return;
6228 }
Mike Stump11289f42009-09-09 15:08:12 +00006229
Fariborz Jahanian33fa9622014-01-28 20:41:15 +00006230 case Type::ObjCObject: {
6231 // hack to match legacy encoding of *id and *Class
6232 QualType Ty = getObjCObjectPointerType(CT);
6233 if (Ty->isObjCIdType()) {
6234 S += "{objc_object=}";
6235 return;
6236 }
6237 else if (Ty->isObjCClassType()) {
6238 S += "{objc_class=}";
6239 return;
6240 }
6241 }
6242
John McCall393a78d2012-12-20 02:45:14 +00006243 case Type::ObjCInterface: {
6244 // Ignore protocol qualifiers when mangling at this level.
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00006245 // @encode(class_name)
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006246 ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00006247 S += '{';
Douglas Gregorb32684e2015-06-16 21:04:55 +00006248 S += OI->getObjCRuntimeNameAsString();
Akira Hatanakafd0fb202016-08-17 19:42:22 +00006249 if (ExpandStructures) {
6250 S += '=';
6251 SmallVector<const ObjCIvarDecl*, 32> Ivars;
6252 DeepCollectObjCIvars(OI, true, Ivars);
6253 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
6254 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
6255 if (Field->isBitField())
6256 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
6257 else
6258 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD,
6259 false, false, false, false, false,
6260 EncodePointerToObjCTypedef,
6261 NotEncodedT);
6262 }
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00006263 }
6264 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00006265 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00006266 }
Mike Stump11289f42009-09-09 15:08:12 +00006267
John McCall393a78d2012-12-20 02:45:14 +00006268 case Type::ObjCObjectPointer: {
6269 const ObjCObjectPointerType *OPT = T->castAs<ObjCObjectPointerType>();
Steve Naroff7cae42b2009-07-10 23:34:53 +00006270 if (OPT->isObjCIdType()) {
6271 S += '@';
6272 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00006273 }
Mike Stump11289f42009-09-09 15:08:12 +00006274
Steve Narofff0c86112009-10-28 22:03:49 +00006275 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
6276 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
6277 // Since this is a binary compatibility issue, need to consult with runtime
6278 // folks. Fortunately, this is a *very* obsure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00006279 S += '#';
6280 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00006281 }
Mike Stump11289f42009-09-09 15:08:12 +00006282
Chris Lattnere7cabb92009-07-13 00:10:46 +00006283 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00006284 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00006285 ExpandPointedToStructures,
6286 ExpandStructures, FD);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006287 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00006288 // Note that we do extended encoding of protocol qualifer list
6289 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00006290 S += '"';
Aaron Ballman83731462014-03-17 16:14:00 +00006291 for (const auto *I : OPT->quals()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00006292 S += '<';
Douglas Gregorb32684e2015-06-16 21:04:55 +00006293 S += I->getObjCRuntimeNameAsString();
Steve Naroff7cae42b2009-07-10 23:34:53 +00006294 S += '>';
6295 }
6296 S += '"';
6297 }
6298 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00006299 }
Mike Stump11289f42009-09-09 15:08:12 +00006300
Chris Lattnere7cabb92009-07-13 00:10:46 +00006301 QualType PointeeTy = OPT->getPointeeType();
6302 if (!EncodingProperty &&
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00006303 isa<TypedefType>(PointeeTy.getTypePtr()) &&
6304 !EncodePointerToObjCTypedef) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00006305 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00006306 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00006307 // {...};
6308 S += '^';
Fariborz Jahanian88890e72013-07-12 16:19:11 +00006309 if (FD && OPT->getInterfaceDecl()) {
Fariborz Jahanianc682ef52013-07-12 16:41:56 +00006310 // Prevent recursive encoding of fields in some rare cases.
Fariborz Jahanian88890e72013-07-12 16:19:11 +00006311 ObjCInterfaceDecl *OI = OPT->getInterfaceDecl();
6312 SmallVector<const ObjCIvarDecl*, 32> Ivars;
6313 DeepCollectObjCIvars(OI, true, Ivars);
6314 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
6315 if (cast<FieldDecl>(Ivars[i]) == FD) {
6316 S += '{';
Douglas Gregorb32684e2015-06-16 21:04:55 +00006317 S += OI->getObjCRuntimeNameAsString();
Fariborz Jahanian88890e72013-07-12 16:19:11 +00006318 S += '}';
6319 return;
6320 }
6321 }
6322 }
Mike Stump11289f42009-09-09 15:08:12 +00006323 getObjCEncodingForTypeImpl(PointeeTy, S,
6324 false, ExpandPointedToStructures,
Craig Topper36250ad2014-05-12 05:36:57 +00006325 nullptr,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00006326 false, false, false, false, false,
6327 /*EncodePointerToObjCTypedef*/true);
Steve Naroff7cae42b2009-07-10 23:34:53 +00006328 return;
6329 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00006330
6331 S += '@';
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006332 if (OPT->getInterfaceDecl() &&
6333 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00006334 S += '"';
Douglas Gregorb32684e2015-06-16 21:04:55 +00006335 S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString();
Aaron Ballman83731462014-03-17 16:14:00 +00006336 for (const auto *I : OPT->quals()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00006337 S += '<';
Douglas Gregorb32684e2015-06-16 21:04:55 +00006338 S += I->getObjCRuntimeNameAsString();
Chris Lattnere7cabb92009-07-13 00:10:46 +00006339 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00006340 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00006341 S += '"';
6342 }
6343 return;
6344 }
Mike Stump11289f42009-09-09 15:08:12 +00006345
John McCalla9e6e8d2010-05-17 23:56:34 +00006346 // gcc just blithely ignores member pointers.
John McCall393a78d2012-12-20 02:45:14 +00006347 // FIXME: we shoul do better than that. 'M' is available.
6348 case Type::MemberPointer:
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006349 // This matches gcc's encoding, even though technically it is insufficient.
6350 //FIXME. We should do a better job than gcc.
John McCall393a78d2012-12-20 02:45:14 +00006351 case Type::Vector:
6352 case Type::ExtVector:
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006353 // Until we have a coherent encoding of these three types, issue warning.
6354 { if (NotEncodedT)
6355 *NotEncodedT = T;
6356 return;
6357 }
6358
6359 // We could see an undeduced auto type here during error recovery.
6360 // Just ignore it.
Richard Smith27d807c2013-04-30 13:56:41 +00006361 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00006362 case Type::DeducedTemplateSpecialization:
Richard Smith27d807c2013-04-30 13:56:41 +00006363 return;
6364
Xiuli Pan9c14e282016-01-09 12:53:17 +00006365 case Type::Pipe:
John McCall393a78d2012-12-20 02:45:14 +00006366#define ABSTRACT_TYPE(KIND, BASE)
6367#define TYPE(KIND, BASE)
6368#define DEPENDENT_TYPE(KIND, BASE) \
6369 case Type::KIND:
6370#define NON_CANONICAL_TYPE(KIND, BASE) \
6371 case Type::KIND:
6372#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
6373 case Type::KIND:
6374#include "clang/AST/TypeNodes.def"
6375 llvm_unreachable("@encode for dependent type!");
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00006376 }
John McCall393a78d2012-12-20 02:45:14 +00006377 llvm_unreachable("bad type kind!");
Anders Carlssond8499822007-10-29 05:01:08 +00006378}
6379
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006380void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
6381 std::string &S,
6382 const FieldDecl *FD,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006383 bool includeVBases,
6384 QualType *NotEncodedT) const {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006385 assert(RDecl && "Expected non-null RecordDecl");
6386 assert(!RDecl->isUnion() && "Should not be called for unions");
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00006387 if (!RDecl->getDefinition() || RDecl->getDefinition()->isInvalidDecl())
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006388 return;
6389
6390 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
6391 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
6392 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
6393
6394 if (CXXRec) {
Aaron Ballman574705e2014-03-13 15:41:46 +00006395 for (const auto &BI : CXXRec->bases()) {
6396 if (!BI.isVirtual()) {
6397 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00006398 if (base->isEmpty())
6399 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00006400 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006401 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
6402 std::make_pair(offs, base));
6403 }
6404 }
6405 }
6406
6407 unsigned i = 0;
Hans Wennborga302cd92014-08-21 16:06:57 +00006408 for (auto *Field : RDecl->fields()) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006409 uint64_t offs = layout.getFieldOffset(i);
6410 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
Hans Wennborga302cd92014-08-21 16:06:57 +00006411 std::make_pair(offs, Field));
6412 ++i;
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006413 }
6414
6415 if (CXXRec && includeVBases) {
Aaron Ballman445a9392014-03-13 16:15:17 +00006416 for (const auto &BI : CXXRec->vbases()) {
6417 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00006418 if (base->isEmpty())
6419 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00006420 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Eli Friedman1d24af82013-09-18 01:59:16 +00006421 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
6422 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
Argyrios Kyrtzidis81c0b5c2011-09-26 18:14:24 +00006423 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
6424 std::make_pair(offs, base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006425 }
6426 }
6427
6428 CharUnits size;
6429 if (CXXRec) {
6430 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
6431 } else {
6432 size = layout.getSize();
6433 }
6434
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006435#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006436 uint64_t CurOffs = 0;
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006437#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006438 std::multimap<uint64_t, NamedDecl *>::iterator
6439 CurLayObj = FieldOrBaseOffsets.begin();
6440
Douglas Gregorf5d6c742012-04-27 22:30:01 +00006441 if (CXXRec && CXXRec->isDynamicClass() &&
6442 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006443 if (FD) {
6444 S += "\"_vptr$";
6445 std::string recname = CXXRec->getNameAsString();
6446 if (recname.empty()) recname = "?";
6447 S += recname;
6448 S += '"';
6449 }
6450 S += "^^?";
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006451#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006452 CurOffs += getTypeSize(VoidPtrTy);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006453#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006454 }
6455
6456 if (!RDecl->hasFlexibleArrayMember()) {
6457 // Mark the end of the structure.
6458 uint64_t offs = toBits(size);
6459 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
Craig Topper36250ad2014-05-12 05:36:57 +00006460 std::make_pair(offs, nullptr));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006461 }
6462
6463 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006464#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006465 assert(CurOffs <= CurLayObj->first);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006466 if (CurOffs < CurLayObj->first) {
6467 uint64_t padding = CurLayObj->first - CurOffs;
6468 // FIXME: There doesn't seem to be a way to indicate in the encoding that
6469 // packing/alignment of members is different that normal, in which case
6470 // the encoding will be out-of-sync with the real layout.
6471 // If the runtime switches to just consider the size of types without
6472 // taking into account alignment, we could make padding explicit in the
6473 // encoding (e.g. using arrays of chars). The encoding strings would be
6474 // longer then though.
6475 CurOffs += padding;
6476 }
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006477#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006478
6479 NamedDecl *dcl = CurLayObj->second;
Craig Topper36250ad2014-05-12 05:36:57 +00006480 if (!dcl)
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006481 break; // reached end of structure.
6482
6483 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
6484 // We expand the bases without their virtual bases since those are going
6485 // in the initial structure. Note that this differs from gcc which
6486 // expands virtual bases each time one is encountered in the hierarchy,
6487 // making the encoding type bigger than it really is.
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006488 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
6489 NotEncodedT);
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00006490 assert(!base->isEmpty());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006491#ifndef NDEBUG
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00006492 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006493#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006494 } else {
6495 FieldDecl *field = cast<FieldDecl>(dcl);
6496 if (FD) {
6497 S += '"';
6498 S += field->getNameAsString();
6499 S += '"';
6500 }
6501
6502 if (field->isBitField()) {
6503 EncodeBitField(this, S, field->getType(), field);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006504#ifndef NDEBUG
Richard Smithcaf33902011-10-10 18:28:20 +00006505 CurOffs += field->getBitWidthValue(*this);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006506#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006507 } else {
6508 QualType qt = field->getType();
6509 getLegacyIntegralTypeEncoding(qt);
6510 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
6511 /*OutermostType*/false,
6512 /*EncodingProperty*/false,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006513 /*StructField*/true,
6514 false, false, false, NotEncodedT);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006515#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006516 CurOffs += getTypeSize(field->getType());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006517#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006518 }
6519 }
6520 }
6521}
6522
Mike Stump11289f42009-09-09 15:08:12 +00006523void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00006524 std::string& S) const {
6525 if (QT & Decl::OBJC_TQ_In)
6526 S += 'n';
6527 if (QT & Decl::OBJC_TQ_Inout)
6528 S += 'N';
6529 if (QT & Decl::OBJC_TQ_Out)
6530 S += 'o';
6531 if (QT & Decl::OBJC_TQ_Bycopy)
6532 S += 'O';
6533 if (QT & Decl::OBJC_TQ_Byref)
6534 S += 'R';
6535 if (QT & Decl::OBJC_TQ_Oneway)
6536 S += 'V';
6537}
6538
Douglas Gregor3ea72692011-08-12 05:46:01 +00006539TypedefDecl *ASTContext::getObjCIdDecl() const {
6540 if (!ObjCIdDecl) {
Douglas Gregore9d95f12015-07-07 03:57:35 +00006541 QualType T = getObjCObjectType(ObjCBuiltinIdTy, { }, { });
Douglas Gregor3ea72692011-08-12 05:46:01 +00006542 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00006543 ObjCIdDecl = buildImplicitTypedef(T, "id");
Douglas Gregor3ea72692011-08-12 05:46:01 +00006544 }
Douglas Gregor3ea72692011-08-12 05:46:01 +00006545 return ObjCIdDecl;
Steve Naroff66e9f332007-10-15 14:41:52 +00006546}
6547
Douglas Gregor52e02802011-08-12 06:17:30 +00006548TypedefDecl *ASTContext::getObjCSelDecl() const {
6549 if (!ObjCSelDecl) {
Alp Toker56b5cc92013-12-15 10:36:26 +00006550 QualType T = getPointerType(ObjCBuiltinSelTy);
6551 ObjCSelDecl = buildImplicitTypedef(T, "SEL");
Douglas Gregor52e02802011-08-12 06:17:30 +00006552 }
6553 return ObjCSelDecl;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00006554}
6555
Douglas Gregor0a586182011-08-12 05:59:41 +00006556TypedefDecl *ASTContext::getObjCClassDecl() const {
6557 if (!ObjCClassDecl) {
Douglas Gregore9d95f12015-07-07 03:57:35 +00006558 QualType T = getObjCObjectType(ObjCBuiltinClassTy, { }, { });
Douglas Gregor0a586182011-08-12 05:59:41 +00006559 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00006560 ObjCClassDecl = buildImplicitTypedef(T, "Class");
Douglas Gregor0a586182011-08-12 05:59:41 +00006561 }
Douglas Gregor0a586182011-08-12 05:59:41 +00006562 return ObjCClassDecl;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00006563}
6564
Douglas Gregord53ae832012-01-17 18:09:05 +00006565ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
6566 if (!ObjCProtocolClassDecl) {
6567 ObjCProtocolClassDecl
6568 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
6569 SourceLocation(),
6570 &Idents.get("Protocol"),
Douglas Gregor85f3f952015-07-07 03:57:15 +00006571 /*typeParamList=*/nullptr,
Craig Topper36250ad2014-05-12 05:36:57 +00006572 /*PrevDecl=*/nullptr,
Douglas Gregord53ae832012-01-17 18:09:05 +00006573 SourceLocation(), true);
6574 }
6575
6576 return ObjCProtocolClassDecl;
6577}
6578
Meador Inge5d3fb222012-06-16 03:34:49 +00006579//===----------------------------------------------------------------------===//
6580// __builtin_va_list Construction Functions
6581//===----------------------------------------------------------------------===//
6582
Charles Davisc7d5c942015-09-17 20:55:33 +00006583static TypedefDecl *CreateCharPtrNamedVaListDecl(const ASTContext *Context,
6584 StringRef Name) {
6585 // typedef char* __builtin[_ms]_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006586 QualType T = Context->getPointerType(Context->CharTy);
Charles Davisc7d5c942015-09-17 20:55:33 +00006587 return Context->buildImplicitTypedef(T, Name);
6588}
6589
6590static TypedefDecl *CreateMSVaListDecl(const ASTContext *Context) {
6591 return CreateCharPtrNamedVaListDecl(Context, "__builtin_ms_va_list");
6592}
6593
6594static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
6595 return CreateCharPtrNamedVaListDecl(Context, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006596}
6597
6598static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
6599 // typedef void* __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006600 QualType T = Context->getPointerType(Context->VoidTy);
6601 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006602}
6603
Tim Northover9bb857a2013-01-31 12:13:10 +00006604static TypedefDecl *
6605CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00006606 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00006607 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00006608 if (Context->getLangOpts().CPlusPlus) {
6609 // namespace std { struct __va_list {
6610 NamespaceDecl *NS;
6611 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
6612 Context->getTranslationUnitDecl(),
Craig Topper36250ad2014-05-12 05:36:57 +00006613 /*Inline*/ false, SourceLocation(),
Tim Northover9bb857a2013-01-31 12:13:10 +00006614 SourceLocation(), &Context->Idents.get("std"),
Craig Topper36250ad2014-05-12 05:36:57 +00006615 /*PrevDecl*/ nullptr);
Alp Toker56b5cc92013-12-15 10:36:26 +00006616 NS->setImplicit();
Tim Northover9bb857a2013-01-31 12:13:10 +00006617 VaListTagDecl->setDeclContext(NS);
Tim Northover9bb857a2013-01-31 12:13:10 +00006618 }
6619
6620 VaListTagDecl->startDefinition();
6621
6622 const size_t NumFields = 5;
6623 QualType FieldTypes[NumFields];
6624 const char *FieldNames[NumFields];
6625
6626 // void *__stack;
6627 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
6628 FieldNames[0] = "__stack";
6629
6630 // void *__gr_top;
6631 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
6632 FieldNames[1] = "__gr_top";
6633
6634 // void *__vr_top;
6635 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6636 FieldNames[2] = "__vr_top";
6637
6638 // int __gr_offs;
6639 FieldTypes[3] = Context->IntTy;
6640 FieldNames[3] = "__gr_offs";
6641
6642 // int __vr_offs;
6643 FieldTypes[4] = Context->IntTy;
6644 FieldNames[4] = "__vr_offs";
6645
6646 // Create fields
6647 for (unsigned i = 0; i < NumFields; ++i) {
6648 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6649 VaListTagDecl,
6650 SourceLocation(),
6651 SourceLocation(),
6652 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006653 FieldTypes[i], /*TInfo=*/nullptr,
6654 /*BitWidth=*/nullptr,
Tim Northover9bb857a2013-01-31 12:13:10 +00006655 /*Mutable=*/false,
6656 ICIS_NoInit);
6657 Field->setAccess(AS_public);
6658 VaListTagDecl->addDecl(Field);
6659 }
6660 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00006661 Context->VaListTagDecl = VaListTagDecl;
Tim Northover9bb857a2013-01-31 12:13:10 +00006662 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Tim Northover9bb857a2013-01-31 12:13:10 +00006663
6664 // } __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006665 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00006666}
6667
Meador Inge5d3fb222012-06-16 03:34:49 +00006668static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
6669 // typedef struct __va_list_tag {
6670 RecordDecl *VaListTagDecl;
6671
Alp Toker2dea15b2013-12-17 01:22:38 +00006672 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00006673 VaListTagDecl->startDefinition();
6674
6675 const size_t NumFields = 5;
6676 QualType FieldTypes[NumFields];
6677 const char *FieldNames[NumFields];
6678
6679 // unsigned char gpr;
6680 FieldTypes[0] = Context->UnsignedCharTy;
6681 FieldNames[0] = "gpr";
6682
6683 // unsigned char fpr;
6684 FieldTypes[1] = Context->UnsignedCharTy;
6685 FieldNames[1] = "fpr";
6686
6687 // unsigned short reserved;
6688 FieldTypes[2] = Context->UnsignedShortTy;
6689 FieldNames[2] = "reserved";
6690
6691 // void* overflow_arg_area;
6692 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6693 FieldNames[3] = "overflow_arg_area";
6694
6695 // void* reg_save_area;
6696 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
6697 FieldNames[4] = "reg_save_area";
6698
6699 // Create fields
6700 for (unsigned i = 0; i < NumFields; ++i) {
6701 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
6702 SourceLocation(),
6703 SourceLocation(),
6704 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006705 FieldTypes[i], /*TInfo=*/nullptr,
6706 /*BitWidth=*/nullptr,
Meador Inge5d3fb222012-06-16 03:34:49 +00006707 /*Mutable=*/false,
6708 ICIS_NoInit);
6709 Field->setAccess(AS_public);
6710 VaListTagDecl->addDecl(Field);
6711 }
6712 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00006713 Context->VaListTagDecl = VaListTagDecl;
Meador Inge5d3fb222012-06-16 03:34:49 +00006714 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6715
6716 // } __va_list_tag;
Alp Toker56b5cc92013-12-15 10:36:26 +00006717 TypedefDecl *VaListTagTypedefDecl =
6718 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
6719
Meador Inge5d3fb222012-06-16 03:34:49 +00006720 QualType VaListTagTypedefType =
6721 Context->getTypedefType(VaListTagTypedefDecl);
6722
6723 // typedef __va_list_tag __builtin_va_list[1];
6724 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6725 QualType VaListTagArrayType
6726 = Context->getConstantArrayType(VaListTagTypedefType,
6727 Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00006728 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006729}
6730
6731static TypedefDecl *
6732CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
Richard Smith9b88a4c2015-07-27 05:40:23 +00006733 // struct __va_list_tag {
Meador Inge5d3fb222012-06-16 03:34:49 +00006734 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00006735 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00006736 VaListTagDecl->startDefinition();
6737
6738 const size_t NumFields = 4;
6739 QualType FieldTypes[NumFields];
6740 const char *FieldNames[NumFields];
6741
6742 // unsigned gp_offset;
6743 FieldTypes[0] = Context->UnsignedIntTy;
6744 FieldNames[0] = "gp_offset";
6745
6746 // unsigned fp_offset;
6747 FieldTypes[1] = Context->UnsignedIntTy;
6748 FieldNames[1] = "fp_offset";
6749
6750 // void* overflow_arg_area;
6751 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6752 FieldNames[2] = "overflow_arg_area";
6753
6754 // void* reg_save_area;
6755 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6756 FieldNames[3] = "reg_save_area";
6757
6758 // Create fields
6759 for (unsigned i = 0; i < NumFields; ++i) {
6760 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6761 VaListTagDecl,
6762 SourceLocation(),
6763 SourceLocation(),
6764 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006765 FieldTypes[i], /*TInfo=*/nullptr,
6766 /*BitWidth=*/nullptr,
Meador Inge5d3fb222012-06-16 03:34:49 +00006767 /*Mutable=*/false,
6768 ICIS_NoInit);
6769 Field->setAccess(AS_public);
6770 VaListTagDecl->addDecl(Field);
6771 }
6772 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00006773 Context->VaListTagDecl = VaListTagDecl;
Meador Inge5d3fb222012-06-16 03:34:49 +00006774 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6775
Richard Smith9b88a4c2015-07-27 05:40:23 +00006776 // };
Alp Toker56b5cc92013-12-15 10:36:26 +00006777
Richard Smith9b88a4c2015-07-27 05:40:23 +00006778 // typedef struct __va_list_tag __builtin_va_list[1];
Meador Inge5d3fb222012-06-16 03:34:49 +00006779 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
Richard Smith9b88a4c2015-07-27 05:40:23 +00006780 QualType VaListTagArrayType =
6781 Context->getConstantArrayType(VaListTagType, Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00006782 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006783}
6784
6785static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
6786 // typedef int __builtin_va_list[4];
6787 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
Yaron Kerene0bcdd42016-10-08 06:45:10 +00006788 QualType IntArrayType =
6789 Context->getConstantArrayType(Context->IntTy, Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00006790 return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00006791}
6792
Logan Chien57086ce2012-10-10 06:56:20 +00006793static TypedefDecl *
6794CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00006795 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00006796 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00006797 if (Context->getLangOpts().CPlusPlus) {
6798 // namespace std { struct __va_list {
6799 NamespaceDecl *NS;
6800 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
6801 Context->getTranslationUnitDecl(),
6802 /*Inline*/false, SourceLocation(),
6803 SourceLocation(), &Context->Idents.get("std"),
Craig Topper36250ad2014-05-12 05:36:57 +00006804 /*PrevDecl*/ nullptr);
Alp Toker56b5cc92013-12-15 10:36:26 +00006805 NS->setImplicit();
Logan Chien57086ce2012-10-10 06:56:20 +00006806 VaListDecl->setDeclContext(NS);
Logan Chien57086ce2012-10-10 06:56:20 +00006807 }
6808
6809 VaListDecl->startDefinition();
6810
6811 // void * __ap;
6812 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6813 VaListDecl,
6814 SourceLocation(),
6815 SourceLocation(),
6816 &Context->Idents.get("__ap"),
6817 Context->getPointerType(Context->VoidTy),
Craig Topper36250ad2014-05-12 05:36:57 +00006818 /*TInfo=*/nullptr,
6819 /*BitWidth=*/nullptr,
Logan Chien57086ce2012-10-10 06:56:20 +00006820 /*Mutable=*/false,
6821 ICIS_NoInit);
6822 Field->setAccess(AS_public);
6823 VaListDecl->addDecl(Field);
6824
6825 // };
6826 VaListDecl->completeDefinition();
Oleg Ranevskyyb88d2472016-03-30 21:30:30 +00006827 Context->VaListTagDecl = VaListDecl;
Logan Chien57086ce2012-10-10 06:56:20 +00006828
6829 // typedef struct __va_list __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00006830 QualType T = Context->getRecordType(VaListDecl);
6831 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00006832}
6833
Ulrich Weigand47445072013-05-06 16:26:41 +00006834static TypedefDecl *
6835CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
Richard Smith9b88a4c2015-07-27 05:40:23 +00006836 // struct __va_list_tag {
Ulrich Weigand47445072013-05-06 16:26:41 +00006837 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00006838 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Ulrich Weigand47445072013-05-06 16:26:41 +00006839 VaListTagDecl->startDefinition();
6840
6841 const size_t NumFields = 4;
6842 QualType FieldTypes[NumFields];
6843 const char *FieldNames[NumFields];
6844
6845 // long __gpr;
6846 FieldTypes[0] = Context->LongTy;
6847 FieldNames[0] = "__gpr";
6848
6849 // long __fpr;
6850 FieldTypes[1] = Context->LongTy;
6851 FieldNames[1] = "__fpr";
6852
6853 // void *__overflow_arg_area;
6854 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6855 FieldNames[2] = "__overflow_arg_area";
6856
6857 // void *__reg_save_area;
6858 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6859 FieldNames[3] = "__reg_save_area";
6860
6861 // Create fields
6862 for (unsigned i = 0; i < NumFields; ++i) {
6863 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6864 VaListTagDecl,
6865 SourceLocation(),
6866 SourceLocation(),
6867 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00006868 FieldTypes[i], /*TInfo=*/nullptr,
6869 /*BitWidth=*/nullptr,
Ulrich Weigand47445072013-05-06 16:26:41 +00006870 /*Mutable=*/false,
6871 ICIS_NoInit);
6872 Field->setAccess(AS_public);
6873 VaListTagDecl->addDecl(Field);
6874 }
6875 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00006876 Context->VaListTagDecl = VaListTagDecl;
Ulrich Weigand47445072013-05-06 16:26:41 +00006877 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Ulrich Weigand47445072013-05-06 16:26:41 +00006878
Richard Smith9b88a4c2015-07-27 05:40:23 +00006879 // };
Ulrich Weigand47445072013-05-06 16:26:41 +00006880
6881 // typedef __va_list_tag __builtin_va_list[1];
6882 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
Richard Smith9b88a4c2015-07-27 05:40:23 +00006883 QualType VaListTagArrayType =
6884 Context->getConstantArrayType(VaListTagType, Size, ArrayType::Normal, 0);
Ulrich Weigand47445072013-05-06 16:26:41 +00006885
Alp Toker56b5cc92013-12-15 10:36:26 +00006886 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Ulrich Weigand47445072013-05-06 16:26:41 +00006887}
6888
Meador Inge5d3fb222012-06-16 03:34:49 +00006889static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
6890 TargetInfo::BuiltinVaListKind Kind) {
6891 switch (Kind) {
6892 case TargetInfo::CharPtrBuiltinVaList:
6893 return CreateCharPtrBuiltinVaListDecl(Context);
6894 case TargetInfo::VoidPtrBuiltinVaList:
6895 return CreateVoidPtrBuiltinVaListDecl(Context);
Tim Northover9bb857a2013-01-31 12:13:10 +00006896 case TargetInfo::AArch64ABIBuiltinVaList:
6897 return CreateAArch64ABIBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00006898 case TargetInfo::PowerABIBuiltinVaList:
6899 return CreatePowerABIBuiltinVaListDecl(Context);
6900 case TargetInfo::X86_64ABIBuiltinVaList:
6901 return CreateX86_64ABIBuiltinVaListDecl(Context);
6902 case TargetInfo::PNaClABIBuiltinVaList:
6903 return CreatePNaClABIBuiltinVaListDecl(Context);
Logan Chien57086ce2012-10-10 06:56:20 +00006904 case TargetInfo::AAPCSABIBuiltinVaList:
6905 return CreateAAPCSABIBuiltinVaListDecl(Context);
Ulrich Weigand47445072013-05-06 16:26:41 +00006906 case TargetInfo::SystemZBuiltinVaList:
6907 return CreateSystemZBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00006908 }
6909
6910 llvm_unreachable("Unhandled __builtin_va_list type kind");
6911}
6912
6913TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00006914 if (!BuiltinVaListDecl) {
Meador Inge5d3fb222012-06-16 03:34:49 +00006915 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
Alp Toker56b5cc92013-12-15 10:36:26 +00006916 assert(BuiltinVaListDecl->isImplicit());
6917 }
Meador Inge5d3fb222012-06-16 03:34:49 +00006918
6919 return BuiltinVaListDecl;
6920}
6921
Richard Smith9b88a4c2015-07-27 05:40:23 +00006922Decl *ASTContext::getVaListTagDecl() const {
6923 // Force the creation of VaListTagDecl by building the __builtin_va_list
Meador Ingecfb60902012-07-01 15:57:25 +00006924 // declaration.
Richard Smith9b88a4c2015-07-27 05:40:23 +00006925 if (!VaListTagDecl)
6926 (void)getBuiltinVaListDecl();
Meador Ingecfb60902012-07-01 15:57:25 +00006927
Richard Smith9b88a4c2015-07-27 05:40:23 +00006928 return VaListTagDecl;
Meador Ingecfb60902012-07-01 15:57:25 +00006929}
6930
Charles Davisc7d5c942015-09-17 20:55:33 +00006931TypedefDecl *ASTContext::getBuiltinMSVaListDecl() const {
6932 if (!BuiltinMSVaListDecl)
6933 BuiltinMSVaListDecl = CreateMSVaListDecl(this);
6934
6935 return BuiltinMSVaListDecl;
6936}
6937
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006938void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00006939 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00006940 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00006941
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006942 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00006943}
6944
John McCalld28ae272009-12-02 08:04:21 +00006945/// \brief Retrieve the template name that corresponds to a non-empty
6946/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00006947TemplateName
6948ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
6949 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00006950 unsigned size = End - Begin;
6951 assert(size > 1 && "set is not overloaded!");
6952
6953 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
6954 size * sizeof(FunctionTemplateDecl*));
6955 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
6956
6957 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00006958 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00006959 NamedDecl *D = *I;
6960 assert(isa<FunctionTemplateDecl>(D) ||
6961 (isa<UsingShadowDecl>(D) &&
6962 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
6963 *Storage++ = D;
6964 }
6965
6966 return TemplateName(OT);
6967}
6968
Douglas Gregordc572a32009-03-30 22:58:21 +00006969/// \brief Retrieve the template name that represents a qualified
6970/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00006971TemplateName
6972ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
6973 bool TemplateKeyword,
6974 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00006975 assert(NNS && "Missing nested-name-specifier in qualified template name");
6976
Douglas Gregorc42075a2010-02-04 18:10:26 +00006977 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00006978 llvm::FoldingSetNodeID ID;
6979 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
6980
Craig Topper36250ad2014-05-12 05:36:57 +00006981 void *InsertPos = nullptr;
Douglas Gregordc572a32009-03-30 22:58:21 +00006982 QualifiedTemplateName *QTN =
6983 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6984 if (!QTN) {
Benjamin Kramerc3f89252016-10-20 14:27:22 +00006985 QTN = new (*this, alignof(QualifiedTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00006986 QualifiedTemplateName(NNS, TemplateKeyword, Template);
Douglas Gregordc572a32009-03-30 22:58:21 +00006987 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
6988 }
6989
6990 return TemplateName(QTN);
6991}
6992
6993/// \brief Retrieve the template name that represents a dependent
6994/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00006995TemplateName
6996ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
6997 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00006998 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00006999 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00007000
7001 llvm::FoldingSetNodeID ID;
7002 DependentTemplateName::Profile(ID, NNS, Name);
7003
Craig Topper36250ad2014-05-12 05:36:57 +00007004 void *InsertPos = nullptr;
Douglas Gregordc572a32009-03-30 22:58:21 +00007005 DependentTemplateName *QTN =
7006 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7007
7008 if (QTN)
7009 return TemplateName(QTN);
7010
7011 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
7012 if (CanonNNS == NNS) {
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007013 QTN = new (*this, alignof(DependentTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00007014 DependentTemplateName(NNS, Name);
Douglas Gregordc572a32009-03-30 22:58:21 +00007015 } else {
7016 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007017 QTN = new (*this, alignof(DependentTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00007018 DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00007019 DependentTemplateName *CheckQTN =
7020 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7021 assert(!CheckQTN && "Dependent type name canonicalization broken");
7022 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00007023 }
7024
7025 DependentTemplateNames.InsertNode(QTN, InsertPos);
7026 return TemplateName(QTN);
7027}
7028
Douglas Gregor71395fa2009-11-04 00:56:37 +00007029/// \brief Retrieve the template name that represents a dependent
7030/// template name such as \c MetaFun::template operator+.
7031TemplateName
7032ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00007033 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00007034 assert((!NNS || NNS->isDependent()) &&
7035 "Nested name specifier must be dependent");
7036
7037 llvm::FoldingSetNodeID ID;
7038 DependentTemplateName::Profile(ID, NNS, Operator);
Craig Topper36250ad2014-05-12 05:36:57 +00007039
7040 void *InsertPos = nullptr;
Douglas Gregorc42075a2010-02-04 18:10:26 +00007041 DependentTemplateName *QTN
7042 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor71395fa2009-11-04 00:56:37 +00007043
7044 if (QTN)
7045 return TemplateName(QTN);
7046
7047 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
7048 if (CanonNNS == NNS) {
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007049 QTN = new (*this, alignof(DependentTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00007050 DependentTemplateName(NNS, Operator);
Douglas Gregor71395fa2009-11-04 00:56:37 +00007051 } else {
7052 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007053 QTN = new (*this, alignof(DependentTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00007054 DependentTemplateName(NNS, Operator, Canon);
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007055
Douglas Gregorc42075a2010-02-04 18:10:26 +00007056 DependentTemplateName *CheckQTN
7057 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7058 assert(!CheckQTN && "Dependent template name canonicalization broken");
7059 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00007060 }
7061
7062 DependentTemplateNames.InsertNode(QTN, InsertPos);
7063 return TemplateName(QTN);
7064}
7065
Douglas Gregor5590be02011-01-15 06:45:20 +00007066TemplateName
John McCalld9dfe3a2011-06-30 08:33:18 +00007067ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
7068 TemplateName replacement) const {
7069 llvm::FoldingSetNodeID ID;
7070 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
Craig Topper36250ad2014-05-12 05:36:57 +00007071
7072 void *insertPos = nullptr;
John McCalld9dfe3a2011-06-30 08:33:18 +00007073 SubstTemplateTemplateParmStorage *subst
7074 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
7075
7076 if (!subst) {
7077 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
7078 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
7079 }
7080
7081 return TemplateName(subst);
7082}
7083
7084TemplateName
Douglas Gregor5590be02011-01-15 06:45:20 +00007085ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
7086 const TemplateArgument &ArgPack) const {
7087 ASTContext &Self = const_cast<ASTContext &>(*this);
7088 llvm::FoldingSetNodeID ID;
7089 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
Craig Topper36250ad2014-05-12 05:36:57 +00007090
7091 void *InsertPos = nullptr;
Douglas Gregor5590be02011-01-15 06:45:20 +00007092 SubstTemplateTemplateParmPackStorage *Subst
7093 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
7094
7095 if (!Subst) {
John McCalld9dfe3a2011-06-30 08:33:18 +00007096 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor5590be02011-01-15 06:45:20 +00007097 ArgPack.pack_size(),
7098 ArgPack.pack_begin());
7099 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
7100 }
7101
7102 return TemplateName(Subst);
7103}
7104
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00007105/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00007106/// TargetInfo, produce the corresponding type. The unsigned @p Type
7107/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00007108CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00007109 switch (Type) {
John McCall48f2d582009-10-23 23:03:21 +00007110 case TargetInfo::NoInt: return CanQualType();
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00007111 case TargetInfo::SignedChar: return SignedCharTy;
7112 case TargetInfo::UnsignedChar: return UnsignedCharTy;
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00007113 case TargetInfo::SignedShort: return ShortTy;
7114 case TargetInfo::UnsignedShort: return UnsignedShortTy;
7115 case TargetInfo::SignedInt: return IntTy;
7116 case TargetInfo::UnsignedInt: return UnsignedIntTy;
7117 case TargetInfo::SignedLong: return LongTy;
7118 case TargetInfo::UnsignedLong: return UnsignedLongTy;
7119 case TargetInfo::SignedLongLong: return LongLongTy;
7120 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
7121 }
7122
David Blaikie83d382b2011-09-23 05:06:16 +00007123 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00007124}
Ted Kremenek77c51b22008-07-24 23:58:27 +00007125
7126//===----------------------------------------------------------------------===//
7127// Type Predicates.
7128//===----------------------------------------------------------------------===//
7129
Fariborz Jahanian96207692009-02-18 21:49:28 +00007130/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
7131/// garbage collection attribute.
7132///
John McCall553d45a2011-01-12 00:34:59 +00007133Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00007134 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCall553d45a2011-01-12 00:34:59 +00007135 return Qualifiers::GCNone;
7136
David Blaikiebbafb8a2012-03-11 07:00:24 +00007137 assert(getLangOpts().ObjC1);
John McCall553d45a2011-01-12 00:34:59 +00007138 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
7139
7140 // Default behaviour under objective-C's gc is for ObjC pointers
7141 // (or pointers to them) be treated as though they were declared
7142 // as __strong.
7143 if (GCAttrs == Qualifiers::GCNone) {
7144 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
7145 return Qualifiers::Strong;
7146 else if (Ty->isPointerType())
7147 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
7148 } else {
7149 // It's not valid to set GC attributes on anything that isn't a
7150 // pointer.
7151#ifndef NDEBUG
7152 QualType CT = Ty->getCanonicalTypeInternal();
7153 while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
7154 CT = AT->getElementType();
7155 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
7156#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00007157 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00007158 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00007159}
7160
Chris Lattner49af6a42008-04-07 06:51:04 +00007161//===----------------------------------------------------------------------===//
7162// Type Compatibility Testing
7163//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00007164
Mike Stump11289f42009-09-09 15:08:12 +00007165/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00007166/// compatible.
7167static bool areCompatVectorTypes(const VectorType *LHS,
7168 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00007169 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00007170 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00007171 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00007172}
7173
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00007174bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
7175 QualType SecondVec) {
7176 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
7177 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
7178
7179 if (hasSameUnqualifiedType(FirstVec, SecondVec))
7180 return true;
7181
Bob Wilsone6aeebb2010-11-12 17:24:54 +00007182 // Treat Neon vector types and most AltiVec vector types as if they are the
7183 // equivalent GCC vector types.
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00007184 const VectorType *First = FirstVec->getAs<VectorType>();
7185 const VectorType *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00007186 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00007187 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00007188 First->getVectorKind() != VectorType::AltiVecPixel &&
7189 First->getVectorKind() != VectorType::AltiVecBool &&
7190 Second->getVectorKind() != VectorType::AltiVecPixel &&
7191 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00007192 return true;
7193
7194 return false;
7195}
7196
Steve Naroff8e6aee52009-07-23 01:01:38 +00007197//===----------------------------------------------------------------------===//
7198// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
7199//===----------------------------------------------------------------------===//
7200
7201/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
7202/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00007203bool
7204ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
7205 ObjCProtocolDecl *rProto) const {
Douglas Gregor33b24292012-01-01 18:09:12 +00007206 if (declaresSameEntity(lProto, rProto))
Steve Naroff8e6aee52009-07-23 01:01:38 +00007207 return true;
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00007208 for (auto *PI : rProto->protocols())
7209 if (ProtocolCompatibleWithProtocol(lProto, PI))
Steve Naroff8e6aee52009-07-23 01:01:38 +00007210 return true;
7211 return false;
7212}
7213
Dmitri Gribenko4364fcf2012-08-28 02:49:14 +00007214/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
7215/// Class<pr1, ...>.
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00007216bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
7217 QualType rhs) {
7218 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
7219 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
7220 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
7221
Aaron Ballman83731462014-03-17 16:14:00 +00007222 for (auto *lhsProto : lhsQID->quals()) {
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00007223 bool match = false;
Aaron Ballman83731462014-03-17 16:14:00 +00007224 for (auto *rhsProto : rhsOPT->quals()) {
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00007225 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
7226 match = true;
7227 break;
7228 }
7229 }
7230 if (!match)
7231 return false;
7232 }
7233 return true;
7234}
7235
Steve Naroff8e6aee52009-07-23 01:01:38 +00007236/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
7237/// ObjCQualifiedIDType.
7238bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
7239 bool compare) {
7240 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00007241 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00007242 lhs->isObjCIdType() || lhs->isObjCClassType())
7243 return true;
Mike Stump11289f42009-09-09 15:08:12 +00007244 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00007245 rhs->isObjCIdType() || rhs->isObjCClassType())
7246 return true;
7247
7248 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
John McCall9dd450b2009-09-21 23:43:11 +00007249 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00007250
Steve Naroff8e6aee52009-07-23 01:01:38 +00007251 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00007252
Steve Naroff8e6aee52009-07-23 01:01:38 +00007253 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00007254 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00007255 // make sure we check the class hierarchy.
7256 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
Aaron Ballman83731462014-03-17 16:14:00 +00007257 for (auto *I : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007258 // when comparing an id<P> on lhs with a static type on rhs,
7259 // see if static class implements all of id's protocols, directly or
7260 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00007261 if (!rhsID->ClassImplementsProtocol(I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00007262 return false;
7263 }
7264 }
7265 // If there are no qualifiers and no interface, we have an 'id'.
7266 return true;
7267 }
Mike Stump11289f42009-09-09 15:08:12 +00007268 // Both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00007269 for (auto *lhsProto : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007270 bool match = false;
7271
7272 // when comparing an id<P> on lhs with a static type on rhs,
7273 // see if static class implements all of id's protocols, directly or
7274 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00007275 for (auto *rhsProto : rhsOPT->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007276 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
7277 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
7278 match = true;
7279 break;
7280 }
7281 }
Mike Stump11289f42009-09-09 15:08:12 +00007282 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00007283 // make sure we check the class hierarchy.
7284 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
Aaron Ballman83731462014-03-17 16:14:00 +00007285 for (auto *I : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007286 // when comparing an id<P> on lhs with a static type on rhs,
7287 // see if static class implements all of id's protocols, directly or
7288 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00007289 if (rhsID->ClassImplementsProtocol(I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007290 match = true;
7291 break;
7292 }
7293 }
7294 }
7295 if (!match)
7296 return false;
7297 }
Mike Stump11289f42009-09-09 15:08:12 +00007298
Steve Naroff8e6aee52009-07-23 01:01:38 +00007299 return true;
7300 }
Mike Stump11289f42009-09-09 15:08:12 +00007301
Steve Naroff8e6aee52009-07-23 01:01:38 +00007302 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
7303 assert(rhsQID && "One of the LHS/RHS should be id<x>");
7304
Mike Stump11289f42009-09-09 15:08:12 +00007305 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00007306 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007307 // If both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00007308 for (auto *lhsProto : lhsOPT->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007309 bool match = false;
7310
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007311 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00007312 // see if static class implements all of id's protocols, directly or
7313 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007314 // First, lhs protocols in the qualifier list must be found, direct
7315 // or indirect in rhs's qualifier list or it is a mismatch.
Aaron Ballman83731462014-03-17 16:14:00 +00007316 for (auto *rhsProto : rhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007317 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
7318 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
7319 match = true;
7320 break;
7321 }
7322 }
7323 if (!match)
7324 return false;
7325 }
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007326
7327 // Static class's protocols, or its super class or category protocols
7328 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
7329 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
7330 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
7331 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
7332 // This is rather dubious but matches gcc's behavior. If lhs has
7333 // no type qualifier and its class has no static protocol(s)
7334 // assume that it is mismatch.
7335 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
7336 return false;
Aaron Ballman83731462014-03-17 16:14:00 +00007337 for (auto *lhsProto : LHSInheritedProtocols) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007338 bool match = false;
Aaron Ballman83731462014-03-17 16:14:00 +00007339 for (auto *rhsProto : rhsQID->quals()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007340 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
7341 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
7342 match = true;
7343 break;
7344 }
7345 }
7346 if (!match)
7347 return false;
7348 }
7349 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00007350 return true;
7351 }
7352 return false;
7353}
7354
Eli Friedman47f77112008-08-22 00:56:42 +00007355/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00007356/// compatible for assignment from RHS to LHS. This handles validation of any
7357/// protocol qualifiers on the LHS or RHS.
7358///
Steve Naroff7cae42b2009-07-10 23:34:53 +00007359bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
7360 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00007361 const ObjCObjectType* LHS = LHSOPT->getObjectType();
7362 const ObjCObjectType* RHS = RHSOPT->getObjectType();
7363
Steve Naroff1329fa02009-07-15 18:40:39 +00007364 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00007365 if (LHS->isObjCUnqualifiedIdOrClass() ||
7366 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00007367 return true;
7368
Douglas Gregorab209d82015-07-07 03:58:42 +00007369 // Function object that propagates a successful result or handles
7370 // __kindof types.
7371 auto finish = [&](bool succeeded) -> bool {
7372 if (succeeded)
7373 return true;
7374
7375 if (!RHS->isKindOfType())
7376 return false;
7377
7378 // Strip off __kindof and protocol qualifiers, then check whether
7379 // we can assign the other way.
7380 return canAssignObjCInterfaces(RHSOPT->stripObjCKindOfTypeAndQuals(*this),
7381 LHSOPT->stripObjCKindOfTypeAndQuals(*this));
7382 };
7383
7384 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) {
7385 return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
7386 QualType(RHSOPT,0),
7387 false));
7388 }
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00007389
Douglas Gregorab209d82015-07-07 03:58:42 +00007390 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) {
7391 return finish(ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
7392 QualType(RHSOPT,0)));
7393 }
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00007394
John McCall8b07ec22010-05-15 11:32:37 +00007395 // If we have 2 user-defined types, fall into that path.
Douglas Gregorab209d82015-07-07 03:58:42 +00007396 if (LHS->getInterface() && RHS->getInterface()) {
7397 return finish(canAssignObjCInterfaces(LHS, RHS));
7398 }
Mike Stump11289f42009-09-09 15:08:12 +00007399
Steve Naroff8e6aee52009-07-23 01:01:38 +00007400 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00007401}
7402
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007403/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Chris Lattner57540c52011-04-15 05:22:18 +00007404/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007405/// arguments in block literals. When passed as arguments, passing 'A*' where
7406/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
7407/// not OK. For the return type, the opposite is not OK.
7408bool ASTContext::canAssignObjCInterfacesInBlockPointer(
7409 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007410 const ObjCObjectPointerType *RHSOPT,
7411 bool BlockReturnType) {
Douglas Gregorab209d82015-07-07 03:58:42 +00007412
7413 // Function object that propagates a successful result or handles
7414 // __kindof types.
7415 auto finish = [&](bool succeeded) -> bool {
7416 if (succeeded)
7417 return true;
7418
7419 const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT;
7420 if (!Expected->isKindOfType())
7421 return false;
7422
7423 // Strip off __kindof and protocol qualifiers, then check whether
7424 // we can assign the other way.
7425 return canAssignObjCInterfacesInBlockPointer(
7426 RHSOPT->stripObjCKindOfTypeAndQuals(*this),
7427 LHSOPT->stripObjCKindOfTypeAndQuals(*this),
7428 BlockReturnType);
7429 };
7430
Fariborz Jahanian440a6832010-04-06 17:23:39 +00007431 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007432 return true;
7433
7434 if (LHSOPT->isObjCBuiltinType()) {
Douglas Gregorab209d82015-07-07 03:58:42 +00007435 return finish(RHSOPT->isObjCBuiltinType() ||
7436 RHSOPT->isObjCQualifiedIdType());
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007437 }
7438
Fariborz Jahanian440a6832010-04-06 17:23:39 +00007439 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Douglas Gregorab209d82015-07-07 03:58:42 +00007440 return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
7441 QualType(RHSOPT,0),
7442 false));
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007443
7444 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
7445 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
7446 if (LHS && RHS) { // We have 2 user-defined types.
7447 if (LHS != RHS) {
7448 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Douglas Gregorab209d82015-07-07 03:58:42 +00007449 return finish(BlockReturnType);
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007450 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Douglas Gregorab209d82015-07-07 03:58:42 +00007451 return finish(!BlockReturnType);
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007452 }
7453 else
7454 return true;
7455 }
7456 return false;
7457}
7458
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007459/// Comparison routine for Objective-C protocols to be used with
7460/// llvm::array_pod_sort.
7461static int compareObjCProtocolsByName(ObjCProtocolDecl * const *lhs,
7462 ObjCProtocolDecl * const *rhs) {
7463 return (*lhs)->getName().compare((*rhs)->getName());
7464
7465}
7466
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007467/// getIntersectionOfProtocols - This routine finds the intersection of set
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007468/// of protocols inherited from two distinct objective-c pointer objects with
7469/// the given common base.
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007470/// It is used to build composite qualifier list of the composite type of
7471/// the conditional expression involving two objective-c pointer objects.
7472static
7473void getIntersectionOfProtocols(ASTContext &Context,
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007474 const ObjCInterfaceDecl *CommonBase,
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007475 const ObjCObjectPointerType *LHSOPT,
7476 const ObjCObjectPointerType *RHSOPT,
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007477 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) {
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007478
John McCall8b07ec22010-05-15 11:32:37 +00007479 const ObjCObjectType* LHS = LHSOPT->getObjectType();
7480 const ObjCObjectType* RHS = RHSOPT->getObjectType();
7481 assert(LHS->getInterface() && "LHS must have an interface base");
7482 assert(RHS->getInterface() && "RHS must have an interface base");
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007483
7484 // Add all of the protocols for the LHS.
7485 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSProtocolSet;
7486
7487 // Start with the protocol qualifiers.
7488 for (auto proto : LHS->quals()) {
7489 Context.CollectInheritedProtocols(proto, LHSProtocolSet);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007490 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007491
7492 // Also add the protocols associated with the LHS interface.
7493 Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet);
7494
7495 // Add all of the protocls for the RHS.
7496 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSProtocolSet;
7497
7498 // Start with the protocol qualifiers.
7499 for (auto proto : RHS->quals()) {
7500 Context.CollectInheritedProtocols(proto, RHSProtocolSet);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007501 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007502
7503 // Also add the protocols associated with the RHS interface.
7504 Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet);
7505
7506 // Compute the intersection of the collected protocol sets.
7507 for (auto proto : LHSProtocolSet) {
7508 if (RHSProtocolSet.count(proto))
7509 IntersectionSet.push_back(proto);
7510 }
7511
7512 // Compute the set of protocols that is implied by either the common type or
7513 // the protocols within the intersection.
7514 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ImpliedProtocols;
7515 Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols);
7516
7517 // Remove any implied protocols from the list of inherited protocols.
7518 if (!ImpliedProtocols.empty()) {
7519 IntersectionSet.erase(
7520 std::remove_if(IntersectionSet.begin(),
7521 IntersectionSet.end(),
7522 [&](ObjCProtocolDecl *proto) -> bool {
7523 return ImpliedProtocols.count(proto) > 0;
7524 }),
7525 IntersectionSet.end());
7526 }
7527
7528 // Sort the remaining protocols by name.
7529 llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(),
7530 compareObjCProtocolsByName);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007531}
7532
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007533/// Determine whether the first type is a subtype of the second.
7534static bool canAssignObjCObjectTypes(ASTContext &ctx, QualType lhs,
7535 QualType rhs) {
7536 // Common case: two object pointers.
7537 const ObjCObjectPointerType *lhsOPT = lhs->getAs<ObjCObjectPointerType>();
7538 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
7539 if (lhsOPT && rhsOPT)
7540 return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT);
7541
7542 // Two block pointers.
7543 const BlockPointerType *lhsBlock = lhs->getAs<BlockPointerType>();
7544 const BlockPointerType *rhsBlock = rhs->getAs<BlockPointerType>();
7545 if (lhsBlock && rhsBlock)
7546 return ctx.typesAreBlockPointerCompatible(lhs, rhs);
7547
7548 // If either is an unqualified 'id' and the other is a block, it's
7549 // acceptable.
7550 if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) ||
7551 (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock))
7552 return true;
7553
7554 return false;
7555}
7556
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007557// Check that the given Objective-C type argument lists are equivalent.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007558static bool sameObjCTypeArgs(ASTContext &ctx,
7559 const ObjCInterfaceDecl *iface,
7560 ArrayRef<QualType> lhsArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00007561 ArrayRef<QualType> rhsArgs,
7562 bool stripKindOf) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007563 if (lhsArgs.size() != rhsArgs.size())
7564 return false;
7565
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007566 ObjCTypeParamList *typeParams = iface->getTypeParamList();
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007567 for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) {
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007568 if (ctx.hasSameType(lhsArgs[i], rhsArgs[i]))
7569 continue;
7570
7571 switch (typeParams->begin()[i]->getVariance()) {
7572 case ObjCTypeParamVariance::Invariant:
Douglas Gregorab209d82015-07-07 03:58:42 +00007573 if (!stripKindOf ||
7574 !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx),
7575 rhsArgs[i].stripObjCKindOfType(ctx))) {
7576 return false;
7577 }
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007578 break;
7579
7580 case ObjCTypeParamVariance::Covariant:
7581 if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i]))
7582 return false;
7583 break;
7584
7585 case ObjCTypeParamVariance::Contravariant:
7586 if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i]))
7587 return false;
7588 break;
Douglas Gregorab209d82015-07-07 03:58:42 +00007589 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007590 }
7591
7592 return true;
7593}
7594
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00007595QualType ASTContext::areCommonBaseCompatible(
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007596 const ObjCObjectPointerType *Lptr,
7597 const ObjCObjectPointerType *Rptr) {
John McCall8b07ec22010-05-15 11:32:37 +00007598 const ObjCObjectType *LHS = Lptr->getObjectType();
7599 const ObjCObjectType *RHS = Rptr->getObjectType();
7600 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
7601 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007602
7603 if (!LDecl || !RDecl)
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00007604 return QualType();
Douglas Gregore83b9562015-07-07 03:57:53 +00007605
Manman Renc46f7d12016-05-06 19:35:02 +00007606 // When either LHS or RHS is a kindof type, we should return a kindof type.
7607 // For example, for common base of kindof(ASub1) and kindof(ASub2), we return
7608 // kindof(A).
7609 bool anyKindOf = LHS->isKindOfType() || RHS->isKindOfType();
7610
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007611 // Follow the left-hand side up the class hierarchy until we either hit a
7612 // root or find the RHS. Record the ancestors in case we don't find it.
7613 llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4>
7614 LHSAncestors;
7615 while (true) {
7616 // Record this ancestor. We'll need this if the common type isn't in the
7617 // path from the LHS to the root.
7618 LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS;
Douglas Gregore83b9562015-07-07 03:57:53 +00007619
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007620 if (declaresSameEntity(LHS->getInterface(), RDecl)) {
7621 // Get the type arguments.
7622 ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten();
7623 bool anyChanges = false;
7624 if (LHS->isSpecialized() && RHS->isSpecialized()) {
7625 // Both have type arguments, compare them.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007626 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
7627 LHS->getTypeArgs(), RHS->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00007628 /*stripKindOf=*/true))
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007629 return QualType();
7630 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
7631 // If only one has type arguments, the result will not have type
7632 // arguments.
7633 LHSTypeArgs = { };
7634 anyChanges = true;
7635 }
7636
7637 // Compute the intersection of protocols.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007638 SmallVector<ObjCProtocolDecl *, 8> Protocols;
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007639 getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr,
7640 Protocols);
John McCall8b07ec22010-05-15 11:32:37 +00007641 if (!Protocols.empty())
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007642 anyChanges = true;
7643
7644 // If anything in the LHS will have changed, build a new result type.
Manman Renc46f7d12016-05-06 19:35:02 +00007645 // If we need to return a kindof type but LHS is not a kindof type, we
7646 // build a new result type.
7647 if (anyChanges || LHS->isKindOfType() != anyKindOf) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007648 QualType Result = getObjCInterfaceType(LHS->getInterface());
Douglas Gregorab209d82015-07-07 03:58:42 +00007649 Result = getObjCObjectType(Result, LHSTypeArgs, Protocols,
Manman Renc46f7d12016-05-06 19:35:02 +00007650 anyKindOf || LHS->isKindOfType());
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007651 return getObjCObjectPointerType(Result);
7652 }
7653
7654 return getObjCObjectPointerType(QualType(LHS, 0));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00007655 }
Douglas Gregore83b9562015-07-07 03:57:53 +00007656
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007657 // Find the superclass.
Douglas Gregore83b9562015-07-07 03:57:53 +00007658 QualType LHSSuperType = LHS->getSuperClassType();
7659 if (LHSSuperType.isNull())
7660 break;
7661
7662 LHS = LHSSuperType->castAs<ObjCObjectType>();
7663 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007664
7665 // We didn't find anything by following the LHS to its root; now check
7666 // the RHS against the cached set of ancestors.
7667 while (true) {
7668 auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl());
7669 if (KnownLHS != LHSAncestors.end()) {
7670 LHS = KnownLHS->second;
7671
7672 // Get the type arguments.
7673 ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten();
7674 bool anyChanges = false;
7675 if (LHS->isSpecialized() && RHS->isSpecialized()) {
7676 // Both have type arguments, compare them.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007677 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
7678 LHS->getTypeArgs(), RHS->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00007679 /*stripKindOf=*/true))
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007680 return QualType();
7681 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
7682 // If only one has type arguments, the result will not have type
7683 // arguments.
7684 RHSTypeArgs = { };
7685 anyChanges = true;
7686 }
7687
7688 // Compute the intersection of protocols.
7689 SmallVector<ObjCProtocolDecl *, 8> Protocols;
7690 getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr,
7691 Protocols);
7692 if (!Protocols.empty())
7693 anyChanges = true;
7694
Manman Renc46f7d12016-05-06 19:35:02 +00007695 // If we need to return a kindof type but RHS is not a kindof type, we
7696 // build a new result type.
7697 if (anyChanges || RHS->isKindOfType() != anyKindOf) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007698 QualType Result = getObjCInterfaceType(RHS->getInterface());
Douglas Gregorab209d82015-07-07 03:58:42 +00007699 Result = getObjCObjectType(Result, RHSTypeArgs, Protocols,
Manman Renc46f7d12016-05-06 19:35:02 +00007700 anyKindOf || RHS->isKindOfType());
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007701 return getObjCObjectPointerType(Result);
7702 }
7703
7704 return getObjCObjectPointerType(QualType(RHS, 0));
7705 }
7706
7707 // Find the superclass of the RHS.
7708 QualType RHSSuperType = RHS->getSuperClassType();
7709 if (RHSSuperType.isNull())
7710 break;
7711
7712 RHS = RHSSuperType->castAs<ObjCObjectType>();
7713 }
7714
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00007715 return QualType();
7716}
7717
John McCall8b07ec22010-05-15 11:32:37 +00007718bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
7719 const ObjCObjectType *RHS) {
7720 assert(LHS->getInterface() && "LHS is not an interface type");
7721 assert(RHS->getInterface() && "RHS is not an interface type");
7722
Chris Lattner49af6a42008-04-07 06:51:04 +00007723 // Verify that the base decls are compatible: the RHS must be a subclass of
7724 // the LHS.
Douglas Gregore83b9562015-07-07 03:57:53 +00007725 ObjCInterfaceDecl *LHSInterface = LHS->getInterface();
7726 bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface());
7727 if (!IsSuperClass)
Chris Lattner49af6a42008-04-07 06:51:04 +00007728 return false;
Mike Stump11289f42009-09-09 15:08:12 +00007729
Douglas Gregore83b9562015-07-07 03:57:53 +00007730 // If the LHS has protocol qualifiers, determine whether all of them are
7731 // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the
7732 // LHS).
7733 if (LHS->getNumProtocols() > 0) {
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00007734 // OK if conversion of LHS to SuperClass results in narrowing of types
7735 // ; i.e., SuperClass may implement at least one of the protocols
7736 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
7737 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
7738 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
7739 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
7740 // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
7741 // qualifiers.
7742 for (auto *RHSPI : RHS->quals())
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007743 CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols);
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00007744 // If there is no protocols associated with RHS, it is not a match.
7745 if (SuperClassInheritedProtocols.empty())
Steve Naroff114aecb2009-03-01 16:12:44 +00007746 return false;
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00007747
7748 for (const auto *LHSProto : LHS->quals()) {
7749 bool SuperImplementsProtocol = false;
7750 for (auto *SuperClassProto : SuperClassInheritedProtocols)
7751 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
7752 SuperImplementsProtocol = true;
7753 break;
7754 }
7755 if (!SuperImplementsProtocol)
7756 return false;
7757 }
Chris Lattner49af6a42008-04-07 06:51:04 +00007758 }
Douglas Gregore83b9562015-07-07 03:57:53 +00007759
7760 // If the LHS is specialized, we may need to check type arguments.
7761 if (LHS->isSpecialized()) {
7762 // Follow the superclass chain until we've matched the LHS class in the
7763 // hierarchy. This substitutes type arguments through.
7764 const ObjCObjectType *RHSSuper = RHS;
7765 while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface))
7766 RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>();
7767
7768 // If the RHS is specializd, compare type arguments.
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007769 if (RHSSuper->isSpecialized() &&
Douglas Gregor1ac1b632015-07-07 03:58:54 +00007770 !sameObjCTypeArgs(*this, LHS->getInterface(),
7771 LHS->getTypeArgs(), RHSSuper->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00007772 /*stripKindOf=*/true)) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00007773 return false;
Douglas Gregore83b9562015-07-07 03:57:53 +00007774 }
7775 }
7776
7777 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00007778}
7779
Steve Naroffb7605152009-02-12 17:52:19 +00007780bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
7781 // get the "pointed to" types
John McCall9dd450b2009-09-21 23:43:11 +00007782 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
7783 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00007784
Steve Naroff7cae42b2009-07-10 23:34:53 +00007785 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00007786 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00007787
7788 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
7789 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00007790}
7791
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00007792bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
7793 return canAssignObjCInterfaces(
7794 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
7795 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
7796}
7797
Mike Stump11289f42009-09-09 15:08:12 +00007798/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00007799/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00007800/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00007801/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007802bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
7803 bool CompareUnqualified) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00007804 if (getLangOpts().CPlusPlus)
Douglas Gregor21e771e2010-02-03 21:02:30 +00007805 return hasSameType(LHS, RHS);
Joey Gouly5788b782016-11-18 14:10:54 +00007806
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007807 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00007808}
7809
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00007810bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanianc87c8792011-07-12 23:20:13 +00007811 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00007812}
7813
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007814bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
7815 return !mergeTypes(LHS, RHS, true).isNull();
7816}
7817
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00007818/// mergeTransparentUnionType - if T is a transparent union type and a member
7819/// of T is compatible with SubType, return the merged type, else return
7820/// QualType()
7821QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
7822 bool OfBlockPointer,
7823 bool Unqualified) {
7824 if (const RecordType *UT = T->getAsUnionType()) {
7825 RecordDecl *UD = UT->getDecl();
7826 if (UD->hasAttr<TransparentUnionAttr>()) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007827 for (const auto *I : UD->fields()) {
7828 QualType ET = I->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00007829 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
7830 if (!MT.isNull())
7831 return MT;
7832 }
7833 }
7834 }
7835
7836 return QualType();
7837}
7838
Alp Toker9cacbab2014-01-20 20:26:09 +00007839/// mergeFunctionParameterTypes - merge two types which appear as function
7840/// parameter types
7841QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs,
7842 bool OfBlockPointer,
7843 bool Unqualified) {
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00007844 // GNU extension: two types are compatible if they appear as a function
7845 // argument, one of the types is a transparent union type and the other
7846 // type is compatible with a union member
7847 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
7848 Unqualified);
7849 if (!lmerge.isNull())
7850 return lmerge;
7851
7852 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
7853 Unqualified);
7854 if (!rmerge.isNull())
7855 return rmerge;
7856
7857 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
7858}
7859
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007860QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007861 bool OfBlockPointer,
7862 bool Unqualified) {
John McCall9dd450b2009-09-21 23:43:11 +00007863 const FunctionType *lbase = lhs->getAs<FunctionType>();
7864 const FunctionType *rbase = rhs->getAs<FunctionType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007865 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
7866 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00007867 bool allLTypes = true;
7868 bool allRTypes = true;
7869
7870 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007871 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00007872 if (OfBlockPointer) {
Alp Toker314cc812014-01-25 16:55:45 +00007873 QualType RHS = rbase->getReturnType();
7874 QualType LHS = lbase->getReturnType();
Fariborz Jahanian17825972011-02-11 18:46:17 +00007875 bool UnqualifiedResult = Unqualified;
7876 if (!UnqualifiedResult)
7877 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007878 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahanian17825972011-02-11 18:46:17 +00007879 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007880 else
Alp Toker314cc812014-01-25 16:55:45 +00007881 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
John McCall8c6b56f2010-12-15 01:06:38 +00007882 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00007883 if (retType.isNull()) return QualType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007884
7885 if (Unqualified)
7886 retType = retType.getUnqualifiedType();
7887
Alp Toker314cc812014-01-25 16:55:45 +00007888 CanQualType LRetType = getCanonicalType(lbase->getReturnType());
7889 CanQualType RRetType = getCanonicalType(rbase->getReturnType());
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007890 if (Unqualified) {
7891 LRetType = LRetType.getUnqualifiedType();
7892 RRetType = RRetType.getUnqualifiedType();
7893 }
7894
7895 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00007896 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007897 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00007898 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00007899
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00007900 // FIXME: double check this
7901 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
7902 // rbase->getRegParmAttr() != 0 &&
7903 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00007904 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
7905 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00007906
Douglas Gregor8c940862010-01-18 17:14:39 +00007907 // Compatible functions must have compatible calling conventions
Reid Kleckner78af0702013-08-27 23:08:25 +00007908 if (lbaseInfo.getCC() != rbaseInfo.getCC())
Douglas Gregor8c940862010-01-18 17:14:39 +00007909 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00007910
John McCall8c6b56f2010-12-15 01:06:38 +00007911 // Regparm is part of the calling convention.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00007912 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
7913 return QualType();
John McCall8c6b56f2010-12-15 01:06:38 +00007914 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
7915 return QualType();
7916
John McCall31168b02011-06-15 23:02:42 +00007917 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
7918 return QualType();
7919
John McCall8c6b56f2010-12-15 01:06:38 +00007920 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
7921 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8c6b56f2010-12-15 01:06:38 +00007922
Rafael Espindola8778c282012-11-29 16:09:03 +00007923 if (lbaseInfo.getNoReturn() != NoReturn)
7924 allLTypes = false;
7925 if (rbaseInfo.getNoReturn() != NoReturn)
7926 allRTypes = false;
7927
John McCall31168b02011-06-15 23:02:42 +00007928 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00007929
Eli Friedman47f77112008-08-22 00:56:42 +00007930 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00007931 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
7932 "C++ shouldn't be here");
Alp Toker601b22c2014-01-21 23:35:24 +00007933 // Compatible functions must have the same number of parameters
7934 if (lproto->getNumParams() != rproto->getNumParams())
Eli Friedman47f77112008-08-22 00:56:42 +00007935 return QualType();
7936
7937 // Variadic and non-variadic functions aren't compatible
7938 if (lproto->isVariadic() != rproto->isVariadic())
7939 return QualType();
7940
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00007941 if (lproto->getTypeQuals() != rproto->getTypeQuals())
7942 return QualType();
7943
John McCall18afab72016-03-01 00:49:02 +00007944 if (!doFunctionTypesMatchOnExtParameterInfos(rproto, lproto))
Fariborz Jahanian97676972011-09-28 21:52:05 +00007945 return QualType();
Alp Toker601b22c2014-01-21 23:35:24 +00007946
7947 // Check parameter type compatibility
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007948 SmallVector<QualType, 10> types;
Alp Toker601b22c2014-01-21 23:35:24 +00007949 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
7950 QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
7951 QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
7952 QualType paramType = mergeFunctionParameterTypes(
7953 lParamType, rParamType, OfBlockPointer, Unqualified);
7954 if (paramType.isNull())
7955 return QualType();
7956
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007957 if (Unqualified)
Alp Toker601b22c2014-01-21 23:35:24 +00007958 paramType = paramType.getUnqualifiedType();
7959
7960 types.push_back(paramType);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007961 if (Unqualified) {
Alp Toker601b22c2014-01-21 23:35:24 +00007962 lParamType = lParamType.getUnqualifiedType();
7963 rParamType = rParamType.getUnqualifiedType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00007964 }
Alp Toker601b22c2014-01-21 23:35:24 +00007965
7966 if (getCanonicalType(paramType) != getCanonicalType(lParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00007967 allLTypes = false;
Alp Toker601b22c2014-01-21 23:35:24 +00007968 if (getCanonicalType(paramType) != getCanonicalType(rParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00007969 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00007970 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00007971
Eli Friedman47f77112008-08-22 00:56:42 +00007972 if (allLTypes) return lhs;
7973 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00007974
7975 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
7976 EPI.ExtInfo = einfo;
Jordan Rose5c382722013-03-08 21:51:21 +00007977 return getFunctionType(retType, types, EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00007978 }
7979
7980 if (lproto) allRTypes = false;
7981 if (rproto) allLTypes = false;
7982
Douglas Gregordeaad8c2009-02-26 23:50:07 +00007983 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00007984 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00007985 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eli Friedman47f77112008-08-22 00:56:42 +00007986 if (proto->isVariadic()) return QualType();
7987 // Check that the types are compatible with the types that
7988 // would result from default argument promotions (C99 6.7.5.3p15).
7989 // The only types actually affected are promotable integer
7990 // types and floats, which would be passed as a different
7991 // type depending on whether the prototype is visible.
Alp Toker601b22c2014-01-21 23:35:24 +00007992 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
7993 QualType paramTy = proto->getParamType(i);
Alp Toker9cacbab2014-01-20 20:26:09 +00007994
Eli Friedman448ce402012-08-30 00:44:15 +00007995 // Look at the converted type of enum types, since that is the type used
Douglas Gregor2973d402010-02-03 19:27:29 +00007996 // to pass enum values.
Alp Toker601b22c2014-01-21 23:35:24 +00007997 if (const EnumType *Enum = paramTy->getAs<EnumType>()) {
7998 paramTy = Enum->getDecl()->getIntegerType();
7999 if (paramTy.isNull())
Eli Friedman448ce402012-08-30 00:44:15 +00008000 return QualType();
8001 }
Alp Toker601b22c2014-01-21 23:35:24 +00008002
8003 if (paramTy->isPromotableIntegerType() ||
8004 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
Eli Friedman47f77112008-08-22 00:56:42 +00008005 return QualType();
8006 }
8007
8008 if (allLTypes) return lhs;
8009 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00008010
8011 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
8012 EPI.ExtInfo = einfo;
Alp Toker9cacbab2014-01-20 20:26:09 +00008013 return getFunctionType(retType, proto->getParamTypes(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00008014 }
8015
8016 if (allLTypes) return lhs;
8017 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00008018 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00008019}
8020
John McCall433c2e62013-03-21 00:10:07 +00008021/// Given that we have an enum type and a non-enum type, try to merge them.
8022static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
8023 QualType other, bool isBlockReturnType) {
8024 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
8025 // a signed integer type, or an unsigned integer type.
8026 // Compatibility is based on the underlying type, not the promotion
8027 // type.
8028 QualType underlyingType = ET->getDecl()->getIntegerType();
8029 if (underlyingType.isNull()) return QualType();
8030 if (Context.hasSameType(underlyingType, other))
8031 return other;
8032
8033 // In block return types, we're more permissive and accept any
8034 // integral type of the same size.
8035 if (isBlockReturnType && other->isIntegerType() &&
8036 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
8037 return other;
8038
8039 return QualType();
8040}
8041
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008042QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008043 bool OfBlockPointer,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00008044 bool Unqualified, bool BlockReturnType) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00008045 // C++ [expr]: If an expression initially has the type "reference to T", the
8046 // type is adjusted to "T" prior to any further analysis, the expression
8047 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00008048 // expression is an lvalue unless the reference is an rvalue reference and
8049 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00008050 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
8051 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008052
8053 if (Unqualified) {
8054 LHS = LHS.getUnqualifiedType();
8055 RHS = RHS.getUnqualifiedType();
8056 }
Douglas Gregor21e771e2010-02-03 21:02:30 +00008057
Eli Friedman47f77112008-08-22 00:56:42 +00008058 QualType LHSCan = getCanonicalType(LHS),
8059 RHSCan = getCanonicalType(RHS);
8060
8061 // If two types are identical, they are compatible.
8062 if (LHSCan == RHSCan)
8063 return LHS;
8064
John McCall8ccfcb52009-09-24 19:53:00 +00008065 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00008066 Qualifiers LQuals = LHSCan.getLocalQualifiers();
8067 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00008068 if (LQuals != RQuals) {
8069 // If any of these qualifiers are different, we have a type
8070 // mismatch.
8071 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCall31168b02011-06-15 23:02:42 +00008072 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
Roger Ferrer Ibanezd93add32017-02-24 08:41:09 +00008073 LQuals.getObjCLifetime() != RQuals.getObjCLifetime() ||
8074 LQuals.hasUnaligned() != RQuals.hasUnaligned())
John McCall8ccfcb52009-09-24 19:53:00 +00008075 return QualType();
8076
8077 // Exactly one GC qualifier difference is allowed: __strong is
8078 // okay if the other type has no GC qualifier but is an Objective
8079 // C object pointer (i.e. implicitly strong by default). We fix
8080 // this by pretending that the unqualified type was actually
8081 // qualified __strong.
8082 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
8083 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
8084 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
8085
8086 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
8087 return QualType();
8088
8089 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
8090 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
8091 }
8092 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
8093 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
8094 }
Eli Friedman47f77112008-08-22 00:56:42 +00008095 return QualType();
John McCall8ccfcb52009-09-24 19:53:00 +00008096 }
8097
8098 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00008099
Eli Friedmandcca6332009-06-01 01:22:52 +00008100 Type::TypeClass LHSClass = LHSCan->getTypeClass();
8101 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00008102
Chris Lattnerfd652912008-01-14 05:45:46 +00008103 // We want to consider the two function types to be the same for these
8104 // comparisons, just force one to the other.
8105 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
8106 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00008107
8108 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00008109 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
8110 LHSClass = Type::ConstantArray;
8111 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
8112 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00008113
John McCall8b07ec22010-05-15 11:32:37 +00008114 // ObjCInterfaces are just specialized ObjCObjects.
8115 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
8116 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
8117
Nate Begemance4d7fc2008-04-18 23:10:10 +00008118 // Canonicalize ExtVector -> Vector.
8119 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
8120 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00008121
Chris Lattner95554662008-04-07 05:43:21 +00008122 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00008123 if (LHSClass != RHSClass) {
John McCall433c2e62013-03-21 00:10:07 +00008124 // Note that we only have special rules for turning block enum
8125 // returns into block int returns, not vice-versa.
John McCall9dd450b2009-09-21 23:43:11 +00008126 if (const EnumType* ETy = LHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00008127 return mergeEnumWithInteger(*this, ETy, RHS, false);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00008128 }
John McCall9dd450b2009-09-21 23:43:11 +00008129 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00008130 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00008131 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00008132 // allow block pointer type to match an 'id' type.
Fariborz Jahanian194904e2012-01-26 17:08:50 +00008133 if (OfBlockPointer && !BlockReturnType) {
8134 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
8135 return LHS;
8136 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
8137 return RHS;
8138 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00008139
Eli Friedman47f77112008-08-22 00:56:42 +00008140 return QualType();
Steve Naroff32e44c02007-10-15 20:41:53 +00008141 }
Eli Friedman47f77112008-08-22 00:56:42 +00008142
Steve Naroffc6edcbd2008-01-09 22:43:08 +00008143 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00008144 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008145#define TYPE(Class, Base)
8146#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00008147#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008148#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
8149#define DEPENDENT_TYPE(Class, Base) case Type::Class:
8150#include "clang/AST/TypeNodes.def"
David Blaikie83d382b2011-09-23 05:06:16 +00008151 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008152
Richard Smith27d807c2013-04-30 13:56:41 +00008153 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00008154 case Type::DeducedTemplateSpecialization:
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00008155 case Type::LValueReference:
8156 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008157 case Type::MemberPointer:
David Blaikie83d382b2011-09-23 05:06:16 +00008158 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008159
John McCall8b07ec22010-05-15 11:32:37 +00008160 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008161 case Type::IncompleteArray:
8162 case Type::VariableArray:
8163 case Type::FunctionProto:
8164 case Type::ExtVector:
David Blaikie83d382b2011-09-23 05:06:16 +00008165 llvm_unreachable("Types are eliminated above");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008166
Chris Lattnerfd652912008-01-14 05:45:46 +00008167 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00008168 {
8169 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00008170 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
8171 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008172 if (Unqualified) {
8173 LHSPointee = LHSPointee.getUnqualifiedType();
8174 RHSPointee = RHSPointee.getUnqualifiedType();
8175 }
8176 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
8177 Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00008178 if (ResultType.isNull()) return QualType();
Eli Friedman091a9ac2009-06-02 05:28:56 +00008179 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00008180 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00008181 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00008182 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00008183 return getPointerType(ResultType);
8184 }
Steve Naroff68e167d2008-12-10 17:49:55 +00008185 case Type::BlockPointer:
8186 {
8187 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00008188 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
8189 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008190 if (Unqualified) {
8191 LHSPointee = LHSPointee.getUnqualifiedType();
8192 RHSPointee = RHSPointee.getUnqualifiedType();
8193 }
Anastasia Stulova81a25e352017-03-10 15:23:07 +00008194 if (getLangOpts().OpenCL) {
8195 Qualifiers LHSPteeQual = LHSPointee.getQualifiers();
8196 Qualifiers RHSPteeQual = RHSPointee.getQualifiers();
8197 // Blocks can't be an expression in a ternary operator (OpenCL v2.0
8198 // 6.12.5) thus the following check is asymmetric.
8199 if (!LHSPteeQual.isAddressSpaceSupersetOf(RHSPteeQual))
8200 return QualType();
8201 LHSPteeQual.removeAddressSpace();
8202 RHSPteeQual.removeAddressSpace();
8203 LHSPointee =
8204 QualType(LHSPointee.getTypePtr(), LHSPteeQual.getAsOpaqueValue());
8205 RHSPointee =
8206 QualType(RHSPointee.getTypePtr(), RHSPteeQual.getAsOpaqueValue());
8207 }
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008208 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
8209 Unqualified);
Steve Naroff68e167d2008-12-10 17:49:55 +00008210 if (ResultType.isNull()) return QualType();
8211 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
8212 return LHS;
8213 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
8214 return RHS;
8215 return getBlockPointerType(ResultType);
8216 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00008217 case Type::Atomic:
8218 {
8219 // Merge two pointer types, while trying to preserve typedef info
8220 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
8221 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
8222 if (Unqualified) {
8223 LHSValue = LHSValue.getUnqualifiedType();
8224 RHSValue = RHSValue.getUnqualifiedType();
8225 }
8226 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
8227 Unqualified);
8228 if (ResultType.isNull()) return QualType();
8229 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
8230 return LHS;
8231 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
8232 return RHS;
8233 return getAtomicType(ResultType);
8234 }
Chris Lattnerfd652912008-01-14 05:45:46 +00008235 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00008236 {
8237 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
8238 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
8239 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
8240 return QualType();
8241
8242 QualType LHSElem = getAsArrayType(LHS)->getElementType();
8243 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008244 if (Unqualified) {
8245 LHSElem = LHSElem.getUnqualifiedType();
8246 RHSElem = RHSElem.getUnqualifiedType();
8247 }
8248
8249 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eli Friedman47f77112008-08-22 00:56:42 +00008250 if (ResultType.isNull()) return QualType();
Chris Lattner465fa322008-10-05 17:34:18 +00008251 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
8252 return LHS;
8253 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
8254 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00008255 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
8256 ArrayType::ArraySizeModifier(), 0);
8257 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
8258 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00008259 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
8260 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
Chris Lattner465fa322008-10-05 17:34:18 +00008261 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
8262 return LHS;
8263 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
8264 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00008265 if (LVAT) {
8266 // FIXME: This isn't correct! But tricky to implement because
8267 // the array's size has to be the size of LHS, but the type
8268 // has to be different.
8269 return LHS;
8270 }
8271 if (RVAT) {
8272 // FIXME: This isn't correct! But tricky to implement because
8273 // the array's size has to be the size of RHS, but the type
8274 // has to be different.
8275 return RHS;
8276 }
Eli Friedman3e62c212008-08-22 01:48:21 +00008277 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
8278 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00008279 return getIncompleteArrayType(ResultType,
8280 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00008281 }
Chris Lattnerfd652912008-01-14 05:45:46 +00008282 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008283 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008284 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008285 case Type::Enum:
Eli Friedman47f77112008-08-22 00:56:42 +00008286 return QualType();
Chris Lattnerfd652912008-01-14 05:45:46 +00008287 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00008288 // Only exactly equal builtin types are compatible, which is tested above.
Eli Friedman47f77112008-08-22 00:56:42 +00008289 return QualType();
Daniel Dunbar804c0442009-01-28 21:22:12 +00008290 case Type::Complex:
8291 // Distinct complex types are incompatible.
8292 return QualType();
Chris Lattner7bbd3d72008-04-07 05:55:38 +00008293 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00008294 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00008295 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
8296 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00008297 return LHS;
Chris Lattner465fa322008-10-05 17:34:18 +00008298 return QualType();
John McCall8b07ec22010-05-15 11:32:37 +00008299 case Type::ObjCObject: {
8300 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00008301 // FIXME: This should be type compatibility, e.g. whether
8302 // "LHS x; RHS x;" at global scope is legal.
John McCall8b07ec22010-05-15 11:32:37 +00008303 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
8304 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
8305 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00008306 return LHS;
8307
Eli Friedman47f77112008-08-22 00:56:42 +00008308 return QualType();
Cedric Venet4fc88b72009-02-21 17:14:49 +00008309 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00008310 case Type::ObjCObjectPointer: {
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008311 if (OfBlockPointer) {
8312 if (canAssignObjCInterfacesInBlockPointer(
8313 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahanian90186f82011-03-14 16:07:00 +00008314 RHS->getAs<ObjCObjectPointerType>(),
8315 BlockReturnType))
David Blaikie8a40f702012-01-17 06:56:22 +00008316 return LHS;
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008317 return QualType();
8318 }
John McCall9dd450b2009-09-21 23:43:11 +00008319 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
8320 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00008321 return LHS;
8322
Steve Naroffc68cfcf2008-12-10 22:14:21 +00008323 return QualType();
David Blaikie8a40f702012-01-17 06:56:22 +00008324 }
Xiuli Pan9c14e282016-01-09 12:53:17 +00008325 case Type::Pipe:
8326 {
Joey Goulye3c85de2016-12-01 11:30:49 +00008327 assert(LHS != RHS &&
8328 "Equivalent pipe types should have already been handled!");
8329 return QualType();
Xiuli Pan9c14e282016-01-09 12:53:17 +00008330 }
Steve Naroff32e44c02007-10-15 20:41:53 +00008331 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008332
David Blaikie8a40f702012-01-17 06:56:22 +00008333 llvm_unreachable("Invalid Type::Class!");
Steve Naroff32e44c02007-10-15 20:41:53 +00008334}
Ted Kremenekfc581a92007-10-31 17:10:13 +00008335
John McCall18afab72016-03-01 00:49:02 +00008336bool ASTContext::doFunctionTypesMatchOnExtParameterInfos(
8337 const FunctionProtoType *firstFnType,
8338 const FunctionProtoType *secondFnType) {
8339 // Fast path: if the first type doesn't have ext parameter infos,
8340 // we match if and only if they second type also doesn't have them.
8341 if (!firstFnType->hasExtParameterInfos())
8342 return !secondFnType->hasExtParameterInfos();
8343
8344 // Otherwise, we can only match if the second type has them.
8345 if (!secondFnType->hasExtParameterInfos())
Fariborz Jahanian97676972011-09-28 21:52:05 +00008346 return false;
John McCall18afab72016-03-01 00:49:02 +00008347
8348 auto firstEPI = firstFnType->getExtParameterInfos();
8349 auto secondEPI = secondFnType->getExtParameterInfos();
8350 assert(firstEPI.size() == secondEPI.size());
8351
8352 for (size_t i = 0, n = firstEPI.size(); i != n; ++i) {
8353 if (firstEPI[i] != secondEPI[i])
8354 return false;
8355 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00008356 return true;
8357}
8358
Chandler Carruth21c90602015-12-30 03:24:14 +00008359void ASTContext::ResetObjCLayout(const ObjCContainerDecl *CD) {
8360 ObjCLayouts[CD] = nullptr;
8361}
8362
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00008363/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
8364/// 'RHS' attributes and returns the merged version; including for function
8365/// return types.
8366QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
8367 QualType LHSCan = getCanonicalType(LHS),
8368 RHSCan = getCanonicalType(RHS);
8369 // If two types are identical, they are compatible.
8370 if (LHSCan == RHSCan)
8371 return LHS;
8372 if (RHSCan->isFunctionType()) {
8373 if (!LHSCan->isFunctionType())
8374 return QualType();
Alp Toker314cc812014-01-25 16:55:45 +00008375 QualType OldReturnType =
8376 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00008377 QualType NewReturnType =
Alp Toker314cc812014-01-25 16:55:45 +00008378 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00008379 QualType ResReturnType =
8380 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
8381 if (ResReturnType.isNull())
8382 return QualType();
8383 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
8384 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
8385 // In either case, use OldReturnType to build the new function type.
8386 const FunctionType *F = LHS->getAs<FunctionType>();
8387 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00008388 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8389 EPI.ExtInfo = getFunctionExtInfo(LHS);
Reid Kleckner896b32f2013-06-10 20:51:09 +00008390 QualType ResultType =
Alp Toker9cacbab2014-01-20 20:26:09 +00008391 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00008392 return ResultType;
8393 }
8394 }
8395 return QualType();
8396 }
8397
8398 // If the qualifiers are different, the types can still be merged.
8399 Qualifiers LQuals = LHSCan.getLocalQualifiers();
8400 Qualifiers RQuals = RHSCan.getLocalQualifiers();
8401 if (LQuals != RQuals) {
8402 // If any of these qualifiers are different, we have a type mismatch.
8403 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
8404 LQuals.getAddressSpace() != RQuals.getAddressSpace())
8405 return QualType();
8406
8407 // Exactly one GC qualifier difference is allowed: __strong is
8408 // okay if the other type has no GC qualifier but is an Objective
8409 // C object pointer (i.e. implicitly strong by default). We fix
8410 // this by pretending that the unqualified type was actually
8411 // qualified __strong.
8412 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
8413 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
8414 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
8415
8416 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
8417 return QualType();
8418
8419 if (GC_L == Qualifiers::Strong)
8420 return LHS;
8421 if (GC_R == Qualifiers::Strong)
8422 return RHS;
8423 return QualType();
8424 }
8425
8426 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
8427 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
8428 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
8429 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
8430 if (ResQT == LHSBaseQT)
8431 return LHS;
8432 if (ResQT == RHSBaseQT)
8433 return RHS;
8434 }
8435 return QualType();
8436}
8437
Chris Lattner4ba0cef2008-04-07 07:01:58 +00008438//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008439// Integer Predicates
8440//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00008441
Jay Foad39c79802011-01-12 09:06:06 +00008442unsigned ASTContext::getIntWidth(QualType T) const {
Richard Smithe9521062013-10-15 04:56:17 +00008443 if (const EnumType *ET = T->getAs<EnumType>())
Eli Friedmanee275c82009-12-10 22:29:29 +00008444 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00008445 if (T->isBooleanType())
8446 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00008447 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008448 return (unsigned)getTypeSize(T);
8449}
8450
Abramo Bagnara13640492012-09-09 10:21:24 +00008451QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00008452 assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
Chris Lattnerec3a1562009-10-17 20:33:28 +00008453
8454 // Turn <4 x signed int> -> <4 x unsigned int>
8455 if (const VectorType *VTy = T->getAs<VectorType>())
8456 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00008457 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00008458
8459 // For enums, we return the unsigned version of the base type.
8460 if (const EnumType *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008461 T = ETy->getDecl()->getIntegerType();
Chris Lattnerec3a1562009-10-17 20:33:28 +00008462
8463 const BuiltinType *BTy = T->getAs<BuiltinType>();
8464 assert(BTy && "Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008465 switch (BTy->getKind()) {
8466 case BuiltinType::Char_S:
8467 case BuiltinType::SChar:
8468 return UnsignedCharTy;
8469 case BuiltinType::Short:
8470 return UnsignedShortTy;
8471 case BuiltinType::Int:
8472 return UnsignedIntTy;
8473 case BuiltinType::Long:
8474 return UnsignedLongTy;
8475 case BuiltinType::LongLong:
8476 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00008477 case BuiltinType::Int128:
8478 return UnsignedInt128Ty;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008479 default:
David Blaikie83d382b2011-09-23 05:06:16 +00008480 llvm_unreachable("Unexpected signed integer type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00008481 }
8482}
8483
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +00008484ASTMutationListener::~ASTMutationListener() { }
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00008485
Richard Smith1fa5d642013-05-11 05:45:24 +00008486void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
8487 QualType ReturnType) {}
Chris Lattnerecd79c62009-06-14 00:45:47 +00008488
8489//===----------------------------------------------------------------------===//
8490// Builtin Type Computation
8491//===----------------------------------------------------------------------===//
8492
8493/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00008494/// pointer over the consumed characters. This returns the resultant type. If
8495/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
8496/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
8497/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008498///
8499/// RequiresICE is filled in on return to indicate whether the value is required
8500/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00008501static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00008502 ASTContext::GetBuiltinTypeError &Error,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008503 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00008504 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00008505 // Modifiers.
8506 int HowLong = 0;
8507 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008508 RequiresICE = false;
Chris Lattner84733392010-10-01 07:13:18 +00008509
Chris Lattnerdc226c22010-10-01 22:42:38 +00008510 // Read the prefixed modifiers first.
Chris Lattnerecd79c62009-06-14 00:45:47 +00008511 bool Done = false;
8512 while (!Done) {
8513 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00008514 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00008515 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008516 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00008517 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008518 case 'S':
8519 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
8520 assert(!Signed && "Can't use 'S' modifier multiple times!");
8521 Signed = true;
8522 break;
8523 case 'U':
8524 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
Sean Silva2a995142015-01-16 21:44:26 +00008525 assert(!Unsigned && "Can't use 'U' modifier multiple times!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00008526 Unsigned = true;
8527 break;
8528 case 'L':
8529 assert(HowLong <= 2 && "Can't have LLLL modifier");
8530 ++HowLong;
8531 break;
Kevin Qinad64f6d2014-02-24 02:45:03 +00008532 case 'W':
8533 // This modifier represents int64 type.
8534 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
8535 switch (Context.getTargetInfo().getInt64Type()) {
8536 default:
8537 llvm_unreachable("Unexpected integer type");
8538 case TargetInfo::SignedLong:
8539 HowLong = 1;
8540 break;
8541 case TargetInfo::SignedLongLong:
8542 HowLong = 2;
8543 break;
8544 }
Chris Lattnerecd79c62009-06-14 00:45:47 +00008545 }
8546 }
8547
8548 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00008549
Chris Lattnerecd79c62009-06-14 00:45:47 +00008550 // Read the base type.
8551 switch (*Str++) {
David Blaikie83d382b2011-09-23 05:06:16 +00008552 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00008553 case 'v':
8554 assert(HowLong == 0 && !Signed && !Unsigned &&
8555 "Bad modifiers used with 'v'!");
8556 Type = Context.VoidTy;
8557 break;
Jack Carter24bef982013-08-15 15:16:57 +00008558 case 'h':
8559 assert(HowLong == 0 && !Signed && !Unsigned &&
Sean Silva2a995142015-01-16 21:44:26 +00008560 "Bad modifiers used with 'h'!");
Jack Carter24bef982013-08-15 15:16:57 +00008561 Type = Context.HalfTy;
8562 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008563 case 'f':
8564 assert(HowLong == 0 && !Signed && !Unsigned &&
8565 "Bad modifiers used with 'f'!");
8566 Type = Context.FloatTy;
8567 break;
8568 case 'd':
8569 assert(HowLong < 2 && !Signed && !Unsigned &&
8570 "Bad modifiers used with 'd'!");
8571 if (HowLong)
8572 Type = Context.LongDoubleTy;
8573 else
8574 Type = Context.DoubleTy;
8575 break;
8576 case 's':
8577 assert(HowLong == 0 && "Bad modifiers used with 's'!");
8578 if (Unsigned)
8579 Type = Context.UnsignedShortTy;
8580 else
8581 Type = Context.ShortTy;
8582 break;
8583 case 'i':
8584 if (HowLong == 3)
8585 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
8586 else if (HowLong == 2)
8587 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
8588 else if (HowLong == 1)
8589 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
8590 else
8591 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
8592 break;
8593 case 'c':
8594 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
8595 if (Signed)
8596 Type = Context.SignedCharTy;
8597 else if (Unsigned)
8598 Type = Context.UnsignedCharTy;
8599 else
8600 Type = Context.CharTy;
8601 break;
8602 case 'b': // boolean
8603 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
8604 Type = Context.BoolTy;
8605 break;
8606 case 'z': // size_t.
8607 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
8608 Type = Context.getSizeType();
8609 break;
Richard Smith8110c9d2016-11-29 19:45:17 +00008610 case 'w': // wchar_t.
8611 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'w'!");
8612 Type = Context.getWideCharType();
8613 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008614 case 'F':
8615 Type = Context.getCFConstantStringType();
8616 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00008617 case 'G':
8618 Type = Context.getObjCIdType();
8619 break;
8620 case 'H':
8621 Type = Context.getObjCSelType();
8622 break;
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00008623 case 'M':
8624 Type = Context.getObjCSuperType();
8625 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008626 case 'a':
8627 Type = Context.getBuiltinVaListType();
8628 assert(!Type.isNull() && "builtin va list type not initialized!");
8629 break;
8630 case 'A':
8631 // This is a "reference" to a va_list; however, what exactly
8632 // this means depends on how va_list is defined. There are two
8633 // different kinds of va_list: ones passed by value, and ones
8634 // passed by reference. An example of a by-value va_list is
8635 // x86, where va_list is a char*. An example of by-ref va_list
8636 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
8637 // we want this argument to be a char*&; for x86-64, we want
8638 // it to be a __va_list_tag*.
8639 Type = Context.getBuiltinVaListType();
8640 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008641 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00008642 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008643 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00008644 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008645 break;
8646 case 'V': {
8647 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008648 unsigned NumElements = strtoul(Str, &End, 10);
8649 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00008650 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00008651
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008652 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
8653 RequiresICE, false);
8654 assert(!RequiresICE && "Can't require vector ICE");
Chris Lattnerdc226c22010-10-01 22:42:38 +00008655
8656 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00008657 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00008658 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008659 break;
8660 }
Douglas Gregorfed66992012-06-07 18:08:25 +00008661 case 'E': {
8662 char *End;
8663
8664 unsigned NumElements = strtoul(Str, &End, 10);
8665 assert(End != Str && "Missing vector size");
8666
8667 Str = End;
8668
8669 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
8670 false);
8671 Type = Context.getExtVectorType(ElementType, NumElements);
8672 break;
8673 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00008674 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008675 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
8676 false);
8677 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00008678 Type = Context.getComplexType(ElementType);
8679 break;
Fariborz Jahanian73952fc2011-08-23 23:33:09 +00008680 }
8681 case 'Y' : {
8682 Type = Context.getPointerDiffType();
8683 break;
8684 }
Chris Lattnera58b3af2009-07-28 22:49:34 +00008685 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00008686 Type = Context.getFILEType();
8687 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00008688 Error = ASTContext::GE_Missing_stdio;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008689 return QualType();
8690 }
Mike Stump2adb4da2009-07-28 23:47:15 +00008691 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00008692 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00008693 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00008694 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00008695 else
8696 Type = Context.getjmp_bufType();
8697
Mike Stump2adb4da2009-07-28 23:47:15 +00008698 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00008699 Error = ASTContext::GE_Missing_setjmp;
Mike Stump2adb4da2009-07-28 23:47:15 +00008700 return QualType();
8701 }
8702 break;
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00008703 case 'K':
8704 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
8705 Type = Context.getucontext_tType();
8706
8707 if (Type.isNull()) {
8708 Error = ASTContext::GE_Missing_ucontext;
8709 return QualType();
8710 }
8711 break;
Eli Friedman4e91899e2012-11-27 02:58:24 +00008712 case 'p':
8713 Type = Context.getProcessIDType();
8714 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00008715 }
Mike Stump11289f42009-09-09 15:08:12 +00008716
Chris Lattnerdc226c22010-10-01 22:42:38 +00008717 // If there are modifiers and if we're allowed to parse them, go for it.
8718 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008719 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00008720 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00008721 default: Done = true; --Str; break;
8722 case '*':
8723 case '&': {
8724 // Both pointers and references can have their pointee types
8725 // qualified with an address space.
8726 char *End;
8727 unsigned AddrSpace = strtoul(Str, &End, 10);
8728 if (End != Str && AddrSpace != 0) {
8729 Type = Context.getAddrSpaceQualType(Type, AddrSpace);
8730 Str = End;
8731 }
8732 if (c == '*')
8733 Type = Context.getPointerType(Type);
8734 else
8735 Type = Context.getLValueReferenceType(Type);
8736 break;
8737 }
8738 // FIXME: There's no way to have a built-in with an rvalue ref arg.
8739 case 'C':
8740 Type = Type.withConst();
8741 break;
8742 case 'D':
8743 Type = Context.getVolatileType(Type);
8744 break;
Ted Kremenekf2a2f5f2012-01-20 21:40:12 +00008745 case 'R':
8746 Type = Type.withRestrict();
8747 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008748 }
8749 }
Chris Lattner84733392010-10-01 07:13:18 +00008750
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008751 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Chris Lattner84733392010-10-01 07:13:18 +00008752 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00008753
Chris Lattnerecd79c62009-06-14 00:45:47 +00008754 return Type;
8755}
8756
8757/// GetBuiltinType - Return the type for the specified builtin.
Chris Lattnerdc226c22010-10-01 22:42:38 +00008758QualType ASTContext::GetBuiltinType(unsigned Id,
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008759 GetBuiltinTypeError &Error,
Jay Foad39c79802011-01-12 09:06:06 +00008760 unsigned *IntegerConstantArgs) const {
Eric Christopher02d5d862015-08-06 01:01:12 +00008761 const char *TypeStr = BuiltinInfo.getTypeString(Id);
Mike Stump11289f42009-09-09 15:08:12 +00008762
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008763 SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00008764
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008765 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00008766 Error = GE_None;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008767 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
8768 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008769 if (Error != GE_None)
8770 return QualType();
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008771
8772 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
8773
Chris Lattnerecd79c62009-06-14 00:45:47 +00008774 while (TypeStr[0] && TypeStr[0] != '.') {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008775 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008776 if (Error != GE_None)
8777 return QualType();
8778
Chris Lattnerbd6e6932010-10-01 22:53:11 +00008779 // If this argument is required to be an IntegerConstantExpression and the
8780 // caller cares, fill in the bitmask we return.
8781 if (RequiresICE && IntegerConstantArgs)
8782 *IntegerConstantArgs |= 1 << ArgTypes.size();
8783
Chris Lattnerecd79c62009-06-14 00:45:47 +00008784 // Do array -> pointer decay. The builtin should use the decayed type.
8785 if (Ty->isArrayType())
8786 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00008787
Chris Lattnerecd79c62009-06-14 00:45:47 +00008788 ArgTypes.push_back(Ty);
8789 }
8790
David Majnemerba3e5ec2015-03-13 18:26:17 +00008791 if (Id == Builtin::BI__GetExceptionInfo)
8792 return QualType();
8793
Chris Lattnerecd79c62009-06-14 00:45:47 +00008794 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
8795 "'.' should only occur at end of builtin type list!");
8796
Reid Kleckner78af0702013-08-27 23:08:25 +00008797 FunctionType::ExtInfo EI(CC_C);
John McCall991eb4b2010-12-21 00:44:39 +00008798 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
8799
8800 bool Variadic = (TypeStr[0] == '.');
8801
Richard Smith836de6b2016-12-19 23:59:34 +00008802 // We really shouldn't be making a no-proto type here.
8803 if (ArgTypes.empty() && Variadic && !getLangOpts().CPlusPlus)
John McCall991eb4b2010-12-21 00:44:39 +00008804 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00008805
John McCalldb40c7f2010-12-14 08:05:40 +00008806 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00008807 EPI.ExtInfo = EI;
8808 EPI.Variadic = Variadic;
Richard Smith391fb862016-10-18 07:13:55 +00008809 if (getLangOpts().CPlusPlus && BuiltinInfo.isNoThrow(Id))
8810 EPI.ExceptionSpec.Type =
8811 getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone;
John McCalldb40c7f2010-12-14 08:05:40 +00008812
Jordan Rose5c382722013-03-08 21:51:21 +00008813 return getFunctionType(ResType, ArgTypes, EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00008814}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00008815
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008816static GVALinkage basicGVALinkageForFunction(const ASTContext &Context,
8817 const FunctionDecl *FD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00008818 if (!FD->isExternallyVisible())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008819 return GVA_Internal;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008820
Yaron Keren4cd211b2017-02-22 14:32:39 +00008821 GVALinkage External;
Rafael Espindola3ae00052013-05-13 00:12:11 +00008822 switch (FD->getTemplateSpecializationKind()) {
8823 case TSK_Undeclared:
8824 case TSK_ExplicitSpecialization:
8825 External = GVA_StrongExternal;
8826 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008827
Rafael Espindola3ae00052013-05-13 00:12:11 +00008828 case TSK_ExplicitInstantiationDefinition:
David Majnemer54e3ba52014-04-02 23:17:29 +00008829 return GVA_StrongODR;
Rafael Espindola3ae00052013-05-13 00:12:11 +00008830
David Majnemerc3d07332014-05-15 06:25:57 +00008831 // C++11 [temp.explicit]p10:
8832 // [ Note: The intent is that an inline function that is the subject of
8833 // an explicit instantiation declaration will still be implicitly
8834 // instantiated when used so that the body can be considered for
8835 // inlining, but that no out-of-line copy of the inline function would be
8836 // generated in the translation unit. -- end note ]
Rafael Espindola3ae00052013-05-13 00:12:11 +00008837 case TSK_ExplicitInstantiationDeclaration:
David Majnemer27d69db2014-04-28 22:17:59 +00008838 return GVA_AvailableExternally;
8839
Rafael Espindola3ae00052013-05-13 00:12:11 +00008840 case TSK_ImplicitInstantiation:
David Majnemer27d69db2014-04-28 22:17:59 +00008841 External = GVA_DiscardableODR;
Rafael Espindola3ae00052013-05-13 00:12:11 +00008842 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008843 }
8844
8845 if (!FD->isInlined())
8846 return External;
David Majnemer62f0ffd2013-08-01 17:26:42 +00008847
David Majnemer3f021502015-10-08 04:53:31 +00008848 if ((!Context.getLangOpts().CPlusPlus &&
8849 !Context.getTargetInfo().getCXXABI().isMicrosoft() &&
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008850 !FD->hasAttr<DLLExportAttr>()) ||
David Majnemer62f0ffd2013-08-01 17:26:42 +00008851 FD->hasAttr<GNUInlineAttr>()) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008852 // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
8853
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008854 // GNU or C99 inline semantics. Determine whether this symbol should be
8855 // externally visible.
8856 if (FD->isInlineDefinitionExternallyVisible())
8857 return External;
8858
8859 // C99 inline semantics, where the symbol is not externally visible.
David Majnemer27d69db2014-04-28 22:17:59 +00008860 return GVA_AvailableExternally;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008861 }
8862
David Majnemer54e3ba52014-04-02 23:17:29 +00008863 // Functions specified with extern and inline in -fms-compatibility mode
8864 // forcibly get emitted. While the body of the function cannot be later
8865 // replaced, the function definition cannot be discarded.
David Majnemer73768702015-03-20 00:02:27 +00008866 if (FD->isMSExternInline())
David Majnemer54e3ba52014-04-02 23:17:29 +00008867 return GVA_StrongODR;
8868
David Majnemer27d69db2014-04-28 22:17:59 +00008869 return GVA_DiscardableODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008870}
8871
Artem Belevichca2b9512016-05-02 20:30:03 +00008872static GVALinkage adjustGVALinkageForAttributes(const ASTContext &Context,
8873 GVALinkage L, const Decl *D) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008874 // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
8875 // dllexport/dllimport on inline functions.
8876 if (D->hasAttr<DLLImportAttr>()) {
8877 if (L == GVA_DiscardableODR || L == GVA_StrongODR)
8878 return GVA_AvailableExternally;
Artem Belevichca2b9512016-05-02 20:30:03 +00008879 } else if (D->hasAttr<DLLExportAttr>()) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008880 if (L == GVA_DiscardableODR)
8881 return GVA_StrongODR;
Artem Belevichca2b9512016-05-02 20:30:03 +00008882 } else if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice &&
8883 D->hasAttr<CUDAGlobalAttr>()) {
8884 // Device-side functions with __global__ attribute must always be
8885 // visible externally so they can be launched from host.
8886 if (L == GVA_DiscardableODR || L == GVA_Internal)
8887 return GVA_StrongODR;
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008888 }
8889 return L;
8890}
8891
8892GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) const {
David Blaikie9ffe5a32017-01-30 05:00:26 +00008893 auto L = adjustGVALinkageForAttributes(
Artem Belevichca2b9512016-05-02 20:30:03 +00008894 *this, basicGVALinkageForFunction(*this, FD), FD);
David Blaikie9ffe5a32017-01-30 05:00:26 +00008895 auto EK = ExternalASTSource::EK_ReplyHazy;
8896 if (auto *Ext = getExternalSource())
8897 EK = Ext->hasExternalDefinitions(FD->getOwningModuleID());
8898 switch (EK) {
8899 case ExternalASTSource::EK_Never:
8900 if (L == GVA_DiscardableODR)
8901 return GVA_StrongODR;
8902 break;
8903 case ExternalASTSource::EK_Always:
8904 return GVA_AvailableExternally;
8905 case ExternalASTSource::EK_ReplyHazy:
8906 break;
8907 }
8908 return L;
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008909}
8910
8911static GVALinkage basicGVALinkageForVariable(const ASTContext &Context,
8912 const VarDecl *VD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00008913 if (!VD->isExternallyVisible())
8914 return GVA_Internal;
8915
David Majnemer27d69db2014-04-28 22:17:59 +00008916 if (VD->isStaticLocal()) {
David Majnemer27d69db2014-04-28 22:17:59 +00008917 const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
8918 while (LexicalContext && !isa<FunctionDecl>(LexicalContext))
8919 LexicalContext = LexicalContext->getLexicalParent();
8920
David Blaikieeb210012017-01-27 23:11:10 +00008921 // ObjC Blocks can create local variables that don't have a FunctionDecl
8922 // LexicalContext.
8923 if (!LexicalContext)
8924 return GVA_DiscardableODR;
David Majnemer27d69db2014-04-28 22:17:59 +00008925
David Blaikieeb210012017-01-27 23:11:10 +00008926 // Otherwise, let the static local variable inherit its linkage from the
8927 // nearest enclosing function.
8928 auto StaticLocalLinkage =
8929 Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext));
8930
8931 // Itanium ABI 5.2.2: "Each COMDAT group [for a static local variable] must
8932 // be emitted in any object with references to the symbol for the object it
8933 // contains, whether inline or out-of-line."
8934 // Similar behavior is observed with MSVC. An alternative ABI could use
8935 // StrongODR/AvailableExternally to match the function, but none are
8936 // known/supported currently.
8937 if (StaticLocalLinkage == GVA_StrongODR ||
8938 StaticLocalLinkage == GVA_AvailableExternally)
8939 return GVA_DiscardableODR;
8940 return StaticLocalLinkage;
David Majnemer27d69db2014-04-28 22:17:59 +00008941 }
8942
Hans Wennborg56fc62b2014-07-17 20:25:23 +00008943 // MSVC treats in-class initialized static data members as definitions.
8944 // By giving them non-strong linkage, out-of-line definitions won't
8945 // cause link errors.
8946 if (Context.isMSStaticDataMemberInlineDefinition(VD))
8947 return GVA_DiscardableODR;
8948
Richard Smithd9b90092016-07-02 01:32:16 +00008949 // Most non-template variables have strong linkage; inline variables are
8950 // linkonce_odr or (occasionally, for compatibility) weak_odr.
8951 GVALinkage StrongLinkage;
8952 switch (Context.getInlineVariableDefinitionKind(VD)) {
8953 case ASTContext::InlineVariableDefinitionKind::None:
8954 StrongLinkage = GVA_StrongExternal;
8955 break;
8956 case ASTContext::InlineVariableDefinitionKind::Weak:
8957 case ASTContext::InlineVariableDefinitionKind::WeakUnknown:
Richard Smith62f19e72016-06-25 00:15:56 +00008958 StrongLinkage = GVA_DiscardableODR;
Richard Smithd9b90092016-07-02 01:32:16 +00008959 break;
8960 case ASTContext::InlineVariableDefinitionKind::Strong:
8961 StrongLinkage = GVA_StrongODR;
8962 break;
8963 }
Richard Smith62f19e72016-06-25 00:15:56 +00008964
Richard Smith8809a0c2013-09-27 20:14:12 +00008965 switch (VD->getTemplateSpecializationKind()) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00008966 case TSK_Undeclared:
Richard Smith62f19e72016-06-25 00:15:56 +00008967 return StrongLinkage;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008968
David Majnemer6d1780c2015-07-17 23:36:49 +00008969 case TSK_ExplicitSpecialization:
David Majnemer3f021502015-10-08 04:53:31 +00008970 return Context.getTargetInfo().getCXXABI().isMicrosoft() &&
8971 VD->isStaticDataMember()
David Majnemer6d1780c2015-07-17 23:36:49 +00008972 ? GVA_StrongODR
Richard Smith62f19e72016-06-25 00:15:56 +00008973 : StrongLinkage;
David Majnemer6d1780c2015-07-17 23:36:49 +00008974
Rafael Espindola3ae00052013-05-13 00:12:11 +00008975 case TSK_ExplicitInstantiationDefinition:
David Majnemer54e3ba52014-04-02 23:17:29 +00008976 return GVA_StrongODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008977
David Majnemer27d69db2014-04-28 22:17:59 +00008978 case TSK_ExplicitInstantiationDeclaration:
8979 return GVA_AvailableExternally;
8980
Rafael Espindola3ae00052013-05-13 00:12:11 +00008981 case TSK_ImplicitInstantiation:
David Majnemer27d69db2014-04-28 22:17:59 +00008982 return GVA_DiscardableODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008983 }
Rafael Espindola27699c82013-05-13 14:05:53 +00008984
8985 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008986}
8987
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008988GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
Artem Belevichca2b9512016-05-02 20:30:03 +00008989 return adjustGVALinkageForAttributes(
8990 *this, basicGVALinkageForVariable(*this, VD), VD);
Hans Wennborgb0f2f142014-05-15 22:07:49 +00008991}
8992
David Blaikie9ffe5a32017-01-30 05:00:26 +00008993bool ASTContext::DeclMustBeEmitted(const Decl *D, bool ForModularCodegen) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00008994 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
8995 if (!VD->isFileVarDecl())
8996 return false;
Renato Golin9258aa52014-05-21 10:40:27 +00008997 // Global named register variables (GNU extension) are never emitted.
8998 if (VD->getStorageClass() == SC_Register)
8999 return false;
Richard Smith7747ce22015-08-19 20:49:38 +00009000 if (VD->getDescribedVarTemplate() ||
9001 isa<VarTemplatePartialSpecializationDecl>(VD))
9002 return false;
Richard Smith5205a8c2013-04-01 20:22:16 +00009003 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
9004 // We never need to emit an uninstantiated function template.
9005 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
9006 return false;
Nico Weber66220292016-03-02 17:28:48 +00009007 } else if (isa<PragmaCommentDecl>(D))
9008 return true;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00009009 else if (isa<OMPThreadPrivateDecl>(D) ||
9010 D->hasAttr<OMPDeclareTargetDeclAttr>())
9011 return true;
Nico Webercbbaeb12016-03-02 19:28:54 +00009012 else if (isa<PragmaDetectMismatchDecl>(D))
9013 return true;
Nico Weber66220292016-03-02 17:28:48 +00009014 else if (isa<OMPThreadPrivateDecl>(D))
Alexey Bataevc5b1d322016-03-04 09:22:22 +00009015 return !D->getDeclContext()->isDependentContext();
9016 else if (isa<OMPDeclareReductionDecl>(D))
9017 return !D->getDeclContext()->isDependentContext();
Richard Smithdc1f0422016-07-20 19:10:16 +00009018 else if (isa<ImportDecl>(D))
9019 return true;
Alexey Bataev97720002014-11-11 04:05:39 +00009020 else
Richard Smith5205a8c2013-04-01 20:22:16 +00009021 return false;
9022
9023 // If this is a member of a class template, we do not need to emit it.
9024 if (D->getDeclContext()->isDependentContext())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009025 return false;
9026
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00009027 // Weak references don't produce any output by themselves.
9028 if (D->hasAttr<WeakRefAttr>())
9029 return false;
9030
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009031 // Aliases and used decls are required.
9032 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
9033 return true;
9034
9035 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
9036 // Forward declarations aren't required.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00009037 if (!FD->doesThisDeclarationHaveABody())
Nick Lewycky26da4dd2011-07-18 05:26:13 +00009038 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009039
9040 // Constructors and destructors are required.
9041 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
9042 return true;
9043
John McCall6bd2a892013-01-25 22:31:03 +00009044 // The key function for a class is required. This rule only comes
9045 // into play when inline functions can be key functions, though.
9046 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
9047 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
9048 const CXXRecordDecl *RD = MD->getParent();
9049 if (MD->isOutOfLine() && RD->isDynamicClass()) {
9050 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
9051 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
9052 return true;
9053 }
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009054 }
9055 }
9056
David Blaikie9ffe5a32017-01-30 05:00:26 +00009057 GVALinkage Linkage = GetGVALinkageForFunction(FD);
9058
9059 if (Linkage == GVA_DiscardableODR && ForModularCodegen)
9060 return true;
9061
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009062 // static, static inline, always_inline, and extern inline functions can
9063 // always be deferred. Normal inline functions can be deferred in C99/C++.
9064 // Implicit template instantiations can also be deferred in C++.
David Blaikie9ffe5a32017-01-30 05:00:26 +00009065 return !isDiscardableGVALinkage(Linkage);
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009066 }
Douglas Gregor87d81242011-09-10 00:22:34 +00009067
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009068 const VarDecl *VD = cast<VarDecl>(D);
9069 assert(VD->isFileVarDecl() && "Expected file scoped var");
9070
Hans Wennborg56fc62b2014-07-17 20:25:23 +00009071 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
9072 !isMSStaticDataMemberInlineDefinition(VD))
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00009073 return false;
9074
Richard Smitha0e5e542012-11-12 21:38:00 +00009075 // Variables that can be needed in other TUs are required.
Justin Lebar606f01f2016-10-13 20:52:17 +00009076 if (!isDiscardableGVALinkage(GetGVALinkageForVariable(VD)))
Richard Smitha0e5e542012-11-12 21:38:00 +00009077 return true;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009078
Richard Smitha0e5e542012-11-12 21:38:00 +00009079 // Variables that have destruction with side-effects are required.
9080 if (VD->getType().isDestructedType())
9081 return true;
9082
9083 // Variables that have initialization with side-effects are required.
Richard Smith7747ce22015-08-19 20:49:38 +00009084 if (VD->getInit() && VD->getInit()->HasSideEffects(*this) &&
Richard Smith187ffb42017-01-20 01:19:46 +00009085 // We can get a value-dependent initializer during error recovery.
9086 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
Richard Smitha0e5e542012-11-12 21:38:00 +00009087 return true;
9088
Richard Smithda383632016-08-15 01:33:41 +00009089 // Likewise, variables with tuple-like bindings are required if their
9090 // bindings have side-effects.
9091 if (auto *DD = dyn_cast<DecompositionDecl>(VD))
9092 for (auto *BD : DD->bindings())
9093 if (auto *BindingVD = BD->getHoldingVar())
9094 if (DeclMustBeEmitted(BindingVD))
9095 return true;
9096
Richard Smitha0e5e542012-11-12 21:38:00 +00009097 return false;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009098}
Charles Davis53c59df2010-08-16 03:33:14 +00009099
Reid Kleckner78af0702013-08-27 23:08:25 +00009100CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic,
9101 bool IsCXXMethod) const {
Charles Davis99202b32010-11-09 18:04:24 +00009102 // Pass through to the C++ ABI object
Reid Kleckner78af0702013-08-27 23:08:25 +00009103 if (IsCXXMethod)
9104 return ABI->getDefaultMethodCallConv(IsVariadic);
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +00009105
Alexey Bataeva7547182016-05-18 09:06:38 +00009106 switch (LangOpts.getDefaultCallingConv()) {
9107 case LangOptions::DCC_None:
9108 break;
9109 case LangOptions::DCC_CDecl:
9110 return CC_C;
9111 case LangOptions::DCC_FastCall:
9112 if (getTargetInfo().hasFeature("sse2"))
9113 return CC_X86FastCall;
9114 break;
9115 case LangOptions::DCC_StdCall:
9116 if (!IsVariadic)
9117 return CC_X86StdCall;
9118 break;
9119 case LangOptions::DCC_VectorCall:
9120 // __vectorcall cannot be applied to variadic functions.
9121 if (!IsVariadic)
9122 return CC_X86VectorCall;
9123 break;
9124 }
Alexander Kornienko21de0ae2015-01-20 11:20:41 +00009125 return Target->getDefaultCallingConv(TargetInfo::CCMT_Unknown);
Charles Davis99202b32010-11-09 18:04:24 +00009126}
9127
Jay Foad39c79802011-01-12 09:06:06 +00009128bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +00009129 // Pass through to the C++ ABI object
9130 return ABI->isNearlyEmpty(RD);
9131}
9132
Reid Kleckner96f8f932014-02-05 17:27:08 +00009133VTableContextBase *ASTContext::getVTableContext() {
9134 if (!VTContext.get()) {
9135 if (Target->getCXXABI().isMicrosoft())
9136 VTContext.reset(new MicrosoftVTableContext(*this));
9137 else
9138 VTContext.reset(new ItaniumVTableContext(*this));
9139 }
9140 return VTContext.get();
9141}
9142
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00009143MangleContext *ASTContext::createMangleContext() {
John McCall359b8852013-01-25 22:30:49 +00009144 switch (Target->getCXXABI().getKind()) {
Tim Northover9bb857a2013-01-31 12:13:10 +00009145 case TargetCXXABI::GenericAArch64:
John McCall359b8852013-01-25 22:30:49 +00009146 case TargetCXXABI::GenericItanium:
9147 case TargetCXXABI::GenericARM:
Zoran Jovanovic26a12162015-02-18 15:21:35 +00009148 case TargetCXXABI::GenericMIPS:
John McCall359b8852013-01-25 22:30:49 +00009149 case TargetCXXABI::iOS:
Tim Northovera2ee4332014-03-29 15:09:45 +00009150 case TargetCXXABI::iOS64:
Dan Gohmanc2853072015-09-03 22:51:53 +00009151 case TargetCXXABI::WebAssembly:
Tim Northover756447a2015-10-30 16:30:36 +00009152 case TargetCXXABI::WatchOS:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00009153 return ItaniumMangleContext::create(*this, getDiagnostics());
John McCall359b8852013-01-25 22:30:49 +00009154 case TargetCXXABI::Microsoft:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00009155 return MicrosoftMangleContext::create(*this, getDiagnostics());
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00009156 }
David Blaikie83d382b2011-09-23 05:06:16 +00009157 llvm_unreachable("Unsupported ABI");
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00009158}
9159
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +00009160CXXABI::~CXXABI() {}
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00009161
9162size_t ASTContext::getSideTableAllocatedMemory() const {
Larisse Voufo39a1e502013-08-06 01:03:05 +00009163 return ASTRecordLayouts.getMemorySize() +
9164 llvm::capacity_in_bytes(ObjCLayouts) +
9165 llvm::capacity_in_bytes(KeyFunctions) +
9166 llvm::capacity_in_bytes(ObjCImpls) +
9167 llvm::capacity_in_bytes(BlockVarCopyInits) +
9168 llvm::capacity_in_bytes(DeclAttrs) +
9169 llvm::capacity_in_bytes(TemplateOrInstantiation) +
9170 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
9171 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
9172 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
9173 llvm::capacity_in_bytes(OverriddenMethods) +
9174 llvm::capacity_in_bytes(Types) +
9175 llvm::capacity_in_bytes(VariableArrayTypes) +
9176 llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00009177}
Ted Kremenek540017e2011-10-06 05:00:56 +00009178
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00009179/// getIntTypeForBitwidth -
9180/// sets integer QualTy according to specified details:
9181/// bitwidth, signed/unsigned.
9182/// Returns empty type if there is no appropriate target types.
9183QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth,
9184 unsigned Signed) const {
9185 TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed);
9186 CanQualType QualTy = getFromTargetType(Ty);
9187 if (!QualTy && DestWidth == 128)
9188 return Signed ? Int128Ty : UnsignedInt128Ty;
9189 return QualTy;
9190}
9191
9192/// getRealTypeForBitwidth -
9193/// sets floating point QualTy according to specified bitwidth.
9194/// Returns empty type if there is no appropriate target types.
9195QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth) const {
9196 TargetInfo::RealType Ty = getTargetInfo().getRealTypeByWidth(DestWidth);
9197 switch (Ty) {
9198 case TargetInfo::Float:
9199 return FloatTy;
9200 case TargetInfo::Double:
9201 return DoubleTy;
9202 case TargetInfo::LongDouble:
9203 return LongDoubleTy;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00009204 case TargetInfo::Float128:
9205 return Float128Ty;
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00009206 case TargetInfo::NoFloat:
9207 return QualType();
9208 }
9209
9210 llvm_unreachable("Unhandled TargetInfo::RealType value");
9211}
9212
Eli Friedman3b7d46c2013-07-10 00:30:46 +00009213void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
9214 if (Number > 1)
9215 MangleNumbers[ND] = Number;
David Blaikie095deba2012-11-14 01:52:05 +00009216}
9217
Eli Friedman3b7d46c2013-07-10 00:30:46 +00009218unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const {
Richard Smithe9b02d62016-03-21 22:33:02 +00009219 auto I = MangleNumbers.find(ND);
Eli Friedman3b7d46c2013-07-10 00:30:46 +00009220 return I != MangleNumbers.end() ? I->second : 1;
David Blaikie095deba2012-11-14 01:52:05 +00009221}
9222
David Majnemer2206bf52014-03-05 08:57:59 +00009223void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
9224 if (Number > 1)
9225 StaticLocalNumbers[VD] = Number;
9226}
9227
9228unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const {
Richard Smithe9b02d62016-03-21 22:33:02 +00009229 auto I = StaticLocalNumbers.find(VD);
David Majnemer2206bf52014-03-05 08:57:59 +00009230 return I != StaticLocalNumbers.end() ? I->second : 1;
9231}
9232
Eli Friedman3b7d46c2013-07-10 00:30:46 +00009233MangleNumberingContext &
9234ASTContext::getManglingNumberContext(const DeclContext *DC) {
Reid Klecknerd8110b62013-09-10 20:14:30 +00009235 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
Justin Lebar20ebffc2016-10-10 16:26:19 +00009236 std::unique_ptr<MangleNumberingContext> &MCtx = MangleNumberingContexts[DC];
Reid Klecknerd8110b62013-09-10 20:14:30 +00009237 if (!MCtx)
9238 MCtx = createMangleNumberingContext();
9239 return *MCtx;
9240}
9241
Justin Lebar20ebffc2016-10-10 16:26:19 +00009242std::unique_ptr<MangleNumberingContext>
9243ASTContext::createMangleNumberingContext() const {
Reid Klecknerd8110b62013-09-10 20:14:30 +00009244 return ABI->createMangleNumberingContext();
Douglas Gregor63798542012-02-20 19:44:39 +00009245}
9246
David Majnemere7a818f2015-03-06 18:53:55 +00009247const CXXConstructorDecl *
9248ASTContext::getCopyConstructorForExceptionObject(CXXRecordDecl *RD) {
9249 return ABI->getCopyConstructorForExceptionObject(
9250 cast<CXXRecordDecl>(RD->getFirstDecl()));
9251}
9252
9253void ASTContext::addCopyConstructorForExceptionObject(CXXRecordDecl *RD,
9254 CXXConstructorDecl *CD) {
9255 return ABI->addCopyConstructorForExceptionObject(
9256 cast<CXXRecordDecl>(RD->getFirstDecl()),
9257 cast<CXXConstructorDecl>(CD->getFirstDecl()));
9258}
9259
David Majnemer00350522015-08-31 18:48:39 +00009260void ASTContext::addTypedefNameForUnnamedTagDecl(TagDecl *TD,
9261 TypedefNameDecl *DD) {
9262 return ABI->addTypedefNameForUnnamedTagDecl(TD, DD);
9263}
9264
9265TypedefNameDecl *
9266ASTContext::getTypedefNameForUnnamedTagDecl(const TagDecl *TD) {
9267 return ABI->getTypedefNameForUnnamedTagDecl(TD);
9268}
9269
9270void ASTContext::addDeclaratorForUnnamedTagDecl(TagDecl *TD,
9271 DeclaratorDecl *DD) {
9272 return ABI->addDeclaratorForUnnamedTagDecl(TD, DD);
9273}
9274
9275DeclaratorDecl *ASTContext::getDeclaratorForUnnamedTagDecl(const TagDecl *TD) {
9276 return ABI->getDeclaratorForUnnamedTagDecl(TD);
9277}
9278
Ted Kremenek540017e2011-10-06 05:00:56 +00009279void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
9280 ParamIndices[D] = index;
9281}
9282
9283unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
9284 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
9285 assert(I != ParamIndices.end() &&
9286 "ParmIndices lacks entry set by ParmVarDecl");
9287 return I->second;
9288}
Fariborz Jahanian615de762013-05-28 17:37:39 +00009289
Richard Smithe6c01442013-06-05 00:46:14 +00009290APValue *
9291ASTContext::getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E,
9292 bool MayCreate) {
9293 assert(E && E->getStorageDuration() == SD_Static &&
9294 "don't need to cache the computed value for this temporary");
David Majnemer2dcef9e2015-08-13 23:50:15 +00009295 if (MayCreate) {
9296 APValue *&MTVI = MaterializedTemporaryValues[E];
9297 if (!MTVI)
9298 MTVI = new (*this) APValue;
9299 return MTVI;
9300 }
Richard Smithe6c01442013-06-05 00:46:14 +00009301
David Majnemer2dcef9e2015-08-13 23:50:15 +00009302 return MaterializedTemporaryValues.lookup(E);
Richard Smithe6c01442013-06-05 00:46:14 +00009303}
9304
Fariborz Jahanian615de762013-05-28 17:37:39 +00009305bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
9306 const llvm::Triple &T = getTargetInfo().getTriple();
9307 if (!T.isOSDarwin())
9308 return false;
9309
Bob Wilson2c82c3d2013-11-02 23:27:49 +00009310 if (!(T.isiOS() && T.isOSVersionLT(7)) &&
9311 !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
9312 return false;
9313
Fariborz Jahanian615de762013-05-28 17:37:39 +00009314 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
9315 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
9316 uint64_t Size = sizeChars.getQuantity();
9317 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
9318 unsigned Align = alignChars.getQuantity();
9319 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
9320 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
9321}
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009322
9323namespace {
9324
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009325ast_type_traits::DynTypedNode getSingleDynTypedNodeFromParentMap(
9326 ASTContext::ParentMapPointers::mapped_type U) {
Benjamin Kramerfbfa7a12015-10-22 11:26:35 +00009327 if (const auto *D = U.dyn_cast<const Decl *>())
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009328 return ast_type_traits::DynTypedNode::create(*D);
Benjamin Kramerfbfa7a12015-10-22 11:26:35 +00009329 if (const auto *S = U.dyn_cast<const Stmt *>())
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009330 return ast_type_traits::DynTypedNode::create(*S);
Benjamin Kramerfbfa7a12015-10-22 11:26:35 +00009331 return *U.get<ast_type_traits::DynTypedNode *>();
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009332}
9333
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009334/// Template specializations to abstract away from pointers and TypeLocs.
9335/// @{
9336template <typename T>
9337ast_type_traits::DynTypedNode createDynTypedNode(const T &Node) {
9338 return ast_type_traits::DynTypedNode::create(*Node);
9339}
9340template <>
9341ast_type_traits::DynTypedNode createDynTypedNode(const TypeLoc &Node) {
9342 return ast_type_traits::DynTypedNode::create(Node);
9343}
9344template <>
9345ast_type_traits::DynTypedNode
9346createDynTypedNode(const NestedNameSpecifierLoc &Node) {
9347 return ast_type_traits::DynTypedNode::create(Node);
9348}
9349/// @}
9350
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009351 /// \brief A \c RecursiveASTVisitor that builds a map from nodes to their
9352 /// parents as defined by the \c RecursiveASTVisitor.
9353 ///
9354 /// Note that the relationship described here is purely in terms of AST
9355 /// traversal - there are other relationships (for example declaration context)
9356 /// in the AST that are better modeled by special matchers.
9357 ///
Benjamin Kramere8c51fd2015-10-21 10:07:26 +00009358 /// FIXME: Currently only builds up the map using \c Stmt and \c Decl nodes.
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009359 class ParentMapASTVisitor : public RecursiveASTVisitor<ParentMapASTVisitor> {
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009360 public:
9361 /// \brief Builds and returns the translation unit's parent map.
9362 ///
9363 /// The caller takes ownership of the returned \c ParentMap.
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009364 static std::pair<ASTContext::ParentMapPointers *,
9365 ASTContext::ParentMapOtherNodes *>
9366 buildMap(TranslationUnitDecl &TU) {
9367 ParentMapASTVisitor Visitor(new ASTContext::ParentMapPointers,
9368 new ASTContext::ParentMapOtherNodes);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009369 Visitor.TraverseDecl(&TU);
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009370 return std::make_pair(Visitor.Parents, Visitor.OtherParents);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009371 }
9372
9373 private:
9374 typedef RecursiveASTVisitor<ParentMapASTVisitor> VisitorBase;
9375
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009376 ParentMapASTVisitor(ASTContext::ParentMapPointers *Parents,
9377 ASTContext::ParentMapOtherNodes *OtherParents)
9378 : Parents(Parents), OtherParents(OtherParents) {}
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009379
9380 bool shouldVisitTemplateInstantiations() const {
9381 return true;
9382 }
9383 bool shouldVisitImplicitCode() const {
9384 return true;
9385 }
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009386
Richard Smith85838722015-11-24 03:09:01 +00009387 template <typename T, typename MapNodeTy, typename BaseTraverseFn,
9388 typename MapTy>
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009389 bool TraverseNode(T Node, MapNodeTy MapNode,
Richard Smith85838722015-11-24 03:09:01 +00009390 BaseTraverseFn BaseTraverse, MapTy *Parents) {
Craig Topper36250ad2014-05-12 05:36:57 +00009391 if (!Node)
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009392 return true;
Manuel Klimek95403e62014-05-21 13:28:59 +00009393 if (ParentStack.size() > 0) {
Benjamin Kramere8c51fd2015-10-21 10:07:26 +00009394 // FIXME: Currently we add the same parent multiple times, but only
9395 // when no memoization data is available for the type.
9396 // For example when we visit all subexpressions of template
9397 // instantiations; this is suboptimal, but benign: the only way to
9398 // visit those is with hasAncestor / hasParent, and those do not create
9399 // new matches.
9400 // The plan is to enable DynTypedNode to be storable in a map or hash
9401 // map. The main problem there is to implement hash functions /
9402 // comparison operators for all types that DynTypedNode supports that
9403 // do not have pointer identity.
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009404 auto &NodeOrVector = (*Parents)[MapNode];
Manuel Klimek95403e62014-05-21 13:28:59 +00009405 if (NodeOrVector.isNull()) {
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009406 if (const auto *D = ParentStack.back().get<Decl>())
9407 NodeOrVector = D;
9408 else if (const auto *S = ParentStack.back().get<Stmt>())
9409 NodeOrVector = S;
9410 else
9411 NodeOrVector =
9412 new ast_type_traits::DynTypedNode(ParentStack.back());
Manuel Klimek95403e62014-05-21 13:28:59 +00009413 } else {
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009414 if (!NodeOrVector.template is<ASTContext::ParentVector *>()) {
9415 auto *Vector = new ASTContext::ParentVector(
9416 1, getSingleDynTypedNodeFromParentMap(NodeOrVector));
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009417 if (auto *Node =
9418 NodeOrVector
9419 .template dyn_cast<ast_type_traits::DynTypedNode *>())
9420 delete Node;
Benjamin Kramer422b3ff2015-10-23 13:24:18 +00009421 NodeOrVector = Vector;
Samuel Benzaquen3ca0a7b2014-06-13 13:31:40 +00009422 }
Samuel Benzaquen3ca0a7b2014-06-13 13:31:40 +00009423
9424 auto *Vector =
9425 NodeOrVector.template get<ASTContext::ParentVector *>();
9426 // Skip duplicates for types that have memoization data.
9427 // We must check that the type has memoization data before calling
9428 // std::find() because DynTypedNode::operator== can't compare all
9429 // types.
9430 bool Found = ParentStack.back().getMemoizationData() &&
9431 std::find(Vector->begin(), Vector->end(),
9432 ParentStack.back()) != Vector->end();
9433 if (!Found)
9434 Vector->push_back(ParentStack.back());
Manuel Klimek95403e62014-05-21 13:28:59 +00009435 }
9436 }
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009437 ParentStack.push_back(createDynTypedNode(Node));
Richard Smith85838722015-11-24 03:09:01 +00009438 bool Result = BaseTraverse();
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009439 ParentStack.pop_back();
9440 return Result;
9441 }
9442
9443 bool TraverseDecl(Decl *DeclNode) {
Richard Smith85838722015-11-24 03:09:01 +00009444 return TraverseNode(DeclNode, DeclNode,
9445 [&] { return VisitorBase::TraverseDecl(DeclNode); },
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009446 Parents);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009447 }
9448
9449 bool TraverseStmt(Stmt *StmtNode) {
Richard Smith85838722015-11-24 03:09:01 +00009450 return TraverseNode(StmtNode, StmtNode,
9451 [&] { return VisitorBase::TraverseStmt(StmtNode); },
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009452 Parents);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009453 }
9454
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009455 bool TraverseTypeLoc(TypeLoc TypeLocNode) {
Richard Smith85838722015-11-24 03:09:01 +00009456 return TraverseNode(
9457 TypeLocNode, ast_type_traits::DynTypedNode::create(TypeLocNode),
9458 [&] { return VisitorBase::TraverseTypeLoc(TypeLocNode); },
9459 OtherParents);
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009460 }
9461
9462 bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNSLocNode) {
9463 return TraverseNode(
9464 NNSLocNode, ast_type_traits::DynTypedNode::create(NNSLocNode),
Richard Smith85838722015-11-24 03:09:01 +00009465 [&] {
9466 return VisitorBase::TraverseNestedNameSpecifierLoc(NNSLocNode);
9467 },
9468 OtherParents);
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009469 }
9470
9471 ASTContext::ParentMapPointers *Parents;
9472 ASTContext::ParentMapOtherNodes *OtherParents;
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009473 llvm::SmallVector<ast_type_traits::DynTypedNode, 16> ParentStack;
9474
9475 friend class RecursiveASTVisitor<ParentMapASTVisitor>;
9476 };
9477
Eugene Zelenkod4304d22015-11-04 21:37:17 +00009478} // anonymous namespace
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009479
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009480template <typename NodeTy, typename MapTy>
9481static ASTContext::DynTypedNodeList getDynNodeFromMap(const NodeTy &Node,
9482 const MapTy &Map) {
9483 auto I = Map.find(Node);
9484 if (I == Map.end()) {
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009485 return llvm::ArrayRef<ast_type_traits::DynTypedNode>();
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009486 }
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009487 if (auto *V = I->second.template dyn_cast<ASTContext::ParentVector *>()) {
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009488 return llvm::makeArrayRef(*V);
Manuel Klimek95403e62014-05-21 13:28:59 +00009489 }
Benjamin Kramer8e4a1762015-10-22 11:21:40 +00009490 return getSingleDynTypedNodeFromParentMap(I->second);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +00009491}
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00009492
Benjamin Kramer94355ae2015-10-23 09:04:55 +00009493ASTContext::DynTypedNodeList
9494ASTContext::getParents(const ast_type_traits::DynTypedNode &Node) {
9495 if (!PointerParents) {
9496 // We always need to run over the whole translation unit, as
9497 // hasAncestor can escape any subtree.
9498 auto Maps = ParentMapASTVisitor::buildMap(*getTranslationUnitDecl());
9499 PointerParents.reset(Maps.first);
9500 OtherParents.reset(Maps.second);
9501 }
9502 if (Node.getNodeKind().hasPointerIdentity())
9503 return getDynNodeFromMap(Node.getMemoizationData(), *PointerParents);
9504 return getDynNodeFromMap(Node, *OtherParents);
9505}
9506
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00009507bool
9508ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
9509 const ObjCMethodDecl *MethodImpl) {
9510 // No point trying to match an unavailable/deprecated mothod.
9511 if (MethodDecl->hasAttr<UnavailableAttr>()
9512 || MethodDecl->hasAttr<DeprecatedAttr>())
9513 return false;
9514 if (MethodDecl->getObjCDeclQualifier() !=
9515 MethodImpl->getObjCDeclQualifier())
9516 return false;
Alp Toker314cc812014-01-25 16:55:45 +00009517 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
Fariborz Jahaniand36150d2013-07-15 21:22:08 +00009518 return false;
9519
9520 if (MethodDecl->param_size() != MethodImpl->param_size())
9521 return false;
9522
9523 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
9524 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
9525 EF = MethodDecl->param_end();
9526 IM != EM && IF != EF; ++IM, ++IF) {
9527 const ParmVarDecl *DeclVar = (*IF);
9528 const ParmVarDecl *ImplVar = (*IM);
9529 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
9530 return false;
9531 if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
9532 return false;
9533 }
9534 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
9535
9536}
Richard Smith053f6c62014-05-16 23:01:30 +00009537
Yaxun Liu402804b2016-12-15 08:09:08 +00009538uint64_t ASTContext::getTargetNullPointerValue(QualType QT) const {
9539 unsigned AS;
9540 if (QT->getUnqualifiedDesugaredType()->isNullPtrType())
9541 AS = 0;
9542 else
9543 AS = QT->getPointeeType().getAddressSpace();
9544
9545 return getTargetInfo().getNullPointerValue(AS);
9546}
9547
Richard Smith053f6c62014-05-16 23:01:30 +00009548// Explicitly instantiate this in case a Redeclarable<T> is used from a TU that
9549// doesn't include ASTContext.h
9550template
9551clang::LazyGenerationalUpdatePtr<
9552 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType
9553clang::LazyGenerationalUpdatePtr<
9554 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue(
9555 const clang::ASTContext &Ctx, Decl *Value);