blob: 21bdc096ae37402239166aab70f06d9514f2ef54 [file] [log] [blame]
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00001//===- ASTContext.cpp - Context to hold long-lived AST nodes --------------===//
Chris Lattnerddc135e2006-11-10 06:34:16 +00002//
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"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000016#include "clang/AST/APValue.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000017#include "clang/AST/ASTMutationListener.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000018#include "clang/AST/ASTTypeTraits.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000019#include "clang/AST/Attr.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000020#include "clang/AST/AttrIterator.h"
Ken Dyck8c89d592009-12-22 14:23:30 +000021#include "clang/AST/CharUnits.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000022#include "clang/AST/Comment.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000023#include "clang/AST/Decl.h"
24#include "clang/AST/DeclBase.h"
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +000025#include "clang/AST/DeclCXX.h"
Chandler Carruthaa36b892015-12-30 03:40:23 +000026#include "clang/AST/DeclContextInternals.h"
Steve Naroff67391b82007-10-01 19:00:59 +000027#include "clang/AST/DeclObjC.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000028#include "clang/AST/DeclOpenMP.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000029#include "clang/AST/DeclTemplate.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000030#include "clang/AST/DeclarationName.h"
Daniel Dunbar221fa942008-08-11 04:54:23 +000031#include "clang/AST/Expr.h"
John McCall87fe5d52010-05-20 01:18:31 +000032#include "clang/AST/ExprCXX.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000033#include "clang/AST/ExternalASTSource.h"
Peter Collingbourne0ff0b372011-01-13 18:57:25 +000034#include "clang/AST/Mangle.h"
Reid Klecknerd8110b62013-09-10 20:14:30 +000035#include "clang/AST/MangleNumberingContext.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000036#include "clang/AST/NestedNameSpecifier.h"
37#include "clang/AST/RawCommentList.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000038#include "clang/AST/RecordLayout.h"
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000039#include "clang/AST/RecursiveASTVisitor.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000040#include "clang/AST/Stmt.h"
41#include "clang/AST/TemplateBase.h"
42#include "clang/AST/TemplateName.h"
43#include "clang/AST/Type.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000044#include "clang/AST/TypeLoc.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000045#include "clang/AST/UnresolvedSet.h"
Reid Kleckner96f8f932014-02-05 17:27:08 +000046#include "clang/AST/VTableBuilder.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000047#include "clang/Basic/AddressSpaces.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000048#include "clang/Basic/Builtins.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000049#include "clang/Basic/CommentOptions.h"
Eugene Zelenko7855e772018-04-03 00:11:50 +000050#include "clang/Basic/ExceptionSpecificationType.h"
Leonard Chana6779422018-08-06 16:42:37 +000051#include "clang/Basic/FixedPoint.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000052#include "clang/Basic/IdentifierTable.h"
53#include "clang/Basic/LLVM.h"
54#include "clang/Basic/LangOptions.h"
55#include "clang/Basic/Linkage.h"
56#include "clang/Basic/ObjCRuntime.h"
57#include "clang/Basic/SanitizerBlacklist.h"
58#include "clang/Basic/SourceLocation.h"
Chris Lattnerd2868512009-03-28 03:45:20 +000059#include "clang/Basic/SourceManager.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000060#include "clang/Basic/Specifiers.h"
61#include "clang/Basic/TargetCXXABI.h"
Chris Lattner4dc8a6f2007-05-20 23:50:58 +000062#include "clang/Basic/TargetInfo.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000063#include "clang/Basic/XRayLists.h"
64#include "llvm/ADT/APInt.h"
65#include "llvm/ADT/APSInt.h"
66#include "llvm/ADT/ArrayRef.h"
67#include "llvm/ADT/DenseMap.h"
68#include "llvm/ADT/DenseSet.h"
69#include "llvm/ADT/FoldingSet.h"
70#include "llvm/ADT/None.h"
71#include "llvm/ADT/Optional.h"
72#include "llvm/ADT/PointerUnion.h"
73#include "llvm/ADT/STLExtras.h"
74#include "llvm/ADT/SmallPtrSet.h"
75#include "llvm/ADT/SmallVector.h"
Anders Carlssond8499822007-10-29 05:01:08 +000076#include "llvm/ADT/StringExtras.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000077#include "llvm/ADT/StringRef.h"
Robert Lyttoneaf6f362013-11-12 10:09:34 +000078#include "llvm/ADT/Triple.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000079#include "llvm/Support/Capacity.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000080#include "llvm/Support/Casting.h"
81#include "llvm/Support/Compiler.h"
82#include "llvm/Support/ErrorHandling.h"
Nate Begemanb699c9b2009-01-18 06:42:49 +000083#include "llvm/Support/MathExtras.h"
Benjamin Kramer1402ce32009-10-24 09:57:09 +000084#include "llvm/Support/raw_ostream.h"
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000085#include <algorithm>
86#include <cassert>
87#include <cstddef>
88#include <cstdint>
89#include <cstdlib>
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +000090#include <map>
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000091#include <memory>
92#include <string>
93#include <tuple>
94#include <utility>
Anders Carlssona4267a62009-07-18 21:19:52 +000095
Chris Lattnerddc135e2006-11-10 06:34:16 +000096using namespace clang;
97
Douglas Gregor9672f922010-07-03 00:47:00 +000098unsigned ASTContext::NumImplicitDefaultConstructors;
99unsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
Douglas Gregora6d69502010-07-02 23:41:54 +0000100unsigned ASTContext::NumImplicitCopyConstructors;
101unsigned ASTContext::NumImplicitCopyConstructorsDeclared;
Alexis Huntfcaeae42011-05-25 20:50:04 +0000102unsigned ASTContext::NumImplicitMoveConstructors;
103unsigned ASTContext::NumImplicitMoveConstructorsDeclared;
Douglas Gregor330b9cf2010-07-02 21:50:04 +0000104unsigned ASTContext::NumImplicitCopyAssignmentOperators;
105unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Alexis Huntfcaeae42011-05-25 20:50:04 +0000106unsigned ASTContext::NumImplicitMoveAssignmentOperators;
107unsigned ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
Douglas Gregor7454c562010-07-02 20:37:36 +0000108unsigned ASTContext::NumImplicitDestructors;
109unsigned ASTContext::NumImplicitDestructorsDeclared;
110
Steve Naroff0af91202007-04-27 21:51:21 +0000111enum FloatingRank {
Sjoerd Meijercc623ad2017-09-08 15:15:00 +0000112 Float16Rank, HalfRank, FloatRank, DoubleRank, LongDoubleRank, Float128Rank
Steve Naroff0af91202007-04-27 21:51:21 +0000113};
114
Dmitri Gribenkof26054f2012-07-11 21:38:39 +0000115RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const {
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000116 if (!CommentsLoaded && ExternalSource) {
117 ExternalSource->ReadComments();
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +0000118
119#ifndef NDEBUG
120 ArrayRef<RawComment *> RawComments = Comments.getComments();
121 assert(std::is_sorted(RawComments.begin(), RawComments.end(),
122 BeforeThanCompare<RawComment>(SourceMgr)));
123#endif
124
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000125 CommentsLoaded = true;
126 }
127
128 assert(D);
129
Dmitri Gribenkodf17d642012-06-28 16:19:39 +0000130 // User can not attach documentation to implicit declarations.
131 if (D->isImplicit())
Craig Topper36250ad2014-05-12 05:36:57 +0000132 return nullptr;
Dmitri Gribenkodf17d642012-06-28 16:19:39 +0000133
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000134 // User can not attach documentation to implicit instantiations.
Eugene Zelenko7855e772018-04-03 00:11:50 +0000135 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000136 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
Craig Topper36250ad2014-05-12 05:36:57 +0000137 return nullptr;
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000138 }
139
Eugene Zelenko7855e772018-04-03 00:11:50 +0000140 if (const auto *VD = dyn_cast<VarDecl>(D)) {
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +0000141 if (VD->isStaticDataMember() &&
142 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
Craig Topper36250ad2014-05-12 05:36:57 +0000143 return nullptr;
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +0000144 }
145
Eugene Zelenko7855e772018-04-03 00:11:50 +0000146 if (const auto *CRD = dyn_cast<CXXRecordDecl>(D)) {
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +0000147 if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
Craig Topper36250ad2014-05-12 05:36:57 +0000148 return nullptr;
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +0000149 }
150
Eugene Zelenko7855e772018-04-03 00:11:50 +0000151 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000152 TemplateSpecializationKind TSK = CTSD->getSpecializationKind();
153 if (TSK == TSK_ImplicitInstantiation ||
154 TSK == TSK_Undeclared)
Craig Topper36250ad2014-05-12 05:36:57 +0000155 return nullptr;
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000156 }
157
Eugene Zelenko7855e772018-04-03 00:11:50 +0000158 if (const auto *ED = dyn_cast<EnumDecl>(D)) {
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +0000159 if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
Craig Topper36250ad2014-05-12 05:36:57 +0000160 return nullptr;
Dmitri Gribenkob1ad9932012-08-20 22:36:31 +0000161 }
Eugene Zelenko7855e772018-04-03 00:11:50 +0000162 if (const auto *TD = dyn_cast<TagDecl>(D)) {
Fariborz Jahanian799a4032013-04-17 21:05:20 +0000163 // When tag declaration (but not definition!) is part of the
164 // decl-specifier-seq of some other declaration, it doesn't get comment
165 if (TD->isEmbeddedInDeclarator() && !TD->isCompleteDefinition())
Craig Topper36250ad2014-05-12 05:36:57 +0000166 return nullptr;
Fariborz Jahanian799a4032013-04-17 21:05:20 +0000167 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000168 // TODO: handle comments for function parameters properly.
169 if (isa<ParmVarDecl>(D))
Craig Topper36250ad2014-05-12 05:36:57 +0000170 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000171
Dmitri Gribenko34df2202012-07-31 22:37:06 +0000172 // TODO: we could look up template parameter documentation in the template
173 // documentation.
174 if (isa<TemplateTypeParmDecl>(D) ||
175 isa<NonTypeTemplateParmDecl>(D) ||
176 isa<TemplateTemplateParmDecl>(D))
Craig Topper36250ad2014-05-12 05:36:57 +0000177 return nullptr;
Dmitri Gribenko34df2202012-07-31 22:37:06 +0000178
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000179 ArrayRef<RawComment *> RawComments = Comments.getComments();
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000180
181 // If there are no comments anywhere, we won't find anything.
182 if (RawComments.empty())
Craig Topper36250ad2014-05-12 05:36:57 +0000183 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000184
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000185 // Find declaration location.
186 // For Objective-C declarations we generally don't expect to have multiple
187 // declarators, thus use declaration starting location as the "declaration
188 // location".
189 // For all other declarations multiple declarators are used quite frequently,
190 // so we use the location of the identifier as the "declaration location".
191 SourceLocation DeclLoc;
192 if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) ||
Dmitri Gribenko34df2202012-07-31 22:37:06 +0000193 isa<ObjCPropertyDecl>(D) ||
Dmitri Gribenko7f4b3772012-08-02 20:49:51 +0000194 isa<RedeclarableTemplateDecl>(D) ||
195 isa<ClassTemplateSpecializationDecl>(D))
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000196 DeclLoc = D->getBeginLoc();
Fariborz Jahanianb64e95f2013-07-24 22:58:51 +0000197 else {
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000198 DeclLoc = D->getLocation();
Dmitri Gribenkoef099dc2014-03-27 16:40:51 +0000199 if (DeclLoc.isMacroID()) {
200 if (isa<TypedefDecl>(D)) {
201 // If location of the typedef name is in a macro, it is because being
202 // declared via a macro. Try using declaration's starting location as
203 // the "declaration location".
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000204 DeclLoc = D->getBeginLoc();
Eugene Zelenko7855e772018-04-03 00:11:50 +0000205 } else if (const auto *TD = dyn_cast<TagDecl>(D)) {
Dmitri Gribenkoef099dc2014-03-27 16:40:51 +0000206 // If location of the tag decl is inside a macro, but the spelling of
207 // the tag name comes from a macro argument, it looks like a special
208 // macro like NS_ENUM is being used to define the tag decl. In that
209 // case, adjust the source location to the expansion loc so that we can
210 // attach the comment to the tag decl.
211 if (SourceMgr.isMacroArgExpansion(DeclLoc) &&
212 TD->isCompleteDefinition())
213 DeclLoc = SourceMgr.getExpansionLoc(DeclLoc);
214 }
215 }
Fariborz Jahanianb64e95f2013-07-24 22:58:51 +0000216 }
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +0000217
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000218 // If the declaration doesn't map directly to a location in a file, we
219 // can't find the comment.
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000220 if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
Craig Topper36250ad2014-05-12 05:36:57 +0000221 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000222
223 // Find the comment that occurs just after this declaration.
Dmitri Gribenko82ea9472012-07-17 22:01:09 +0000224 ArrayRef<RawComment *>::iterator Comment;
225 {
226 // When searching for comments during parsing, the comment we are looking
227 // for is usually among the last two comments we parsed -- check them
228 // first.
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +0000229 RawComment CommentAtDeclLoc(
David L. Jones13d5a872018-03-02 00:07:45 +0000230 SourceMgr, SourceRange(DeclLoc), LangOpts.CommentOpts, false);
Dmitri Gribenko82ea9472012-07-17 22:01:09 +0000231 BeforeThanCompare<RawComment> Compare(SourceMgr);
232 ArrayRef<RawComment *>::iterator MaybeBeforeDecl = RawComments.end() - 1;
233 bool Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
234 if (!Found && RawComments.size() >= 2) {
235 MaybeBeforeDecl--;
236 Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
237 }
238
239 if (Found) {
240 Comment = MaybeBeforeDecl + 1;
241 assert(Comment == std::lower_bound(RawComments.begin(), RawComments.end(),
242 &CommentAtDeclLoc, Compare));
243 } else {
244 // Slow path.
245 Comment = std::lower_bound(RawComments.begin(), RawComments.end(),
246 &CommentAtDeclLoc, Compare);
247 }
248 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000249
250 // Decompose the location for the declaration and find the beginning of the
251 // file buffer.
252 std::pair<FileID, unsigned> DeclLocDecomp = SourceMgr.getDecomposedLoc(DeclLoc);
253
254 // First check whether we have a trailing comment.
255 if (Comment != RawComments.end() &&
David L. Jones13d5a872018-03-02 00:07:45 +0000256 ((*Comment)->isDocumentation() || LangOpts.CommentOpts.ParseAllComments)
257 && (*Comment)->isTrailingComment() &&
Fariborz Jahanianfad28542013-08-06 23:29:00 +0000258 (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D) ||
Fariborz Jahanian3ab62222013-08-07 16:40:29 +0000259 isa<ObjCMethodDecl>(D) || isa<ObjCPropertyDecl>(D))) {
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000260 std::pair<FileID, unsigned> CommentBeginDecomp
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000261 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getBegin());
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000262 // Check that Doxygen trailing comment comes after the declaration, starts
263 // on the same line and in the same file as the declaration.
264 if (DeclLocDecomp.first == CommentBeginDecomp.first &&
265 SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second)
266 == SourceMgr.getLineNumber(CommentBeginDecomp.first,
267 CommentBeginDecomp.second)) {
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000268 return *Comment;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000269 }
270 }
271
272 // The comment just after the declaration was not a trailing comment.
273 // Let's look at the previous comment.
274 if (Comment == RawComments.begin())
Craig Topper36250ad2014-05-12 05:36:57 +0000275 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000276 --Comment;
277
278 // Check that we actually have a non-member Doxygen comment.
David L. Jones13d5a872018-03-02 00:07:45 +0000279 if (!((*Comment)->isDocumentation() ||
280 LangOpts.CommentOpts.ParseAllComments) ||
281 (*Comment)->isTrailingComment())
Craig Topper36250ad2014-05-12 05:36:57 +0000282 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000283
284 // Decompose the end of the comment.
285 std::pair<FileID, unsigned> CommentEndDecomp
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000286 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getEnd());
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000287
288 // If the comment and the declaration aren't in the same file, then they
289 // aren't related.
290 if (DeclLocDecomp.first != CommentEndDecomp.first)
Craig Topper36250ad2014-05-12 05:36:57 +0000291 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000292
293 // Get the corresponding buffer.
294 bool Invalid = false;
295 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
296 &Invalid).data();
297 if (Invalid)
Craig Topper36250ad2014-05-12 05:36:57 +0000298 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000299
300 // Extract text between the comment and declaration.
301 StringRef Text(Buffer + CommentEndDecomp.second,
302 DeclLocDecomp.second - CommentEndDecomp.second);
303
Dmitri Gribenko7e8729b2012-06-27 23:43:37 +0000304 // There should be no other declarations or preprocessor directives between
305 // comment and declaration.
Argyrios Kyrtzidisb534d3a2013-07-26 18:38:12 +0000306 if (Text.find_first_of(";{}#@") != StringRef::npos)
Craig Topper36250ad2014-05-12 05:36:57 +0000307 return nullptr;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000308
Dmitri Gribenko7dd29d42012-07-06 18:19:34 +0000309 return *Comment;
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000310}
311
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000312/// If we have a 'templated' declaration for a template, adjust 'D' to
313/// refer to the actual template.
Dmitri Gribenko90631802012-08-22 17:44:32 +0000314/// If we have an implicit instantiation, adjust 'D' to refer to template.
Eugene Zelenko5e5e5642017-11-23 01:20:07 +0000315static const Decl *adjustDeclToTemplate(const Decl *D) {
Eugene Zelenko7855e772018-04-03 00:11:50 +0000316 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
Dmitri Gribenko90631802012-08-22 17:44:32 +0000317 // Is this function declaration part of a function template?
Douglas Gregor35ceb272012-08-13 16:37:30 +0000318 if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
Dmitri Gribenko90631802012-08-22 17:44:32 +0000319 return FTD;
320
321 // Nothing to do if function is not an implicit instantiation.
322 if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
323 return D;
324
325 // Function is an implicit instantiation of a function template?
326 if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate())
327 return FTD;
328
329 // Function is instantiated from a member definition of a class template?
330 if (const FunctionDecl *MemberDecl =
331 FD->getInstantiatedFromMemberFunction())
332 return MemberDecl;
333
334 return D;
Douglas Gregor35ceb272012-08-13 16:37:30 +0000335 }
Eugene Zelenko7855e772018-04-03 00:11:50 +0000336 if (const auto *VD = dyn_cast<VarDecl>(D)) {
Dmitri Gribenko90631802012-08-22 17:44:32 +0000337 // Static data member is instantiated from a member definition of a class
338 // template?
339 if (VD->isStaticDataMember())
340 if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember())
341 return MemberDecl;
342
343 return D;
344 }
Eugene Zelenko7855e772018-04-03 00:11:50 +0000345 if (const auto *CRD = dyn_cast<CXXRecordDecl>(D)) {
Dmitri Gribenko90631802012-08-22 17:44:32 +0000346 // Is this class declaration part of a class template?
347 if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate())
348 return CTD;
349
350 // Class is an implicit instantiation of a class template or partial
351 // specialization?
Eugene Zelenko7855e772018-04-03 00:11:50 +0000352 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(CRD)) {
Dmitri Gribenko90631802012-08-22 17:44:32 +0000353 if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation)
354 return D;
355 llvm::PointerUnion<ClassTemplateDecl *,
356 ClassTemplatePartialSpecializationDecl *>
357 PU = CTSD->getSpecializedTemplateOrPartial();
358 return PU.is<ClassTemplateDecl*>() ?
359 static_cast<const Decl*>(PU.get<ClassTemplateDecl *>()) :
360 static_cast<const Decl*>(
361 PU.get<ClassTemplatePartialSpecializationDecl *>());
362 }
363
364 // Class is instantiated from a member definition of a class template?
365 if (const MemberSpecializationInfo *Info =
366 CRD->getMemberSpecializationInfo())
367 return Info->getInstantiatedFrom();
368
369 return D;
370 }
Eugene Zelenko7855e772018-04-03 00:11:50 +0000371 if (const auto *ED = dyn_cast<EnumDecl>(D)) {
Dmitri Gribenko90631802012-08-22 17:44:32 +0000372 // Enum is instantiated from a member definition of a class template?
373 if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum())
374 return MemberDecl;
375
376 return D;
377 }
378 // FIXME: Adjust alias templates?
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000379 return D;
380}
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000381
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000382const RawComment *ASTContext::getRawCommentForAnyRedecl(
383 const Decl *D,
384 const Decl **OriginalDecl) const {
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000385 D = adjustDeclToTemplate(D);
Douglas Gregor35ceb272012-08-13 16:37:30 +0000386
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000387 // Check whether we have cached a comment for this declaration already.
388 {
389 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
390 RedeclComments.find(D);
391 if (Pos != RedeclComments.end()) {
392 const RawCommentAndCacheFlags &Raw = Pos->second;
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000393 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
394 if (OriginalDecl)
395 *OriginalDecl = Raw.getOriginalDecl();
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000396 return Raw.getRaw();
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000397 }
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000398 }
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000399 }
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000400
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000401 // Search for comments attached to declarations in the redeclaration chain.
Craig Topper36250ad2014-05-12 05:36:57 +0000402 const RawComment *RC = nullptr;
403 const Decl *OriginalDeclForRC = nullptr;
Aaron Ballman86c93902014-03-06 23:45:36 +0000404 for (auto I : D->redecls()) {
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000405 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
Aaron Ballman86c93902014-03-06 23:45:36 +0000406 RedeclComments.find(I);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000407 if (Pos != RedeclComments.end()) {
408 const RawCommentAndCacheFlags &Raw = Pos->second;
409 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
410 RC = Raw.getRaw();
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000411 OriginalDeclForRC = Raw.getOriginalDecl();
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000412 break;
413 }
414 } else {
Aaron Ballman86c93902014-03-06 23:45:36 +0000415 RC = getRawCommentForDeclNoCache(I);
416 OriginalDeclForRC = I;
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000417 RawCommentAndCacheFlags Raw;
418 if (RC) {
Will Wilsonf9de5362015-10-27 17:01:10 +0000419 // Call order swapped to work around ICE in VS2015 RTM (Release Win32)
420 // https://connect.microsoft.com/VisualStudio/feedback/details/1741530
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000421 Raw.setKind(RawCommentAndCacheFlags::FromDecl);
Will Wilsonf9de5362015-10-27 17:01:10 +0000422 Raw.setRaw(RC);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000423 } else
424 Raw.setKind(RawCommentAndCacheFlags::NoCommentInDecl);
Aaron Ballman86c93902014-03-06 23:45:36 +0000425 Raw.setOriginalDecl(I);
426 RedeclComments[I] = Raw;
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000427 if (RC)
428 break;
429 }
430 }
431
Dmitri Gribenko5c8897d2012-06-28 16:25:36 +0000432 // If we found a comment, it should be a documentation comment.
David L. Jones13d5a872018-03-02 00:07:45 +0000433 assert(!RC || RC->isDocumentation() || LangOpts.CommentOpts.ParseAllComments);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000434
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000435 if (OriginalDecl)
436 *OriginalDecl = OriginalDeclForRC;
437
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000438 // Update cache for every declaration in the redeclaration chain.
439 RawCommentAndCacheFlags Raw;
440 Raw.setRaw(RC);
441 Raw.setKind(RawCommentAndCacheFlags::FromRedecl);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000442 Raw.setOriginalDecl(OriginalDeclForRC);
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000443
Aaron Ballman86c93902014-03-06 23:45:36 +0000444 for (auto I : D->redecls()) {
445 RawCommentAndCacheFlags &R = RedeclComments[I];
Dmitri Gribenkoa43ec182012-08-11 00:51:43 +0000446 if (R.getKind() == RawCommentAndCacheFlags::NoCommentInDecl)
447 R = Raw;
448 }
449
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000450 return RC;
451}
452
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000453static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
454 SmallVectorImpl<const NamedDecl *> &Redeclared) {
455 const DeclContext *DC = ObjCMethod->getDeclContext();
Eugene Zelenko7855e772018-04-03 00:11:50 +0000456 if (const auto *IMD = dyn_cast<ObjCImplDecl>(DC)) {
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000457 const ObjCInterfaceDecl *ID = IMD->getClassInterface();
458 if (!ID)
459 return;
460 // Add redeclared method here.
Aaron Ballmanb4a53452014-03-13 21:57:01 +0000461 for (const auto *Ext : ID->known_extensions()) {
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000462 if (ObjCMethodDecl *RedeclaredMethod =
Douglas Gregor048fbfa2013-01-16 23:00:23 +0000463 Ext->getMethod(ObjCMethod->getSelector(),
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000464 ObjCMethod->isInstanceMethod()))
465 Redeclared.push_back(RedeclaredMethod);
466 }
467 }
468}
469
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000470comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC,
471 const Decl *D) const {
Eugene Zelenko7855e772018-04-03 00:11:50 +0000472 auto *ThisDeclInfo = new (*this) comments::DeclInfo;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000473 ThisDeclInfo->CommentDecl = D;
474 ThisDeclInfo->IsFilled = false;
475 ThisDeclInfo->fill();
476 ThisDeclInfo->CommentDecl = FC->getDecl();
Argyrios Kyrtzidis7daabbd2014-04-27 22:53:03 +0000477 if (!ThisDeclInfo->TemplateParameters)
478 ThisDeclInfo->TemplateParameters = FC->getDeclInfo()->TemplateParameters;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000479 comments::FullComment *CFC =
480 new (*this) comments::FullComment(FC->getBlocks(),
481 ThisDeclInfo);
482 return CFC;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000483}
484
Richard Smithb39b9d52013-05-21 05:24:00 +0000485comments::FullComment *ASTContext::getLocalCommentForDeclUncached(const Decl *D) const {
486 const RawComment *RC = getRawCommentForDeclNoCache(D);
Craig Topper36250ad2014-05-12 05:36:57 +0000487 return RC ? RC->parse(*this, nullptr, D) : nullptr;
Richard Smithb39b9d52013-05-21 05:24:00 +0000488}
489
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000490comments::FullComment *ASTContext::getCommentForDecl(
491 const Decl *D,
492 const Preprocessor *PP) const {
Fariborz Jahanian096f7c12013-05-13 17:27:00 +0000493 if (D->isInvalidDecl())
Craig Topper36250ad2014-05-12 05:36:57 +0000494 return nullptr;
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000495 D = adjustDeclToTemplate(D);
Fangrui Song6907ce22018-07-30 19:24:48 +0000496
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000497 const Decl *Canonical = D->getCanonicalDecl();
498 llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
499 ParsedComments.find(Canonical);
Fangrui Song6907ce22018-07-30 19:24:48 +0000500
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000501 if (Pos != ParsedComments.end()) {
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000502 if (Canonical != D) {
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000503 comments::FullComment *FC = Pos->second;
Fariborz Jahanian42e31322012-10-11 23:52:50 +0000504 comments::FullComment *CFC = cloneFullComment(FC, D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000505 return CFC;
506 }
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000507 return Pos->second;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000508 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000509
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000510 const Decl *OriginalDecl;
Fangrui Song6907ce22018-07-30 19:24:48 +0000511
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000512 const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000513 if (!RC) {
514 if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +0000515 SmallVector<const NamedDecl*, 8> Overridden;
Eugene Zelenko7855e772018-04-03 00:11:50 +0000516 const auto *OMD = dyn_cast<ObjCMethodDecl>(D);
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000517 if (OMD && OMD->isPropertyAccessor())
518 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
519 if (comments::FullComment *FC = getCommentForDecl(PDecl, PP))
520 return cloneFullComment(FC, D);
Fariborz Jahanian37494a12013-01-12 00:28:34 +0000521 if (OMD)
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +0000522 addRedeclaredMethods(OMD, Overridden);
523 getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000524 for (unsigned i = 0, e = Overridden.size(); i < e; i++)
525 if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
526 return cloneFullComment(FC, D);
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000527 }
Eugene Zelenko7855e772018-04-03 00:11:50 +0000528 else if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) {
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000529 // Attach any tag type's documentation to its typedef if latter
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000530 // does not have one of its own.
Fariborz Jahanian40abf342013-01-25 22:48:32 +0000531 QualType QT = TD->getUnderlyingType();
Eugene Zelenko7855e772018-04-03 00:11:50 +0000532 if (const auto *TT = QT->getAs<TagType>())
Dmitri Gribenko01b06512013-01-27 21:18:39 +0000533 if (const Decl *TD = TT->getDecl())
534 if (comments::FullComment *FC = getCommentForDecl(TD, PP))
Fariborz Jahanian66024d02013-01-25 23:08:39 +0000535 return cloneFullComment(FC, D);
Fariborz Jahanian40abf342013-01-25 22:48:32 +0000536 }
Eugene Zelenko7855e772018-04-03 00:11:50 +0000537 else if (const auto *IC = dyn_cast<ObjCInterfaceDecl>(D)) {
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000538 while (IC->getSuperClass()) {
539 IC = IC->getSuperClass();
540 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
541 return cloneFullComment(FC, D);
542 }
543 }
Eugene Zelenko7855e772018-04-03 00:11:50 +0000544 else if (const auto *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000545 if (const ObjCInterfaceDecl *IC = CD->getClassInterface())
546 if (comments::FullComment *FC = getCommentForDecl(IC, PP))
547 return cloneFullComment(FC, D);
548 }
Eugene Zelenko7855e772018-04-03 00:11:50 +0000549 else if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) {
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000550 if (!(RD = RD->getDefinition()))
Craig Topper36250ad2014-05-12 05:36:57 +0000551 return nullptr;
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000552 // Check non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +0000553 for (const auto &I : RD->bases()) {
554 if (I.isVirtual() || (I.getAccessSpecifier() != AS_public))
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000555 continue;
Aaron Ballman574705e2014-03-13 15:41:46 +0000556 QualType Ty = I.getType();
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000557 if (Ty.isNull())
558 continue;
559 if (const CXXRecordDecl *NonVirtualBase = Ty->getAsCXXRecordDecl()) {
560 if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
561 continue;
Fangrui Song6907ce22018-07-30 19:24:48 +0000562
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000563 if (comments::FullComment *FC = getCommentForDecl((NonVirtualBase), PP))
564 return cloneFullComment(FC, D);
565 }
566 }
567 // Check virtual bases.
Aaron Ballman445a9392014-03-13 16:15:17 +0000568 for (const auto &I : RD->vbases()) {
569 if (I.getAccessSpecifier() != AS_public)
Fariborz Jahanian5a2e4a22013-04-26 23:34:36 +0000570 continue;
Aaron Ballman445a9392014-03-13 16:15:17 +0000571 QualType Ty = I.getType();
Fariborz Jahaniane970c1b2013-04-26 20:55:38 +0000572 if (Ty.isNull())
573 continue;
574 if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
575 if (!(VirtualBase= VirtualBase->getDefinition()))
576 continue;
577 if (comments::FullComment *FC = getCommentForDecl((VirtualBase), PP))
578 return cloneFullComment(FC, D);
579 }
580 }
581 }
Craig Topper36250ad2014-05-12 05:36:57 +0000582 return nullptr;
Fariborz Jahanian1c883b92012-10-10 18:34:52 +0000583 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000584
Dmitri Gribenkobfda9f72012-08-22 18:12:19 +0000585 // If the RawComment was attached to other redeclaration of this Decl, we
586 // should parse the comment in context of that other Decl. This is important
587 // because comments can contain references to parameter names which can be
588 // different across redeclarations.
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000589 if (D != OriginalDecl)
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000590 return getCommentForDecl(OriginalDecl, PP);
Dmitri Gribenko4ae66a32012-08-16 18:19:43 +0000591
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000592 comments::FullComment *FC = RC->parse(*this, PP, D);
Dmitri Gribenkob2610882012-08-14 17:17:18 +0000593 ParsedComments[Canonical] = FC;
594 return FC;
Dmitri Gribenkoec925312012-07-06 00:28:32 +0000595}
596
Fangrui Song6907ce22018-07-30 19:24:48 +0000597void
598ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000599 TemplateTemplateParmDecl *Parm) {
600 ID.AddInteger(Parm->getDepth());
601 ID.AddInteger(Parm->getPosition());
Douglas Gregorf5500772011-01-05 15:48:55 +0000602 ID.AddBoolean(Parm->isParameterPack());
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000603
604 TemplateParameterList *Params = Parm->getTemplateParameters();
605 ID.AddInteger(Params->size());
Fangrui Song6907ce22018-07-30 19:24:48 +0000606 for (TemplateParameterList::const_iterator P = Params->begin(),
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000607 PEnd = Params->end();
608 P != PEnd; ++P) {
Eugene Zelenko7855e772018-04-03 00:11:50 +0000609 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000610 ID.AddInteger(0);
611 ID.AddBoolean(TTP->isParameterPack());
612 continue;
613 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000614
Eugene Zelenko7855e772018-04-03 00:11:50 +0000615 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000616 ID.AddInteger(1);
Douglas Gregorf5500772011-01-05 15:48:55 +0000617 ID.AddBoolean(NTTP->isParameterPack());
Eli Friedman205a4292012-03-07 01:09:33 +0000618 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000619 if (NTTP->isExpandedParameterPack()) {
620 ID.AddBoolean(true);
621 ID.AddInteger(NTTP->getNumExpansionTypes());
Eli Friedman205a4292012-03-07 01:09:33 +0000622 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
623 QualType T = NTTP->getExpansionType(I);
624 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
625 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000626 } else
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000627 ID.AddBoolean(false);
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000628 continue;
629 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000630
Eugene Zelenko7855e772018-04-03 00:11:50 +0000631 auto *TTP = cast<TemplateTemplateParmDecl>(*P);
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000632 ID.AddInteger(2);
633 Profile(ID, TTP);
634 }
635}
636
637TemplateTemplateParmDecl *
638ASTContext::getCanonicalTemplateTemplateParmDecl(
Jay Foad39c79802011-01-12 09:06:06 +0000639 TemplateTemplateParmDecl *TTP) const {
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000640 // Check if we already have a canonical template template parameter.
641 llvm::FoldingSetNodeID ID;
642 CanonicalTemplateTemplateParm::Profile(ID, TTP);
Craig Topper36250ad2014-05-12 05:36:57 +0000643 void *InsertPos = nullptr;
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000644 CanonicalTemplateTemplateParm *Canonical
645 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
646 if (Canonical)
647 return Canonical->getParam();
Fangrui Song6907ce22018-07-30 19:24:48 +0000648
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000649 // Build a canonical template parameter list.
650 TemplateParameterList *Params = TTP->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000651 SmallVector<NamedDecl *, 4> CanonParams;
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000652 CanonParams.reserve(Params->size());
Fangrui Song6907ce22018-07-30 19:24:48 +0000653 for (TemplateParameterList::const_iterator P = Params->begin(),
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000654 PEnd = Params->end();
655 P != PEnd; ++P) {
Eugene Zelenko7855e772018-04-03 00:11:50 +0000656 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000657 CanonParams.push_back(
Fangrui Song6907ce22018-07-30 19:24:48 +0000658 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnarab3185b02011-03-06 15:48:19 +0000659 SourceLocation(),
660 SourceLocation(),
661 TTP->getDepth(),
Craig Topper36250ad2014-05-12 05:36:57 +0000662 TTP->getIndex(), nullptr, false,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000663 TTP->isParameterPack()));
Eugene Zelenko7855e772018-04-03 00:11:50 +0000664 else if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000665 QualType T = getCanonicalType(NTTP->getType());
666 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
667 NonTypeTemplateParmDecl *Param;
668 if (NTTP->isExpandedParameterPack()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000669 SmallVector<QualType, 2> ExpandedTypes;
670 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000671 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
672 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
673 ExpandedTInfos.push_back(
674 getTrivialTypeSourceInfo(ExpandedTypes.back()));
675 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000676
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000677 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000678 SourceLocation(),
679 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000680 NTTP->getDepth(),
Craig Topper36250ad2014-05-12 05:36:57 +0000681 NTTP->getPosition(), nullptr,
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000682 T,
683 TInfo,
David Majnemerdfecf1a2016-07-06 04:19:16 +0000684 ExpandedTypes,
685 ExpandedTInfos);
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000686 } else {
687 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +0000688 SourceLocation(),
689 SourceLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000690 NTTP->getDepth(),
Craig Topper36250ad2014-05-12 05:36:57 +0000691 NTTP->getPosition(), nullptr,
Douglas Gregor0231d8d2011-01-19 20:10:05 +0000692 T,
693 NTTP->isParameterPack(),
694 TInfo);
695 }
696 CanonParams.push_back(Param);
697
698 } else
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000699 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
700 cast<TemplateTemplateParmDecl>(*P)));
701 }
702
Hubert Tonge4a0c0e2016-07-30 22:33:34 +0000703 assert(!TTP->getRequiresClause() &&
704 "Unexpected requires-clause on template template-parameter");
George Burgess IVb7e4e482016-08-25 01:54:37 +0000705 Expr *const CanonRequiresClause = nullptr;
Hubert Tonge4a0c0e2016-07-30 22:33:34 +0000706
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000707 TemplateTemplateParmDecl *CanonTTP
Fangrui Song6907ce22018-07-30 19:24:48 +0000708 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000709 SourceLocation(), TTP->getDepth(),
Fangrui Song6907ce22018-07-30 19:24:48 +0000710 TTP->getPosition(),
Douglas Gregorf5500772011-01-05 15:48:55 +0000711 TTP->isParameterPack(),
Craig Topper36250ad2014-05-12 05:36:57 +0000712 nullptr,
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000713 TemplateParameterList::Create(*this, SourceLocation(),
714 SourceLocation(),
David Majnemer902f8c62015-12-27 07:16:27 +0000715 CanonParams,
Hubert Tonge4a0c0e2016-07-30 22:33:34 +0000716 SourceLocation(),
717 CanonRequiresClause));
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000718
719 // Get the new insert position for the node we care about.
720 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +0000721 assert(!Canonical && "Shouldn't be in the map!");
Douglas Gregor7dbfb462010-06-16 21:09:37 +0000722 (void)Canonical;
723
724 // Create the canonical template template parameter entry.
725 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
726 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
727 return CanonTTP;
728}
729
Charles Davis53c59df2010-08-16 03:33:14 +0000730CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
Craig Topper36250ad2014-05-12 05:36:57 +0000731 if (!LangOpts.CPlusPlus) return nullptr;
John McCall86353412010-08-21 22:46:04 +0000732
John McCall359b8852013-01-25 22:30:49 +0000733 switch (T.getCXXABI().getKind()) {
Joerg Sonnenbergerdaa13aa2014-05-13 11:20:16 +0000734 case TargetCXXABI::GenericARM: // Same as Itanium at this level
John McCall359b8852013-01-25 22:30:49 +0000735 case TargetCXXABI::iOS:
Tim Northovera2ee4332014-03-29 15:09:45 +0000736 case TargetCXXABI::iOS64:
Tim Northover756447a2015-10-30 16:30:36 +0000737 case TargetCXXABI::WatchOS:
Joerg Sonnenbergerdaa13aa2014-05-13 11:20:16 +0000738 case TargetCXXABI::GenericAArch64:
Zoran Jovanovic26a12162015-02-18 15:21:35 +0000739 case TargetCXXABI::GenericMIPS:
John McCall359b8852013-01-25 22:30:49 +0000740 case TargetCXXABI::GenericItanium:
Dan Gohmanc2853072015-09-03 22:51:53 +0000741 case TargetCXXABI::WebAssembly:
Charles Davis53c59df2010-08-16 03:33:14 +0000742 return CreateItaniumCXXABI(*this);
John McCall359b8852013-01-25 22:30:49 +0000743 case TargetCXXABI::Microsoft:
Charles Davis6bcb07a2010-08-19 02:18:14 +0000744 return CreateMicrosoftCXXABI(*this);
745 }
David Blaikie8a40f702012-01-17 06:56:22 +0000746 llvm_unreachable("Invalid CXXABI type!");
Charles Davis53c59df2010-08-16 03:33:14 +0000747}
748
Alexander Richardson6d989432017-10-15 18:48:14 +0000749static const LangASMap *getAddressSpaceMap(const TargetInfo &T,
750 const LangOptions &LOpts) {
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000751 if (LOpts.FakeAddressSpaceMap) {
752 // The fake address space map must have a distinct entry for each
753 // language-specific address space.
754 static const unsigned FakeAddrSpaceMap[] = {
Yaxun Liub34ec822017-04-11 17:24:23 +0000755 0, // Default
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000756 1, // opencl_global
Egor Churaev28f00aa2016-12-23 16:11:25 +0000757 3, // opencl_local
758 2, // opencl_constant
Yaxun Liub7318e02017-10-13 03:37:48 +0000759 0, // opencl_private
Anastasia Stulova2c8dcfb2014-11-26 14:10:06 +0000760 4, // opencl_generic
761 5, // cuda_device
762 6, // cuda_constant
763 7 // cuda_shared
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000764 };
Douglas Gregore8bbc122011-09-02 00:18:52 +0000765 return &FakeAddrSpaceMap;
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000766 } else {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000767 return &T.getAddressSpaceMap();
Peter Collingbourne599cb8e2011-03-18 22:38:29 +0000768 }
769}
770
David Tweed31d09b02013-09-13 12:04:22 +0000771static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI,
772 const LangOptions &LangOpts) {
773 switch (LangOpts.getAddressSpaceMapMangling()) {
David Tweed31d09b02013-09-13 12:04:22 +0000774 case LangOptions::ASMM_Target:
775 return TI.useAddressSpaceMapMangling();
776 case LangOptions::ASMM_On:
777 return true;
778 case LangOptions::ASMM_Off:
779 return false;
780 }
NAKAMURA Takumi5c81ca42013-09-13 17:12:09 +0000781 llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.");
David Tweed31d09b02013-09-13 12:04:22 +0000782}
783
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000784ASTContext::ASTContext(LangOptions &LOpts, SourceManager &SM,
Daniel Dunbar221fa942008-08-11 04:54:23 +0000785 IdentifierTable &idents, SelectorTable &sels,
Alp Toker08043432014-05-03 03:46:04 +0000786 Builtin::Context &builtins)
Alexey Samsonov0b15e342014-10-15 22:17:27 +0000787 : FunctionProtoTypes(this_()), TemplateSpecializationTypes(this_()),
788 DependentTemplateSpecializationTypes(this_()),
Eugene Zelenko5e5e5642017-11-23 01:20:07 +0000789 SubstTemplateTemplateParmPacks(this_()), SourceMgr(SM), LangOpts(LOpts),
Alexey Samsonova511cdd2015-02-04 17:40:08 +0000790 SanitizerBL(new SanitizerBlacklist(LangOpts.SanitizerBlacklistFiles, SM)),
Dean Michael Berris835832d2017-03-30 00:29:36 +0000791 XRayFilter(new XRayFunctionFilter(LangOpts.XRayAlwaysInstrumentFiles,
Dean Michael Berris20dc6ef2018-04-09 04:02:09 +0000792 LangOpts.XRayNeverInstrumentFiles,
793 LangOpts.XRayAttrListFiles, SM)),
Artem Belevichb5bc9232015-09-22 17:23:22 +0000794 PrintingPolicy(LOpts), Idents(idents), Selectors(sels),
Eugene Zelenko5e5e5642017-11-23 01:20:07 +0000795 BuiltinInfo(builtins), DeclarationNames(*this), Comments(SM),
Eric Fiselier0683c0e2018-05-07 21:07:10 +0000796 CommentCommandTraits(BumpAlloc, LOpts.CommentOpts),
797 CompCategories(this_()), LastSDM(nullptr, 0) {
Daniel Dunbar221fa942008-08-11 04:54:23 +0000798 TUDecl = TranslationUnitDecl::Create(*this);
799}
800
Chris Lattnerd5973eb2006-11-12 00:53:46 +0000801ASTContext::~ASTContext() {
Manuel Klimek95403e62014-05-21 13:28:59 +0000802 ReleaseParentMapEntries();
803
Ted Kremenekda4e0d32010-02-11 07:12:28 +0000804 // Release the DenseMaps associated with DeclContext objects.
805 // FIXME: Is this the ideal solution?
806 ReleaseDeclContextMaps();
Douglas Gregor832940b2010-03-02 23:58:15 +0000807
Manuel Klimeka7328992013-06-03 13:51:33 +0000808 // Call all of the deallocation functions on all of their targets.
Chandler Carruthff5a01a2015-12-30 03:00:23 +0000809 for (auto &Pair : Deallocations)
810 (Pair.first)(Pair.second);
Manuel Klimeka7328992013-06-03 13:51:33 +0000811
Ted Kremenek076baeb2010-06-08 23:00:58 +0000812 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
Douglas Gregor5b11d492010-07-25 17:53:33 +0000813 // because they can contain DenseMaps.
814 for (llvm::DenseMap<const ObjCContainerDecl*,
815 const ASTRecordLayout*>::iterator
816 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
817 // Increment in loop to prevent using deallocated memory.
Eugene Zelenko7855e772018-04-03 00:11:50 +0000818 if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
Douglas Gregor5b11d492010-07-25 17:53:33 +0000819 R->Destroy(*this);
820
Ted Kremenek076baeb2010-06-08 23:00:58 +0000821 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
822 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
823 // Increment in loop to prevent using deallocated memory.
Eugene Zelenko7855e772018-04-03 00:11:50 +0000824 if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
Ted Kremenek076baeb2010-06-08 23:00:58 +0000825 R->Destroy(*this);
826 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000827
Douglas Gregor561eceb2010-08-30 16:49:28 +0000828 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
829 AEnd = DeclAttrs.end();
830 A != AEnd; ++A)
831 A->second->~AttrVec();
Reid Klecknerd8110b62013-09-10 20:14:30 +0000832
David Majnemere694f3e2015-08-14 14:43:50 +0000833 for (std::pair<const MaterializeTemporaryExpr *, APValue *> &MTVPair :
834 MaterializedTemporaryValues)
835 MTVPair.second->~APValue();
836
Richard Smith423f46f2016-07-20 21:38:26 +0000837 for (const auto &Value : ModuleInitializers)
838 Value.second->~PerModuleInitializers();
Douglas Gregor561eceb2010-08-30 16:49:28 +0000839}
Douglas Gregorf21eb492009-03-26 23:50:42 +0000840
Manuel Klimek95403e62014-05-21 13:28:59 +0000841void ASTContext::ReleaseParentMapEntries() {
Benjamin Kramer94355ae2015-10-23 09:04:55 +0000842 if (!PointerParents) return;
843 for (const auto &Entry : *PointerParents) {
844 if (Entry.second.is<ast_type_traits::DynTypedNode *>()) {
845 delete Entry.second.get<ast_type_traits::DynTypedNode *>();
846 } else if (Entry.second.is<ParentVector *>()) {
847 delete Entry.second.get<ParentVector *>();
848 }
849 }
850 for (const auto &Entry : *OtherParents) {
Manuel Klimek95403e62014-05-21 13:28:59 +0000851 if (Entry.second.is<ast_type_traits::DynTypedNode *>()) {
852 delete Entry.second.get<ast_type_traits::DynTypedNode *>();
Benjamin Kramer8e4a1762015-10-22 11:21:40 +0000853 } else if (Entry.second.is<ParentVector *>()) {
Manuel Klimek95403e62014-05-21 13:28:59 +0000854 delete Entry.second.get<ParentVector *>();
855 }
856 }
857}
858
Douglas Gregor1a809332010-05-23 18:26:36 +0000859void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
Chandler Carruthff5a01a2015-12-30 03:00:23 +0000860 Deallocations.push_back({Callback, Data});
Douglas Gregor1a809332010-05-23 18:26:36 +0000861}
862
Mike Stump11289f42009-09-09 15:08:12 +0000863void
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000864ASTContext::setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source) {
Benjamin Kramerd6da1a02016-06-12 20:05:23 +0000865 ExternalSource = std::move(Source);
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000866}
867
Chris Lattner4eb445d2007-01-26 01:27:23 +0000868void ASTContext::PrintStats() const {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000869 llvm::errs() << "\n*** AST Context Stats:\n";
870 llvm::errs() << " " << Types.size() << " types total.\n";
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000871
Douglas Gregora30d0462009-05-26 14:40:08 +0000872 unsigned counts[] = {
Mike Stump11289f42009-09-09 15:08:12 +0000873#define TYPE(Name, Parent) 0,
Douglas Gregora30d0462009-05-26 14:40:08 +0000874#define ABSTRACT_TYPE(Name, Parent)
875#include "clang/AST/TypeNodes.def"
876 0 // Extra
877 };
Douglas Gregorb1fe2c92009-04-07 17:20:56 +0000878
Chris Lattner4eb445d2007-01-26 01:27:23 +0000879 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
880 Type *T = Types[i];
Douglas Gregora30d0462009-05-26 14:40:08 +0000881 counts[(unsigned)T->getTypeClass()]++;
Chris Lattner4eb445d2007-01-26 01:27:23 +0000882 }
883
Douglas Gregora30d0462009-05-26 14:40:08 +0000884 unsigned Idx = 0;
885 unsigned TotalBytes = 0;
886#define TYPE(Name, Parent) \
887 if (counts[Idx]) \
Chandler Carruth3c147a72011-07-04 05:32:14 +0000888 llvm::errs() << " " << counts[Idx] << " " << #Name \
Bruno Ricci58e03222018-08-06 15:17:32 +0000889 << " types, " << sizeof(Name##Type) << " each " \
890 << "(" << counts[Idx] * sizeof(Name##Type) \
891 << " bytes)\n"; \
Douglas Gregora30d0462009-05-26 14:40:08 +0000892 TotalBytes += counts[Idx] * sizeof(Name##Type); \
893 ++Idx;
894#define ABSTRACT_TYPE(Name, Parent)
895#include "clang/AST/TypeNodes.def"
Mike Stump11289f42009-09-09 15:08:12 +0000896
Chandler Carruth3c147a72011-07-04 05:32:14 +0000897 llvm::errs() << "Total bytes = " << TotalBytes << "\n";
898
Douglas Gregor7454c562010-07-02 20:37:36 +0000899 // Implicit special member functions.
Chandler Carruth3c147a72011-07-04 05:32:14 +0000900 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
901 << NumImplicitDefaultConstructors
902 << " implicit default constructors created\n";
903 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
904 << NumImplicitCopyConstructors
905 << " implicit copy constructors created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000906 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000907 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
908 << NumImplicitMoveConstructors
909 << " implicit move constructors created\n";
910 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
911 << NumImplicitCopyAssignmentOperators
912 << " implicit copy assignment operators created\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +0000913 if (getLangOpts().CPlusPlus)
Chandler Carruth3c147a72011-07-04 05:32:14 +0000914 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
915 << NumImplicitMoveAssignmentOperators
916 << " implicit move assignment operators created\n";
917 llvm::errs() << NumImplicitDestructorsDeclared << "/"
918 << NumImplicitDestructors
919 << " implicit destructors created\n";
920
Argyrios Kyrtzidis1b7ed912014-02-27 04:11:59 +0000921 if (ExternalSource) {
Chandler Carruth3c147a72011-07-04 05:32:14 +0000922 llvm::errs() << "\n";
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000923 ExternalSource->PrintStats();
924 }
Chandler Carruth3c147a72011-07-04 05:32:14 +0000925
Douglas Gregor5b11d492010-07-25 17:53:33 +0000926 BumpAlloc.PrintStats();
Chris Lattner4eb445d2007-01-26 01:27:23 +0000927}
928
Richard Smith42413142015-05-15 20:05:43 +0000929void ASTContext::mergeDefinitionIntoModule(NamedDecl *ND, Module *M,
930 bool NotifyListeners) {
931 if (NotifyListeners)
932 if (auto *Listener = getASTMutationListener())
933 Listener->RedefinedHiddenDefinition(ND, M);
934
Richard Smith13897eb2018-09-12 23:37:00 +0000935 MergedDefModules[cast<NamedDecl>(ND->getCanonicalDecl())].push_back(M);
Richard Smith42413142015-05-15 20:05:43 +0000936}
937
938void ASTContext::deduplicateMergedDefinitonsFor(NamedDecl *ND) {
Richard Smith20fbdb32018-09-12 02:13:46 +0000939 auto It = MergedDefModules.find(cast<NamedDecl>(ND->getCanonicalDecl()));
Richard Smith42413142015-05-15 20:05:43 +0000940 if (It == MergedDefModules.end())
941 return;
942
Benjamin Kramera72a70a2016-10-17 13:00:44 +0000943 auto &Merged = It->second;
Richard Smith42413142015-05-15 20:05:43 +0000944 llvm::DenseSet<Module*> Found;
945 for (Module *&M : Merged)
946 if (!Found.insert(M).second)
947 M = nullptr;
948 Merged.erase(std::remove(Merged.begin(), Merged.end(), nullptr), Merged.end());
949}
950
Richard Smithdc1f0422016-07-20 19:10:16 +0000951void ASTContext::PerModuleInitializers::resolve(ASTContext &Ctx) {
952 if (LazyInitializers.empty())
953 return;
954
955 auto *Source = Ctx.getExternalSource();
956 assert(Source && "lazy initializers but no external source");
957
958 auto LazyInits = std::move(LazyInitializers);
959 LazyInitializers.clear();
960
961 for (auto ID : LazyInits)
962 Initializers.push_back(Source->GetExternalDecl(ID));
963
964 assert(LazyInitializers.empty() &&
965 "GetExternalDecl for lazy module initializer added more inits");
966}
967
968void ASTContext::addModuleInitializer(Module *M, Decl *D) {
969 // One special case: if we add a module initializer that imports another
970 // module, and that module's only initializer is an ImportDecl, simplify.
Eugene Zelenko7855e772018-04-03 00:11:50 +0000971 if (const auto *ID = dyn_cast<ImportDecl>(D)) {
Richard Smithdc1f0422016-07-20 19:10:16 +0000972 auto It = ModuleInitializers.find(ID->getImportedModule());
973
974 // Maybe the ImportDecl does nothing at all. (Common case.)
975 if (It == ModuleInitializers.end())
976 return;
977
978 // Maybe the ImportDecl only imports another ImportDecl.
979 auto &Imported = *It->second;
980 if (Imported.Initializers.size() + Imported.LazyInitializers.size() == 1) {
981 Imported.resolve(*this);
982 auto *OnlyDecl = Imported.Initializers.front();
983 if (isa<ImportDecl>(OnlyDecl))
984 D = OnlyDecl;
985 }
986 }
987
988 auto *&Inits = ModuleInitializers[M];
989 if (!Inits)
990 Inits = new (*this) PerModuleInitializers;
991 Inits->Initializers.push_back(D);
992}
993
994void ASTContext::addLazyModuleInitializers(Module *M, ArrayRef<uint32_t> IDs) {
995 auto *&Inits = ModuleInitializers[M];
996 if (!Inits)
997 Inits = new (*this) PerModuleInitializers;
998 Inits->LazyInitializers.insert(Inits->LazyInitializers.end(),
999 IDs.begin(), IDs.end());
1000}
1001
Eugene Zelenko7855e772018-04-03 00:11:50 +00001002ArrayRef<Decl *> ASTContext::getModuleInitializers(Module *M) {
Richard Smithdc1f0422016-07-20 19:10:16 +00001003 auto It = ModuleInitializers.find(M);
Fangrui Song6907ce22018-07-30 19:24:48 +00001004 if (It == ModuleInitializers.end())
Richard Smithdc1f0422016-07-20 19:10:16 +00001005 return None;
1006
1007 auto *Inits = It->second;
1008 Inits->resolve(*this);
1009 return Inits->Initializers;
1010}
1011
Richard Smithf19e1272015-03-07 00:04:49 +00001012ExternCContextDecl *ASTContext::getExternCContextDecl() const {
1013 if (!ExternCContext)
1014 ExternCContext = ExternCContextDecl::Create(*this, getTranslationUnitDecl());
1015
1016 return ExternCContext;
1017}
1018
David Majnemerd9b1a4f2015-11-04 03:40:30 +00001019BuiltinTemplateDecl *
1020ASTContext::buildBuiltinTemplateDecl(BuiltinTemplateKind BTK,
1021 const IdentifierInfo *II) const {
1022 auto *BuiltinTemplate = BuiltinTemplateDecl::Create(*this, TUDecl, II, BTK);
1023 BuiltinTemplate->setImplicit();
1024 TUDecl->addDecl(BuiltinTemplate);
1025
1026 return BuiltinTemplate;
1027}
1028
1029BuiltinTemplateDecl *
1030ASTContext::getMakeIntegerSeqDecl() const {
1031 if (!MakeIntegerSeqDecl)
1032 MakeIntegerSeqDecl = buildBuiltinTemplateDecl(BTK__make_integer_seq,
1033 getMakeIntegerSeqName());
1034 return MakeIntegerSeqDecl;
1035}
1036
Eric Fiselier6ad68552016-07-01 01:24:09 +00001037BuiltinTemplateDecl *
1038ASTContext::getTypePackElementDecl() const {
1039 if (!TypePackElementDecl)
1040 TypePackElementDecl = buildBuiltinTemplateDecl(BTK__type_pack_element,
1041 getTypePackElementName());
1042 return TypePackElementDecl;
1043}
1044
Alp Toker2dea15b2013-12-17 01:22:38 +00001045RecordDecl *ASTContext::buildImplicitRecord(StringRef Name,
1046 RecordDecl::TagKind TK) const {
Alp Toker56b5cc92013-12-15 10:36:26 +00001047 SourceLocation Loc;
1048 RecordDecl *NewDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00001049 if (getLangOpts().CPlusPlus)
1050 NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc,
1051 Loc, &Idents.get(Name));
Alp Toker56b5cc92013-12-15 10:36:26 +00001052 else
Alp Toker2dea15b2013-12-17 01:22:38 +00001053 NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
1054 &Idents.get(Name));
Alp Toker56b5cc92013-12-15 10:36:26 +00001055 NewDecl->setImplicit();
David Majnemerf8637362015-01-15 08:41:25 +00001056 NewDecl->addAttr(TypeVisibilityAttr::CreateImplicit(
1057 const_cast<ASTContext &>(*this), TypeVisibilityAttr::Default));
Alp Toker56b5cc92013-12-15 10:36:26 +00001058 return NewDecl;
1059}
1060
1061TypedefDecl *ASTContext::buildImplicitTypedef(QualType T,
1062 StringRef Name) const {
1063 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
1064 TypedefDecl *NewDecl = TypedefDecl::Create(
1065 const_cast<ASTContext &>(*this), getTranslationUnitDecl(),
1066 SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo);
1067 NewDecl->setImplicit();
1068 return NewDecl;
1069}
1070
Douglas Gregor801c99d2011-08-12 06:49:56 +00001071TypedefDecl *ASTContext::getInt128Decl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00001072 if (!Int128Decl)
1073 Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t");
Douglas Gregor801c99d2011-08-12 06:49:56 +00001074 return Int128Decl;
1075}
1076
1077TypedefDecl *ASTContext::getUInt128Decl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00001078 if (!UInt128Decl)
1079 UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t");
Douglas Gregor801c99d2011-08-12 06:49:56 +00001080 return UInt128Decl;
1081}
Chris Lattner4eb445d2007-01-26 01:27:23 +00001082
John McCall48f2d582009-10-23 23:03:21 +00001083void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00001084 auto *Ty = new (*this, TypeAlignment) BuiltinType(K);
John McCall48f2d582009-10-23 23:03:21 +00001085 R = CanQualType::CreateUnsafe(QualType(Ty, 0));
John McCall90d1c2d2009-09-24 23:30:46 +00001086 Types.push_back(Ty);
Chris Lattnerd5973eb2006-11-12 00:53:46 +00001087}
1088
Artem Belevichb5bc9232015-09-22 17:23:22 +00001089void ASTContext::InitBuiltinTypes(const TargetInfo &Target,
1090 const TargetInfo *AuxTarget) {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001091 assert((!this->Target || this->Target == &Target) &&
1092 "Incorrect target reinitialization");
Chris Lattner970e54e2006-11-12 00:37:36 +00001093 assert(VoidTy.isNull() && "Context reinitialized?");
Mike Stump11289f42009-09-09 15:08:12 +00001094
Douglas Gregore8bbc122011-09-02 00:18:52 +00001095 this->Target = &Target;
Artem Belevichb5bc9232015-09-22 17:23:22 +00001096 this->AuxTarget = AuxTarget;
1097
Douglas Gregore8bbc122011-09-02 00:18:52 +00001098 ABI.reset(createCXXABI(Target));
1099 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
David Tweed31d09b02013-09-13 12:04:22 +00001100 AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
Fangrui Song6907ce22018-07-30 19:24:48 +00001101
Chris Lattner970e54e2006-11-12 00:37:36 +00001102 // C99 6.2.5p19.
Chris Lattner726f97b2006-12-03 02:57:32 +00001103 InitBuiltinType(VoidTy, BuiltinType::Void);
Mike Stump11289f42009-09-09 15:08:12 +00001104
Chris Lattner970e54e2006-11-12 00:37:36 +00001105 // C99 6.2.5p2.
Chris Lattner726f97b2006-12-03 02:57:32 +00001106 InitBuiltinType(BoolTy, BuiltinType::Bool);
Chris Lattner970e54e2006-11-12 00:37:36 +00001107 // C99 6.2.5p3.
Eli Friedman9ffd4a92009-06-05 07:05:05 +00001108 if (LangOpts.CharIsSigned)
Chris Lattnerb16f4552007-06-03 07:25:34 +00001109 InitBuiltinType(CharTy, BuiltinType::Char_S);
1110 else
1111 InitBuiltinType(CharTy, BuiltinType::Char_U);
Chris Lattner970e54e2006-11-12 00:37:36 +00001112 // C99 6.2.5p4.
Chris Lattner726f97b2006-12-03 02:57:32 +00001113 InitBuiltinType(SignedCharTy, BuiltinType::SChar);
1114 InitBuiltinType(ShortTy, BuiltinType::Short);
1115 InitBuiltinType(IntTy, BuiltinType::Int);
1116 InitBuiltinType(LongTy, BuiltinType::Long);
1117 InitBuiltinType(LongLongTy, BuiltinType::LongLong);
Mike Stump11289f42009-09-09 15:08:12 +00001118
Chris Lattner970e54e2006-11-12 00:37:36 +00001119 // C99 6.2.5p6.
Chris Lattner726f97b2006-12-03 02:57:32 +00001120 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
1121 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
1122 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
1123 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
1124 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
Mike Stump11289f42009-09-09 15:08:12 +00001125
Chris Lattner970e54e2006-11-12 00:37:36 +00001126 // C99 6.2.5p10.
Chris Lattner726f97b2006-12-03 02:57:32 +00001127 InitBuiltinType(FloatTy, BuiltinType::Float);
1128 InitBuiltinType(DoubleTy, BuiltinType::Double);
1129 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001130
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001131 // GNU extension, __float128 for IEEE quadruple precision
1132 InitBuiltinType(Float128Ty, BuiltinType::Float128);
1133
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00001134 // C11 extension ISO/IEC TS 18661-3
1135 InitBuiltinType(Float16Ty, BuiltinType::Float16);
1136
Leonard Chanf921d852018-06-04 16:07:52 +00001137 // ISO/IEC JTC1 SC22 WG14 N1169 Extension
Leonard Chanab80f3c2018-06-14 14:53:51 +00001138 InitBuiltinType(ShortAccumTy, BuiltinType::ShortAccum);
1139 InitBuiltinType(AccumTy, BuiltinType::Accum);
1140 InitBuiltinType(LongAccumTy, BuiltinType::LongAccum);
1141 InitBuiltinType(UnsignedShortAccumTy, BuiltinType::UShortAccum);
1142 InitBuiltinType(UnsignedAccumTy, BuiltinType::UAccum);
1143 InitBuiltinType(UnsignedLongAccumTy, BuiltinType::ULongAccum);
1144 InitBuiltinType(ShortFractTy, BuiltinType::ShortFract);
1145 InitBuiltinType(FractTy, BuiltinType::Fract);
1146 InitBuiltinType(LongFractTy, BuiltinType::LongFract);
1147 InitBuiltinType(UnsignedShortFractTy, BuiltinType::UShortFract);
1148 InitBuiltinType(UnsignedFractTy, BuiltinType::UFract);
1149 InitBuiltinType(UnsignedLongFractTy, BuiltinType::ULongFract);
1150 InitBuiltinType(SatShortAccumTy, BuiltinType::SatShortAccum);
1151 InitBuiltinType(SatAccumTy, BuiltinType::SatAccum);
1152 InitBuiltinType(SatLongAccumTy, BuiltinType::SatLongAccum);
1153 InitBuiltinType(SatUnsignedShortAccumTy, BuiltinType::SatUShortAccum);
1154 InitBuiltinType(SatUnsignedAccumTy, BuiltinType::SatUAccum);
1155 InitBuiltinType(SatUnsignedLongAccumTy, BuiltinType::SatULongAccum);
1156 InitBuiltinType(SatShortFractTy, BuiltinType::SatShortFract);
1157 InitBuiltinType(SatFractTy, BuiltinType::SatFract);
1158 InitBuiltinType(SatLongFractTy, BuiltinType::SatLongFract);
1159 InitBuiltinType(SatUnsignedShortFractTy, BuiltinType::SatUShortFract);
1160 InitBuiltinType(SatUnsignedFractTy, BuiltinType::SatUFract);
1161 InitBuiltinType(SatUnsignedLongFractTy, BuiltinType::SatULongFract);
Leonard Chanf921d852018-06-04 16:07:52 +00001162
Chris Lattnerf122cef2009-04-30 02:43:43 +00001163 // GNU extension, 128-bit integers.
1164 InitBuiltinType(Int128Ty, BuiltinType::Int128);
1165 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
1166
Hans Wennborg0d81e012013-05-10 10:08:40 +00001167 // C++ 3.9.1p5
1168 if (TargetInfo::isTypeSigned(Target.getWCharType()))
1169 InitBuiltinType(WCharTy, BuiltinType::WChar_S);
1170 else // -fshort-wchar makes wchar_t be unsigned.
1171 InitBuiltinType(WCharTy, BuiltinType::WChar_U);
1172 if (LangOpts.CPlusPlus && LangOpts.WChar)
1173 WideCharTy = WCharTy;
1174 else {
1175 // C99 (or C++ using -fno-wchar).
1176 WideCharTy = getFromTargetType(Target.getWCharType());
1177 }
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001178
James Molloy36365542012-05-04 10:55:22 +00001179 WIntTy = getFromTargetType(Target.getWIntType());
1180
Richard Smith3a8244d2018-05-01 05:02:45 +00001181 // C++20 (proposed)
1182 InitBuiltinType(Char8Ty, BuiltinType::Char8);
1183
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001184 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1185 InitBuiltinType(Char16Ty, BuiltinType::Char16);
1186 else // C99
1187 Char16Ty = getFromTargetType(Target.getChar16Type());
1188
1189 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1190 InitBuiltinType(Char32Ty, BuiltinType::Char32);
1191 else // C99
1192 Char32Ty = getFromTargetType(Target.getChar32Type());
1193
Douglas Gregor4619e432008-12-05 23:32:09 +00001194 // Placeholder type for type-dependent expressions whose type is
1195 // completely unknown. No code should ever check a type against
1196 // DependentTy and users should never see it; however, it is here to
1197 // help diagnose failures to properly check for type-dependent
1198 // expressions.
1199 InitBuiltinType(DependentTy, BuiltinType::Dependent);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001200
John McCall36e7fe32010-10-12 00:20:44 +00001201 // Placeholder type for functions.
1202 InitBuiltinType(OverloadTy, BuiltinType::Overload);
1203
John McCall0009fcc2011-04-26 20:42:42 +00001204 // Placeholder type for bound members.
1205 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
1206
John McCall526ab472011-10-25 17:37:35 +00001207 // Placeholder type for pseudo-objects.
1208 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
1209
John McCall31996342011-04-07 08:22:57 +00001210 // "any" type; useful for debugger-like clients.
1211 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
1212
John McCall8a6b59a2011-10-17 18:09:15 +00001213 // Placeholder type for unbridged ARC casts.
1214 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
1215
Eli Friedman34866c72012-08-31 00:14:07 +00001216 // Placeholder type for builtin functions.
1217 InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
1218
Alexey Bataev1a3320e2015-08-25 14:24:04 +00001219 // Placeholder type for OMP array sections.
1220 if (LangOpts.OpenMP)
1221 InitBuiltinType(OMPArraySectionTy, BuiltinType::OMPArraySection);
1222
Chris Lattner970e54e2006-11-12 00:37:36 +00001223 // C99 6.2.5p11.
Chris Lattnerc6395932007-06-22 20:56:16 +00001224 FloatComplexTy = getComplexType(FloatTy);
1225 DoubleComplexTy = getComplexType(DoubleTy);
1226 LongDoubleComplexTy = getComplexType(LongDoubleTy);
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001227 Float128ComplexTy = getComplexType(Float128Ty);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001228
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001229 // Builtin types for 'id', 'Class', and 'SEL'.
Steve Naroff1329fa02009-07-15 18:40:39 +00001230 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
1231 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
Fariborz Jahanian252ba5f2009-11-21 19:53:08 +00001232 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001233
Alexey Bader954ba212016-04-08 13:40:33 +00001234 if (LangOpts.OpenCL) {
1235#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1236 InitBuiltinType(SingletonId, BuiltinType::Id);
Alexey Baderb62f1442016-04-13 08:33:41 +00001237#include "clang/Basic/OpenCLImageTypes.def"
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001238
Guy Benyei61054192013-02-07 10:55:47 +00001239 InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001240 InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
Alexey Bader9c8453f2015-09-15 11:18:52 +00001241 InitBuiltinType(OCLClkEventTy, BuiltinType::OCLClkEvent);
1242 InitBuiltinType(OCLQueueTy, BuiltinType::OCLQueue);
Alexey Bader9c8453f2015-09-15 11:18:52 +00001243 InitBuiltinType(OCLReserveIDTy, BuiltinType::OCLReserveID);
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001244 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001245
Ted Kremeneke65b0862012-03-06 20:05:56 +00001246 // Builtin type for __objc_yes and __objc_no
Fariborz Jahanian29898f42012-04-16 21:03:30 +00001247 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1248 SignedCharTy : BoolTy);
Fangrui Song6907ce22018-07-30 19:24:48 +00001249
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001250 ObjCConstantStringType = QualType();
Fangrui Song6907ce22018-07-30 19:24:48 +00001251
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00001252 ObjCSuperType = QualType();
Mike Stump11289f42009-09-09 15:08:12 +00001253
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00001254 // void * type
Yaxun Liu39195062017-08-04 18:16:31 +00001255 if (LangOpts.OpenCLVersion >= 200) {
1256 auto Q = VoidTy.getQualifiers();
1257 Q.setAddressSpace(LangAS::opencl_generic);
1258 VoidPtrTy = getPointerType(getCanonicalType(
1259 getQualifiedType(VoidTy.getUnqualifiedType(), Q)));
1260 } else {
1261 VoidPtrTy = getPointerType(VoidTy);
1262 }
Sebastian Redl576fd422009-05-10 18:38:11 +00001263
1264 // nullptr type (C++0x 2.14.7)
1265 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001266
1267 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1268 InitBuiltinType(HalfTy, BuiltinType::Half);
Meador Ingecfb60902012-07-01 15:57:25 +00001269
1270 // Builtin type used to help define __builtin_va_list.
Richard Smith9b88a4c2015-07-27 05:40:23 +00001271 VaListTagDecl = nullptr;
Chris Lattner970e54e2006-11-12 00:37:36 +00001272}
1273
David Blaikie9c902b52011-09-25 23:23:43 +00001274DiagnosticsEngine &ASTContext::getDiagnostics() const {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001275 return SourceMgr.getDiagnostics();
1276}
1277
Douglas Gregor561eceb2010-08-30 16:49:28 +00001278AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
1279 AttrVec *&Result = DeclAttrs[D];
1280 if (!Result) {
1281 void *Mem = Allocate(sizeof(AttrVec));
1282 Result = new (Mem) AttrVec;
1283 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001284
Douglas Gregor561eceb2010-08-30 16:49:28 +00001285 return *Result;
1286}
1287
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001288/// Erase the attributes corresponding to the given declaration.
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00001289void ASTContext::eraseDeclAttrs(const Decl *D) {
Douglas Gregor561eceb2010-08-30 16:49:28 +00001290 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1291 if (Pos != DeclAttrs.end()) {
1292 Pos->second->~AttrVec();
1293 DeclAttrs.erase(Pos);
1294 }
1295}
1296
Larisse Voufo39a1e502013-08-06 01:03:05 +00001297// FIXME: Remove ?
Douglas Gregor86d142a2009-10-08 07:24:58 +00001298MemberSpecializationInfo *
Douglas Gregor3c74d412009-10-14 20:14:33 +00001299ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001300 assert(Var->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001301 return getTemplateOrSpecializationInfo(Var)
1302 .dyn_cast<MemberSpecializationInfo *>();
1303}
1304
1305ASTContext::TemplateOrSpecializationInfo
1306ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) {
1307 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1308 TemplateOrInstantiation.find(Var);
1309 if (Pos == TemplateOrInstantiation.end())
Eugene Zelenko7855e772018-04-03 00:11:50 +00001310 return {};
Mike Stump11289f42009-09-09 15:08:12 +00001311
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001312 return Pos->second;
1313}
1314
Mike Stump11289f42009-09-09 15:08:12 +00001315void
Douglas Gregor86d142a2009-10-08 07:24:58 +00001316ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
Argyrios Kyrtzidiscdb8b3f2010-07-04 21:44:00 +00001317 TemplateSpecializationKind TSK,
1318 SourceLocation PointOfInstantiation) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001319 assert(Inst->isStaticDataMember() && "Not a static data member");
1320 assert(Tmpl->isStaticDataMember() && "Not a static data member");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001321 setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo(
1322 Tmpl, TSK, PointOfInstantiation));
1323}
1324
1325void
1326ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst,
1327 TemplateOrSpecializationInfo TSI) {
1328 assert(!TemplateOrInstantiation[Inst] &&
1329 "Already noted what the variable was instantiated from");
1330 TemplateOrInstantiation[Inst] = TSI;
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001331}
1332
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001333FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
1334 const FunctionDecl *FD){
1335 assert(FD && "Specialization is 0");
1336 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
Francois Pichet57928252011-08-14 14:28:49 +00001337 = ClassScopeSpecializationPattern.find(FD);
1338 if (Pos == ClassScopeSpecializationPattern.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001339 return nullptr;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001340
1341 return Pos->second;
1342}
1343
1344void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
1345 FunctionDecl *Pattern) {
1346 assert(FD && "Specialization is 0");
1347 assert(Pattern && "Class scope specialization pattern is 0");
Francois Pichet57928252011-08-14 14:28:49 +00001348 ClassScopeSpecializationPattern[FD] = Pattern;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001349}
1350
John McCalle61f2ba2009-11-18 02:36:19 +00001351NamedDecl *
Richard Smithd8a9e372016-12-18 21:39:37 +00001352ASTContext::getInstantiatedFromUsingDecl(NamedDecl *UUD) {
1353 auto Pos = InstantiatedFromUsingDecl.find(UUD);
John McCallb96ec562009-12-04 22:46:56 +00001354 if (Pos == InstantiatedFromUsingDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001355 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001356
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001357 return Pos->second;
1358}
1359
1360void
Richard Smithd8a9e372016-12-18 21:39:37 +00001361ASTContext::setInstantiatedFromUsingDecl(NamedDecl *Inst, NamedDecl *Pattern) {
John McCallb96ec562009-12-04 22:46:56 +00001362 assert((isa<UsingDecl>(Pattern) ||
1363 isa<UnresolvedUsingValueDecl>(Pattern) ||
Fangrui Song6907ce22018-07-30 19:24:48 +00001364 isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
John McCallb96ec562009-12-04 22:46:56 +00001365 "pattern decl is not a using decl");
Richard Smithd8a9e372016-12-18 21:39:37 +00001366 assert((isa<UsingDecl>(Inst) ||
1367 isa<UnresolvedUsingValueDecl>(Inst) ||
Fangrui Song6907ce22018-07-30 19:24:48 +00001368 isa<UnresolvedUsingTypenameDecl>(Inst)) &&
Richard Smithd8a9e372016-12-18 21:39:37 +00001369 "instantiation did not produce a using decl");
John McCallb96ec562009-12-04 22:46:56 +00001370 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1371 InstantiatedFromUsingDecl[Inst] = Pattern;
1372}
1373
1374UsingShadowDecl *
1375ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1376 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1377 = InstantiatedFromUsingShadowDecl.find(Inst);
1378 if (Pos == InstantiatedFromUsingShadowDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001379 return nullptr;
John McCallb96ec562009-12-04 22:46:56 +00001380
1381 return Pos->second;
1382}
1383
1384void
1385ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1386 UsingShadowDecl *Pattern) {
1387 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1388 InstantiatedFromUsingShadowDecl[Inst] = Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001389}
1390
Anders Carlsson5da84842009-09-01 04:26:58 +00001391FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1392 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1393 = InstantiatedFromUnnamedFieldDecl.find(Field);
1394 if (Pos == InstantiatedFromUnnamedFieldDecl.end())
Craig Topper36250ad2014-05-12 05:36:57 +00001395 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001396
Anders Carlsson5da84842009-09-01 04:26:58 +00001397 return Pos->second;
1398}
1399
1400void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1401 FieldDecl *Tmpl) {
1402 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1403 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1404 assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1405 "Already noted what unnamed field was instantiated from");
Mike Stump11289f42009-09-09 15:08:12 +00001406
Anders Carlsson5da84842009-09-01 04:26:58 +00001407 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1408}
1409
Douglas Gregor832940b2010-03-02 23:58:15 +00001410ASTContext::overridden_cxx_method_iterator
1411ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
Benjamin Krameracfa3392017-12-17 23:52:45 +00001412 return overridden_methods(Method).begin();
Douglas Gregor832940b2010-03-02 23:58:15 +00001413}
1414
1415ASTContext::overridden_cxx_method_iterator
1416ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
Benjamin Krameracfa3392017-12-17 23:52:45 +00001417 return overridden_methods(Method).end();
Douglas Gregor832940b2010-03-02 23:58:15 +00001418}
1419
Argyrios Kyrtzidis6685e8a2010-07-04 21:44:35 +00001420unsigned
1421ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
Benjamin Krameracfa3392017-12-17 23:52:45 +00001422 auto Range = overridden_methods(Method);
1423 return Range.end() - Range.begin();
Clement Courbet8251ebf2016-06-10 11:54:43 +00001424}
1425
Clement Courbet6ecaec82016-07-05 07:49:31 +00001426ASTContext::overridden_method_range
1427ASTContext::overridden_methods(const CXXMethodDecl *Method) const {
Benjamin Krameracfa3392017-12-17 23:52:45 +00001428 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
1429 OverriddenMethods.find(Method->getCanonicalDecl());
1430 if (Pos == OverriddenMethods.end())
1431 return overridden_method_range(nullptr, nullptr);
1432 return overridden_method_range(Pos->second.begin(), Pos->second.end());
Clement Courbet6ecaec82016-07-05 07:49:31 +00001433}
1434
Fangrui Song6907ce22018-07-30 19:24:48 +00001435void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
Douglas Gregor832940b2010-03-02 23:58:15 +00001436 const CXXMethodDecl *Overridden) {
Argyrios Kyrtzidiscc4ca0a2012-10-09 01:23:45 +00001437 assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
Douglas Gregor832940b2010-03-02 23:58:15 +00001438 OverriddenMethods[Method].push_back(Overridden);
1439}
1440
Dmitri Gribenko941ab0f2012-11-03 14:24:57 +00001441void ASTContext::getOverriddenMethods(
1442 const NamedDecl *D,
1443 SmallVectorImpl<const NamedDecl *> &Overridden) const {
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001444 assert(D);
1445
Eugene Zelenko7855e772018-04-03 00:11:50 +00001446 if (const auto *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidisc8e70082013-04-17 00:09:03 +00001447 Overridden.append(overridden_methods_begin(CXXMethod),
1448 overridden_methods_end(CXXMethod));
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001449 return;
1450 }
1451
Eugene Zelenko7855e772018-04-03 00:11:50 +00001452 const auto *Method = dyn_cast<ObjCMethodDecl>(D);
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001453 if (!Method)
1454 return;
1455
Argyrios Kyrtzidis353f6a42012-10-09 18:19:01 +00001456 SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1457 Method->getOverriddenMethods(OverDecls);
Argyrios Kyrtzidisa7a10812012-10-09 20:08:43 +00001458 Overridden.append(OverDecls.begin(), OverDecls.end());
Argyrios Kyrtzidisb9556e62012-10-09 01:23:50 +00001459}
1460
Douglas Gregor0f2a3602011-12-03 00:30:27 +00001461void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1462 assert(!Import->NextLocalImport && "Import declaration already in the chain");
1463 assert(!Import->isFromASTFile() && "Non-local import declaration");
1464 if (!FirstLocalImport) {
1465 FirstLocalImport = Import;
1466 LastLocalImport = Import;
1467 return;
1468 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001469
Douglas Gregor0f2a3602011-12-03 00:30:27 +00001470 LastLocalImport->NextLocalImport = Import;
1471 LastLocalImport = Import;
1472}
1473
Chris Lattner53cfe802007-07-18 17:52:12 +00001474//===----------------------------------------------------------------------===//
1475// Type Sizing and Analysis
1476//===----------------------------------------------------------------------===//
Chris Lattner983a8bb2007-07-13 22:13:22 +00001477
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001478/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1479/// scalar floating point type.
1480const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
Eugene Zelenko7855e772018-04-03 00:11:50 +00001481 const auto *BT = T->getAs<BuiltinType>();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001482 assert(BT && "Not a floating point type!");
1483 switch (BT->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001484 default: llvm_unreachable("Not a floating point type!");
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00001485 case BuiltinType::Float16:
1486 case BuiltinType::Half:
1487 return Target->getHalfFormat();
Douglas Gregore8bbc122011-09-02 00:18:52 +00001488 case BuiltinType::Float: return Target->getFloatFormat();
1489 case BuiltinType::Double: return Target->getDoubleFormat();
1490 case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001491 case BuiltinType::Float128: return Target->getFloat128Format();
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001492 }
1493}
1494
Rafael Espindola71eccb32013-08-08 19:53:46 +00001495CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00001496 unsigned Align = Target->getCharWidth();
Eli Friedman19a546c2009-02-22 02:56:25 +00001497
John McCall94268702010-10-08 18:24:19 +00001498 bool UseAlignAttrOnly = false;
1499 if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1500 Align = AlignFromAttr;
Eli Friedman19a546c2009-02-22 02:56:25 +00001501
John McCall94268702010-10-08 18:24:19 +00001502 // __attribute__((aligned)) can increase or decrease alignment
1503 // *except* on a struct or struct member, where it only increases
1504 // alignment unless 'packed' is also specified.
1505 //
Peter Collingbourne2f3cf4b2011-09-29 18:04:28 +00001506 // It is an error for alignas to decrease alignment, so we can
John McCall94268702010-10-08 18:24:19 +00001507 // ignore that possibility; Sema should diagnose it.
1508 if (isa<FieldDecl>(D)) {
1509 UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1510 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1511 } else {
1512 UseAlignAttrOnly = true;
1513 }
1514 }
Fariborz Jahanian9f107182011-05-05 21:19:14 +00001515 else if (isa<FieldDecl>(D))
Fangrui Song6907ce22018-07-30 19:24:48 +00001516 UseAlignAttrOnly =
Fariborz Jahanian9f107182011-05-05 21:19:14 +00001517 D->hasAttr<PackedAttr>() ||
1518 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
John McCall94268702010-10-08 18:24:19 +00001519
John McCall4e819612011-01-20 07:57:12 +00001520 // If we're using the align attribute only, just ignore everything
1521 // else about the declaration and its type.
John McCall94268702010-10-08 18:24:19 +00001522 if (UseAlignAttrOnly) {
John McCall4e819612011-01-20 07:57:12 +00001523 // do nothing
Eugene Zelenko7855e772018-04-03 00:11:50 +00001524 } else if (const auto *VD = dyn_cast<ValueDecl>(D)) {
Chris Lattner68061312009-01-24 21:53:27 +00001525 QualType T = VD->getType();
Eugene Zelenko7855e772018-04-03 00:11:50 +00001526 if (const auto *RT = T->getAs<ReferenceType>()) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001527 if (ForAlignof)
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001528 T = RT->getPointeeType();
1529 else
1530 T = getPointerType(RT->getPointeeType());
1531 }
Richard Smithf6d70302014-06-10 23:34:28 +00001532 QualType BaseT = getBaseElementType(T);
Akira Hatanakad62f2c82017-01-06 17:56:15 +00001533 if (T->isFunctionType())
1534 Align = getTypeInfoImpl(T.getTypePtr()).Align;
1535 else if (!BaseT->isIncompleteType()) {
John McCall33ddac02011-01-19 10:06:00 +00001536 // Adjust alignments of declarations with array type by the
1537 // large-array alignment on the target.
Rafael Espindola88572752013-08-07 18:08:19 +00001538 if (const ArrayType *arrayType = getAsArrayType(T)) {
Rafael Espindola71eccb32013-08-08 19:53:46 +00001539 unsigned MinWidth = Target->getLargeArrayMinWidth();
1540 if (!ForAlignof && MinWidth) {
Rafael Espindola88572752013-08-07 18:08:19 +00001541 if (isa<VariableArrayType>(arrayType))
1542 Align = std::max(Align, Target->getLargeArrayAlign());
1543 else if (isa<ConstantArrayType>(arrayType) &&
1544 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
1545 Align = std::max(Align, Target->getLargeArrayAlign());
1546 }
John McCall33ddac02011-01-19 10:06:00 +00001547 }
Chad Rosier99ee7822011-07-26 07:03:04 +00001548 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
Roger Ferrer Ibanez3fa38a12017-03-08 14:00:44 +00001549 if (BaseT.getQualifiers().hasUnaligned())
1550 Align = Target->getCharWidth();
Eugene Zelenko7855e772018-04-03 00:11:50 +00001551 if (const auto *VD = dyn_cast<VarDecl>(D)) {
Ulrich Weigandb63f7792015-04-21 17:26:18 +00001552 if (VD->hasGlobalStorage() && !ForAlignof)
Ulrich Weigandfa806422013-05-06 16:23:57 +00001553 Align = std::max(Align, getTargetInfo().getMinGlobalAlign());
1554 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001555 }
John McCall4e819612011-01-20 07:57:12 +00001556
1557 // Fields can be subject to extra alignment constraints, like if
1558 // the field is packed, the struct is packed, or the struct has a
1559 // a max-field-alignment constraint (#pragma pack). So calculate
1560 // the actual alignment of the field within the struct, and then
1561 // (as we're expected to) constrain that by the alignment of the type.
Eugene Zelenko7855e772018-04-03 00:11:50 +00001562 if (const auto *Field = dyn_cast<FieldDecl>(VD)) {
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001563 const RecordDecl *Parent = Field->getParent();
1564 // We can only produce a sensible answer if the record is valid.
1565 if (!Parent->isInvalidDecl()) {
1566 const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
John McCall4e819612011-01-20 07:57:12 +00001567
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001568 // Start with the record's overall alignment.
1569 unsigned FieldAlign = toBits(Layout.getAlignment());
John McCall4e819612011-01-20 07:57:12 +00001570
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00001571 // Use the GCD of that and the offset within the record.
1572 uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1573 if (Offset > 0) {
1574 // Alignment is always a power of 2, so the GCD will be a power of 2,
1575 // which means we get to do this crazy thing instead of Euclid's.
1576 uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1577 if (LowBitOfOffset < FieldAlign)
1578 FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1579 }
1580
1581 Align = std::min(Align, FieldAlign);
John McCall4e819612011-01-20 07:57:12 +00001582 }
Charles Davis3fc51072010-02-23 04:52:00 +00001583 }
Chris Lattner68061312009-01-24 21:53:27 +00001584 }
Eli Friedman19a546c2009-02-22 02:56:25 +00001585
Ken Dyckcc56c542011-01-15 18:38:59 +00001586 return toCharUnitsFromBits(Align);
Chris Lattner68061312009-01-24 21:53:27 +00001587}
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001588
John McCallf1249922012-08-21 04:10:00 +00001589// getTypeInfoDataSizeInChars - Return the size of a type, in
1590// chars. If the type is a record, its data size is returned. This is
1591// the size of the memcpy that's performed when assigning this type
1592// using a trivial copy/move assignment operator.
1593std::pair<CharUnits, CharUnits>
1594ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1595 std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1596
1597 // In C++, objects can sometimes be allocated into the tail padding
1598 // of a base-class subobject. We decide whether that's possible
1599 // during class layout, so here we can just trust the layout results.
1600 if (getLangOpts().CPlusPlus) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00001601 if (const auto *RT = T->getAs<RecordType>()) {
John McCallf1249922012-08-21 04:10:00 +00001602 const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1603 sizeAndAlign.first = layout.getDataSize();
1604 }
1605 }
1606
1607 return sizeAndAlign;
1608}
1609
Richard Trieu04d2d942013-05-14 21:59:17 +00001610/// getConstantArrayInfoInChars - Performing the computation in CharUnits
1611/// instead of in bits prevents overflowing the uint64_t for some large arrays.
1612std::pair<CharUnits, CharUnits>
1613static getConstantArrayInfoInChars(const ASTContext &Context,
1614 const ConstantArrayType *CAT) {
1615 std::pair<CharUnits, CharUnits> EltInfo =
1616 Context.getTypeInfoInChars(CAT->getElementType());
1617 uint64_t Size = CAT->getSize().getZExtValue();
Richard Trieuc7509072013-05-14 23:41:50 +00001618 assert((Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity()) <=
1619 (uint64_t)(-1)/Size) &&
Richard Trieu04d2d942013-05-14 21:59:17 +00001620 "Overflow in array type char size evaluation");
1621 uint64_t Width = EltInfo.first.getQuantity() * Size;
1622 unsigned Align = EltInfo.second.getQuantity();
Warren Hunt5ae586a2013-11-01 23:59:41 +00001623 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1624 Context.getTargetInfo().getPointerWidth(0) == 64)
Rui Ueyama83aa9792016-01-14 21:00:27 +00001625 Width = llvm::alignTo(Width, Align);
Richard Trieu04d2d942013-05-14 21:59:17 +00001626 return std::make_pair(CharUnits::fromQuantity(Width),
1627 CharUnits::fromQuantity(Align));
1628}
1629
John McCall87fe5d52010-05-20 01:18:31 +00001630std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001631ASTContext::getTypeInfoInChars(const Type *T) const {
Eugene Zelenko7855e772018-04-03 00:11:50 +00001632 if (const auto *CAT = dyn_cast<ConstantArrayType>(T))
Richard Trieu04d2d942013-05-14 21:59:17 +00001633 return getConstantArrayInfoInChars(*this, CAT);
David Majnemer34b57492014-07-30 01:30:47 +00001634 TypeInfo Info = getTypeInfo(T);
1635 return std::make_pair(toCharUnitsFromBits(Info.Width),
1636 toCharUnitsFromBits(Info.Align));
John McCall87fe5d52010-05-20 01:18:31 +00001637}
1638
1639std::pair<CharUnits, CharUnits>
Ken Dyckd24099d2011-02-20 01:55:18 +00001640ASTContext::getTypeInfoInChars(QualType T) const {
John McCall87fe5d52010-05-20 01:18:31 +00001641 return getTypeInfoInChars(T.getTypePtr());
1642}
1643
David Majnemer34b57492014-07-30 01:30:47 +00001644bool ASTContext::isAlignmentRequired(const Type *T) const {
1645 return getTypeInfo(T).AlignIsRequired;
1646}
Daniel Dunbarc6475872012-03-09 04:12:54 +00001647
David Majnemer34b57492014-07-30 01:30:47 +00001648bool ASTContext::isAlignmentRequired(QualType T) const {
1649 return isAlignmentRequired(T.getTypePtr());
1650}
1651
Richard Smithb2f0f052016-10-10 18:54:32 +00001652unsigned ASTContext::getTypeAlignIfKnown(QualType T) const {
1653 // An alignment on a typedef overrides anything else.
Eugene Zelenko7855e772018-04-03 00:11:50 +00001654 if (const auto *TT = T->getAs<TypedefType>())
Richard Smithb2f0f052016-10-10 18:54:32 +00001655 if (unsigned Align = TT->getDecl()->getMaxAlignment())
1656 return Align;
1657
1658 // If we have an (array of) complete type, we're done.
1659 T = getBaseElementType(T);
1660 if (!T->isIncompleteType())
1661 return getTypeAlign(T);
1662
1663 // If we had an array type, its element type might be a typedef
1664 // type with an alignment attribute.
Eugene Zelenko7855e772018-04-03 00:11:50 +00001665 if (const auto *TT = T->getAs<TypedefType>())
Richard Smithb2f0f052016-10-10 18:54:32 +00001666 if (unsigned Align = TT->getDecl()->getMaxAlignment())
1667 return Align;
1668
1669 // Otherwise, see if the declaration of the type had an attribute.
Eugene Zelenko7855e772018-04-03 00:11:50 +00001670 if (const auto *TT = T->getAs<TagType>())
Richard Smithb2f0f052016-10-10 18:54:32 +00001671 return TT->getDecl()->getMaxAlignment();
1672
1673 return 0;
1674}
1675
David Majnemer34b57492014-07-30 01:30:47 +00001676TypeInfo ASTContext::getTypeInfo(const Type *T) const {
David Majnemerf8d38642014-07-30 08:42:33 +00001677 TypeInfoMap::iterator I = MemoizedTypeInfo.find(T);
1678 if (I != MemoizedTypeInfo.end())
1679 return I->second;
1680
1681 // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup.
1682 TypeInfo TI = getTypeInfoImpl(T);
1683 MemoizedTypeInfo[T] = TI;
Rafael Espindolaeaa88c12014-07-30 04:40:23 +00001684 return TI;
Daniel Dunbarc6475872012-03-09 04:12:54 +00001685}
1686
1687/// getTypeInfoImpl - Return the size of the specified type, in bits. This
1688/// method does not work on incomplete types.
John McCall8ccfcb52009-09-24 19:53:00 +00001689///
1690/// FIXME: Pointers into different addr spaces could have different sizes and
1691/// alignment requirements: getPointerInfo should take an AddrSpace, this
1692/// should take a QualType, &c.
David Majnemer34b57492014-07-30 01:30:47 +00001693TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
1694 uint64_t Width = 0;
1695 unsigned Align = 8;
1696 bool AlignIsRequired = false;
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00001697 unsigned AS = 0;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001698 switch (T->getTypeClass()) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001699#define TYPE(Class, Base)
1700#define ABSTRACT_TYPE(Class, Base)
Douglas Gregoref462e62009-04-30 17:32:17 +00001701#define NON_CANONICAL_TYPE(Class, Base)
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001702#define DEPENDENT_TYPE(Class, Base) case Type::Class:
David Blaikieab277d62013-07-13 21:08:03 +00001703#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
1704 case Type::Class: \
1705 assert(!T->isDependentType() && "should not see dependent types here"); \
1706 return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001707#include "clang/AST/TypeNodes.def"
John McCall15547bb2011-06-28 16:49:23 +00001708 llvm_unreachable("Should not see dependent types");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001709
Chris Lattner355332d2007-07-13 22:27:08 +00001710 case Type::FunctionNoProto:
1711 case Type::FunctionProto:
Douglas Gregoref462e62009-04-30 17:32:17 +00001712 // GCC extension: alignof(function) = 32 bits
1713 Width = 0;
1714 Align = 32;
1715 break;
1716
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001717 case Type::IncompleteArray:
Steve Naroff5c131802007-08-30 01:06:46 +00001718 case Type::VariableArray:
Douglas Gregoref462e62009-04-30 17:32:17 +00001719 Width = 0;
1720 Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1721 break;
1722
Steve Naroff5c131802007-08-30 01:06:46 +00001723 case Type::ConstantArray: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00001724 const auto *CAT = cast<ConstantArrayType>(T);
Mike Stump11289f42009-09-09 15:08:12 +00001725
David Majnemer34b57492014-07-30 01:30:47 +00001726 TypeInfo EltInfo = getTypeInfo(CAT->getElementType());
Abramo Bagnarad541a4c2011-12-13 11:23:52 +00001727 uint64_t Size = CAT->getSize().getZExtValue();
David Majnemer34b57492014-07-30 01:30:47 +00001728 assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
Daniel Dunbarc6475872012-03-09 04:12:54 +00001729 "Overflow in array type bit size evaluation");
David Majnemer34b57492014-07-30 01:30:47 +00001730 Width = EltInfo.Width * Size;
1731 Align = EltInfo.Align;
Warren Hunt5ae586a2013-11-01 23:59:41 +00001732 if (!getTargetInfo().getCXXABI().isMicrosoft() ||
1733 getTargetInfo().getPointerWidth(0) == 64)
Rui Ueyama83aa9792016-01-14 21:00:27 +00001734 Width = llvm::alignTo(Width, Align);
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001735 break;
Christopher Lambc5fafa22007-12-29 05:10:55 +00001736 }
Nate Begemance4d7fc2008-04-18 23:10:10 +00001737 case Type::ExtVector:
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001738 case Type::Vector: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00001739 const auto *VT = cast<VectorType>(T);
David Majnemer34b57492014-07-30 01:30:47 +00001740 TypeInfo EltInfo = getTypeInfo(VT->getElementType());
1741 Width = EltInfo.Width * VT->getNumElements();
Eli Friedman3df5efe2008-05-30 09:31:38 +00001742 Align = Width;
Nate Begemanb699c9b2009-01-18 06:42:49 +00001743 // If the alignment is not a power of 2, round up to the next power of 2.
1744 // This happens for non-power-of-2 length vectors.
Dan Gohmanef78c8e2010-04-21 23:32:43 +00001745 if (Align & (Align-1)) {
Chris Lattner63d2b362009-10-22 05:17:15 +00001746 Align = llvm::NextPowerOf2(Align);
Rui Ueyama83aa9792016-01-14 21:00:27 +00001747 Width = llvm::alignTo(Width, Align);
Chris Lattner63d2b362009-10-22 05:17:15 +00001748 }
Chad Rosiercc40ea72012-07-13 23:57:43 +00001749 // Adjust the alignment based on the target max.
1750 uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1751 if (TargetVectorAlign && TargetVectorAlign < Align)
1752 Align = TargetVectorAlign;
Chris Lattnerf2e101f2007-07-19 22:06:24 +00001753 break;
1754 }
Chris Lattner647fb222007-07-18 18:26:58 +00001755
Chris Lattner7570e9c2008-03-08 08:52:55 +00001756 case Type::Builtin:
Chris Lattner983a8bb2007-07-13 22:13:22 +00001757 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001758 default: llvm_unreachable("Unknown builtin type!");
Chris Lattner4481b422007-07-14 01:29:45 +00001759 case BuiltinType::Void:
Douglas Gregoref462e62009-04-30 17:32:17 +00001760 // GCC extension: alignof(void) = 8 bits.
1761 Width = 0;
1762 Align = 8;
1763 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +00001764 case BuiltinType::Bool:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001765 Width = Target->getBoolWidth();
1766 Align = Target->getBoolAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001767 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001768 case BuiltinType::Char_S:
1769 case BuiltinType::Char_U:
1770 case BuiltinType::UChar:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001771 case BuiltinType::SChar:
Richard Smith3a8244d2018-05-01 05:02:45 +00001772 case BuiltinType::Char8:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001773 Width = Target->getCharWidth();
1774 Align = Target->getCharAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001775 break;
Chris Lattnerad3467e2010-12-25 23:25:43 +00001776 case BuiltinType::WChar_S:
1777 case BuiltinType::WChar_U:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001778 Width = Target->getWCharWidth();
1779 Align = Target->getWCharAlign();
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00001780 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001781 case BuiltinType::Char16:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001782 Width = Target->getChar16Width();
1783 Align = Target->getChar16Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001784 break;
1785 case BuiltinType::Char32:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001786 Width = Target->getChar32Width();
1787 Align = Target->getChar32Align();
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001788 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001789 case BuiltinType::UShort:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001790 case BuiltinType::Short:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001791 Width = Target->getShortWidth();
1792 Align = Target->getShortAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001793 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001794 case BuiltinType::UInt:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001795 case BuiltinType::Int:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001796 Width = Target->getIntWidth();
1797 Align = Target->getIntAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001798 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001799 case BuiltinType::ULong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001800 case BuiltinType::Long:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001801 Width = Target->getLongWidth();
1802 Align = Target->getLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001803 break;
Chris Lattner355332d2007-07-13 22:27:08 +00001804 case BuiltinType::ULongLong:
Chris Lattner6a4f7452007-12-19 19:23:28 +00001805 case BuiltinType::LongLong:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001806 Width = Target->getLongLongWidth();
1807 Align = Target->getLongLongAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001808 break;
Chris Lattner0a415ec2009-04-30 02:55:13 +00001809 case BuiltinType::Int128:
1810 case BuiltinType::UInt128:
1811 Width = 128;
1812 Align = 128; // int128_t is 128-bit aligned on all targets.
1813 break;
Leonard Chanf921d852018-06-04 16:07:52 +00001814 case BuiltinType::ShortAccum:
1815 case BuiltinType::UShortAccum:
Leonard Chanab80f3c2018-06-14 14:53:51 +00001816 case BuiltinType::SatShortAccum:
1817 case BuiltinType::SatUShortAccum:
Leonard Chanf921d852018-06-04 16:07:52 +00001818 Width = Target->getShortAccumWidth();
1819 Align = Target->getShortAccumAlign();
1820 break;
1821 case BuiltinType::Accum:
1822 case BuiltinType::UAccum:
Leonard Chanab80f3c2018-06-14 14:53:51 +00001823 case BuiltinType::SatAccum:
1824 case BuiltinType::SatUAccum:
Leonard Chanf921d852018-06-04 16:07:52 +00001825 Width = Target->getAccumWidth();
1826 Align = Target->getAccumAlign();
1827 break;
1828 case BuiltinType::LongAccum:
1829 case BuiltinType::ULongAccum:
Leonard Chanab80f3c2018-06-14 14:53:51 +00001830 case BuiltinType::SatLongAccum:
1831 case BuiltinType::SatULongAccum:
Leonard Chanf921d852018-06-04 16:07:52 +00001832 Width = Target->getLongAccumWidth();
1833 Align = Target->getLongAccumAlign();
1834 break;
Leonard Chanab80f3c2018-06-14 14:53:51 +00001835 case BuiltinType::ShortFract:
1836 case BuiltinType::UShortFract:
1837 case BuiltinType::SatShortFract:
1838 case BuiltinType::SatUShortFract:
1839 Width = Target->getShortFractWidth();
1840 Align = Target->getShortFractAlign();
1841 break;
1842 case BuiltinType::Fract:
1843 case BuiltinType::UFract:
1844 case BuiltinType::SatFract:
1845 case BuiltinType::SatUFract:
1846 Width = Target->getFractWidth();
1847 Align = Target->getFractAlign();
1848 break;
1849 case BuiltinType::LongFract:
1850 case BuiltinType::ULongFract:
1851 case BuiltinType::SatLongFract:
1852 case BuiltinType::SatULongFract:
1853 Width = Target->getLongFractWidth();
1854 Align = Target->getLongFractAlign();
1855 break;
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00001856 case BuiltinType::Float16:
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001857 case BuiltinType::Half:
1858 Width = Target->getHalfWidth();
1859 Align = Target->getHalfAlign();
1860 break;
Chris Lattner6a4f7452007-12-19 19:23:28 +00001861 case BuiltinType::Float:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001862 Width = Target->getFloatWidth();
1863 Align = Target->getFloatAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001864 break;
1865 case BuiltinType::Double:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001866 Width = Target->getDoubleWidth();
1867 Align = Target->getDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001868 break;
1869 case BuiltinType::LongDouble:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001870 Width = Target->getLongDoubleWidth();
1871 Align = Target->getLongDoubleAlign();
Chris Lattner6a4f7452007-12-19 19:23:28 +00001872 break;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001873 case BuiltinType::Float128:
1874 Width = Target->getFloat128Width();
1875 Align = Target->getFloat128Align();
1876 break;
Sebastian Redl576fd422009-05-10 18:38:11 +00001877 case BuiltinType::NullPtr:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001878 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1879 Align = Target->getPointerAlign(0); // == sizeof(void*)
Sebastian Redla81b0b72009-05-27 19:34:06 +00001880 break;
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001881 case BuiltinType::ObjCId:
1882 case BuiltinType::ObjCClass:
1883 case BuiltinType::ObjCSel:
Fangrui Song6907ce22018-07-30 19:24:48 +00001884 Width = Target->getPointerWidth(0);
Douglas Gregore8bbc122011-09-02 00:18:52 +00001885 Align = Target->getPointerAlign(0);
Fariborz Jahanian9c6a39e2010-08-02 18:03:20 +00001886 break;
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00001887 case BuiltinType::OCLSampler:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001888 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00001889 case BuiltinType::OCLClkEvent:
1890 case BuiltinType::OCLQueue:
Alexey Bader9c8453f2015-09-15 11:18:52 +00001891 case BuiltinType::OCLReserveID:
Yaxun Liu99444cb2016-08-03 20:38:06 +00001892#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1893 case BuiltinType::Id:
1894#include "clang/Basic/OpenCLImageTypes.def"
Sven van Haastregt3bb7eaf2017-12-06 10:11:28 +00001895 AS = getTargetAddressSpace(
1896 Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T)));
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00001897 Width = Target->getPointerWidth(AS);
1898 Align = Target->getPointerAlign(AS);
1899 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001900 }
Chris Lattner48f84b82007-07-15 23:46:53 +00001901 break;
Steve Narofffb4330f2009-06-17 22:40:22 +00001902 case Type::ObjCObjectPointer:
Douglas Gregore8bbc122011-09-02 00:18:52 +00001903 Width = Target->getPointerWidth(0);
1904 Align = Target->getPointerAlign(0);
Chris Lattner6a4f7452007-12-19 19:23:28 +00001905 break;
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00001906 case Type::BlockPointer:
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00001907 AS = getTargetAddressSpace(cast<BlockPointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001908 Width = Target->getPointerWidth(AS);
1909 Align = Target->getPointerAlign(AS);
Steve Naroff921a45c2008-09-24 15:05:44 +00001910 break;
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001911 case Type::LValueReference:
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00001912 case Type::RValueReference:
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001913 // alignof and sizeof should never enter this code path here, so we go
1914 // the pointer route.
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00001915 AS = getTargetAddressSpace(cast<ReferenceType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001916 Width = Target->getPointerWidth(AS);
1917 Align = Target->getPointerAlign(AS);
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001918 break;
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00001919 case Type::Pointer:
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00001920 AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
Douglas Gregore8bbc122011-09-02 00:18:52 +00001921 Width = Target->getPointerWidth(AS);
1922 Align = Target->getPointerAlign(AS);
Chris Lattner2dca6ff2008-03-08 08:34:58 +00001923 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001924 case Type::MemberPointer: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00001925 const auto *MPT = cast<MemberPointerType>(T);
Erich Keane8a6b7402017-11-30 16:37:02 +00001926 CXXABI::MemberPointerInfo MPI = ABI->getMemberPointerInfo(MPT);
1927 Width = MPI.Width;
1928 Align = MPI.Align;
Anders Carlsson32440a02009-05-17 02:06:04 +00001929 break;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00001930 }
Chris Lattner647fb222007-07-18 18:26:58 +00001931 case Type::Complex: {
1932 // Complex types have the same alignment as their elements, but twice the
1933 // size.
David Majnemer34b57492014-07-30 01:30:47 +00001934 TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType());
1935 Width = EltInfo.Width * 2;
1936 Align = EltInfo.Align;
Chris Lattner647fb222007-07-18 18:26:58 +00001937 break;
1938 }
John McCall8b07ec22010-05-15 11:32:37 +00001939 case Type::ObjCObject:
1940 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
Reid Kleckner0503a872013-12-05 01:23:43 +00001941 case Type::Adjusted:
Reid Kleckner8a365022013-06-24 17:51:48 +00001942 case Type::Decayed:
Reid Kleckner0503a872013-12-05 01:23:43 +00001943 return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
Devang Pateldbb72632008-06-04 21:54:36 +00001944 case Type::ObjCInterface: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00001945 const auto *ObjCI = cast<ObjCInterfaceType>(T);
Devang Pateldbb72632008-06-04 21:54:36 +00001946 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
Ken Dyckb0fcc592011-02-11 01:54:29 +00001947 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001948 Align = toBits(Layout.getAlignment());
Devang Pateldbb72632008-06-04 21:54:36 +00001949 break;
1950 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001951 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001952 case Type::Enum: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00001953 const auto *TT = cast<TagType>(T);
Daniel Dunbarbbc0af72008-11-08 05:48:37 +00001954
1955 if (TT->getDecl()->isInvalidDecl()) {
Douglas Gregor7f971892011-04-20 17:29:44 +00001956 Width = 8;
1957 Align = 8;
Chris Lattner572100b2008-08-09 21:35:13 +00001958 break;
1959 }
Mike Stump11289f42009-09-09 15:08:12 +00001960
Eugene Zelenko7855e772018-04-03 00:11:50 +00001961 if (const auto *ET = dyn_cast<EnumType>(TT)) {
David Majnemer475b25e2015-01-21 10:54:38 +00001962 const EnumDecl *ED = ET->getDecl();
1963 TypeInfo Info =
1964 getTypeInfo(ED->getIntegerType()->getUnqualifiedDesugaredType());
1965 if (unsigned AttrAlign = ED->getMaxAlignment()) {
1966 Info.Align = AttrAlign;
1967 Info.AlignIsRequired = true;
1968 }
1969 return Info;
1970 }
Chris Lattner8b23c252008-04-06 22:05:18 +00001971
Eugene Zelenko7855e772018-04-03 00:11:50 +00001972 const auto *RT = cast<RecordType>(TT);
David Majnemer5821ff72015-02-03 08:49:29 +00001973 const RecordDecl *RD = RT->getDecl();
1974 const ASTRecordLayout &Layout = getASTRecordLayout(RD);
Ken Dyckb0fcc592011-02-11 01:54:29 +00001975 Width = toBits(Layout.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +00001976 Align = toBits(Layout.getAlignment());
David Majnemer5821ff72015-02-03 08:49:29 +00001977 AlignIsRequired = RD->hasAttr<AlignedAttr>();
Chris Lattner49a953a2007-07-23 22:46:22 +00001978 break;
Chris Lattner983a8bb2007-07-13 22:13:22 +00001979 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001980
Chris Lattner63d2b362009-10-22 05:17:15 +00001981 case Type::SubstTemplateTypeParm:
John McCallcebee162009-10-18 09:09:24 +00001982 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1983 getReplacementType().getTypePtr());
John McCallcebee162009-10-18 09:09:24 +00001984
Richard Smith600b5262017-01-26 20:40:47 +00001985 case Type::Auto:
1986 case Type::DeducedTemplateSpecialization: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00001987 const auto *A = cast<DeducedType>(T);
Richard Smith27d807c2013-04-30 13:56:41 +00001988 assert(!A->getDeducedType().isNull() &&
1989 "cannot request the size of an undeduced or dependent auto type");
Matt Beaumont-Gay7a24210e2011-02-22 20:00:16 +00001990 return getTypeInfo(A->getDeducedType().getTypePtr());
Richard Smith30482bc2011-02-20 03:19:35 +00001991 }
1992
Abramo Bagnara924a8f32010-12-10 16:29:40 +00001993 case Type::Paren:
1994 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1995
Manman Rene6be26c2016-09-13 17:25:08 +00001996 case Type::ObjCTypeParam:
1997 return getTypeInfo(cast<ObjCTypeParamType>(T)->desugar().getTypePtr());
1998
Douglas Gregoref462e62009-04-30 17:32:17 +00001999 case Type::Typedef: {
Richard Smithdda56e42011-04-15 14:24:37 +00002000 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
David Majnemer34b57492014-07-30 01:30:47 +00002001 TypeInfo Info = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
Chris Lattner29eb47b2011-02-19 22:55:41 +00002002 // If the typedef has an aligned attribute on it, it overrides any computed
2003 // alignment we have. This violates the GCC documentation (which says that
2004 // attribute(aligned) can only round up) but matches its implementation.
David Majnemer34b57492014-07-30 01:30:47 +00002005 if (unsigned AttrAlign = Typedef->getMaxAlignment()) {
Chris Lattner29eb47b2011-02-19 22:55:41 +00002006 Align = AttrAlign;
David Majnemer34b57492014-07-30 01:30:47 +00002007 AlignIsRequired = true;
David Majnemer37bffb62014-08-04 05:11:01 +00002008 } else {
David Majnemer34b57492014-07-30 01:30:47 +00002009 Align = Info.Align;
David Majnemer37bffb62014-08-04 05:11:01 +00002010 AlignIsRequired = Info.AlignIsRequired;
2011 }
David Majnemer34b57492014-07-30 01:30:47 +00002012 Width = Info.Width;
Douglas Gregordc572a32009-03-30 22:58:21 +00002013 break;
Chris Lattner8b23c252008-04-06 22:05:18 +00002014 }
Douglas Gregoref462e62009-04-30 17:32:17 +00002015
Abramo Bagnara6150c882010-05-11 21:36:43 +00002016 case Type::Elaborated:
2017 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
Mike Stump11289f42009-09-09 15:08:12 +00002018
John McCall81904512011-01-06 01:58:22 +00002019 case Type::Attributed:
2020 return getTypeInfo(
2021 cast<AttributedType>(T)->getEquivalentType().getTypePtr());
2022
Eli Friedman0dfb8892011-10-06 23:00:33 +00002023 case Type::Atomic: {
John McCalla8ec7eb2013-03-07 21:37:17 +00002024 // Start with the base type information.
David Majnemer34b57492014-07-30 01:30:47 +00002025 TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType());
2026 Width = Info.Width;
2027 Align = Info.Align;
John McCalla8ec7eb2013-03-07 21:37:17 +00002028
JF Bastien801fca22018-05-09 03:51:12 +00002029 if (!Width) {
2030 // An otherwise zero-sized type should still generate an
2031 // atomic operation.
2032 Width = Target->getCharWidth();
2033 assert(Align);
2034 } else if (Width <= Target->getMaxAtomicPromoteWidth()) {
2035 // If the size of the type doesn't exceed the platform's max
2036 // atomic promotion width, make the size and alignment more
2037 // favorable to atomic operations:
2038
John McCalla8ec7eb2013-03-07 21:37:17 +00002039 // Round the size up to a power of 2.
2040 if (!llvm::isPowerOf2_64(Width))
2041 Width = llvm::NextPowerOf2(Width);
2042
2043 // Set the alignment equal to the size.
Eli Friedman4b72fdd2011-10-14 20:59:01 +00002044 Align = static_cast<unsigned>(Width);
2045 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00002046 }
Xiuli Pan9c14e282016-01-09 12:53:17 +00002047 break;
2048
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00002049 case Type::Pipe:
Anastasia Stulovab3398932017-06-05 11:27:03 +00002050 Width = Target->getPointerWidth(getTargetAddressSpace(LangAS::opencl_global));
2051 Align = Target->getPointerAlign(getTargetAddressSpace(LangAS::opencl_global));
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00002052 break;
Douglas Gregoref462e62009-04-30 17:32:17 +00002053 }
Mike Stump11289f42009-09-09 15:08:12 +00002054
Eli Friedman4b72fdd2011-10-14 20:59:01 +00002055 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
David Majnemer34b57492014-07-30 01:30:47 +00002056 return TypeInfo(Width, Align, AlignIsRequired);
Chris Lattner983a8bb2007-07-13 22:13:22 +00002057}
2058
Momchil Velikov20208cc2018-07-30 17:48:23 +00002059unsigned ASTContext::getTypeUnadjustedAlign(const Type *T) const {
2060 UnadjustedAlignMap::iterator I = MemoizedUnadjustedAlign.find(T);
2061 if (I != MemoizedUnadjustedAlign.end())
2062 return I->second;
2063
2064 unsigned UnadjustedAlign;
2065 if (const auto *RT = T->getAs<RecordType>()) {
2066 const RecordDecl *RD = RT->getDecl();
2067 const ASTRecordLayout &Layout = getASTRecordLayout(RD);
2068 UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
2069 } else if (const auto *ObjCI = T->getAs<ObjCInterfaceType>()) {
2070 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
2071 UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
2072 } else {
2073 UnadjustedAlign = getTypeAlign(T);
2074 }
2075
2076 MemoizedUnadjustedAlign[T] = UnadjustedAlign;
2077 return UnadjustedAlign;
2078}
2079
Alexey Bataev00396512015-07-02 03:40:19 +00002080unsigned ASTContext::getOpenMPDefaultSimdAlign(QualType T) const {
2081 unsigned SimdAlign = getTargetInfo().getSimdDefaultAlign();
2082 // Target ppc64 with QPX: simd default alignment for pointer to double is 32.
2083 if ((getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64 ||
2084 getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64le) &&
2085 getTargetInfo().getABI() == "elfv1-qpx" &&
2086 T->isSpecificBuiltinType(BuiltinType::Double))
2087 SimdAlign = 256;
2088 return SimdAlign;
2089}
2090
Ken Dyckcc56c542011-01-15 18:38:59 +00002091/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
2092CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
2093 return CharUnits::fromQuantity(BitSize / getCharWidth());
2094}
2095
Ken Dyckb0fcc592011-02-11 01:54:29 +00002096/// toBits - Convert a size in characters to a size in characters.
2097int64_t ASTContext::toBits(CharUnits CharSize) const {
2098 return CharSize.getQuantity() * getCharWidth();
2099}
2100
Ken Dyck8c89d592009-12-22 14:23:30 +00002101/// getTypeSizeInChars - Return the size of the specified type, in characters.
2102/// This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00002103CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00002104 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00002105}
Jay Foad39c79802011-01-12 09:06:06 +00002106CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
Richard Trieu04d2d942013-05-14 21:59:17 +00002107 return getTypeInfoInChars(T).first;
Ken Dyck8c89d592009-12-22 14:23:30 +00002108}
2109
Fangrui Song6907ce22018-07-30 19:24:48 +00002110/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
Ken Dyck24d28d62010-01-26 17:22:55 +00002111/// characters. This method does not work on incomplete types.
Jay Foad39c79802011-01-12 09:06:06 +00002112CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00002113 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00002114}
Jay Foad39c79802011-01-12 09:06:06 +00002115CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
Ken Dyckcc56c542011-01-15 18:38:59 +00002116 return toCharUnitsFromBits(getTypeAlign(T));
Ken Dyck24d28d62010-01-26 17:22:55 +00002117}
2118
Momchil Velikov20208cc2018-07-30 17:48:23 +00002119/// getTypeUnadjustedAlignInChars - Return the ABI-specified alignment of a
2120/// type, in characters, before alignment adustments. This method does
2121/// not work on incomplete types.
2122CharUnits ASTContext::getTypeUnadjustedAlignInChars(QualType T) const {
2123 return toCharUnitsFromBits(getTypeUnadjustedAlign(T));
2124}
2125CharUnits ASTContext::getTypeUnadjustedAlignInChars(const Type *T) const {
2126 return toCharUnitsFromBits(getTypeUnadjustedAlign(T));
2127}
2128
Chris Lattnera3402cd2009-01-27 18:08:34 +00002129/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
2130/// type for the current target in bits. This can be different than the ABI
2131/// alignment in cases where it is beneficial for performance to overalign
2132/// a data type.
Jay Foad39c79802011-01-12 09:06:06 +00002133unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
David Majnemer34b57492014-07-30 01:30:47 +00002134 TypeInfo TI = getTypeInfo(T);
2135 unsigned ABIAlign = TI.Align;
Eli Friedman7ab09572009-05-25 21:27:19 +00002136
David Majnemere1544562015-04-24 01:25:05 +00002137 T = T->getBaseElementTypeUnsafe();
2138
2139 // The preferred alignment of member pointers is that of a pointer.
2140 if (T->isMemberPointerType())
2141 return getPreferredTypeAlign(getPointerDiffType().getTypePtr());
2142
Andrey Turetskiydb6655f2016-02-10 11:58:46 +00002143 if (!Target->allowsLargerPreferedTypeAlignment())
2144 return ABIAlign;
Robert Lyttoneaf6f362013-11-12 10:09:34 +00002145
Eli Friedman7ab09572009-05-25 21:27:19 +00002146 // Double and long long should be naturally aligned if possible.
Eugene Zelenko7855e772018-04-03 00:11:50 +00002147 if (const auto *CT = T->getAs<ComplexType>())
Eli Friedman7ab09572009-05-25 21:27:19 +00002148 T = CT->getElementType().getTypePtr();
Eugene Zelenko7855e772018-04-03 00:11:50 +00002149 if (const auto *ET = T->getAs<EnumType>())
David Majnemer475b25e2015-01-21 10:54:38 +00002150 T = ET->getDecl()->getIntegerType().getTypePtr();
Eli Friedman7ab09572009-05-25 21:27:19 +00002151 if (T->isSpecificBuiltinType(BuiltinType::Double) ||
Chad Rosierb57321a2012-03-21 20:20:47 +00002152 T->isSpecificBuiltinType(BuiltinType::LongLong) ||
2153 T->isSpecificBuiltinType(BuiltinType::ULongLong))
David Majnemer8b6bd572014-02-24 23:34:17 +00002154 // Don't increase the alignment if an alignment attribute was specified on a
2155 // typedef declaration.
David Majnemer34b57492014-07-30 01:30:47 +00002156 if (!TI.AlignIsRequired)
David Majnemer8b6bd572014-02-24 23:34:17 +00002157 return std::max(ABIAlign, (unsigned)getTypeSize(T));
Eli Friedman7ab09572009-05-25 21:27:19 +00002158
Chris Lattnera3402cd2009-01-27 18:08:34 +00002159 return ABIAlign;
2160}
2161
Ulrich Weigandca3cb7f2015-04-21 17:29:35 +00002162/// getTargetDefaultAlignForAttributeAligned - Return the default alignment
2163/// for __attribute__((aligned)) on this target, to be used if no alignment
2164/// value is specified.
Eugene Zelenkod4304d22015-11-04 21:37:17 +00002165unsigned ASTContext::getTargetDefaultAlignForAttributeAligned() const {
Ulrich Weigandca3cb7f2015-04-21 17:29:35 +00002166 return getTargetInfo().getDefaultAlignForAttributeAligned();
2167}
2168
Ulrich Weigandfa806422013-05-06 16:23:57 +00002169/// getAlignOfGlobalVar - Return the alignment in bits that should be given
2170/// to a global variable of the specified type.
2171unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
2172 return std::max(getTypeAlign(T), getTargetInfo().getMinGlobalAlign());
2173}
2174
2175/// getAlignOfGlobalVarInChars - Return the alignment in characters that
2176/// should be given to a global variable of the specified type.
2177CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
2178 return toCharUnitsFromBits(getAlignOfGlobalVar(T));
2179}
2180
David Majnemer08ef2ba2015-06-23 20:34:18 +00002181CharUnits ASTContext::getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const {
2182 CharUnits Offset = CharUnits::Zero();
2183 const ASTRecordLayout *Layout = &getASTRecordLayout(RD);
2184 while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) {
2185 Offset += Layout->getBaseClassOffset(Base);
2186 Layout = &getASTRecordLayout(Base);
2187 }
2188 return Offset;
2189}
2190
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00002191/// DeepCollectObjCIvars -
2192/// This routine first collects all declared, but not synthesized, ivars in
2193/// super class and then collects all ivars, including those synthesized for
2194/// current class. This routine is used for implementation of current class
2195/// when all ivars, declared and synthesized are known.
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00002196void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
2197 bool leafClass,
Jordy Rosea91768e2011-07-22 02:08:32 +00002198 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00002199 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
2200 DeepCollectObjCIvars(SuperClass, false, Ivars);
2201 if (!leafClass) {
Aaron Ballman59abbd42014-03-13 21:09:43 +00002202 for (const auto *I : OI->ivars())
2203 Ivars.push_back(I);
Chad Rosier6fdf38b2011-08-17 23:08:45 +00002204 } else {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002205 auto *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
Fangrui Song6907ce22018-07-30 19:24:48 +00002206 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00002207 Iv= Iv->getNextIvar())
2208 Ivars.push_back(Iv);
2209 }
Fariborz Jahanian0f44d812009-05-12 18:14:29 +00002210}
2211
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002212/// CollectInheritedProtocols - Collect all protocols in current class and
2213/// those inherited by it.
2214void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
Fariborz Jahaniandc68f952010-02-12 19:27:33 +00002215 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002216 if (const auto *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
Ted Kremenek0ef508d2010-09-01 01:21:15 +00002217 // We can use protocol_iterator here instead of
Fangrui Song6907ce22018-07-30 19:24:48 +00002218 // all_referenced_protocol_iterator since we are walking all categories.
Aaron Ballmana9f49e32014-03-13 20:55:22 +00002219 for (auto *Proto : OI->all_referenced_protocols()) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00002220 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian8e3b9db2010-02-25 18:24:33 +00002221 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002222
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002223 // Categories of this Interface.
Aaron Ballman3fe486a2014-03-13 21:23:55 +00002224 for (const auto *Cat : OI->visible_categories())
2225 CollectInheritedProtocols(Cat, Protocols);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002226
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002227 if (ObjCInterfaceDecl *SD = OI->getSuperClass())
2228 while (SD) {
2229 CollectInheritedProtocols(SD, Protocols);
2230 SD = SD->getSuperClass();
2231 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00002232 } else if (const auto *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Aaron Ballman19a41762014-03-14 12:55:57 +00002233 for (auto *Proto : OC->protocols()) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00002234 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002235 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00002236 } else if (const auto *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00002237 // Insert the protocol.
2238 if (!Protocols.insert(
2239 const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second)
2240 return;
2241
2242 for (auto *Proto : OP->protocols())
2243 CollectInheritedProtocols(Proto, Protocols);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00002244 }
2245}
2246
Erich Keane8a6b7402017-11-30 16:37:02 +00002247static bool unionHasUniqueObjectRepresentations(const ASTContext &Context,
2248 const RecordDecl *RD) {
2249 assert(RD->isUnion() && "Must be union type");
2250 CharUnits UnionSize = Context.getTypeSizeInChars(RD->getTypeForDecl());
2251
2252 for (const auto *Field : RD->fields()) {
2253 if (!Context.hasUniqueObjectRepresentations(Field->getType()))
2254 return false;
2255 CharUnits FieldSize = Context.getTypeSizeInChars(Field->getType());
2256 if (FieldSize != UnionSize)
2257 return false;
2258 }
Eric Fiselier12a9f342018-02-02 20:30:39 +00002259 return !RD->field_empty();
Erich Keane8a6b7402017-11-30 16:37:02 +00002260}
2261
Benjamin Kramer802e6252017-12-24 12:46:22 +00002262static bool isStructEmpty(QualType Ty) {
Erich Keane8a6b7402017-11-30 16:37:02 +00002263 const RecordDecl *RD = Ty->castAs<RecordType>()->getDecl();
2264
2265 if (!RD->field_empty())
2266 return false;
2267
2268 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RD))
2269 return ClassDecl->isEmpty();
2270
2271 return true;
2272}
2273
2274static llvm::Optional<int64_t>
2275structHasUniqueObjectRepresentations(const ASTContext &Context,
2276 const RecordDecl *RD) {
2277 assert(!RD->isUnion() && "Must be struct/class type");
2278 const auto &Layout = Context.getASTRecordLayout(RD);
2279
2280 int64_t CurOffsetInBits = 0;
2281 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RD)) {
2282 if (ClassDecl->isDynamicClass())
2283 return llvm::None;
2284
2285 SmallVector<std::pair<QualType, int64_t>, 4> Bases;
2286 for (const auto Base : ClassDecl->bases()) {
2287 // Empty types can be inherited from, and non-empty types can potentially
2288 // have tail padding, so just make sure there isn't an error.
2289 if (!isStructEmpty(Base.getType())) {
2290 llvm::Optional<int64_t> Size = structHasUniqueObjectRepresentations(
2291 Context, Base.getType()->getAs<RecordType>()->getDecl());
2292 if (!Size)
2293 return llvm::None;
2294 Bases.emplace_back(Base.getType(), Size.getValue());
2295 }
2296 }
2297
Fangrui Song1d38c132018-09-30 21:41:11 +00002298 llvm::sort(Bases, [&](const std::pair<QualType, int64_t> &L,
2299 const std::pair<QualType, int64_t> &R) {
2300 return Layout.getBaseClassOffset(L.first->getAsCXXRecordDecl()) <
2301 Layout.getBaseClassOffset(R.first->getAsCXXRecordDecl());
2302 });
Erich Keane8a6b7402017-11-30 16:37:02 +00002303
2304 for (const auto Base : Bases) {
2305 int64_t BaseOffset = Context.toBits(
2306 Layout.getBaseClassOffset(Base.first->getAsCXXRecordDecl()));
2307 int64_t BaseSize = Base.second;
2308 if (BaseOffset != CurOffsetInBits)
2309 return llvm::None;
2310 CurOffsetInBits = BaseOffset + BaseSize;
2311 }
2312 }
2313
2314 for (const auto *Field : RD->fields()) {
2315 if (!Field->getType()->isReferenceType() &&
2316 !Context.hasUniqueObjectRepresentations(Field->getType()))
2317 return llvm::None;
2318
2319 int64_t FieldSizeInBits =
2320 Context.toBits(Context.getTypeSizeInChars(Field->getType()));
2321 if (Field->isBitField()) {
2322 int64_t BitfieldSize = Field->getBitWidthValue(Context);
2323
2324 if (BitfieldSize > FieldSizeInBits)
2325 return llvm::None;
2326 FieldSizeInBits = BitfieldSize;
2327 }
2328
2329 int64_t FieldOffsetInBits = Context.getFieldOffset(Field);
2330
2331 if (FieldOffsetInBits != CurOffsetInBits)
2332 return llvm::None;
2333
2334 CurOffsetInBits = FieldSizeInBits + FieldOffsetInBits;
2335 }
2336
2337 return CurOffsetInBits;
2338}
2339
2340bool ASTContext::hasUniqueObjectRepresentations(QualType Ty) const {
2341 // C++17 [meta.unary.prop]:
2342 // The predicate condition for a template specialization
2343 // has_unique_object_representations<T> shall be
2344 // satisfied if and only if:
2345 // (9.1) - T is trivially copyable, and
2346 // (9.2) - any two objects of type T with the same value have the same
2347 // object representation, where two objects
2348 // of array or non-union class type are considered to have the same value
2349 // if their respective sequences of
2350 // direct subobjects have the same values, and two objects of union type
2351 // are considered to have the same
2352 // value if they have the same active member and the corresponding members
2353 // have the same value.
2354 // The set of scalar types for which this condition holds is
2355 // implementation-defined. [ Note: If a type has padding
2356 // bits, the condition does not hold; otherwise, the condition holds true
2357 // for unsigned integral types. -- end note ]
2358 assert(!Ty.isNull() && "Null QualType sent to unique object rep check");
2359
2360 // Arrays are unique only if their element type is unique.
2361 if (Ty->isArrayType())
2362 return hasUniqueObjectRepresentations(getBaseElementType(Ty));
2363
2364 // (9.1) - T is trivially copyable...
2365 if (!Ty.isTriviallyCopyableType(*this))
2366 return false;
2367
2368 // All integrals and enums are unique.
2369 if (Ty->isIntegralOrEnumerationType())
2370 return true;
2371
2372 // All other pointers are unique.
2373 if (Ty->isPointerType())
2374 return true;
2375
2376 if (Ty->isMemberPointerType()) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002377 const auto *MPT = Ty->getAs<MemberPointerType>();
Erich Keane8a6b7402017-11-30 16:37:02 +00002378 return !ABI->getMemberPointerInfo(MPT).HasPadding;
2379 }
2380
2381 if (Ty->isRecordType()) {
2382 const RecordDecl *Record = Ty->getAs<RecordType>()->getDecl();
2383
Erich Keanebd2197c2017-12-12 16:02:06 +00002384 if (Record->isInvalidDecl())
2385 return false;
2386
Erich Keane8a6b7402017-11-30 16:37:02 +00002387 if (Record->isUnion())
2388 return unionHasUniqueObjectRepresentations(*this, Record);
2389
2390 Optional<int64_t> StructSize =
2391 structHasUniqueObjectRepresentations(*this, Record);
2392
2393 return StructSize &&
2394 StructSize.getValue() == static_cast<int64_t>(getTypeSize(Ty));
2395 }
2396
2397 // FIXME: More cases to handle here (list by rsmith):
2398 // vectors (careful about, eg, vector of 3 foo)
2399 // _Complex int and friends
2400 // _Atomic T
2401 // Obj-C block pointers
2402 // Obj-C object pointers
2403 // and perhaps OpenCL's various builtin types (pipe, sampler_t, event_t,
2404 // clk_event_t, queue_t, reserve_id_t)
2405 // There're also Obj-C class types and the Obj-C selector type, but I think it
2406 // makes sense for those to return false here.
2407
2408 return false;
2409}
2410
Jay Foad39c79802011-01-12 09:06:06 +00002411unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00002412 unsigned count = 0;
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00002413 // Count ivars declared in class extension.
Aaron Ballmanb4a53452014-03-13 21:57:01 +00002414 for (const auto *Ext : OI->known_extensions())
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002415 count += Ext->ivar_size();
Fangrui Song6907ce22018-07-30 19:24:48 +00002416
Fariborz Jahaniand2ae2d02010-03-22 18:25:57 +00002417 // Count ivar defined in this class's implementation. This
2418 // includes synthesized ivars.
2419 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
Benjamin Kramer0a3fe042010-04-27 17:47:25 +00002420 count += ImplDecl->ivar_size();
2421
Fariborz Jahanian7c809592009-06-04 01:19:09 +00002422 return count;
2423}
2424
Argyrios Kyrtzidis2e809ce2012-02-03 05:58:16 +00002425bool ASTContext::isSentinelNullExpr(const Expr *E) {
2426 if (!E)
2427 return false;
2428
2429 // nullptr_t is always treated as null.
2430 if (E->getType()->isNullPtrType()) return true;
2431
2432 if (E->getType()->isAnyPointerType() &&
2433 E->IgnoreParenCasts()->isNullPointerConstant(*this,
2434 Expr::NPC_ValueDependentIsNull))
2435 return true;
2436
2437 // Unfortunately, __null has type 'int'.
2438 if (isa<GNUNullExpr>(E)) return true;
2439
2440 return false;
2441}
2442
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002443/// Get the implementation of ObjCInterfaceDecl, or nullptr if none
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00002444/// exists.
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002445ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
2446 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2447 I = ObjCImpls.find(D);
2448 if (I != ObjCImpls.end())
2449 return cast<ObjCImplementationDecl>(I->second);
Craig Topper36250ad2014-05-12 05:36:57 +00002450 return nullptr;
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002451}
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00002452
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002453/// Get the implementation of ObjCCategoryDecl, or nullptr if none
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00002454/// exists.
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002455ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
2456 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
2457 I = ObjCImpls.find(D);
2458 if (I != ObjCImpls.end())
2459 return cast<ObjCCategoryImplDecl>(I->second);
Craig Topper36250ad2014-05-12 05:36:57 +00002460 return nullptr;
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002461}
2462
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002463/// Set the implementation of ObjCInterfaceDecl.
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002464void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
2465 ObjCImplementationDecl *ImplD) {
2466 assert(IFaceD && ImplD && "Passed null params");
2467 ObjCImpls[IFaceD] = ImplD;
2468}
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00002469
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002470/// Set the implementation of ObjCCategoryDecl.
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002471void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
2472 ObjCCategoryImplDecl *ImplD) {
2473 assert(CatD && ImplD && "Passed null params");
2474 ObjCImpls[CatD] = ImplD;
2475}
2476
Chandler Carruth21c90602015-12-30 03:24:14 +00002477const ObjCMethodDecl *
2478ASTContext::getObjCMethodRedeclaration(const ObjCMethodDecl *MD) const {
2479 return ObjCMethodRedecls.lookup(MD);
2480}
2481
2482void ASTContext::setObjCMethodRedeclaration(const ObjCMethodDecl *MD,
2483 const ObjCMethodDecl *Redecl) {
2484 assert(!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration");
2485 ObjCMethodRedecls[MD] = Redecl;
2486}
2487
Dmitri Gribenko37527c22013-02-03 13:23:21 +00002488const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
2489 const NamedDecl *ND) const {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002490 if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002491 return ID;
Eugene Zelenko7855e772018-04-03 00:11:50 +00002492 if (const auto *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002493 return CD->getClassInterface();
Eugene Zelenko7855e772018-04-03 00:11:50 +00002494 if (const auto *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002495 return IMD->getClassInterface();
2496
Craig Topper36250ad2014-05-12 05:36:57 +00002497 return nullptr;
Argyrios Kyrtzidisb9689bb2011-11-01 17:14:12 +00002498}
2499
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002500/// Get the copy initialization expression of VarDecl, or nullptr if
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002501/// none exists.
Akira Hatanaka9978da32018-08-10 15:09:24 +00002502ASTContext::BlockVarCopyInit
2503ASTContext::getBlockVarCopyInit(const VarDecl*VD) const {
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002504 assert(VD && "Passed null params");
Fangrui Song6907ce22018-07-30 19:24:48 +00002505 assert(VD->hasAttr<BlocksAttr>() &&
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002506 "getBlockVarCopyInits - not __block var");
Akira Hatanaka9978da32018-08-10 15:09:24 +00002507 auto I = BlockVarCopyInits.find(VD);
2508 if (I != BlockVarCopyInits.end())
2509 return I->second;
2510 return {nullptr, false};
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002511}
2512
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002513/// Set the copy inialization expression of a block var decl.
Akira Hatanaka9978da32018-08-10 15:09:24 +00002514void ASTContext::setBlockVarCopyInit(const VarDecl*VD, Expr *CopyExpr,
2515 bool CanThrow) {
2516 assert(VD && CopyExpr && "Passed null params");
Fangrui Song6907ce22018-07-30 19:24:48 +00002517 assert(VD->hasAttr<BlocksAttr>() &&
Fariborz Jahanian1321cbb2010-12-06 17:28:17 +00002518 "setBlockVarCopyInits - not __block var");
Akira Hatanaka9978da32018-08-10 15:09:24 +00002519 BlockVarCopyInits[VD].setExprAndFlag(CopyExpr, CanThrow);
Fariborz Jahanian7cfe7672010-12-01 22:29:46 +00002520}
2521
John McCallbcd03502009-12-07 02:54:59 +00002522TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00002523 unsigned DataSize) const {
John McCall26fe7e02009-10-21 00:23:54 +00002524 if (!DataSize)
2525 DataSize = TypeLoc::getFullDataSizeForType(T);
2526 else
2527 assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
John McCallbcd03502009-12-07 02:54:59 +00002528 "incorrect data size provided to CreateTypeSourceInfo!");
John McCall26fe7e02009-10-21 00:23:54 +00002529
Eugene Zelenko7855e772018-04-03 00:11:50 +00002530 auto *TInfo =
John McCallbcd03502009-12-07 02:54:59 +00002531 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
2532 new (TInfo) TypeSourceInfo(T);
2533 return TInfo;
Argyrios Kyrtzidis3f79ad72009-08-19 01:27:32 +00002534}
2535
John McCallbcd03502009-12-07 02:54:59 +00002536TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002537 SourceLocation L) const {
John McCallbcd03502009-12-07 02:54:59 +00002538 TypeSourceInfo *DI = CreateTypeSourceInfo(T);
Douglas Gregor2d525f02011-01-25 19:13:18 +00002539 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
John McCall3665e002009-10-23 21:14:09 +00002540 return DI;
2541}
2542
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002543const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00002544ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
Craig Topper36250ad2014-05-12 05:36:57 +00002545 return getObjCLayout(D, nullptr);
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002546}
2547
2548const ASTRecordLayout &
Jay Foad39c79802011-01-12 09:06:06 +00002549ASTContext::getASTObjCImplementationLayout(
2550 const ObjCImplementationDecl *D) const {
Daniel Dunbar02f7f5f2009-05-03 10:38:35 +00002551 return getObjCLayout(D->getClassInterface(), D);
2552}
2553
Chris Lattner983a8bb2007-07-13 22:13:22 +00002554//===----------------------------------------------------------------------===//
2555// Type creation/memoization methods
2556//===----------------------------------------------------------------------===//
2557
Jay Foad39c79802011-01-12 09:06:06 +00002558QualType
John McCall33ddac02011-01-19 10:06:00 +00002559ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
2560 unsigned fastQuals = quals.getFastQualifiers();
2561 quals.removeFastQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00002562
2563 // Check if we've already instantiated this type.
2564 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00002565 ExtQuals::Profile(ID, baseType, quals);
Craig Topper36250ad2014-05-12 05:36:57 +00002566 void *insertPos = nullptr;
John McCall33ddac02011-01-19 10:06:00 +00002567 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
2568 assert(eq->getQualifiers() == quals);
2569 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002570 }
2571
John McCall33ddac02011-01-19 10:06:00 +00002572 // If the base type is not canonical, make the appropriate canonical type.
2573 QualType canon;
2574 if (!baseType->isCanonicalUnqualified()) {
2575 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
John McCall18ce25e2012-02-08 00:46:36 +00002576 canonSplit.Quals.addConsistentQualifiers(quals);
2577 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00002578
2579 // Re-find the insert position.
2580 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
2581 }
2582
Eugene Zelenko7855e772018-04-03 00:11:50 +00002583 auto *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
John McCall33ddac02011-01-19 10:06:00 +00002584 ExtQualNodes.InsertNode(eq, insertPos);
2585 return QualType(eq, fastQuals);
John McCall8ccfcb52009-09-24 19:53:00 +00002586}
2587
Alexander Richardson6d989432017-10-15 18:48:14 +00002588QualType ASTContext::getAddrSpaceQualType(QualType T,
2589 LangAS AddressSpace) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002590 QualType CanT = getCanonicalType(T);
2591 if (CanT.getAddressSpace() == AddressSpace)
Chris Lattner445fcab2008-02-20 20:55:12 +00002592 return T;
Chris Lattnerd60183d2009-02-18 22:53:11 +00002593
John McCall8ccfcb52009-09-24 19:53:00 +00002594 // If we are composing extended qualifiers together, merge together
2595 // into one ExtQuals node.
2596 QualifierCollector Quals;
2597 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002598
John McCall8ccfcb52009-09-24 19:53:00 +00002599 // If this type already has an address space specified, it cannot get
2600 // another one.
2601 assert(!Quals.hasAddressSpace() &&
2602 "Type cannot be in multiple addr spaces!");
2603 Quals.addAddressSpace(AddressSpace);
Mike Stump11289f42009-09-09 15:08:12 +00002604
John McCall8ccfcb52009-09-24 19:53:00 +00002605 return getExtQualType(TypeNode, Quals);
Christopher Lamb025b5fb2008-02-04 02:31:56 +00002606}
2607
Andrew Gozillon572bbb02017-10-02 06:25:51 +00002608QualType ASTContext::removeAddrSpaceQualType(QualType T) const {
2609 // If we are composing extended qualifiers together, merge together
2610 // into one ExtQuals node.
2611 QualifierCollector Quals;
2612 const Type *TypeNode = Quals.strip(T);
2613
2614 // If the qualifier doesn't have an address space just return it.
2615 if (!Quals.hasAddressSpace())
2616 return T;
2617
2618 Quals.removeAddressSpace();
2619
2620 // Removal of the address space can mean there are no longer any
2621 // non-fast qualifiers, so creating an ExtQualType isn't possible (asserts)
2622 // or required.
2623 if (Quals.hasNonFastQualifiers())
2624 return getExtQualType(TypeNode, Quals);
2625 else
2626 return QualType(TypeNode, Quals.getFastQualifiers());
2627}
2628
Chris Lattnerd60183d2009-02-18 22:53:11 +00002629QualType ASTContext::getObjCGCQualType(QualType T,
Jay Foad39c79802011-01-12 09:06:06 +00002630 Qualifiers::GC GCAttr) const {
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002631 QualType CanT = getCanonicalType(T);
Chris Lattnerd60183d2009-02-18 22:53:11 +00002632 if (CanT.getObjCGCAttr() == GCAttr)
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002633 return T;
Mike Stump11289f42009-09-09 15:08:12 +00002634
Eugene Zelenko7855e772018-04-03 00:11:50 +00002635 if (const auto *ptr = T->getAs<PointerType>()) {
John McCall53fa7142010-12-24 02:08:15 +00002636 QualType Pointee = ptr->getPointeeType();
Steve Naroff6b712a72009-07-14 18:25:06 +00002637 if (Pointee->isAnyPointerType()) {
Fariborz Jahanianb68215c2009-06-03 17:15:17 +00002638 QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
2639 return getPointerType(ResultType);
2640 }
2641 }
Mike Stump11289f42009-09-09 15:08:12 +00002642
John McCall8ccfcb52009-09-24 19:53:00 +00002643 // If we are composing extended qualifiers together, merge together
2644 // into one ExtQuals node.
2645 QualifierCollector Quals;
2646 const Type *TypeNode = Quals.strip(T);
Mike Stump11289f42009-09-09 15:08:12 +00002647
John McCall8ccfcb52009-09-24 19:53:00 +00002648 // If this type already has an ObjCGC specified, it cannot get
2649 // another one.
2650 assert(!Quals.hasObjCGCAttr() &&
2651 "Type cannot have multiple ObjCGCs!");
2652 Quals.addObjCGCAttr(GCAttr);
Mike Stump11289f42009-09-09 15:08:12 +00002653
John McCall8ccfcb52009-09-24 19:53:00 +00002654 return getExtQualType(TypeNode, Quals);
Fariborz Jahaniane27e9342009-02-18 05:09:49 +00002655}
Chris Lattner983a8bb2007-07-13 22:13:22 +00002656
John McCall4f5019e2010-12-19 02:44:49 +00002657const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
2658 FunctionType::ExtInfo Info) {
2659 if (T->getExtInfo() == Info)
2660 return T;
2661
2662 QualType Result;
Eugene Zelenko7855e772018-04-03 00:11:50 +00002663 if (const auto *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
Alp Toker314cc812014-01-25 16:55:45 +00002664 Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
John McCall4f5019e2010-12-19 02:44:49 +00002665 } else {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002666 const auto *FPT = cast<FunctionProtoType>(T);
John McCall4f5019e2010-12-19 02:44:49 +00002667 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2668 EPI.ExtInfo = Info;
Alp Toker314cc812014-01-25 16:55:45 +00002669 Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
John McCall4f5019e2010-12-19 02:44:49 +00002670 }
2671
2672 return cast<FunctionType>(Result.getTypePtr());
2673}
2674
Richard Smith2a7d4812013-05-04 07:00:32 +00002675void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
2676 QualType ResultType) {
Richard Smith1fa5d642013-05-11 05:45:24 +00002677 FD = FD->getMostRecentDecl();
2678 while (true) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00002679 const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
Richard Smith2a7d4812013-05-04 07:00:32 +00002680 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
Alp Toker9cacbab2014-01-20 20:26:09 +00002681 FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI));
Richard Smith1fa5d642013-05-11 05:45:24 +00002682 if (FunctionDecl *Next = FD->getPreviousDecl())
2683 FD = Next;
2684 else
2685 break;
Richard Smith2a7d4812013-05-04 07:00:32 +00002686 }
Richard Smith1fa5d642013-05-11 05:45:24 +00002687 if (ASTMutationListener *L = getASTMutationListener())
2688 L->DeducedReturnType(FD, ResultType);
Richard Smith2a7d4812013-05-04 07:00:32 +00002689}
2690
Richard Smith0b3a4622014-11-13 20:01:57 +00002691/// Get a function type and produce the equivalent function type with the
2692/// specified exception specification. Type sugar that can be present on a
2693/// declaration of a function with an exception specification is permitted
2694/// and preserved. Other type sugar (for instance, typedefs) is not.
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002695QualType ASTContext::getFunctionTypeWithExceptionSpec(
2696 QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI) {
Richard Smith0b3a4622014-11-13 20:01:57 +00002697 // Might have some parens.
Eugene Zelenko7855e772018-04-03 00:11:50 +00002698 if (const auto *PT = dyn_cast<ParenType>(Orig))
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002699 return getParenType(
2700 getFunctionTypeWithExceptionSpec(PT->getInnerType(), ESI));
Richard Smith0b3a4622014-11-13 20:01:57 +00002701
2702 // Might have a calling-convention attribute.
Eugene Zelenko7855e772018-04-03 00:11:50 +00002703 if (const auto *AT = dyn_cast<AttributedType>(Orig))
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002704 return getAttributedType(
Richard Smith0b3a4622014-11-13 20:01:57 +00002705 AT->getAttrKind(),
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002706 getFunctionTypeWithExceptionSpec(AT->getModifiedType(), ESI),
2707 getFunctionTypeWithExceptionSpec(AT->getEquivalentType(), ESI));
Richard Smith0b3a4622014-11-13 20:01:57 +00002708
2709 // Anything else must be a function type. Rebuild it with the new exception
2710 // specification.
Eugene Zelenko7855e772018-04-03 00:11:50 +00002711 const auto *Proto = cast<FunctionProtoType>(Orig);
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002712 return getFunctionType(
Richard Smith0b3a4622014-11-13 20:01:57 +00002713 Proto->getReturnType(), Proto->getParamTypes(),
2714 Proto->getExtProtoInfo().withExceptionSpec(ESI));
2715}
2716
Richard Smithdfe85e22016-12-15 02:35:39 +00002717bool ASTContext::hasSameFunctionTypeIgnoringExceptionSpec(QualType T,
2718 QualType U) {
2719 return hasSameType(T, U) ||
Aaron Ballmanc351fba2017-12-04 20:27:34 +00002720 (getLangOpts().CPlusPlus17 &&
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002721 hasSameType(getFunctionTypeWithExceptionSpec(T, EST_None),
2722 getFunctionTypeWithExceptionSpec(U, EST_None)));
Richard Smithdfe85e22016-12-15 02:35:39 +00002723}
2724
Richard Smith0b3a4622014-11-13 20:01:57 +00002725void ASTContext::adjustExceptionSpec(
2726 FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI,
2727 bool AsWritten) {
2728 // Update the type.
2729 QualType Updated =
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002730 getFunctionTypeWithExceptionSpec(FD->getType(), ESI);
Richard Smith0b3a4622014-11-13 20:01:57 +00002731 FD->setType(Updated);
2732
2733 if (!AsWritten)
2734 return;
2735
2736 // Update the type in the type source information too.
2737 if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
2738 // If the type and the type-as-written differ, we may need to update
2739 // the type-as-written too.
2740 if (TSInfo->getType() != FD->getType())
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00002741 Updated = getFunctionTypeWithExceptionSpec(TSInfo->getType(), ESI);
Richard Smith0b3a4622014-11-13 20:01:57 +00002742
2743 // FIXME: When we get proper type location information for exceptions,
2744 // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
2745 // up the TypeSourceInfo;
2746 assert(TypeLoc::getFullDataSizeForType(Updated) ==
2747 TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
2748 "TypeLoc size mismatch from updating exception specification");
2749 TSInfo->overrideType(Updated);
2750 }
2751}
2752
Chris Lattnerc6395932007-06-22 20:56:16 +00002753/// getComplexType - Return the uniqued reference to the type for a complex
2754/// number with the specified element type.
Jay Foad39c79802011-01-12 09:06:06 +00002755QualType ASTContext::getComplexType(QualType T) const {
Chris Lattnerc6395932007-06-22 20:56:16 +00002756 // Unique pointers, to guarantee there is only one pointer of a particular
2757 // structure.
2758 llvm::FoldingSetNodeID ID;
2759 ComplexType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002760
Craig Topper36250ad2014-05-12 05:36:57 +00002761 void *InsertPos = nullptr;
Chris Lattnerc6395932007-06-22 20:56:16 +00002762 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
2763 return QualType(CT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002764
Chris Lattnerc6395932007-06-22 20:56:16 +00002765 // If the pointee type isn't canonical, this won't be a canonical type either,
2766 // so fill in the canonical type field.
2767 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002768 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002769 Canonical = getComplexType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002770
Chris Lattnerc6395932007-06-22 20:56:16 +00002771 // Get the new insert position for the node we care about.
2772 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002773 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6395932007-06-22 20:56:16 +00002774 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00002775 auto *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
Chris Lattnerc6395932007-06-22 20:56:16 +00002776 Types.push_back(New);
2777 ComplexTypes.InsertNode(New, InsertPos);
2778 return QualType(New, 0);
2779}
2780
Chris Lattner970e54e2006-11-12 00:37:36 +00002781/// getPointerType - Return the uniqued reference to the type for a pointer to
2782/// the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002783QualType ASTContext::getPointerType(QualType T) const {
Chris Lattnerd5973eb2006-11-12 00:53:46 +00002784 // Unique pointers, to guarantee there is only one pointer of a particular
2785 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002786 llvm::FoldingSetNodeID ID;
Chris Lattner67521df2007-01-27 01:29:36 +00002787 PointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002788
Craig Topper36250ad2014-05-12 05:36:57 +00002789 void *InsertPos = nullptr;
Chris Lattner67521df2007-01-27 01:29:36 +00002790 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002791 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002792
Chris Lattner7ccecb92006-11-12 08:50:50 +00002793 // If the pointee type isn't canonical, this won't be a canonical type either,
2794 // so fill in the canonical type field.
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002795 QualType Canonical;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002796 if (!T.isCanonical()) {
Chris Lattner76a00cf2008-04-06 22:59:24 +00002797 Canonical = getPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002798
Bob Wilsonc8541f22013-03-15 17:12:43 +00002799 // Get the new insert position for the node we care about.
2800 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002801 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Bob Wilsonc8541f22013-03-15 17:12:43 +00002802 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00002803 auto *New = new (*this, TypeAlignment) PointerType(T, Canonical);
Chris Lattner67521df2007-01-27 01:29:36 +00002804 Types.push_back(New);
2805 PointerTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00002806 return QualType(New, 0);
Chris Lattnerddc135e2006-11-10 06:34:16 +00002807}
2808
Reid Kleckner0503a872013-12-05 01:23:43 +00002809QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const {
2810 llvm::FoldingSetNodeID ID;
2811 AdjustedType::Profile(ID, Orig, New);
Craig Topper36250ad2014-05-12 05:36:57 +00002812 void *InsertPos = nullptr;
Reid Kleckner0503a872013-12-05 01:23:43 +00002813 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2814 if (AT)
2815 return QualType(AT, 0);
2816
2817 QualType Canonical = getCanonicalType(New);
2818
2819 // Get the new insert position for the node we care about.
2820 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002821 assert(!AT && "Shouldn't be in the map!");
Reid Kleckner0503a872013-12-05 01:23:43 +00002822
2823 AT = new (*this, TypeAlignment)
2824 AdjustedType(Type::Adjusted, Orig, New, Canonical);
2825 Types.push_back(AT);
2826 AdjustedTypes.InsertNode(AT, InsertPos);
2827 return QualType(AT, 0);
2828}
2829
Reid Kleckner8a365022013-06-24 17:51:48 +00002830QualType ASTContext::getDecayedType(QualType T) const {
2831 assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
2832
Reid Kleckner8a365022013-06-24 17:51:48 +00002833 QualType Decayed;
2834
2835 // C99 6.7.5.3p7:
2836 // A declaration of a parameter as "array of type" shall be
2837 // adjusted to "qualified pointer to type", where the type
2838 // qualifiers (if any) are those specified within the [ and ] of
2839 // the array type derivation.
2840 if (T->isArrayType())
2841 Decayed = getArrayDecayedType(T);
2842
2843 // C99 6.7.5.3p8:
2844 // A declaration of a parameter as "function returning type"
2845 // shall be adjusted to "pointer to function returning type", as
2846 // in 6.3.2.1.
2847 if (T->isFunctionType())
2848 Decayed = getPointerType(T);
2849
Reid Kleckner0503a872013-12-05 01:23:43 +00002850 llvm::FoldingSetNodeID ID;
2851 AdjustedType::Profile(ID, T, Decayed);
Craig Topper36250ad2014-05-12 05:36:57 +00002852 void *InsertPos = nullptr;
Reid Kleckner0503a872013-12-05 01:23:43 +00002853 AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2854 if (AT)
2855 return QualType(AT, 0);
2856
Reid Kleckner8a365022013-06-24 17:51:48 +00002857 QualType Canonical = getCanonicalType(Decayed);
2858
2859 // Get the new insert position for the node we care about.
Reid Kleckner0503a872013-12-05 01:23:43 +00002860 AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002861 assert(!AT && "Shouldn't be in the map!");
Reid Kleckner8a365022013-06-24 17:51:48 +00002862
Reid Kleckner0503a872013-12-05 01:23:43 +00002863 AT = new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical);
2864 Types.push_back(AT);
2865 AdjustedTypes.InsertNode(AT, InsertPos);
2866 return QualType(AT, 0);
Reid Kleckner8a365022013-06-24 17:51:48 +00002867}
2868
Mike Stump11289f42009-09-09 15:08:12 +00002869/// getBlockPointerType - Return the uniqued reference to the type for
Steve Naroffec33ed92008-08-27 16:04:49 +00002870/// a pointer to the specified block.
Jay Foad39c79802011-01-12 09:06:06 +00002871QualType ASTContext::getBlockPointerType(QualType T) const {
Steve Naroff0ac012832008-08-28 19:20:44 +00002872 assert(T->isFunctionType() && "block of function types only");
2873 // Unique pointers, to guarantee there is only one block of a particular
Steve Naroffec33ed92008-08-27 16:04:49 +00002874 // structure.
2875 llvm::FoldingSetNodeID ID;
2876 BlockPointerType::Profile(ID, T);
Mike Stump11289f42009-09-09 15:08:12 +00002877
Craig Topper36250ad2014-05-12 05:36:57 +00002878 void *InsertPos = nullptr;
Steve Naroffec33ed92008-08-27 16:04:49 +00002879 if (BlockPointerType *PT =
2880 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2881 return QualType(PT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002882
2883 // If the block pointee type isn't canonical, this won't be a canonical
Steve Naroffec33ed92008-08-27 16:04:49 +00002884 // type either so fill in the canonical type field.
2885 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00002886 if (!T.isCanonical()) {
Steve Naroffec33ed92008-08-27 16:04:49 +00002887 Canonical = getBlockPointerType(getCanonicalType(T));
Mike Stump11289f42009-09-09 15:08:12 +00002888
Steve Naroffec33ed92008-08-27 16:04:49 +00002889 // Get the new insert position for the node we care about.
2890 BlockPointerType *NewIP =
2891 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002892 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroffec33ed92008-08-27 16:04:49 +00002893 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00002894 auto *New = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
Steve Naroffec33ed92008-08-27 16:04:49 +00002895 Types.push_back(New);
2896 BlockPointerTypes.InsertNode(New, InsertPos);
2897 return QualType(New, 0);
2898}
2899
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002900/// getLValueReferenceType - Return the uniqued reference to the type for an
2901/// lvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002902QualType
2903ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00002904 assert(getCanonicalType(T) != OverloadTy &&
Douglas Gregor291e8ee2011-05-21 22:16:50 +00002905 "Unresolved overloaded function type");
Fangrui Song6907ce22018-07-30 19:24:48 +00002906
Bill Wendling3708c182007-05-27 10:15:43 +00002907 // Unique pointers, to guarantee there is only one pointer of a particular
2908 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002909 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002910 ReferenceType::Profile(ID, T, SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002911
Craig Topper36250ad2014-05-12 05:36:57 +00002912 void *InsertPos = nullptr;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002913 if (LValueReferenceType *RT =
2914 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
Bill Wendling3708c182007-05-27 10:15:43 +00002915 return QualType(RT, 0);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002916
Eugene Zelenko7855e772018-04-03 00:11:50 +00002917 const auto *InnerRef = T->getAs<ReferenceType>();
John McCallfc93cf92009-10-22 22:37:11 +00002918
Bill Wendling3708c182007-05-27 10:15:43 +00002919 // If the referencee type isn't canonical, this won't be a canonical type
2920 // either, so fill in the canonical type field.
2921 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002922 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
2923 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2924 Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002925
Bill Wendling3708c182007-05-27 10:15:43 +00002926 // Get the new insert position for the node we care about.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002927 LValueReferenceType *NewIP =
2928 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002929 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Bill Wendling3708c182007-05-27 10:15:43 +00002930 }
2931
Eugene Zelenko7855e772018-04-03 00:11:50 +00002932 auto *New = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
2933 SpelledAsLValue);
Bill Wendling3708c182007-05-27 10:15:43 +00002934 Types.push_back(New);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002935 LValueReferenceTypes.InsertNode(New, InsertPos);
John McCallfc93cf92009-10-22 22:37:11 +00002936
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002937 return QualType(New, 0);
2938}
2939
2940/// getRValueReferenceType - Return the uniqued reference to the type for an
2941/// rvalue reference to the specified type.
Jay Foad39c79802011-01-12 09:06:06 +00002942QualType ASTContext::getRValueReferenceType(QualType T) const {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002943 // Unique pointers, to guarantee there is only one pointer of a particular
2944 // structure.
2945 llvm::FoldingSetNodeID ID;
John McCallfc93cf92009-10-22 22:37:11 +00002946 ReferenceType::Profile(ID, T, false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002947
Craig Topper36250ad2014-05-12 05:36:57 +00002948 void *InsertPos = nullptr;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002949 if (RValueReferenceType *RT =
2950 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2951 return QualType(RT, 0);
2952
Eugene Zelenko7855e772018-04-03 00:11:50 +00002953 const auto *InnerRef = T->getAs<ReferenceType>();
John McCallfc93cf92009-10-22 22:37:11 +00002954
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002955 // If the referencee type isn't canonical, this won't be a canonical type
2956 // either, so fill in the canonical type field.
2957 QualType Canonical;
John McCallfc93cf92009-10-22 22:37:11 +00002958 if (InnerRef || !T.isCanonical()) {
2959 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2960 Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002961
2962 // Get the new insert position for the node we care about.
2963 RValueReferenceType *NewIP =
2964 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002965 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002966 }
2967
Eugene Zelenko7855e772018-04-03 00:11:50 +00002968 auto *New = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002969 Types.push_back(New);
2970 RValueReferenceTypes.InsertNode(New, InsertPos);
Bill Wendling3708c182007-05-27 10:15:43 +00002971 return QualType(New, 0);
2972}
2973
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002974/// getMemberPointerType - Return the uniqued reference to the type for a
2975/// member pointer to the specified type, in the specified class.
Jay Foad39c79802011-01-12 09:06:06 +00002976QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002977 // Unique pointers, to guarantee there is only one pointer of a particular
2978 // structure.
2979 llvm::FoldingSetNodeID ID;
2980 MemberPointerType::Profile(ID, T, Cls);
2981
Craig Topper36250ad2014-05-12 05:36:57 +00002982 void *InsertPos = nullptr;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002983 if (MemberPointerType *PT =
2984 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2985 return QualType(PT, 0);
2986
2987 // If the pointee or class type isn't canonical, this won't be a canonical
2988 // type either, so fill in the canonical type field.
2989 QualType Canonical;
Douglas Gregor615ac672009-11-04 16:49:01 +00002990 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002991 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
2992
2993 // Get the new insert position for the node we care about.
2994 MemberPointerType *NewIP =
2995 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00002996 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002997 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00002998 auto *New = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
Sebastian Redl9ed6efd2009-01-24 21:16:55 +00002999 Types.push_back(New);
3000 MemberPointerTypes.InsertNode(New, InsertPos);
3001 return QualType(New, 0);
3002}
3003
Mike Stump11289f42009-09-09 15:08:12 +00003004/// getConstantArrayType - Return the unique reference to the type for an
Steve Naroff5c131802007-08-30 01:06:46 +00003005/// array of the specified element type.
Mike Stump11289f42009-09-09 15:08:12 +00003006QualType ASTContext::getConstantArrayType(QualType EltTy,
Chris Lattnere2df3f92009-05-13 04:12:56 +00003007 const llvm::APInt &ArySizeIn,
Steve Naroff90dfdd52007-08-30 18:10:14 +00003008 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00003009 unsigned IndexTypeQuals) const {
Sebastian Redl2dfdb822009-11-05 15:52:31 +00003010 assert((EltTy->isDependentType() ||
3011 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00003012 "Constant array of VLAs is illegal!");
3013
Chris Lattnere2df3f92009-05-13 04:12:56 +00003014 // Convert the array size into a canonical width matching the pointer size for
3015 // the target.
3016 llvm::APInt ArySize(ArySizeIn);
Konstantin Zhuravlyov9c1e3102017-03-21 18:55:39 +00003017 ArySize = ArySize.zextOrTrunc(Target->getMaxPointerWidth());
Mike Stump11289f42009-09-09 15:08:12 +00003018
Chris Lattner23b7eb62007-06-15 23:05:46 +00003019 llvm::FoldingSetNodeID ID;
Abramo Bagnara92141d22011-01-27 19:55:10 +00003020 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
Mike Stump11289f42009-09-09 15:08:12 +00003021
Craig Topper36250ad2014-05-12 05:36:57 +00003022 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003023 if (ConstantArrayType *ATP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00003024 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003025 return QualType(ATP, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003026
John McCall33ddac02011-01-19 10:06:00 +00003027 // If the element type isn't canonical or has qualifiers, this won't
3028 // be a canonical type either, so fill in the canonical type field.
3029 QualType Canon;
3030 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
3031 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00003032 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
Abramo Bagnara92141d22011-01-27 19:55:10 +00003033 ASM, IndexTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00003034 Canon = getQualifiedType(Canon, canonSplit.Quals);
John McCall33ddac02011-01-19 10:06:00 +00003035
Chris Lattner36f8e652007-01-27 08:31:04 +00003036 // Get the new insert position for the node we care about.
Mike Stump11289f42009-09-09 15:08:12 +00003037 ConstantArrayType *NewIP =
Ted Kremenekfc581a92007-10-31 17:10:13 +00003038 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003039 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner36f8e652007-01-27 08:31:04 +00003040 }
Mike Stump11289f42009-09-09 15:08:12 +00003041
Eugene Zelenko7855e772018-04-03 00:11:50 +00003042 auto *New = new (*this,TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00003043 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
Ted Kremenekfc581a92007-10-31 17:10:13 +00003044 ConstantArrayTypes.InsertNode(New, InsertPos);
Chris Lattner36f8e652007-01-27 08:31:04 +00003045 Types.push_back(New);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003046 return QualType(New, 0);
Chris Lattner7ccecb92006-11-12 08:50:50 +00003047}
3048
John McCall06549462011-01-18 08:40:38 +00003049/// getVariableArrayDecayedType - Turns the given type, which may be
3050/// variably-modified, into the corresponding type with all the known
3051/// sizes replaced with [*].
3052QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
3053 // Vastly most common case.
3054 if (!type->isVariablyModifiedType()) return type;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003055
John McCall06549462011-01-18 08:40:38 +00003056 QualType result;
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003057
John McCall06549462011-01-18 08:40:38 +00003058 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00003059 const Type *ty = split.Ty;
John McCall06549462011-01-18 08:40:38 +00003060 switch (ty->getTypeClass()) {
3061#define TYPE(Class, Base)
3062#define ABSTRACT_TYPE(Class, Base)
3063#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3064#include "clang/AST/TypeNodes.def"
3065 llvm_unreachable("didn't desugar past all non-canonical types?");
3066
3067 // These types should never be variably-modified.
3068 case Type::Builtin:
3069 case Type::Complex:
3070 case Type::Vector:
Erich Keanef702b022018-07-13 19:46:04 +00003071 case Type::DependentVector:
John McCall06549462011-01-18 08:40:38 +00003072 case Type::ExtVector:
3073 case Type::DependentSizedExtVector:
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003074 case Type::DependentAddressSpace:
John McCall06549462011-01-18 08:40:38 +00003075 case Type::ObjCObject:
3076 case Type::ObjCInterface:
3077 case Type::ObjCObjectPointer:
3078 case Type::Record:
3079 case Type::Enum:
3080 case Type::UnresolvedUsing:
3081 case Type::TypeOfExpr:
3082 case Type::TypeOf:
3083 case Type::Decltype:
Alexis Hunte852b102011-05-24 22:41:36 +00003084 case Type::UnaryTransform:
John McCall06549462011-01-18 08:40:38 +00003085 case Type::DependentName:
3086 case Type::InjectedClassName:
3087 case Type::TemplateSpecialization:
3088 case Type::DependentTemplateSpecialization:
3089 case Type::TemplateTypeParm:
3090 case Type::SubstTemplateTypeParmPack:
Richard Smith30482bc2011-02-20 03:19:35 +00003091 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00003092 case Type::DeducedTemplateSpecialization:
John McCall06549462011-01-18 08:40:38 +00003093 case Type::PackExpansion:
3094 llvm_unreachable("type should never be variably-modified");
3095
3096 // These types can be variably-modified but should never need to
3097 // further decay.
3098 case Type::FunctionNoProto:
3099 case Type::FunctionProto:
3100 case Type::BlockPointer:
3101 case Type::MemberPointer:
Xiuli Pan9c14e282016-01-09 12:53:17 +00003102 case Type::Pipe:
John McCall06549462011-01-18 08:40:38 +00003103 return type;
3104
3105 // These types can be variably-modified. All these modifications
3106 // preserve structure except as noted by comments.
3107 // TODO: if we ever care about optimizing VLAs, there are no-op
3108 // optimizations available here.
3109 case Type::Pointer:
3110 result = getPointerType(getVariableArrayDecayedType(
3111 cast<PointerType>(ty)->getPointeeType()));
3112 break;
3113
3114 case Type::LValueReference: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003115 const auto *lv = cast<LValueReferenceType>(ty);
John McCall06549462011-01-18 08:40:38 +00003116 result = getLValueReferenceType(
3117 getVariableArrayDecayedType(lv->getPointeeType()),
3118 lv->isSpelledAsLValue());
3119 break;
3120 }
3121
3122 case Type::RValueReference: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003123 const auto *lv = cast<RValueReferenceType>(ty);
John McCall06549462011-01-18 08:40:38 +00003124 result = getRValueReferenceType(
3125 getVariableArrayDecayedType(lv->getPointeeType()));
3126 break;
3127 }
3128
Eli Friedman0dfb8892011-10-06 23:00:33 +00003129 case Type::Atomic: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003130 const auto *at = cast<AtomicType>(ty);
Eli Friedman0dfb8892011-10-06 23:00:33 +00003131 result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
3132 break;
3133 }
3134
John McCall06549462011-01-18 08:40:38 +00003135 case Type::ConstantArray: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003136 const auto *cat = cast<ConstantArrayType>(ty);
John McCall06549462011-01-18 08:40:38 +00003137 result = getConstantArrayType(
3138 getVariableArrayDecayedType(cat->getElementType()),
3139 cat->getSize(),
3140 cat->getSizeModifier(),
3141 cat->getIndexTypeCVRQualifiers());
3142 break;
3143 }
3144
3145 case Type::DependentSizedArray: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003146 const auto *dat = cast<DependentSizedArrayType>(ty);
John McCall06549462011-01-18 08:40:38 +00003147 result = getDependentSizedArrayType(
3148 getVariableArrayDecayedType(dat->getElementType()),
3149 dat->getSizeExpr(),
3150 dat->getSizeModifier(),
3151 dat->getIndexTypeCVRQualifiers(),
3152 dat->getBracketsRange());
3153 break;
3154 }
3155
3156 // Turn incomplete types into [*] types.
3157 case Type::IncompleteArray: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003158 const auto *iat = cast<IncompleteArrayType>(ty);
John McCall06549462011-01-18 08:40:38 +00003159 result = getVariableArrayType(
3160 getVariableArrayDecayedType(iat->getElementType()),
Craig Topper36250ad2014-05-12 05:36:57 +00003161 /*size*/ nullptr,
John McCall06549462011-01-18 08:40:38 +00003162 ArrayType::Normal,
3163 iat->getIndexTypeCVRQualifiers(),
3164 SourceRange());
3165 break;
3166 }
3167
3168 // Turn VLA types into [*] types.
3169 case Type::VariableArray: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003170 const auto *vat = cast<VariableArrayType>(ty);
John McCall06549462011-01-18 08:40:38 +00003171 result = getVariableArrayType(
3172 getVariableArrayDecayedType(vat->getElementType()),
Craig Topper36250ad2014-05-12 05:36:57 +00003173 /*size*/ nullptr,
John McCall06549462011-01-18 08:40:38 +00003174 ArrayType::Star,
3175 vat->getIndexTypeCVRQualifiers(),
3176 vat->getBracketsRange());
3177 break;
3178 }
3179 }
3180
3181 // Apply the top-level qualifiers from the original.
John McCall18ce25e2012-02-08 00:46:36 +00003182 return getQualifiedType(result, split.Quals);
John McCall06549462011-01-18 08:40:38 +00003183}
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003184
Steve Naroffcadebd02007-08-30 18:14:25 +00003185/// getVariableArrayType - Returns a non-unique reference to the type for a
3186/// variable array of the specified element type.
Douglas Gregor04318252009-07-06 15:59:29 +00003187QualType ASTContext::getVariableArrayType(QualType EltTy,
3188 Expr *NumElts,
Steve Naroff90dfdd52007-08-30 18:10:14 +00003189 ArrayType::ArraySizeModifier ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00003190 unsigned IndexTypeQuals,
Jay Foad39c79802011-01-12 09:06:06 +00003191 SourceRange Brackets) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00003192 // Since we don't unique expressions, it isn't possible to unique VLA's
3193 // that have an expression provided for their size.
John McCall33ddac02011-01-19 10:06:00 +00003194 QualType Canon;
Fangrui Song6907ce22018-07-30 19:24:48 +00003195
John McCall33ddac02011-01-19 10:06:00 +00003196 // Be sure to pull qualifiers off the element type.
3197 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
3198 SplitQualType canonSplit = getCanonicalType(EltTy).split();
John McCall18ce25e2012-02-08 00:46:36 +00003199 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
Abramo Bagnara92141d22011-01-27 19:55:10 +00003200 IndexTypeQuals, Brackets);
John McCall18ce25e2012-02-08 00:46:36 +00003201 Canon = getQualifiedType(Canon, canonSplit.Quals);
Douglas Gregor5e8c8c02010-05-23 16:10:32 +00003202 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003203
Eugene Zelenko7855e772018-04-03 00:11:50 +00003204 auto *New = new (*this, TypeAlignment)
Abramo Bagnara92141d22011-01-27 19:55:10 +00003205 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
Eli Friedmanbd258282008-02-15 18:16:39 +00003206
3207 VariableArrayTypes.push_back(New);
3208 Types.push_back(New);
3209 return QualType(New, 0);
3210}
3211
Douglas Gregor4619e432008-12-05 23:32:09 +00003212/// getDependentSizedArrayType - Returns a non-unique reference to
3213/// the type for a dependently-sized array of the specified element
Douglas Gregorf3f95522009-07-31 00:23:35 +00003214/// type.
John McCall33ddac02011-01-19 10:06:00 +00003215QualType ASTContext::getDependentSizedArrayType(QualType elementType,
3216 Expr *numElements,
Douglas Gregor4619e432008-12-05 23:32:09 +00003217 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00003218 unsigned elementTypeQuals,
3219 SourceRange brackets) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00003220 assert((!numElements || numElements->isTypeDependent() ||
John McCall33ddac02011-01-19 10:06:00 +00003221 numElements->isValueDependent()) &&
Douglas Gregor4619e432008-12-05 23:32:09 +00003222 "Size must be type- or value-dependent!");
3223
John McCall33ddac02011-01-19 10:06:00 +00003224 // Dependently-sized array types that do not have a specified number
3225 // of elements will have their sizes deduced from a dependent
3226 // initializer. We do no canonicalization here at all, which is okay
3227 // because they can't be used in most locations.
3228 if (!numElements) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00003229 auto *newType
John McCall33ddac02011-01-19 10:06:00 +00003230 = new (*this, TypeAlignment)
3231 DependentSizedArrayType(*this, elementType, QualType(),
3232 numElements, ASM, elementTypeQuals,
3233 brackets);
3234 Types.push_back(newType);
3235 return QualType(newType, 0);
3236 }
3237
3238 // Otherwise, we actually build a new type every time, but we
3239 // also build a canonical type.
3240
3241 SplitQualType canonElementType = getCanonicalType(elementType).split();
3242
Craig Topper36250ad2014-05-12 05:36:57 +00003243 void *insertPos = nullptr;
Douglas Gregorc42075a2010-02-04 18:10:26 +00003244 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00003245 DependentSizedArrayType::Profile(ID, *this,
John McCall18ce25e2012-02-08 00:46:36 +00003246 QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00003247 ASM, elementTypeQuals, numElements);
Douglas Gregorad2956c2009-11-19 18:03:26 +00003248
John McCall33ddac02011-01-19 10:06:00 +00003249 // Look for an existing type with these properties.
3250 DependentSizedArrayType *canonTy =
3251 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
Douglas Gregorad2956c2009-11-19 18:03:26 +00003252
John McCall33ddac02011-01-19 10:06:00 +00003253 // If we don't have one, build one.
3254 if (!canonTy) {
3255 canonTy = new (*this, TypeAlignment)
John McCall18ce25e2012-02-08 00:46:36 +00003256 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00003257 QualType(), numElements, ASM, elementTypeQuals,
3258 brackets);
3259 DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
3260 Types.push_back(canonTy);
Douglas Gregorad2956c2009-11-19 18:03:26 +00003261 }
3262
John McCall33ddac02011-01-19 10:06:00 +00003263 // Apply qualifiers from the element type to the array.
3264 QualType canon = getQualifiedType(QualType(canonTy,0),
John McCall18ce25e2012-02-08 00:46:36 +00003265 canonElementType.Quals);
Mike Stump11289f42009-09-09 15:08:12 +00003266
David Majnemer16a74702015-07-24 05:54:19 +00003267 // If we didn't need extra canonicalization for the element type or the size
3268 // expression, then just use that as our result.
3269 if (QualType(canonElementType.Ty, 0) == elementType &&
3270 canonTy->getSizeExpr() == numElements)
John McCall33ddac02011-01-19 10:06:00 +00003271 return canon;
3272
3273 // Otherwise, we need to build a type which follows the spelling
3274 // of the element type.
Eugene Zelenko7855e772018-04-03 00:11:50 +00003275 auto *sugaredType
John McCall33ddac02011-01-19 10:06:00 +00003276 = new (*this, TypeAlignment)
3277 DependentSizedArrayType(*this, elementType, canon, numElements,
3278 ASM, elementTypeQuals, brackets);
3279 Types.push_back(sugaredType);
3280 return QualType(sugaredType, 0);
Douglas Gregor4619e432008-12-05 23:32:09 +00003281}
3282
John McCall33ddac02011-01-19 10:06:00 +00003283QualType ASTContext::getIncompleteArrayType(QualType elementType,
Eli Friedmanbd258282008-02-15 18:16:39 +00003284 ArrayType::ArraySizeModifier ASM,
John McCall33ddac02011-01-19 10:06:00 +00003285 unsigned elementTypeQuals) const {
Eli Friedmanbd258282008-02-15 18:16:39 +00003286 llvm::FoldingSetNodeID ID;
John McCall33ddac02011-01-19 10:06:00 +00003287 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00003288
Craig Topper36250ad2014-05-12 05:36:57 +00003289 void *insertPos = nullptr;
John McCall33ddac02011-01-19 10:06:00 +00003290 if (IncompleteArrayType *iat =
3291 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
3292 return QualType(iat, 0);
Eli Friedmanbd258282008-02-15 18:16:39 +00003293
3294 // If the element type isn't canonical, this won't be a canonical type
John McCall33ddac02011-01-19 10:06:00 +00003295 // either, so fill in the canonical type field. We also have to pull
3296 // qualifiers off the element type.
3297 QualType canon;
Eli Friedmanbd258282008-02-15 18:16:39 +00003298
John McCall33ddac02011-01-19 10:06:00 +00003299 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
3300 SplitQualType canonSplit = getCanonicalType(elementType).split();
John McCall18ce25e2012-02-08 00:46:36 +00003301 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
John McCall33ddac02011-01-19 10:06:00 +00003302 ASM, elementTypeQuals);
John McCall18ce25e2012-02-08 00:46:36 +00003303 canon = getQualifiedType(canon, canonSplit.Quals);
Eli Friedmanbd258282008-02-15 18:16:39 +00003304
3305 // Get the new insert position for the node we care about.
John McCall33ddac02011-01-19 10:06:00 +00003306 IncompleteArrayType *existing =
3307 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
3308 assert(!existing && "Shouldn't be in the map!"); (void) existing;
Ted Kremenek843ebedd2007-10-29 23:37:31 +00003309 }
Eli Friedmanbd258282008-02-15 18:16:39 +00003310
Eugene Zelenko7855e772018-04-03 00:11:50 +00003311 auto *newType = new (*this, TypeAlignment)
John McCall33ddac02011-01-19 10:06:00 +00003312 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
Eli Friedmanbd258282008-02-15 18:16:39 +00003313
John McCall33ddac02011-01-19 10:06:00 +00003314 IncompleteArrayTypes.InsertNode(newType, insertPos);
3315 Types.push_back(newType);
3316 return QualType(newType, 0);
Steve Naroff5c131802007-08-30 01:06:46 +00003317}
3318
Steve Naroff91fcddb2007-07-18 18:00:27 +00003319/// getVectorType - Return the unique reference to a vector type of
3320/// the specified element type and size. VectorType must be a built-in type.
John Thompson22334602010-02-05 00:12:22 +00003321QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
Jay Foad39c79802011-01-12 09:06:06 +00003322 VectorType::VectorKind VecKind) const {
John McCall33ddac02011-01-19 10:06:00 +00003323 assert(vecType->isBuiltinType());
Mike Stump11289f42009-09-09 15:08:12 +00003324
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003325 // Check if we've already instantiated a vector of this type.
3326 llvm::FoldingSetNodeID ID;
Bob Wilsonaeb56442010-11-10 21:56:12 +00003327 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
Chris Lattner37141f42010-06-23 06:00:24 +00003328
Craig Topper36250ad2014-05-12 05:36:57 +00003329 void *InsertPos = nullptr;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003330 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
3331 return QualType(VTP, 0);
3332
3333 // If the element type isn't canonical, this won't be a canonical type either,
3334 // so fill in the canonical type field.
3335 QualType Canonical;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00003336 if (!vecType.isCanonical()) {
Bob Wilson77954802010-11-16 00:32:20 +00003337 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
Mike Stump11289f42009-09-09 15:08:12 +00003338
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003339 // Get the new insert position for the node we care about.
3340 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003341 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003342 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00003343 auto *New = new (*this, TypeAlignment)
Bob Wilsonaeb56442010-11-10 21:56:12 +00003344 VectorType(vecType, NumElts, Canonical, VecKind);
Steve Naroff4ae0ac62007-07-06 23:09:18 +00003345 VectorTypes.InsertNode(New, InsertPos);
3346 Types.push_back(New);
3347 return QualType(New, 0);
3348}
3349
Erich Keanef702b022018-07-13 19:46:04 +00003350QualType
3351ASTContext::getDependentVectorType(QualType VecType, Expr *SizeExpr,
3352 SourceLocation AttrLoc,
3353 VectorType::VectorKind VecKind) const {
3354 llvm::FoldingSetNodeID ID;
3355 DependentVectorType::Profile(ID, *this, getCanonicalType(VecType), SizeExpr,
3356 VecKind);
3357 void *InsertPos = nullptr;
3358 DependentVectorType *Canon =
3359 DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3360 DependentVectorType *New;
3361
3362 if (Canon) {
3363 New = new (*this, TypeAlignment) DependentVectorType(
3364 *this, VecType, QualType(Canon, 0), SizeExpr, AttrLoc, VecKind);
3365 } else {
3366 QualType CanonVecTy = getCanonicalType(VecType);
3367 if (CanonVecTy == VecType) {
3368 New = new (*this, TypeAlignment) DependentVectorType(
3369 *this, VecType, QualType(), SizeExpr, AttrLoc, VecKind);
3370
3371 DependentVectorType *CanonCheck =
3372 DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3373 assert(!CanonCheck &&
3374 "Dependent-sized vector_size canonical type broken");
3375 (void)CanonCheck;
3376 DependentVectorTypes.InsertNode(New, InsertPos);
3377 } else {
3378 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
3379 SourceLocation());
3380 New = new (*this, TypeAlignment) DependentVectorType(
3381 *this, VecType, Canon, SizeExpr, AttrLoc, VecKind);
3382 }
3383 }
3384
3385 Types.push_back(New);
3386 return QualType(New, 0);
3387}
3388
Nate Begemance4d7fc2008-04-18 23:10:10 +00003389/// getExtVectorType - Return the unique reference to an extended vector type of
Steve Naroff91fcddb2007-07-18 18:00:27 +00003390/// the specified element type and size. VectorType must be a built-in type.
Jay Foad39c79802011-01-12 09:06:06 +00003391QualType
3392ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
Douglas Gregor39c02722011-06-15 16:02:29 +00003393 assert(vecType->isBuiltinType() || vecType->isDependentType());
Mike Stump11289f42009-09-09 15:08:12 +00003394
Steve Naroff91fcddb2007-07-18 18:00:27 +00003395 // Check if we've already instantiated a vector of this type.
3396 llvm::FoldingSetNodeID ID;
Chris Lattner37141f42010-06-23 06:00:24 +00003397 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
Bob Wilsonaeb56442010-11-10 21:56:12 +00003398 VectorType::GenericVector);
Craig Topper36250ad2014-05-12 05:36:57 +00003399 void *InsertPos = nullptr;
Steve Naroff91fcddb2007-07-18 18:00:27 +00003400 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
3401 return QualType(VTP, 0);
3402
3403 // If the element type isn't canonical, this won't be a canonical type either,
3404 // so fill in the canonical type field.
3405 QualType Canonical;
John McCallb692a092009-10-22 20:10:53 +00003406 if (!vecType.isCanonical()) {
Nate Begemance4d7fc2008-04-18 23:10:10 +00003407 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
Mike Stump11289f42009-09-09 15:08:12 +00003408
Steve Naroff91fcddb2007-07-18 18:00:27 +00003409 // Get the new insert position for the node we care about.
3410 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003411 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Steve Naroff91fcddb2007-07-18 18:00:27 +00003412 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00003413 auto *New = new (*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00003414 ExtVectorType(vecType, NumElts, Canonical);
Steve Naroff91fcddb2007-07-18 18:00:27 +00003415 VectorTypes.InsertNode(New, InsertPos);
3416 Types.push_back(New);
3417 return QualType(New, 0);
3418}
3419
Jay Foad39c79802011-01-12 09:06:06 +00003420QualType
3421ASTContext::getDependentSizedExtVectorType(QualType vecType,
3422 Expr *SizeExpr,
3423 SourceLocation AttrLoc) const {
Douglas Gregor352169a2009-07-31 03:54:25 +00003424 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00003425 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
Douglas Gregor352169a2009-07-31 03:54:25 +00003426 SizeExpr);
Mike Stump11289f42009-09-09 15:08:12 +00003427
Craig Topper36250ad2014-05-12 05:36:57 +00003428 void *InsertPos = nullptr;
Douglas Gregor352169a2009-07-31 03:54:25 +00003429 DependentSizedExtVectorType *Canon
3430 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3431 DependentSizedExtVectorType *New;
3432 if (Canon) {
3433 // We already have a canonical version of this array type; use it as
3434 // the canonical type for a newly-built type.
John McCall90d1c2d2009-09-24 23:30:46 +00003435 New = new (*this, TypeAlignment)
3436 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
3437 SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00003438 } else {
3439 QualType CanonVecTy = getCanonicalType(vecType);
3440 if (CanonVecTy == vecType) {
John McCall90d1c2d2009-09-24 23:30:46 +00003441 New = new (*this, TypeAlignment)
3442 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
3443 AttrLoc);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003444
3445 DependentSizedExtVectorType *CanonCheck
3446 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
3447 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
3448 (void)CanonCheck;
Douglas Gregor352169a2009-07-31 03:54:25 +00003449 DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
3450 } else {
3451 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
3452 SourceLocation());
Fangrui Song6907ce22018-07-30 19:24:48 +00003453 New = new (*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00003454 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
Douglas Gregor352169a2009-07-31 03:54:25 +00003455 }
3456 }
Mike Stump11289f42009-09-09 15:08:12 +00003457
Douglas Gregor758a8692009-06-17 21:51:59 +00003458 Types.push_back(New);
3459 return QualType(New, 0);
3460}
3461
Fangrui Song6907ce22018-07-30 19:24:48 +00003462QualType ASTContext::getDependentAddressSpaceType(QualType PointeeType,
3463 Expr *AddrSpaceExpr,
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003464 SourceLocation AttrLoc) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00003465 assert(AddrSpaceExpr->isInstantiationDependent());
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003466
3467 QualType canonPointeeType = getCanonicalType(PointeeType);
3468
3469 void *insertPos = nullptr;
3470 llvm::FoldingSetNodeID ID;
3471 DependentAddressSpaceType::Profile(ID, *this, canonPointeeType,
3472 AddrSpaceExpr);
3473
3474 DependentAddressSpaceType *canonTy =
3475 DependentAddressSpaceTypes.FindNodeOrInsertPos(ID, insertPos);
3476
3477 if (!canonTy) {
3478 canonTy = new (*this, TypeAlignment)
Fangrui Song6907ce22018-07-30 19:24:48 +00003479 DependentAddressSpaceType(*this, canonPointeeType,
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003480 QualType(), AddrSpaceExpr, AttrLoc);
3481 DependentAddressSpaceTypes.InsertNode(canonTy, insertPos);
3482 Types.push_back(canonTy);
3483 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003484
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003485 if (canonPointeeType == PointeeType &&
3486 canonTy->getAddrSpaceExpr() == AddrSpaceExpr)
Fangrui Song6907ce22018-07-30 19:24:48 +00003487 return QualType(canonTy, 0);
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003488
Eugene Zelenko7855e772018-04-03 00:11:50 +00003489 auto *sugaredType
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003490 = new (*this, TypeAlignment)
Fangrui Song6907ce22018-07-30 19:24:48 +00003491 DependentAddressSpaceType(*this, PointeeType, QualType(canonTy, 0),
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003492 AddrSpaceExpr, AttrLoc);
3493 Types.push_back(sugaredType);
Fangrui Song6907ce22018-07-30 19:24:48 +00003494 return QualType(sugaredType, 0);
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003495}
3496
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003497/// Determine whether \p T is canonical as the result type of a function.
John McCall18afab72016-03-01 00:49:02 +00003498static bool isCanonicalResultType(QualType T) {
3499 return T.isCanonical() &&
3500 (T.getObjCLifetime() == Qualifiers::OCL_None ||
3501 T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
3502}
3503
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003504/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
Jay Foad39c79802011-01-12 09:06:06 +00003505QualType
3506ASTContext::getFunctionNoProtoType(QualType ResultTy,
3507 const FunctionType::ExtInfo &Info) const {
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003508 // Unique functions, to guarantee there is only one function of a particular
3509 // structure.
Chris Lattner23b7eb62007-06-15 23:05:46 +00003510 llvm::FoldingSetNodeID ID;
Rafael Espindolac50c27c2010-03-30 20:24:48 +00003511 FunctionNoProtoType::Profile(ID, ResultTy, Info);
Mike Stump11289f42009-09-09 15:08:12 +00003512
Craig Topper36250ad2014-05-12 05:36:57 +00003513 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003514 if (FunctionNoProtoType *FT =
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003515 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003516 return QualType(FT, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003517
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003518 QualType Canonical;
John McCall18afab72016-03-01 00:49:02 +00003519 if (!isCanonicalResultType(ResultTy)) {
3520 Canonical =
3521 getFunctionNoProtoType(getCanonicalFunctionResultType(ResultTy), Info);
Mike Stump11289f42009-09-09 15:08:12 +00003522
Chris Lattner47955de2007-01-27 08:37:20 +00003523 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003524 FunctionNoProtoType *NewIP =
3525 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003526 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattner47955de2007-01-27 08:37:20 +00003527 }
Mike Stump11289f42009-09-09 15:08:12 +00003528
Eugene Zelenko7855e772018-04-03 00:11:50 +00003529 auto *New = new (*this, TypeAlignment)
John McCall18afab72016-03-01 00:49:02 +00003530 FunctionNoProtoType(ResultTy, Canonical, Info);
Chris Lattner47955de2007-01-27 08:37:20 +00003531 Types.push_back(New);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003532 FunctionNoProtoTypes.InsertNode(New, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003533 return QualType(New, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003534}
3535
Douglas Gregora602a152015-10-01 20:20:47 +00003536CanQualType
3537ASTContext::getCanonicalFunctionResultType(QualType ResultType) const {
3538 CanQualType CanResultType = getCanonicalType(ResultType);
3539
3540 // Canonical result types do not have ARC lifetime qualifiers.
3541 if (CanResultType.getQualifiers().hasObjCLifetime()) {
3542 Qualifiers Qs = CanResultType.getQualifiers();
3543 Qs.removeObjCLifetime();
3544 return CanQualType::CreateUnsafe(
3545 getQualifiedType(CanResultType.getUnqualifiedType(), Qs));
3546 }
3547
3548 return CanResultType;
3549}
3550
Richard Smith3c4f8d22016-10-16 17:54:23 +00003551static bool isCanonicalExceptionSpecification(
3552 const FunctionProtoType::ExceptionSpecInfo &ESI, bool NoexceptInType) {
3553 if (ESI.Type == EST_None)
3554 return true;
3555 if (!NoexceptInType)
3556 return false;
3557
3558 // C++17 onwards: exception specification is part of the type, as a simple
3559 // boolean "can this function type throw".
3560 if (ESI.Type == EST_BasicNoexcept)
3561 return true;
3562
Richard Smitheaf11ad2018-05-03 03:58:32 +00003563 // A noexcept(expr) specification is (possibly) canonical if expr is
3564 // value-dependent.
3565 if (ESI.Type == EST_DependentNoexcept)
3566 return true;
3567
Richard Smith3c4f8d22016-10-16 17:54:23 +00003568 // A dynamic exception specification is canonical if it only contains pack
Richard Smith2a2cda52016-10-18 19:29:18 +00003569 // expansions (so we can't tell whether it's non-throwing) and all its
3570 // contained types are canonical.
Richard Smith3c4f8d22016-10-16 17:54:23 +00003571 if (ESI.Type == EST_Dynamic) {
Richard Smithfda59e52016-10-26 01:05:54 +00003572 bool AnyPackExpansions = false;
3573 for (QualType ET : ESI.Exceptions) {
3574 if (!ET.isCanonical())
Richard Smith3c4f8d22016-10-16 17:54:23 +00003575 return false;
Richard Smithfda59e52016-10-26 01:05:54 +00003576 if (ET->getAs<PackExpansionType>())
3577 AnyPackExpansions = true;
3578 }
3579 return AnyPackExpansions;
Richard Smith3c4f8d22016-10-16 17:54:23 +00003580 }
3581
Richard Smith3c4f8d22016-10-16 17:54:23 +00003582 return false;
3583}
3584
Richard Smith304b1242016-10-18 20:13:25 +00003585QualType ASTContext::getFunctionTypeInternal(
3586 QualType ResultTy, ArrayRef<QualType> ArgArray,
3587 const FunctionProtoType::ExtProtoInfo &EPI, bool OnlyWantCanonical) const {
Jordan Rose5c382722013-03-08 21:51:21 +00003588 size_t NumArgs = ArgArray.size();
3589
Richard Smith2a2cda52016-10-18 19:29:18 +00003590 // Unique functions, to guarantee there is only one function of a particular
3591 // structure.
3592 llvm::FoldingSetNodeID ID;
3593 FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
3594 *this, true);
Richard Smith3c4f8d22016-10-16 17:54:23 +00003595
Richard Smith2a2cda52016-10-18 19:29:18 +00003596 QualType Canonical;
3597 bool Unique = false;
3598
3599 void *InsertPos = nullptr;
3600 if (FunctionProtoType *FPT =
3601 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) {
3602 QualType Existing = QualType(FPT, 0);
3603
3604 // If we find a pre-existing equivalent FunctionProtoType, we can just reuse
3605 // it so long as our exception specification doesn't contain a dependent
Richard Smith304b1242016-10-18 20:13:25 +00003606 // noexcept expression, or we're just looking for a canonical type.
3607 // Otherwise, we're going to need to create a type
Richard Smith2a2cda52016-10-18 19:29:18 +00003608 // sugar node to hold the concrete expression.
Richard Smitheaf11ad2018-05-03 03:58:32 +00003609 if (OnlyWantCanonical || !isComputedNoexcept(EPI.ExceptionSpec.Type) ||
Richard Smith2a2cda52016-10-18 19:29:18 +00003610 EPI.ExceptionSpec.NoexceptExpr == FPT->getNoexceptExpr())
3611 return Existing;
3612
3613 // We need a new type sugar node for this one, to hold the new noexcept
3614 // expression. We do no canonicalization here, but that's OK since we don't
3615 // expect to see the same noexcept expression much more than once.
3616 Canonical = getCanonicalType(Existing);
3617 Unique = true;
3618 }
3619
Aaron Ballmanc351fba2017-12-04 20:27:34 +00003620 bool NoexceptInType = getLangOpts().CPlusPlus17;
Richard Smith3c4f8d22016-10-16 17:54:23 +00003621 bool IsCanonicalExceptionSpec =
3622 isCanonicalExceptionSpecification(EPI.ExceptionSpec, NoexceptInType);
3623
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003624 // Determine whether the type being created is already canonical or not.
Richard Smith2a2cda52016-10-18 19:29:18 +00003625 bool isCanonical = !Unique && IsCanonicalExceptionSpec &&
Richard Smith3c4f8d22016-10-16 17:54:23 +00003626 isCanonicalResultType(ResultTy) && !EPI.HasTrailingReturn;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003627 for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00003628 if (!ArgArray[i].isCanonicalAsParam())
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003629 isCanonical = false;
3630
Richard Smith304b1242016-10-18 20:13:25 +00003631 if (OnlyWantCanonical)
3632 assert(isCanonical &&
3633 "given non-canonical parameters constructing canonical type");
3634
Richard Smith2a2cda52016-10-18 19:29:18 +00003635 // If this type isn't canonical, get the canonical version of it if we don't
3636 // already have it. The exception spec is only partially part of the
3637 // canonical type, and only in C++17 onwards.
3638 if (!isCanonical && Canonical.isNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003639 SmallVector<QualType, 16> CanonicalArgs;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003640 CanonicalArgs.reserve(NumArgs);
3641 for (unsigned i = 0; i != NumArgs; ++i)
John McCallfc93cf92009-10-22 22:37:11 +00003642 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003643
Benjamin Kramer3f515cd2016-10-26 12:51:45 +00003644 llvm::SmallVector<QualType, 8> ExceptionTypeStorage;
John McCalldb40c7f2010-12-14 08:05:40 +00003645 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
Richard Smith5e580292012-02-10 09:58:53 +00003646 CanonicalEPI.HasTrailingReturn = false;
Richard Smith3c4f8d22016-10-16 17:54:23 +00003647
3648 if (IsCanonicalExceptionSpec) {
3649 // Exception spec is already OK.
3650 } else if (NoexceptInType) {
3651 switch (EPI.ExceptionSpec.Type) {
3652 case EST_Unparsed: case EST_Unevaluated: case EST_Uninstantiated:
3653 // We don't know yet. It shouldn't matter what we pick here; no-one
3654 // should ever look at this.
3655 LLVM_FALLTHROUGH;
Richard Smitheaf11ad2018-05-03 03:58:32 +00003656 case EST_None: case EST_MSAny: case EST_NoexceptFalse:
Richard Smith3c4f8d22016-10-16 17:54:23 +00003657 CanonicalEPI.ExceptionSpec.Type = EST_None;
3658 break;
3659
Richard Smith2a2cda52016-10-18 19:29:18 +00003660 // A dynamic exception specification is almost always "not noexcept",
3661 // with the exception that a pack expansion might expand to no types.
3662 case EST_Dynamic: {
3663 bool AnyPacks = false;
3664 for (QualType ET : EPI.ExceptionSpec.Exceptions) {
3665 if (ET->getAs<PackExpansionType>())
3666 AnyPacks = true;
3667 ExceptionTypeStorage.push_back(getCanonicalType(ET));
3668 }
3669 if (!AnyPacks)
3670 CanonicalEPI.ExceptionSpec.Type = EST_None;
3671 else {
3672 CanonicalEPI.ExceptionSpec.Type = EST_Dynamic;
3673 CanonicalEPI.ExceptionSpec.Exceptions = ExceptionTypeStorage;
3674 }
3675 break;
3676 }
3677
Richard Smitheaf11ad2018-05-03 03:58:32 +00003678 case EST_DynamicNone: case EST_BasicNoexcept: case EST_NoexceptTrue:
Richard Smith3c4f8d22016-10-16 17:54:23 +00003679 CanonicalEPI.ExceptionSpec.Type = EST_BasicNoexcept;
3680 break;
3681
Richard Smitheaf11ad2018-05-03 03:58:32 +00003682 case EST_DependentNoexcept:
3683 llvm_unreachable("dependent noexcept is already canonical");
Richard Smith3c4f8d22016-10-16 17:54:23 +00003684 }
Richard Smith3c4f8d22016-10-16 17:54:23 +00003685 } else {
3686 CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo();
3687 }
John McCalldb40c7f2010-12-14 08:05:40 +00003688
Douglas Gregora602a152015-10-01 20:20:47 +00003689 // Adjust the canonical function result type.
3690 CanQualType CanResultTy = getCanonicalFunctionResultType(ResultTy);
Richard Smith304b1242016-10-18 20:13:25 +00003691 Canonical =
3692 getFunctionTypeInternal(CanResultTy, CanonicalArgs, CanonicalEPI, true);
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003693
Chris Lattnerfd4de792007-01-27 01:15:32 +00003694 // Get the new insert position for the node we care about.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003695 FunctionProtoType *NewIP =
3696 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00003697 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003698 }
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00003699
John McCall31168b02011-06-15 23:02:42 +00003700 // FunctionProtoType objects are allocated with extra bytes after
3701 // them for three variable size arrays at the end:
3702 // - parameter types
3703 // - exception types
John McCall18afab72016-03-01 00:49:02 +00003704 // - extended parameter information
John McCall31168b02011-06-15 23:02:42 +00003705 // Instead of the exception types, there could be a noexcept
Richard Smithd3b5c9082012-07-27 04:22:15 +00003706 // expression, or information used to resolve the exception
3707 // specification.
Richard Smitheaf11ad2018-05-03 03:58:32 +00003708 size_t Size =
3709 sizeof(FunctionProtoType) + NumArgs * sizeof(QualType) +
3710 FunctionProtoType::getExceptionSpecSize(
3711 EPI.ExceptionSpec.Type, EPI.ExceptionSpec.Exceptions.size());
John McCall18afab72016-03-01 00:49:02 +00003712
3713 // Put the ExtParameterInfos last. If all were equal, it would make
3714 // more sense to put these before the exception specification, because
3715 // it's much easier to skip past them compared to the elaborate switch
3716 // required to skip the exception specification. However, all is not
3717 // equal; ExtParameterInfos are used to model very uncommon features,
3718 // and it's better not to burden the more common paths.
3719 if (EPI.ExtParameterInfos) {
3720 Size += NumArgs * sizeof(FunctionProtoType::ExtParameterInfo);
3721 }
John McCall31168b02011-06-15 23:02:42 +00003722
Eugene Zelenko7855e772018-04-03 00:11:50 +00003723 auto *FTP = (FunctionProtoType *) Allocate(Size, TypeAlignment);
Roman Divacky65b88cd2011-03-01 17:40:53 +00003724 FunctionProtoType::ExtProtoInfo newEPI = EPI;
Jordan Rose5c382722013-03-08 21:51:21 +00003725 new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003726 Types.push_back(FTP);
Richard Smith2a2cda52016-10-18 19:29:18 +00003727 if (!Unique)
3728 FunctionProtoTypes.InsertNode(FTP, InsertPos);
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003729 return QualType(FTP, 0);
Chris Lattnerc6ad8132006-12-02 07:52:18 +00003730}
Chris Lattneref51c202006-11-10 07:17:23 +00003731
Joey Goulye3c85de2016-12-01 11:30:49 +00003732QualType ASTContext::getPipeType(QualType T, bool ReadOnly) const {
Xiuli Pan9c14e282016-01-09 12:53:17 +00003733 llvm::FoldingSetNodeID ID;
Joey Goulye3c85de2016-12-01 11:30:49 +00003734 PipeType::Profile(ID, T, ReadOnly);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003735
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00003736 void *InsertPos = nullptr;
Joey Goulye3c85de2016-12-01 11:30:49 +00003737 if (PipeType *PT = PipeTypes.FindNodeOrInsertPos(ID, InsertPos))
Xiuli Pan9c14e282016-01-09 12:53:17 +00003738 return QualType(PT, 0);
3739
3740 // If the pipe element type isn't canonical, this won't be a canonical type
3741 // either, so fill in the canonical type field.
3742 QualType Canonical;
3743 if (!T.isCanonical()) {
Joey Goulye3c85de2016-12-01 11:30:49 +00003744 Canonical = getPipeType(getCanonicalType(T), ReadOnly);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003745
3746 // Get the new insert position for the node we care about.
Joey Goulye3c85de2016-12-01 11:30:49 +00003747 PipeType *NewIP = PipeTypes.FindNodeOrInsertPos(ID, InsertPos);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003748 assert(!NewIP && "Shouldn't be in the map!");
3749 (void)NewIP;
3750 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00003751 auto *New = new (*this, TypeAlignment) PipeType(T, Canonical, ReadOnly);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003752 Types.push_back(New);
Joey Goulye3c85de2016-12-01 11:30:49 +00003753 PipeTypes.InsertNode(New, InsertPos);
Joey Gouly5788b782016-11-18 14:10:54 +00003754 return QualType(New, 0);
3755}
3756
Anastasia Stulova59055b92018-05-09 13:23:26 +00003757QualType ASTContext::adjustStringLiteralBaseType(QualType Ty) const {
3758 // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
3759 return LangOpts.OpenCL ? getAddrSpaceQualType(Ty, LangAS::opencl_constant)
3760 : Ty;
3761}
3762
Joey Goulye3c85de2016-12-01 11:30:49 +00003763QualType ASTContext::getReadPipeType(QualType T) const {
3764 return getPipeType(T, true);
3765}
3766
Joey Gouly5788b782016-11-18 14:10:54 +00003767QualType ASTContext::getWritePipeType(QualType T) const {
Joey Goulye3c85de2016-12-01 11:30:49 +00003768 return getPipeType(T, false);
Xiuli Pan9c14e282016-01-09 12:53:17 +00003769}
3770
John McCalle78aac42010-03-10 03:28:59 +00003771#ifndef NDEBUG
3772static bool NeedsInjectedClassNameType(const RecordDecl *D) {
3773 if (!isa<CXXRecordDecl>(D)) return false;
Eugene Zelenko7855e772018-04-03 00:11:50 +00003774 const auto *RD = cast<CXXRecordDecl>(D);
John McCalle78aac42010-03-10 03:28:59 +00003775 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
3776 return true;
3777 if (RD->getDescribedClassTemplate() &&
3778 !isa<ClassTemplateSpecializationDecl>(RD))
3779 return true;
3780 return false;
3781}
3782#endif
3783
3784/// getInjectedClassNameType - Return the unique reference to the
3785/// injected class name type for the specified templated declaration.
3786QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
Jay Foad39c79802011-01-12 09:06:06 +00003787 QualType TST) const {
John McCalle78aac42010-03-10 03:28:59 +00003788 assert(NeedsInjectedClassNameType(Decl));
3789 if (Decl->TypeForDecl) {
3790 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
Douglas Gregorec9fd132012-01-14 16:38:05 +00003791 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
John McCalle78aac42010-03-10 03:28:59 +00003792 assert(PrevDecl->TypeForDecl && "previous declaration has no type");
3793 Decl->TypeForDecl = PrevDecl->TypeForDecl;
3794 assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
3795 } else {
John McCall424cec92011-01-19 06:33:43 +00003796 Type *newType =
John McCall2408e322010-04-27 00:57:59 +00003797 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
John McCall424cec92011-01-19 06:33:43 +00003798 Decl->TypeForDecl = newType;
3799 Types.push_back(newType);
John McCalle78aac42010-03-10 03:28:59 +00003800 }
3801 return QualType(Decl->TypeForDecl, 0);
3802}
3803
Douglas Gregor83a586e2008-04-13 21:07:44 +00003804/// getTypeDeclType - Return the unique reference to the type for the
3805/// specified type declaration.
Jay Foad39c79802011-01-12 09:06:06 +00003806QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
Argyrios Kyrtzidis89656d22008-10-16 16:50:47 +00003807 assert(Decl && "Passed null for Decl param");
John McCall96f0b5f2010-03-10 06:48:02 +00003808 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
Mike Stump11289f42009-09-09 15:08:12 +00003809
Eugene Zelenko7855e772018-04-03 00:11:50 +00003810 if (const auto *Typedef = dyn_cast<TypedefNameDecl>(Decl))
Douglas Gregor83a586e2008-04-13 21:07:44 +00003811 return getTypedefType(Typedef);
John McCall96f0b5f2010-03-10 06:48:02 +00003812
John McCall96f0b5f2010-03-10 06:48:02 +00003813 assert(!isa<TemplateTypeParmDecl>(Decl) &&
3814 "Template type parameter types are always available.");
3815
Eugene Zelenko7855e772018-04-03 00:11:50 +00003816 if (const auto *Record = dyn_cast<RecordDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00003817 assert(Record->isFirstDecl() && "struct/union has previous declaration");
John McCall96f0b5f2010-03-10 06:48:02 +00003818 assert(!NeedsInjectedClassNameType(Record));
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003819 return getRecordType(Record);
Eugene Zelenko7855e772018-04-03 00:11:50 +00003820 } else if (const auto *Enum = dyn_cast<EnumDecl>(Decl)) {
Rafael Espindola3f9e4442013-10-19 02:13:21 +00003821 assert(Enum->isFirstDecl() && "enum has previous declaration");
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003822 return getEnumType(Enum);
Eugene Zelenko7855e772018-04-03 00:11:50 +00003823 } else if (const auto *Using = dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
John McCall424cec92011-01-19 06:33:43 +00003824 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
3825 Decl->TypeForDecl = newType;
3826 Types.push_back(newType);
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00003827 } else
John McCall96f0b5f2010-03-10 06:48:02 +00003828 llvm_unreachable("TypeDecl without a type?");
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00003829
Argyrios Kyrtzidisfaf08762008-08-07 20:55:28 +00003830 return QualType(Decl->TypeForDecl, 0);
Douglas Gregor83a586e2008-04-13 21:07:44 +00003831}
3832
Chris Lattner32d920b2007-01-26 02:01:53 +00003833/// getTypedefType - Return the unique reference to the type for the
Richard Smithdda56e42011-04-15 14:24:37 +00003834/// specified typedef name decl.
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003835QualType
Richard Smithdda56e42011-04-15 14:24:37 +00003836ASTContext::getTypedefType(const TypedefNameDecl *Decl,
3837 QualType Canonical) const {
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003838 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003839
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00003840 if (Canonical.isNull())
3841 Canonical = getCanonicalType(Decl->getUnderlyingType());
Eugene Zelenko7855e772018-04-03 00:11:50 +00003842 auto *newType = new (*this, TypeAlignment)
John McCall90d1c2d2009-09-24 23:30:46 +00003843 TypedefType(Type::Typedef, Decl, Canonical);
John McCall424cec92011-01-19 06:33:43 +00003844 Decl->TypeForDecl = newType;
3845 Types.push_back(newType);
3846 return QualType(newType, 0);
Chris Lattnerd0342e52006-11-20 04:02:15 +00003847}
3848
Jay Foad39c79802011-01-12 09:06:06 +00003849QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003850 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3851
Douglas Gregorec9fd132012-01-14 16:38:05 +00003852 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003853 if (PrevDecl->TypeForDecl)
Fangrui Song6907ce22018-07-30 19:24:48 +00003854 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003855
Eugene Zelenko7855e772018-04-03 00:11:50 +00003856 auto *newType = new (*this, TypeAlignment) RecordType(Decl);
John McCall424cec92011-01-19 06:33:43 +00003857 Decl->TypeForDecl = newType;
3858 Types.push_back(newType);
3859 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003860}
3861
Jay Foad39c79802011-01-12 09:06:06 +00003862QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003863 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3864
Douglas Gregorec9fd132012-01-14 16:38:05 +00003865 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003866 if (PrevDecl->TypeForDecl)
Fangrui Song6907ce22018-07-30 19:24:48 +00003867 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003868
Eugene Zelenko7855e772018-04-03 00:11:50 +00003869 auto *newType = new (*this, TypeAlignment) EnumType(Decl);
John McCall424cec92011-01-19 06:33:43 +00003870 Decl->TypeForDecl = newType;
3871 Types.push_back(newType);
3872 return QualType(newType, 0);
Argyrios Kyrtzidisb5fcdc22010-07-04 21:44:47 +00003873}
3874
Richard Smithe43e2b32018-08-20 21:47:29 +00003875QualType ASTContext::getAttributedType(attr::Kind attrKind,
John McCall81904512011-01-06 01:58:22 +00003876 QualType modifiedType,
3877 QualType equivalentType) {
3878 llvm::FoldingSetNodeID id;
3879 AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
3880
Craig Topper36250ad2014-05-12 05:36:57 +00003881 void *insertPos = nullptr;
John McCall81904512011-01-06 01:58:22 +00003882 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
3883 if (type) return QualType(type, 0);
3884
3885 QualType canon = getCanonicalType(equivalentType);
3886 type = new (*this, TypeAlignment)
3887 AttributedType(canon, attrKind, modifiedType, equivalentType);
3888
3889 Types.push_back(type);
3890 AttributedTypes.InsertNode(type, insertPos);
3891
3892 return QualType(type, 0);
3893}
3894
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003895/// Retrieve a substitution-result type.
John McCallcebee162009-10-18 09:09:24 +00003896QualType
3897ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
Jay Foad39c79802011-01-12 09:06:06 +00003898 QualType Replacement) const {
John McCallb692a092009-10-22 20:10:53 +00003899 assert(Replacement.isCanonical()
John McCallcebee162009-10-18 09:09:24 +00003900 && "replacement types must always be canonical");
3901
3902 llvm::FoldingSetNodeID ID;
3903 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
Craig Topper36250ad2014-05-12 05:36:57 +00003904 void *InsertPos = nullptr;
John McCallcebee162009-10-18 09:09:24 +00003905 SubstTemplateTypeParmType *SubstParm
3906 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3907
3908 if (!SubstParm) {
3909 SubstParm = new (*this, TypeAlignment)
3910 SubstTemplateTypeParmType(Parm, Replacement);
3911 Types.push_back(SubstParm);
3912 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3913 }
3914
3915 return QualType(SubstParm, 0);
3916}
3917
Fangrui Song6907ce22018-07-30 19:24:48 +00003918/// Retrieve a
Douglas Gregorada4b792011-01-14 02:55:32 +00003919QualType ASTContext::getSubstTemplateTypeParmPackType(
3920 const TemplateTypeParmType *Parm,
3921 const TemplateArgument &ArgPack) {
3922#ifndef NDEBUG
Aaron Ballman2a89e852014-07-15 21:32:31 +00003923 for (const auto &P : ArgPack.pack_elements()) {
3924 assert(P.getKind() == TemplateArgument::Type &&"Pack contains a non-type");
3925 assert(P.getAsType().isCanonical() && "Pack contains non-canonical type");
Douglas Gregorada4b792011-01-14 02:55:32 +00003926 }
3927#endif
Fangrui Song6907ce22018-07-30 19:24:48 +00003928
Douglas Gregorada4b792011-01-14 02:55:32 +00003929 llvm::FoldingSetNodeID ID;
3930 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
Craig Topper36250ad2014-05-12 05:36:57 +00003931 void *InsertPos = nullptr;
Douglas Gregorada4b792011-01-14 02:55:32 +00003932 if (SubstTemplateTypeParmPackType *SubstParm
3933 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
3934 return QualType(SubstParm, 0);
Fangrui Song6907ce22018-07-30 19:24:48 +00003935
Douglas Gregorada4b792011-01-14 02:55:32 +00003936 QualType Canon;
3937 if (!Parm->isCanonicalUnqualified()) {
3938 Canon = getCanonicalType(QualType(Parm, 0));
3939 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
3940 ArgPack);
3941 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
3942 }
3943
Eugene Zelenko7855e772018-04-03 00:11:50 +00003944 auto *SubstParm
Douglas Gregorada4b792011-01-14 02:55:32 +00003945 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
3946 ArgPack);
3947 Types.push_back(SubstParm);
George Burgess IVb5fe8552017-06-12 17:44:30 +00003948 SubstTemplateTypeParmPackTypes.InsertNode(SubstParm, InsertPos);
Fangrui Song6907ce22018-07-30 19:24:48 +00003949 return QualType(SubstParm, 0);
Douglas Gregorada4b792011-01-14 02:55:32 +00003950}
3951
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003952/// Retrieve the template type parameter type for a template
Mike Stump11289f42009-09-09 15:08:12 +00003953/// parameter or parameter pack with the given depth, index, and (optionally)
Anders Carlsson90036dc2009-06-16 00:30:48 +00003954/// name.
Mike Stump11289f42009-09-09 15:08:12 +00003955QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
Anders Carlsson90036dc2009-06-16 00:30:48 +00003956 bool ParameterPack,
Chandler Carruth08836322011-05-01 00:51:33 +00003957 TemplateTypeParmDecl *TTPDecl) const {
Douglas Gregoreff93e02009-02-05 23:33:38 +00003958 llvm::FoldingSetNodeID ID;
Chandler Carruth08836322011-05-01 00:51:33 +00003959 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
Craig Topper36250ad2014-05-12 05:36:57 +00003960 void *InsertPos = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003961 TemplateTypeParmType *TypeParm
Douglas Gregoreff93e02009-02-05 23:33:38 +00003962 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3963
3964 if (TypeParm)
3965 return QualType(TypeParm, 0);
Mike Stump11289f42009-09-09 15:08:12 +00003966
Chandler Carruth08836322011-05-01 00:51:33 +00003967 if (TTPDecl) {
Anders Carlsson90036dc2009-06-16 00:30:48 +00003968 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
Chandler Carruth08836322011-05-01 00:51:33 +00003969 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00003970
Fangrui Song6907ce22018-07-30 19:24:48 +00003971 TemplateTypeParmType *TypeCheck
Douglas Gregorc42075a2010-02-04 18:10:26 +00003972 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3973 assert(!TypeCheck && "Template type parameter canonical type broken");
3974 (void)TypeCheck;
Anders Carlsson90036dc2009-06-16 00:30:48 +00003975 } else
John McCall90d1c2d2009-09-24 23:30:46 +00003976 TypeParm = new (*this, TypeAlignment)
3977 TemplateTypeParmType(Depth, Index, ParameterPack);
Douglas Gregoreff93e02009-02-05 23:33:38 +00003978
3979 Types.push_back(TypeParm);
3980 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
3981
3982 return QualType(TypeParm, 0);
3983}
3984
John McCalle78aac42010-03-10 03:28:59 +00003985TypeSourceInfo *
3986ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
3987 SourceLocation NameLoc,
3988 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00003989 QualType Underlying) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00003990 assert(!Name.getAsDependentTemplateName() &&
Douglas Gregore16af532011-02-28 18:50:33 +00003991 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00003992 QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
John McCalle78aac42010-03-10 03:28:59 +00003993
3994 TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
David Blaikie6adc78e2013-02-18 22:06:02 +00003995 TemplateSpecializationTypeLoc TL =
3996 DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
Abramo Bagnara48c05be2012-02-06 14:41:24 +00003997 TL.setTemplateKeywordLoc(SourceLocation());
John McCalle78aac42010-03-10 03:28:59 +00003998 TL.setTemplateNameLoc(NameLoc);
3999 TL.setLAngleLoc(Args.getLAngleLoc());
4000 TL.setRAngleLoc(Args.getRAngleLoc());
4001 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
4002 TL.setArgLocInfo(i, Args[i].getLocInfo());
4003 return DI;
4004}
4005
Mike Stump11289f42009-09-09 15:08:12 +00004006QualType
Douglas Gregordc572a32009-03-30 22:58:21 +00004007ASTContext::getTemplateSpecializationType(TemplateName Template,
John McCall6b51f282009-11-23 01:53:49 +00004008 const TemplateArgumentListInfo &Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00004009 QualType Underlying) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00004010 assert(!Template.getAsDependentTemplateName() &&
Douglas Gregore16af532011-02-28 18:50:33 +00004011 "No dependent template names here!");
John McCall6b51f282009-11-23 01:53:49 +00004012
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004013 SmallVector<TemplateArgument, 4> ArgVec;
David Majnemer6fbeee32016-07-07 04:43:07 +00004014 ArgVec.reserve(Args.size());
4015 for (const TemplateArgumentLoc &Arg : Args.arguments())
4016 ArgVec.push_back(Arg.getArgument());
John McCall0ad16662009-10-29 08:12:44 +00004017
David Majnemer6fbeee32016-07-07 04:43:07 +00004018 return getTemplateSpecializationType(Template, ArgVec, Underlying);
John McCall0ad16662009-10-29 08:12:44 +00004019}
4020
Douglas Gregor1f79ca82012-02-03 17:16:23 +00004021#ifndef NDEBUG
David Majnemer6fbeee32016-07-07 04:43:07 +00004022static bool hasAnyPackExpansions(ArrayRef<TemplateArgument> Args) {
4023 for (const TemplateArgument &Arg : Args)
4024 if (Arg.isPackExpansion())
Douglas Gregor1f79ca82012-02-03 17:16:23 +00004025 return true;
Fangrui Song6907ce22018-07-30 19:24:48 +00004026
Douglas Gregor1f79ca82012-02-03 17:16:23 +00004027 return true;
4028}
4029#endif
4030
John McCall0ad16662009-10-29 08:12:44 +00004031QualType
4032ASTContext::getTemplateSpecializationType(TemplateName Template,
David Majnemer6fbeee32016-07-07 04:43:07 +00004033 ArrayRef<TemplateArgument> Args,
Richard Smith3f1b5d02011-05-05 21:57:07 +00004034 QualType Underlying) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00004035 assert(!Template.getAsDependentTemplateName() &&
Douglas Gregore16af532011-02-28 18:50:33 +00004036 "No dependent template names here!");
Douglas Gregore29139c2011-03-03 17:04:51 +00004037 // Look through qualified template names.
4038 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
4039 Template = TemplateName(QTN->getTemplateDecl());
Fangrui Song6907ce22018-07-30 19:24:48 +00004040
4041 bool IsTypeAlias =
Richard Smith3f1b5d02011-05-05 21:57:07 +00004042 Template.getAsTemplateDecl() &&
4043 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00004044 QualType CanonType;
4045 if (!Underlying.isNull())
4046 CanonType = getCanonicalType(Underlying);
4047 else {
Douglas Gregor1f79ca82012-02-03 17:16:23 +00004048 // We can get here with an alias template when the specialization contains
4049 // a pack expansion that does not match up with a parameter pack.
David Majnemer6fbeee32016-07-07 04:43:07 +00004050 assert((!IsTypeAlias || hasAnyPackExpansions(Args)) &&
Douglas Gregor1f79ca82012-02-03 17:16:23 +00004051 "Caller must compute aliased type");
4052 IsTypeAlias = false;
David Majnemer6fbeee32016-07-07 04:43:07 +00004053 CanonType = getCanonicalTemplateSpecializationType(Template, Args);
Richard Smith3f1b5d02011-05-05 21:57:07 +00004054 }
Douglas Gregord56a91e2009-02-26 22:19:44 +00004055
Douglas Gregora8e02e72009-07-28 23:00:59 +00004056 // Allocate the (non-canonical) template specialization type, but don't
4057 // try to unique it: these types typically have location information that
4058 // we don't unique and don't want to lose.
Richard Smith3f1b5d02011-05-05 21:57:07 +00004059 void *Mem = Allocate(sizeof(TemplateSpecializationType) +
David Majnemer6fbeee32016-07-07 04:43:07 +00004060 sizeof(TemplateArgument) * Args.size() +
Douglas Gregor1f79ca82012-02-03 17:16:23 +00004061 (IsTypeAlias? sizeof(QualType) : 0),
John McCall90d1c2d2009-09-24 23:30:46 +00004062 TypeAlignment);
Eugene Zelenko7855e772018-04-03 00:11:50 +00004063 auto *Spec
David Majnemer6fbeee32016-07-07 04:43:07 +00004064 = new (Mem) TemplateSpecializationType(Template, Args, CanonType,
Douglas Gregor1f79ca82012-02-03 17:16:23 +00004065 IsTypeAlias ? Underlying : QualType());
Mike Stump11289f42009-09-09 15:08:12 +00004066
Douglas Gregor8bf42052009-02-09 18:46:07 +00004067 Types.push_back(Spec);
Mike Stump11289f42009-09-09 15:08:12 +00004068 return QualType(Spec, 0);
Douglas Gregor8bf42052009-02-09 18:46:07 +00004069}
4070
David Majnemer6fbeee32016-07-07 04:43:07 +00004071QualType ASTContext::getCanonicalTemplateSpecializationType(
4072 TemplateName Template, ArrayRef<TemplateArgument> Args) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00004073 assert(!Template.getAsDependentTemplateName() &&
Douglas Gregore16af532011-02-28 18:50:33 +00004074 "No dependent template names here!");
Richard Smith3f1b5d02011-05-05 21:57:07 +00004075
Douglas Gregore29139c2011-03-03 17:04:51 +00004076 // Look through qualified template names.
4077 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
4078 Template = TemplateName(QTN->getTemplateDecl());
Fangrui Song6907ce22018-07-30 19:24:48 +00004079
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00004080 // Build the canonical template specialization type.
4081 TemplateName CanonTemplate = getCanonicalTemplateName(Template);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004082 SmallVector<TemplateArgument, 4> CanonArgs;
David Majnemer6fbeee32016-07-07 04:43:07 +00004083 unsigned NumArgs = Args.size();
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00004084 CanonArgs.reserve(NumArgs);
David Majnemer6fbeee32016-07-07 04:43:07 +00004085 for (const TemplateArgument &Arg : Args)
4086 CanonArgs.push_back(getCanonicalTemplateArgument(Arg));
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00004087
4088 // Determine whether this canonical template specialization type already
4089 // exists.
4090 llvm::FoldingSetNodeID ID;
4091 TemplateSpecializationType::Profile(ID, CanonTemplate,
David Majnemer6fbeee32016-07-07 04:43:07 +00004092 CanonArgs, *this);
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00004093
Craig Topper36250ad2014-05-12 05:36:57 +00004094 void *InsertPos = nullptr;
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00004095 TemplateSpecializationType *Spec
4096 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
4097
4098 if (!Spec) {
4099 // Allocate a new canonical template specialization type.
4100 void *Mem = Allocate((sizeof(TemplateSpecializationType) +
4101 sizeof(TemplateArgument) * NumArgs),
4102 TypeAlignment);
4103 Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
David Majnemer6fbeee32016-07-07 04:43:07 +00004104 CanonArgs,
Richard Smith3f1b5d02011-05-05 21:57:07 +00004105 QualType(), QualType());
Argyrios Kyrtzidis45a83f92010-07-02 11:55:11 +00004106 Types.push_back(Spec);
4107 TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
4108 }
4109
4110 assert(Spec->isDependentType() &&
4111 "Non-dependent template-id type must have a canonical type");
4112 return QualType(Spec, 0);
4113}
4114
Joel E. Denny7509a2f2018-05-14 19:36:45 +00004115QualType ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
4116 NestedNameSpecifier *NNS,
4117 QualType NamedType,
4118 TagDecl *OwnedTagDecl) const {
Douglas Gregor52537682009-03-19 00:18:19 +00004119 llvm::FoldingSetNodeID ID;
Joel E. Denny7509a2f2018-05-14 19:36:45 +00004120 ElaboratedType::Profile(ID, Keyword, NNS, NamedType, OwnedTagDecl);
Douglas Gregor52537682009-03-19 00:18:19 +00004121
Craig Topper36250ad2014-05-12 05:36:57 +00004122 void *InsertPos = nullptr;
Abramo Bagnara6150c882010-05-11 21:36:43 +00004123 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00004124 if (T)
4125 return QualType(T, 0);
4126
Douglas Gregorc42075a2010-02-04 18:10:26 +00004127 QualType Canon = NamedType;
4128 if (!Canon.isCanonical()) {
4129 Canon = getCanonicalType(NamedType);
Abramo Bagnara6150c882010-05-11 21:36:43 +00004130 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
4131 assert(!CheckT && "Elaborated canonical type broken");
Douglas Gregorc42075a2010-02-04 18:10:26 +00004132 (void)CheckT;
4133 }
4134
Bruno Riccid6bd5982018-08-16 10:48:16 +00004135 void *Mem = Allocate(ElaboratedType::totalSizeToAlloc<TagDecl *>(!!OwnedTagDecl),
4136 TypeAlignment);
4137 T = new (Mem) ElaboratedType(Keyword, NNS, NamedType, Canon, OwnedTagDecl);
4138
Douglas Gregor52537682009-03-19 00:18:19 +00004139 Types.push_back(T);
Abramo Bagnara6150c882010-05-11 21:36:43 +00004140 ElaboratedTypes.InsertNode(T, InsertPos);
Douglas Gregor52537682009-03-19 00:18:19 +00004141 return QualType(T, 0);
4142}
4143
Abramo Bagnara924a8f32010-12-10 16:29:40 +00004144QualType
Jay Foad39c79802011-01-12 09:06:06 +00004145ASTContext::getParenType(QualType InnerType) const {
Abramo Bagnara924a8f32010-12-10 16:29:40 +00004146 llvm::FoldingSetNodeID ID;
4147 ParenType::Profile(ID, InnerType);
4148
Craig Topper36250ad2014-05-12 05:36:57 +00004149 void *InsertPos = nullptr;
Abramo Bagnara924a8f32010-12-10 16:29:40 +00004150 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
4151 if (T)
4152 return QualType(T, 0);
4153
4154 QualType Canon = InnerType;
4155 if (!Canon.isCanonical()) {
4156 Canon = getCanonicalType(InnerType);
4157 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
4158 assert(!CheckT && "Paren canonical type broken");
4159 (void)CheckT;
4160 }
4161
Benjamin Kramer8adeef92015-04-02 16:19:54 +00004162 T = new (*this, TypeAlignment) ParenType(InnerType, Canon);
Abramo Bagnara924a8f32010-12-10 16:29:40 +00004163 Types.push_back(T);
4164 ParenTypes.InsertNode(T, InsertPos);
4165 return QualType(T, 0);
4166}
4167
Douglas Gregor02085352010-03-31 20:19:30 +00004168QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
4169 NestedNameSpecifier *NNS,
4170 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00004171 QualType Canon) const {
Douglas Gregor333489b2009-03-27 23:10:48 +00004172 if (Canon.isNull()) {
4173 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Richard Smith74f02342017-01-19 21:00:13 +00004174 if (CanonNNS != NNS)
4175 Canon = getDependentNameType(Keyword, CanonNNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00004176 }
4177
4178 llvm::FoldingSetNodeID ID;
Douglas Gregor02085352010-03-31 20:19:30 +00004179 DependentNameType::Profile(ID, Keyword, NNS, Name);
Douglas Gregor333489b2009-03-27 23:10:48 +00004180
Craig Topper36250ad2014-05-12 05:36:57 +00004181 void *InsertPos = nullptr;
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00004182 DependentNameType *T
4183 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor333489b2009-03-27 23:10:48 +00004184 if (T)
4185 return QualType(T, 0);
4186
Benjamin Kramer8adeef92015-04-02 16:19:54 +00004187 T = new (*this, TypeAlignment) DependentNameType(Keyword, NNS, Name, Canon);
Douglas Gregor333489b2009-03-27 23:10:48 +00004188 Types.push_back(T);
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00004189 DependentNameTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00004190 return QualType(T, 0);
Douglas Gregor333489b2009-03-27 23:10:48 +00004191}
4192
Mike Stump11289f42009-09-09 15:08:12 +00004193QualType
John McCallc392f372010-06-11 00:33:02 +00004194ASTContext::getDependentTemplateSpecializationType(
4195 ElaboratedTypeKeyword Keyword,
Douglas Gregor02085352010-03-31 20:19:30 +00004196 NestedNameSpecifier *NNS,
John McCallc392f372010-06-11 00:33:02 +00004197 const IdentifierInfo *Name,
Jay Foad39c79802011-01-12 09:06:06 +00004198 const TemplateArgumentListInfo &Args) const {
John McCallc392f372010-06-11 00:33:02 +00004199 // TODO: avoid this copy
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004200 SmallVector<TemplateArgument, 16> ArgCopy;
John McCallc392f372010-06-11 00:33:02 +00004201 for (unsigned I = 0, E = Args.size(); I != E; ++I)
4202 ArgCopy.push_back(Args[I].getArgument());
David Majnemer6fbeee32016-07-07 04:43:07 +00004203 return getDependentTemplateSpecializationType(Keyword, NNS, Name, ArgCopy);
John McCallc392f372010-06-11 00:33:02 +00004204}
4205
4206QualType
4207ASTContext::getDependentTemplateSpecializationType(
4208 ElaboratedTypeKeyword Keyword,
4209 NestedNameSpecifier *NNS,
4210 const IdentifierInfo *Name,
David Majnemer6fbeee32016-07-07 04:43:07 +00004211 ArrayRef<TemplateArgument> Args) const {
Fangrui Song6907ce22018-07-30 19:24:48 +00004212 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor6e068012011-02-28 00:04:36 +00004213 "nested-name-specifier must be dependent");
Douglas Gregordce2b622009-04-01 00:28:59 +00004214
Douglas Gregorc42075a2010-02-04 18:10:26 +00004215 llvm::FoldingSetNodeID ID;
John McCallc392f372010-06-11 00:33:02 +00004216 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
David Majnemer6fbeee32016-07-07 04:43:07 +00004217 Name, Args);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004218
Craig Topper36250ad2014-05-12 05:36:57 +00004219 void *InsertPos = nullptr;
John McCallc392f372010-06-11 00:33:02 +00004220 DependentTemplateSpecializationType *T
4221 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004222 if (T)
4223 return QualType(T, 0);
4224
John McCallc392f372010-06-11 00:33:02 +00004225 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
Douglas Gregorc42075a2010-02-04 18:10:26 +00004226
John McCallc392f372010-06-11 00:33:02 +00004227 ElaboratedTypeKeyword CanonKeyword = Keyword;
4228 if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
4229
4230 bool AnyNonCanonArgs = false;
David Majnemer6fbeee32016-07-07 04:43:07 +00004231 unsigned NumArgs = Args.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004232 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
John McCallc392f372010-06-11 00:33:02 +00004233 for (unsigned I = 0; I != NumArgs; ++I) {
4234 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
4235 if (!CanonArgs[I].structurallyEquals(Args[I]))
4236 AnyNonCanonArgs = true;
Douglas Gregordce2b622009-04-01 00:28:59 +00004237 }
4238
John McCallc392f372010-06-11 00:33:02 +00004239 QualType Canon;
4240 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
4241 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
David Majnemer6fbeee32016-07-07 04:43:07 +00004242 Name,
4243 CanonArgs);
John McCallc392f372010-06-11 00:33:02 +00004244
4245 // Find the insert position again.
4246 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
4247 }
4248
4249 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
4250 sizeof(TemplateArgument) * NumArgs),
4251 TypeAlignment);
John McCall773cc982010-06-11 11:07:21 +00004252 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
David Majnemer6fbeee32016-07-07 04:43:07 +00004253 Name, Args, Canon);
Douglas Gregordce2b622009-04-01 00:28:59 +00004254 Types.push_back(T);
John McCallc392f372010-06-11 00:33:02 +00004255 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00004256 return QualType(T, 0);
Douglas Gregordce2b622009-04-01 00:28:59 +00004257}
4258
Richard Smith32918772017-02-14 00:25:28 +00004259TemplateArgument ASTContext::getInjectedTemplateArg(NamedDecl *Param) {
4260 TemplateArgument Arg;
Eugene Zelenko7855e772018-04-03 00:11:50 +00004261 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
Richard Smith32918772017-02-14 00:25:28 +00004262 QualType ArgType = getTypeDeclType(TTP);
4263 if (TTP->isParameterPack())
4264 ArgType = getPackExpansionType(ArgType, None);
4265
4266 Arg = TemplateArgument(ArgType);
4267 } else if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
4268 Expr *E = new (*this) DeclRefExpr(
4269 NTTP, /*enclosing*/false,
4270 NTTP->getType().getNonLValueExprType(*this),
4271 Expr::getValueKindForType(NTTP->getType()), NTTP->getLocation());
4272
4273 if (NTTP->isParameterPack())
4274 E = new (*this) PackExpansionExpr(DependentTy, E, NTTP->getLocation(),
4275 None);
4276 Arg = TemplateArgument(E);
4277 } else {
4278 auto *TTP = cast<TemplateTemplateParmDecl>(Param);
4279 if (TTP->isParameterPack())
4280 Arg = TemplateArgument(TemplateName(TTP), Optional<unsigned>());
4281 else
4282 Arg = TemplateArgument(TemplateName(TTP));
4283 }
4284
4285 if (Param->isTemplateParameterPack())
4286 Arg = TemplateArgument::CreatePackCopy(*this, Arg);
4287
4288 return Arg;
4289}
4290
Richard Smith43e14d22016-12-23 02:10:11 +00004291void
4292ASTContext::getInjectedTemplateArgs(const TemplateParameterList *Params,
4293 SmallVectorImpl<TemplateArgument> &Args) {
4294 Args.reserve(Args.size() + Params->size());
4295
Richard Smith32918772017-02-14 00:25:28 +00004296 for (NamedDecl *Param : *Params)
4297 Args.push_back(getInjectedTemplateArg(Param));
Richard Smith43e14d22016-12-23 02:10:11 +00004298}
4299
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00004300QualType ASTContext::getPackExpansionType(QualType Pattern,
David Blaikie05785d12013-02-20 22:23:23 +00004301 Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +00004302 llvm::FoldingSetNodeID ID;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00004303 PackExpansionType::Profile(ID, Pattern, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00004304
4305 assert(Pattern->containsUnexpandedParameterPack() &&
4306 "Pack expansions must expand one or more parameter packs");
Craig Topper36250ad2014-05-12 05:36:57 +00004307 void *InsertPos = nullptr;
Douglas Gregord2fa7662010-12-20 02:24:11 +00004308 PackExpansionType *T
4309 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
4310 if (T)
4311 return QualType(T, 0);
4312
4313 QualType Canon;
4314 if (!Pattern.isCanonical()) {
Richard Smith68eea502012-07-16 00:20:35 +00004315 Canon = getCanonicalType(Pattern);
4316 // The canonical type might not contain an unexpanded parameter pack, if it
4317 // contains an alias template specialization which ignores one of its
4318 // parameters.
4319 if (Canon->containsUnexpandedParameterPack()) {
Richard Smith8b4e1e22014-07-10 01:20:17 +00004320 Canon = getPackExpansionType(Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00004321
Richard Smith68eea502012-07-16 00:20:35 +00004322 // Find the insert position again, in case we inserted an element into
4323 // PackExpansionTypes and invalidated our insert position.
4324 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
4325 }
Douglas Gregord2fa7662010-12-20 02:24:11 +00004326 }
4327
Benjamin Kramer8adeef92015-04-02 16:19:54 +00004328 T = new (*this, TypeAlignment)
4329 PackExpansionType(Pattern, Canon, NumExpansions);
Douglas Gregord2fa7662010-12-20 02:24:11 +00004330 Types.push_back(T);
4331 PackExpansionTypes.InsertNode(T, InsertPos);
Richard Smith8b4e1e22014-07-10 01:20:17 +00004332 return QualType(T, 0);
Douglas Gregord2fa7662010-12-20 02:24:11 +00004333}
4334
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004335/// CmpProtocolNames - Comparison predicate for sorting protocols
4336/// alphabetically.
Benjamin Kramer0eb262f2015-03-14 13:32:49 +00004337static int CmpProtocolNames(ObjCProtocolDecl *const *LHS,
4338 ObjCProtocolDecl *const *RHS) {
4339 return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName());
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004340}
4341
Craig Topper1f26d5b2016-01-03 19:43:23 +00004342static bool areSortedAndUniqued(ArrayRef<ObjCProtocolDecl *> Protocols) {
4343 if (Protocols.empty()) return true;
John McCallfc93cf92009-10-22 22:37:11 +00004344
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00004345 if (Protocols[0]->getCanonicalDecl() != Protocols[0])
4346 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00004347
Craig Topper1f26d5b2016-01-03 19:43:23 +00004348 for (unsigned i = 1; i != Protocols.size(); ++i)
Benjamin Kramer0eb262f2015-03-14 13:32:49 +00004349 if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 ||
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00004350 Protocols[i]->getCanonicalDecl() != Protocols[i])
John McCallfc93cf92009-10-22 22:37:11 +00004351 return false;
4352 return true;
4353}
4354
Craig Topper6a8c1512015-10-22 01:56:18 +00004355static void
4356SortAndUniqueProtocols(SmallVectorImpl<ObjCProtocolDecl *> &Protocols) {
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004357 // Sort protocols, keyed by name.
Craig Topper6a8c1512015-10-22 01:56:18 +00004358 llvm::array_pod_sort(Protocols.begin(), Protocols.end(), CmpProtocolNames);
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004359
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00004360 // Canonicalize.
Craig Topper6a8c1512015-10-22 01:56:18 +00004361 for (ObjCProtocolDecl *&P : Protocols)
4362 P = P->getCanonicalDecl();
4363
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004364 // Remove duplicates.
Craig Topper6a8c1512015-10-22 01:56:18 +00004365 auto ProtocolsEnd = std::unique(Protocols.begin(), Protocols.end());
4366 Protocols.erase(ProtocolsEnd, Protocols.end());
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004367}
4368
John McCall8b07ec22010-05-15 11:32:37 +00004369QualType ASTContext::getObjCObjectType(QualType BaseType,
4370 ObjCProtocolDecl * const *Protocols,
Jay Foad39c79802011-01-12 09:06:06 +00004371 unsigned NumProtocols) const {
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00004372 return getObjCObjectType(BaseType, {},
Douglas Gregorab209d82015-07-07 03:58:42 +00004373 llvm::makeArrayRef(Protocols, NumProtocols),
4374 /*isKindOf=*/false);
Douglas Gregore9d95f12015-07-07 03:57:35 +00004375}
4376
4377QualType ASTContext::getObjCObjectType(
4378 QualType baseType,
4379 ArrayRef<QualType> typeArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00004380 ArrayRef<ObjCProtocolDecl *> protocols,
4381 bool isKindOf) const {
Douglas Gregore9d95f12015-07-07 03:57:35 +00004382 // If the base type is an interface and there aren't any protocols or
4383 // type arguments to add, then the interface type will do just fine.
Douglas Gregorab209d82015-07-07 03:58:42 +00004384 if (typeArgs.empty() && protocols.empty() && !isKindOf &&
4385 isa<ObjCInterfaceType>(baseType))
Douglas Gregore9d95f12015-07-07 03:57:35 +00004386 return baseType;
John McCall8b07ec22010-05-15 11:32:37 +00004387
4388 // Look in the folding set for an existing type.
Steve Narofffb4330f2009-06-17 22:40:22 +00004389 llvm::FoldingSetNodeID ID;
Douglas Gregorab209d82015-07-07 03:58:42 +00004390 ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols, isKindOf);
Craig Topper36250ad2014-05-12 05:36:57 +00004391 void *InsertPos = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00004392 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
4393 return QualType(QT, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00004394
Douglas Gregore9d95f12015-07-07 03:57:35 +00004395 // Determine the type arguments to be used for canonicalization,
4396 // which may be explicitly specified here or written on the base
4397 // type.
4398 ArrayRef<QualType> effectiveTypeArgs = typeArgs;
4399 if (effectiveTypeArgs.empty()) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00004400 if (const auto *baseObject = baseType->getAs<ObjCObjectType>())
Douglas Gregore9d95f12015-07-07 03:57:35 +00004401 effectiveTypeArgs = baseObject->getTypeArgs();
4402 }
John McCallfc93cf92009-10-22 22:37:11 +00004403
Douglas Gregore9d95f12015-07-07 03:57:35 +00004404 // Build the canonical type, which has the canonical base type and a
4405 // sorted-and-uniqued list of protocols and the type arguments
4406 // canonicalized.
4407 QualType canonical;
4408 bool typeArgsAreCanonical = std::all_of(effectiveTypeArgs.begin(),
4409 effectiveTypeArgs.end(),
4410 [&](QualType type) {
4411 return type.isCanonical();
4412 });
Craig Topper1f26d5b2016-01-03 19:43:23 +00004413 bool protocolsSorted = areSortedAndUniqued(protocols);
Douglas Gregore9d95f12015-07-07 03:57:35 +00004414 if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) {
4415 // Determine the canonical type arguments.
4416 ArrayRef<QualType> canonTypeArgs;
4417 SmallVector<QualType, 4> canonTypeArgsVec;
4418 if (!typeArgsAreCanonical) {
4419 canonTypeArgsVec.reserve(effectiveTypeArgs.size());
4420 for (auto typeArg : effectiveTypeArgs)
4421 canonTypeArgsVec.push_back(getCanonicalType(typeArg));
4422 canonTypeArgs = canonTypeArgsVec;
John McCallfc93cf92009-10-22 22:37:11 +00004423 } else {
Douglas Gregore9d95f12015-07-07 03:57:35 +00004424 canonTypeArgs = effectiveTypeArgs;
John McCallfc93cf92009-10-22 22:37:11 +00004425 }
4426
Douglas Gregore9d95f12015-07-07 03:57:35 +00004427 ArrayRef<ObjCProtocolDecl *> canonProtocols;
4428 SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec;
4429 if (!protocolsSorted) {
Craig Topper6a8c1512015-10-22 01:56:18 +00004430 canonProtocolsVec.append(protocols.begin(), protocols.end());
4431 SortAndUniqueProtocols(canonProtocolsVec);
4432 canonProtocols = canonProtocolsVec;
Douglas Gregore9d95f12015-07-07 03:57:35 +00004433 } else {
4434 canonProtocols = protocols;
4435 }
4436
4437 canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00004438 canonProtocols, isKindOf);
Douglas Gregore9d95f12015-07-07 03:57:35 +00004439
John McCallfc93cf92009-10-22 22:37:11 +00004440 // Regenerate InsertPos.
John McCall8b07ec22010-05-15 11:32:37 +00004441 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
4442 }
4443
Douglas Gregore9d95f12015-07-07 03:57:35 +00004444 unsigned size = sizeof(ObjCObjectTypeImpl);
4445 size += typeArgs.size() * sizeof(QualType);
4446 size += protocols.size() * sizeof(ObjCProtocolDecl *);
4447 void *mem = Allocate(size, TypeAlignment);
Eugene Zelenko7855e772018-04-03 00:11:50 +00004448 auto *T =
Douglas Gregorab209d82015-07-07 03:58:42 +00004449 new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols,
4450 isKindOf);
John McCall8b07ec22010-05-15 11:32:37 +00004451
4452 Types.push_back(T);
4453 ObjCObjectTypes.InsertNode(T, InsertPos);
4454 return QualType(T, 0);
4455}
4456
Manman Ren3569eb52016-09-13 17:03:12 +00004457/// Apply Objective-C protocol qualifiers to the given type.
4458/// If this is for the canonical type of a type parameter, we can apply
4459/// protocol qualifiers on the ObjCObjectPointerType.
4460QualType
4461ASTContext::applyObjCProtocolQualifiers(QualType type,
4462 ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError,
4463 bool allowOnPointerType) const {
4464 hasError = false;
4465
Eugene Zelenko7855e772018-04-03 00:11:50 +00004466 if (const auto *objT = dyn_cast<ObjCTypeParamType>(type.getTypePtr())) {
Manman Renc5705ba2016-09-13 17:41:05 +00004467 return getObjCTypeParamType(objT->getDecl(), protocols);
4468 }
4469
Manman Ren3569eb52016-09-13 17:03:12 +00004470 // Apply protocol qualifiers to ObjCObjectPointerType.
4471 if (allowOnPointerType) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00004472 if (const auto *objPtr =
4473 dyn_cast<ObjCObjectPointerType>(type.getTypePtr())) {
Manman Ren3569eb52016-09-13 17:03:12 +00004474 const ObjCObjectType *objT = objPtr->getObjectType();
4475 // Merge protocol lists and construct ObjCObjectType.
4476 SmallVector<ObjCProtocolDecl*, 8> protocolsVec;
4477 protocolsVec.append(objT->qual_begin(),
4478 objT->qual_end());
4479 protocolsVec.append(protocols.begin(), protocols.end());
4480 ArrayRef<ObjCProtocolDecl *> protocols = protocolsVec;
4481 type = getObjCObjectType(
4482 objT->getBaseType(),
4483 objT->getTypeArgsAsWritten(),
4484 protocols,
4485 objT->isKindOfTypeAsWritten());
4486 return getObjCObjectPointerType(type);
4487 }
4488 }
4489
4490 // Apply protocol qualifiers to ObjCObjectType.
Eugene Zelenko7855e772018-04-03 00:11:50 +00004491 if (const auto *objT = dyn_cast<ObjCObjectType>(type.getTypePtr())){
Manman Ren3569eb52016-09-13 17:03:12 +00004492 // FIXME: Check for protocols to which the class type is already
4493 // known to conform.
4494
4495 return getObjCObjectType(objT->getBaseType(),
4496 objT->getTypeArgsAsWritten(),
4497 protocols,
4498 objT->isKindOfTypeAsWritten());
4499 }
4500
4501 // If the canonical type is ObjCObjectType, ...
4502 if (type->isObjCObjectType()) {
4503 // Silently overwrite any existing protocol qualifiers.
4504 // TODO: determine whether that's the right thing to do.
4505
4506 // FIXME: Check for protocols to which the class type is already
4507 // known to conform.
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00004508 return getObjCObjectType(type, {}, protocols, false);
Manman Ren3569eb52016-09-13 17:03:12 +00004509 }
4510
4511 // id<protocol-list>
4512 if (type->isObjCIdType()) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00004513 const auto *objPtr = type->castAs<ObjCObjectPointerType>();
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00004514 type = getObjCObjectType(ObjCBuiltinIdTy, {}, protocols,
Manman Ren3569eb52016-09-13 17:03:12 +00004515 objPtr->isKindOfType());
4516 return getObjCObjectPointerType(type);
4517 }
4518
4519 // Class<protocol-list>
4520 if (type->isObjCClassType()) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00004521 const auto *objPtr = type->castAs<ObjCObjectPointerType>();
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00004522 type = getObjCObjectType(ObjCBuiltinClassTy, {}, protocols,
Manman Ren3569eb52016-09-13 17:03:12 +00004523 objPtr->isKindOfType());
4524 return getObjCObjectPointerType(type);
4525 }
4526
4527 hasError = true;
4528 return type;
4529}
4530
Manman Rene6be26c2016-09-13 17:25:08 +00004531QualType
4532ASTContext::getObjCTypeParamType(const ObjCTypeParamDecl *Decl,
4533 ArrayRef<ObjCProtocolDecl *> protocols,
4534 QualType Canonical) const {
4535 // Look in the folding set for an existing type.
4536 llvm::FoldingSetNodeID ID;
4537 ObjCTypeParamType::Profile(ID, Decl, protocols);
4538 void *InsertPos = nullptr;
4539 if (ObjCTypeParamType *TypeParam =
4540 ObjCTypeParamTypes.FindNodeOrInsertPos(ID, InsertPos))
4541 return QualType(TypeParam, 0);
4542
4543 if (Canonical.isNull()) {
4544 // We canonicalize to the underlying type.
4545 Canonical = getCanonicalType(Decl->getUnderlyingType());
4546 if (!protocols.empty()) {
4547 // Apply the protocol qualifers.
4548 bool hasError;
Richard Trieua986a312018-08-30 01:57:52 +00004549 Canonical = getCanonicalType(applyObjCProtocolQualifiers(
4550 Canonical, protocols, hasError, true /*allowOnPointerType*/));
Manman Rene6be26c2016-09-13 17:25:08 +00004551 assert(!hasError && "Error when apply protocol qualifier to bound type");
4552 }
4553 }
4554
4555 unsigned size = sizeof(ObjCTypeParamType);
4556 size += protocols.size() * sizeof(ObjCProtocolDecl *);
4557 void *mem = Allocate(size, TypeAlignment);
Eugene Zelenko7855e772018-04-03 00:11:50 +00004558 auto *newType = new (mem) ObjCTypeParamType(Decl, Canonical, protocols);
Manman Rene6be26c2016-09-13 17:25:08 +00004559
4560 Types.push_back(newType);
4561 ObjCTypeParamTypes.InsertNode(newType, InsertPos);
4562 return QualType(newType, 0);
4563}
4564
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004565/// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
4566/// protocol list adopt all protocols in QT's qualified-id protocol
4567/// list.
4568bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT,
4569 ObjCInterfaceDecl *IC) {
4570 if (!QT->isObjCQualifiedIdType())
4571 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00004572
Eugene Zelenko7855e772018-04-03 00:11:50 +00004573 if (const auto *OPT = QT->getAs<ObjCObjectPointerType>()) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004574 // If both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00004575 for (auto *Proto : OPT->quals()) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004576 if (!IC->ClassImplementsProtocol(Proto, false))
4577 return false;
4578 }
4579 return true;
4580 }
4581 return false;
4582}
4583
4584/// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
4585/// QT's qualified-id protocol list adopt all protocols in IDecl's list
4586/// of protocols.
4587bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
4588 ObjCInterfaceDecl *IDecl) {
4589 if (!QT->isObjCQualifiedIdType())
4590 return false;
Eugene Zelenko7855e772018-04-03 00:11:50 +00004591 const auto *OPT = QT->getAs<ObjCObjectPointerType>();
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004592 if (!OPT)
4593 return false;
4594 if (!IDecl->hasDefinition())
4595 return false;
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00004596 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols;
4597 CollectInheritedProtocols(IDecl, InheritedProtocols);
4598 if (InheritedProtocols.empty())
4599 return false;
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00004600 // Check that if every protocol in list of id<plist> conforms to a protocol
Fariborz Jahanian48a01cb2014-04-04 23:53:45 +00004601 // of IDecl's, then bridge casting is ok.
4602 bool Conforms = false;
4603 for (auto *Proto : OPT->quals()) {
4604 Conforms = false;
4605 for (auto *PI : InheritedProtocols) {
4606 if (ProtocolCompatibleWithProtocol(Proto, PI)) {
4607 Conforms = true;
4608 break;
4609 }
4610 }
4611 if (!Conforms)
4612 break;
4613 }
4614 if (Conforms)
4615 return true;
Fangrui Song6907ce22018-07-30 19:24:48 +00004616
Aaron Ballman83731462014-03-17 16:14:00 +00004617 for (auto *PI : InheritedProtocols) {
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004618 // If both the right and left sides have qualifiers.
4619 bool Adopts = false;
Aaron Ballman83731462014-03-17 16:14:00 +00004620 for (auto *Proto : OPT->quals()) {
Fariborz Jahanian48a01cb2014-04-04 23:53:45 +00004621 // return 'true' if 'PI' is in the inheritance hierarchy of Proto
Aaron Ballman83731462014-03-17 16:14:00 +00004622 if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004623 break;
4624 }
4625 if (!Adopts)
Fariborz Jahanian91fb0be2013-11-20 19:01:50 +00004626 return false;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00004627 }
4628 return true;
4629}
4630
John McCall8b07ec22010-05-15 11:32:37 +00004631/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
4632/// the given object type.
Jay Foad39c79802011-01-12 09:06:06 +00004633QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
John McCall8b07ec22010-05-15 11:32:37 +00004634 llvm::FoldingSetNodeID ID;
4635 ObjCObjectPointerType::Profile(ID, ObjectT);
4636
Craig Topper36250ad2014-05-12 05:36:57 +00004637 void *InsertPos = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00004638 if (ObjCObjectPointerType *QT =
4639 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
4640 return QualType(QT, 0);
4641
4642 // Find the canonical object type.
4643 QualType Canonical;
4644 if (!ObjectT.isCanonical()) {
4645 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
4646
4647 // Regenerate InsertPos.
John McCallfc93cf92009-10-22 22:37:11 +00004648 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
4649 }
4650
Douglas Gregorf85bee62010-02-08 22:59:26 +00004651 // No match.
John McCall8b07ec22010-05-15 11:32:37 +00004652 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
Eugene Zelenko7855e772018-04-03 00:11:50 +00004653 auto *QType =
John McCall8b07ec22010-05-15 11:32:37 +00004654 new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
Mike Stump11289f42009-09-09 15:08:12 +00004655
Steve Narofffb4330f2009-06-17 22:40:22 +00004656 Types.push_back(QType);
4657 ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
John McCall8b07ec22010-05-15 11:32:37 +00004658 return QualType(QType, 0);
Steve Narofffb4330f2009-06-17 22:40:22 +00004659}
Chris Lattnere0ea37a2008-04-07 04:56:42 +00004660
Douglas Gregor1c283312010-08-11 12:19:30 +00004661/// getObjCInterfaceType - Return the unique reference to the type for the
4662/// specified ObjC interface decl. The list of protocols is optional.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00004663QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
4664 ObjCInterfaceDecl *PrevDecl) const {
Douglas Gregor1c283312010-08-11 12:19:30 +00004665 if (Decl->TypeForDecl)
4666 return QualType(Decl->TypeForDecl, 0);
Mike Stump11289f42009-09-09 15:08:12 +00004667
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00004668 if (PrevDecl) {
4669 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
4670 Decl->TypeForDecl = PrevDecl->TypeForDecl;
4671 return QualType(PrevDecl->TypeForDecl, 0);
4672 }
4673
Douglas Gregor7671e532011-12-16 16:34:57 +00004674 // Prefer the definition, if there is one.
4675 if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
4676 Decl = Def;
Fangrui Song6907ce22018-07-30 19:24:48 +00004677
Douglas Gregor1c283312010-08-11 12:19:30 +00004678 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
Eugene Zelenko7855e772018-04-03 00:11:50 +00004679 auto *T = new (Mem) ObjCInterfaceType(Decl);
Douglas Gregor1c283312010-08-11 12:19:30 +00004680 Decl->TypeForDecl = T;
4681 Types.push_back(T);
4682 return QualType(T, 0);
Fariborz Jahanian70e8f102007-10-11 00:55:41 +00004683}
4684
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004685/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
4686/// TypeOfExprType AST's (since expression's are never shared). For example,
Steve Naroffa773cd52007-08-01 18:02:17 +00004687/// multiple declarations that refer to "typeof(x)" all contain different
Mike Stump11289f42009-09-09 15:08:12 +00004688/// DeclRefExpr's. This doesn't effect the type checker, since it operates
Steve Naroffa773cd52007-08-01 18:02:17 +00004689/// on canonical type's (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00004690QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00004691 TypeOfExprType *toe;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004692 if (tofExpr->isTypeDependent()) {
4693 llvm::FoldingSetNodeID ID;
4694 DependentTypeOfExprType::Profile(ID, *this, tofExpr);
Mike Stump11289f42009-09-09 15:08:12 +00004695
Craig Topper36250ad2014-05-12 05:36:57 +00004696 void *InsertPos = nullptr;
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004697 DependentTypeOfExprType *Canon
4698 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
4699 if (Canon) {
4700 // We already have a "canonical" version of an identical, dependent
4701 // typeof(expr) type. Use that as our canonical type.
John McCall90d1c2d2009-09-24 23:30:46 +00004702 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004703 QualType((TypeOfExprType*)Canon, 0));
Chad Rosier6fdf38b2011-08-17 23:08:45 +00004704 } else {
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004705 // Build a new, canonical typeof(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00004706 Canon
4707 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
Douglas Gregora5dd9f82009-07-30 23:18:24 +00004708 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
4709 toe = Canon;
4710 }
4711 } else {
Douglas Gregorabd68132009-07-08 00:03:05 +00004712 QualType Canonical = getCanonicalType(tofExpr->getType());
John McCall90d1c2d2009-09-24 23:30:46 +00004713 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
Douglas Gregorabd68132009-07-08 00:03:05 +00004714 }
Steve Naroffa773cd52007-08-01 18:02:17 +00004715 Types.push_back(toe);
4716 return QualType(toe, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00004717}
4718
Steve Naroffa773cd52007-08-01 18:02:17 +00004719/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
Richard Smith8eb1d322014-06-05 20:13:13 +00004720/// TypeOfType nodes. The only motivation to unique these nodes would be
Steve Naroffa773cd52007-08-01 18:02:17 +00004721/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
Richard Smith8eb1d322014-06-05 20:13:13 +00004722/// an issue. This doesn't affect the type checker, since it operates
4723/// on canonical types (which are always unique).
Jay Foad39c79802011-01-12 09:06:06 +00004724QualType ASTContext::getTypeOfType(QualType tofType) const {
Chris Lattner76a00cf2008-04-06 22:59:24 +00004725 QualType Canonical = getCanonicalType(tofType);
Eugene Zelenko7855e772018-04-03 00:11:50 +00004726 auto *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
Steve Naroffa773cd52007-08-01 18:02:17 +00004727 Types.push_back(tot);
4728 return QualType(tot, 0);
Steve Naroffad373bd2007-07-31 12:34:36 +00004729}
4730
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004731/// Unlike many "get<Type>" functions, we don't unique DecltypeType
Richard Smith8eb1d322014-06-05 20:13:13 +00004732/// nodes. This would never be helpful, since each such type has its own
4733/// expression, and would not give a significant memory saving, since there
4734/// is an Expr tree under each such type.
Douglas Gregor81495f32012-02-12 18:42:33 +00004735QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
Douglas Gregorabd68132009-07-08 00:03:05 +00004736 DecltypeType *dt;
Richard Smith8eb1d322014-06-05 20:13:13 +00004737
4738 // C++11 [temp.type]p2:
Douglas Gregor678d76c2011-07-01 01:22:09 +00004739 // If an expression e involves a template parameter, decltype(e) denotes a
Richard Smith8eb1d322014-06-05 20:13:13 +00004740 // unique dependent type. Two such decltype-specifiers refer to the same
4741 // type only if their expressions are equivalent (14.5.6.1).
Douglas Gregor678d76c2011-07-01 01:22:09 +00004742 if (e->isInstantiationDependent()) {
Douglas Gregora21f6c32009-07-30 23:36:40 +00004743 llvm::FoldingSetNodeID ID;
4744 DependentDecltypeType::Profile(ID, *this, e);
Mike Stump11289f42009-09-09 15:08:12 +00004745
Craig Topper36250ad2014-05-12 05:36:57 +00004746 void *InsertPos = nullptr;
Douglas Gregora21f6c32009-07-30 23:36:40 +00004747 DependentDecltypeType *Canon
4748 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
Richard Smith8eb1d322014-06-05 20:13:13 +00004749 if (!Canon) {
Yaron Keren633e14a2016-11-29 10:08:20 +00004750 // Build a new, canonical decltype(expr) type.
John McCall90d1c2d2009-09-24 23:30:46 +00004751 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
Douglas Gregora21f6c32009-07-30 23:36:40 +00004752 DependentDecltypeTypes.InsertNode(Canon, InsertPos);
Douglas Gregora21f6c32009-07-30 23:36:40 +00004753 }
Richard Smith8eb1d322014-06-05 20:13:13 +00004754 dt = new (*this, TypeAlignment)
4755 DecltypeType(e, UnderlyingType, QualType((DecltypeType *)Canon, 0));
Douglas Gregora21f6c32009-07-30 23:36:40 +00004756 } else {
Richard Smith8eb1d322014-06-05 20:13:13 +00004757 dt = new (*this, TypeAlignment)
4758 DecltypeType(e, UnderlyingType, getCanonicalType(UnderlyingType));
Douglas Gregorabd68132009-07-08 00:03:05 +00004759 }
Anders Carlsson81df7b82009-06-24 19:06:50 +00004760 Types.push_back(dt);
4761 return QualType(dt, 0);
4762}
4763
Alexis Hunte852b102011-05-24 22:41:36 +00004764/// getUnaryTransformationType - We don't unique these, since the memory
4765/// savings are minimal and these are rare.
4766QualType ASTContext::getUnaryTransformType(QualType BaseType,
4767 QualType UnderlyingType,
4768 UnaryTransformType::UTTKind Kind)
4769 const {
Vassil Vassilevbab6f962016-03-30 22:18:29 +00004770 UnaryTransformType *ut = nullptr;
4771
4772 if (BaseType->isDependentType()) {
4773 // Look in the folding set for an existing type.
4774 llvm::FoldingSetNodeID ID;
4775 DependentUnaryTransformType::Profile(ID, getCanonicalType(BaseType), Kind);
4776
4777 void *InsertPos = nullptr;
4778 DependentUnaryTransformType *Canon
4779 = DependentUnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos);
4780
4781 if (!Canon) {
4782 // Build a new, canonical __underlying_type(type) type.
4783 Canon = new (*this, TypeAlignment)
4784 DependentUnaryTransformType(*this, getCanonicalType(BaseType),
4785 Kind);
4786 DependentUnaryTransformTypes.InsertNode(Canon, InsertPos);
4787 }
4788 ut = new (*this, TypeAlignment) UnaryTransformType (BaseType,
4789 QualType(), Kind,
4790 QualType(Canon, 0));
4791 } else {
4792 QualType CanonType = getCanonicalType(UnderlyingType);
4793 ut = new (*this, TypeAlignment) UnaryTransformType (BaseType,
4794 UnderlyingType, Kind,
4795 CanonType);
4796 }
4797 Types.push_back(ut);
4798 return QualType(ut, 0);
Alexis Hunte852b102011-05-24 22:41:36 +00004799}
4800
Richard Smith2a7d4812013-05-04 07:00:32 +00004801/// getAutoType - Return the uniqued reference to the 'auto' type which has been
4802/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
4803/// canonical deduced-but-dependent 'auto' type.
Richard Smithe301ba22015-11-11 02:02:15 +00004804QualType ASTContext::getAutoType(QualType DeducedType, AutoTypeKeyword Keyword,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00004805 bool IsDependent) const {
Richard Smithe301ba22015-11-11 02:02:15 +00004806 if (DeducedType.isNull() && Keyword == AutoTypeKeyword::Auto && !IsDependent)
Richard Smith2a7d4812013-05-04 07:00:32 +00004807 return getAutoDeductType();
Manuel Klimek2fdbea22013-08-22 12:12:24 +00004808
Richard Smith2a7d4812013-05-04 07:00:32 +00004809 // Look in the folding set for an existing type.
Craig Topper36250ad2014-05-12 05:36:57 +00004810 void *InsertPos = nullptr;
Richard Smith2a7d4812013-05-04 07:00:32 +00004811 llvm::FoldingSetNodeID ID;
Richard Smithe301ba22015-11-11 02:02:15 +00004812 AutoType::Profile(ID, DeducedType, Keyword, IsDependent);
Richard Smith2a7d4812013-05-04 07:00:32 +00004813 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
4814 return QualType(AT, 0);
Richard Smithb2bc2e62011-02-21 20:05:19 +00004815
Eugene Zelenko7855e772018-04-03 00:11:50 +00004816 auto *AT = new (*this, TypeAlignment)
4817 AutoType(DeducedType, Keyword, IsDependent);
Richard Smithb2bc2e62011-02-21 20:05:19 +00004818 Types.push_back(AT);
4819 if (InsertPos)
4820 AutoTypes.InsertNode(AT, InsertPos);
4821 return QualType(AT, 0);
Richard Smith30482bc2011-02-20 03:19:35 +00004822}
4823
Richard Smith600b5262017-01-26 20:40:47 +00004824/// Return the uniqued reference to the deduced template specialization type
4825/// which has been deduced to the given type, or to the canonical undeduced
4826/// such type, or the canonical deduced-but-dependent such type.
4827QualType ASTContext::getDeducedTemplateSpecializationType(
4828 TemplateName Template, QualType DeducedType, bool IsDependent) const {
4829 // Look in the folding set for an existing type.
4830 void *InsertPos = nullptr;
4831 llvm::FoldingSetNodeID ID;
4832 DeducedTemplateSpecializationType::Profile(ID, Template, DeducedType,
4833 IsDependent);
4834 if (DeducedTemplateSpecializationType *DTST =
4835 DeducedTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos))
4836 return QualType(DTST, 0);
4837
Eugene Zelenko7855e772018-04-03 00:11:50 +00004838 auto *DTST = new (*this, TypeAlignment)
Richard Smith600b5262017-01-26 20:40:47 +00004839 DeducedTemplateSpecializationType(Template, DeducedType, IsDependent);
4840 Types.push_back(DTST);
4841 if (InsertPos)
4842 DeducedTemplateSpecializationTypes.InsertNode(DTST, InsertPos);
4843 return QualType(DTST, 0);
4844}
4845
Eli Friedman0dfb8892011-10-06 23:00:33 +00004846/// getAtomicType - Return the uniqued reference to the atomic type for
4847/// the given value type.
4848QualType ASTContext::getAtomicType(QualType T) const {
4849 // Unique pointers, to guarantee there is only one pointer of a particular
4850 // structure.
4851 llvm::FoldingSetNodeID ID;
4852 AtomicType::Profile(ID, T);
4853
Craig Topper36250ad2014-05-12 05:36:57 +00004854 void *InsertPos = nullptr;
Eli Friedman0dfb8892011-10-06 23:00:33 +00004855 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
4856 return QualType(AT, 0);
4857
4858 // If the atomic value type isn't canonical, this won't be a canonical type
4859 // either, so fill in the canonical type field.
4860 QualType Canonical;
4861 if (!T.isCanonical()) {
4862 Canonical = getAtomicType(getCanonicalType(T));
4863
4864 // Get the new insert position for the node we care about.
4865 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
Craig Topper36250ad2014-05-12 05:36:57 +00004866 assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
Eli Friedman0dfb8892011-10-06 23:00:33 +00004867 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00004868 auto *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
Eli Friedman0dfb8892011-10-06 23:00:33 +00004869 Types.push_back(New);
4870 AtomicTypes.InsertNode(New, InsertPos);
4871 return QualType(New, 0);
4872}
4873
Richard Smith02e85f32011-04-14 22:09:26 +00004874/// getAutoDeductType - Get type pattern for deducing against 'auto'.
4875QualType ASTContext::getAutoDeductType() const {
4876 if (AutoDeductTy.isNull())
Richard Smith2a7d4812013-05-04 07:00:32 +00004877 AutoDeductTy = QualType(
Richard Smithe301ba22015-11-11 02:02:15 +00004878 new (*this, TypeAlignment) AutoType(QualType(), AutoTypeKeyword::Auto,
Manuel Klimek2fdbea22013-08-22 12:12:24 +00004879 /*dependent*/false),
Richard Smith2a7d4812013-05-04 07:00:32 +00004880 0);
Richard Smith02e85f32011-04-14 22:09:26 +00004881 return AutoDeductTy;
4882}
4883
4884/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
4885QualType ASTContext::getAutoRRefDeductType() const {
4886 if (AutoRRefDeductTy.isNull())
4887 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
4888 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
4889 return AutoRRefDeductTy;
4890}
4891
Chris Lattnerfb072462007-01-23 05:45:31 +00004892/// getTagDeclType - Return the unique reference to the type for the
4893/// specified TagDecl (struct/union/class/enum) decl.
Jay Foad39c79802011-01-12 09:06:06 +00004894QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00004895 assert(Decl);
Mike Stumpb93185d2009-08-07 18:05:12 +00004896 // FIXME: What is the design on getTagDeclType when it requires casting
4897 // away const? mutable?
4898 return getTypeDeclType(const_cast<TagDecl*>(Decl));
Chris Lattnerfb072462007-01-23 05:45:31 +00004899}
4900
Mike Stump11289f42009-09-09 15:08:12 +00004901/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
4902/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
4903/// needs to agree with the definition in <stddef.h>.
Anders Carlsson22f443f2009-12-12 00:26:23 +00004904CanQualType ASTContext::getSizeType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00004905 return getFromTargetType(Target->getSizeType());
Steve Naroff92e30f82007-04-02 22:35:25 +00004906}
Chris Lattnerfb072462007-01-23 05:45:31 +00004907
Fangrui Song6907ce22018-07-30 19:24:48 +00004908/// Return the unique signed counterpart of the integer type
Alexander Shaposhnikov1e898d92017-07-14 17:30:14 +00004909/// corresponding to size_t.
4910CanQualType ASTContext::getSignedSizeType() const {
4911 return getFromTargetType(Target->getSignedSizeType());
4912}
4913
Hans Wennborg27541db2011-10-27 08:29:09 +00004914/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
4915CanQualType ASTContext::getIntMaxType() const {
4916 return getFromTargetType(Target->getIntMaxType());
4917}
4918
4919/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
4920CanQualType ASTContext::getUIntMaxType() const {
4921 return getFromTargetType(Target->getUIntMaxType());
4922}
4923
Argyrios Kyrtzidis40e9e482008-08-09 16:51:54 +00004924/// getSignedWCharType - Return the type of "signed wchar_t".
4925/// Used when in C++, as a GCC extension.
4926QualType ASTContext::getSignedWCharType() const {
4927 // FIXME: derive from "Target" ?
4928 return WCharTy;
4929}
4930
4931/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
4932/// Used when in C++, as a GCC extension.
4933QualType ASTContext::getUnsignedWCharType() const {
4934 // FIXME: derive from "Target" ?
4935 return UnsignedIntTy;
4936}
4937
Enea Zaffanellaf11ceb62013-01-26 17:08:37 +00004938QualType ASTContext::getIntPtrType() const {
4939 return getFromTargetType(Target->getIntPtrType());
4940}
4941
4942QualType ASTContext::getUIntPtrType() const {
4943 return getCorrespondingUnsignedType(getIntPtrType());
4944}
4945
Hans Wennborg27541db2011-10-27 08:29:09 +00004946/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00004947/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
4948QualType ASTContext::getPointerDiffType() const {
Douglas Gregore8bbc122011-09-02 00:18:52 +00004949 return getFromTargetType(Target->getPtrDiffType(0));
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00004950}
4951
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004952/// Return the unique unsigned counterpart of "ptrdiff_t"
Alexander Shaposhnikov195b25c2017-09-28 23:11:31 +00004953/// integer type. The standard (C11 7.21.6.1p7) refers to this type
4954/// in the definition of %tu format specifier.
4955QualType ASTContext::getUnsignedPointerDiffType() const {
4956 return getFromTargetType(Target->getUnsignedPtrDiffType(0));
4957}
4958
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004959/// Return the unique type for "pid_t" defined in
Eli Friedman4e91899e2012-11-27 02:58:24 +00004960/// <sys/types.h>. We need this to compute the correct type for vfork().
4961QualType ASTContext::getProcessIDType() const {
4962 return getFromTargetType(Target->getProcessIDType());
4963}
4964
Chris Lattnera21ad802008-04-02 05:18:44 +00004965//===----------------------------------------------------------------------===//
4966// Type Operators
4967//===----------------------------------------------------------------------===//
4968
Jay Foad39c79802011-01-12 09:06:06 +00004969CanQualType ASTContext::getCanonicalParamType(QualType T) const {
John McCallfc93cf92009-10-22 22:37:11 +00004970 // Push qualifiers into arrays, and then discard any remaining
4971 // qualifiers.
4972 T = getCanonicalType(T);
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00004973 T = getVariableArrayDecayedType(T);
John McCallfc93cf92009-10-22 22:37:11 +00004974 const Type *Ty = T.getTypePtr();
John McCallfc93cf92009-10-22 22:37:11 +00004975 QualType Result;
4976 if (isa<ArrayType>(Ty)) {
4977 Result = getArrayDecayedType(QualType(Ty,0));
4978 } else if (isa<FunctionType>(Ty)) {
4979 Result = getPointerType(QualType(Ty, 0));
4980 } else {
4981 Result = QualType(Ty, 0);
4982 }
4983
4984 return CanQualType::CreateUnsafe(Result);
4985}
4986
John McCall6c9dd522011-01-18 07:41:22 +00004987QualType ASTContext::getUnqualifiedArrayType(QualType type,
4988 Qualifiers &quals) {
4989 SplitQualType splitType = type.getSplitUnqualifiedType();
4990
4991 // FIXME: getSplitUnqualifiedType() actually walks all the way to
4992 // the unqualified desugared type and then drops it on the floor.
4993 // We then have to strip that sugar back off with
4994 // getUnqualifiedDesugaredType(), which is silly.
Eugene Zelenko7855e772018-04-03 00:11:50 +00004995 const auto *AT =
4996 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
John McCall6c9dd522011-01-18 07:41:22 +00004997
4998 // If we don't have an array, just use the results in splitType.
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00004999 if (!AT) {
John McCall18ce25e2012-02-08 00:46:36 +00005000 quals = splitType.Quals;
5001 return QualType(splitType.Ty, 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00005002 }
5003
John McCall6c9dd522011-01-18 07:41:22 +00005004 // Otherwise, recurse on the array's element type.
5005 QualType elementType = AT->getElementType();
5006 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
5007
5008 // If that didn't change the element type, AT has no qualifiers, so we
5009 // can just use the results in splitType.
5010 if (elementType == unqualElementType) {
5011 assert(quals.empty()); // from the recursive call
John McCall18ce25e2012-02-08 00:46:36 +00005012 quals = splitType.Quals;
5013 return QualType(splitType.Ty, 0);
John McCall6c9dd522011-01-18 07:41:22 +00005014 }
5015
5016 // Otherwise, add in the qualifiers from the outermost type, then
5017 // build the type back up.
John McCall18ce25e2012-02-08 00:46:36 +00005018 quals.addConsistentQualifiers(splitType.Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00005019
Eugene Zelenko7855e772018-04-03 00:11:50 +00005020 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00005021 return getConstantArrayType(unqualElementType, CAT->getSize(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00005022 CAT->getSizeModifier(), 0);
5023 }
5024
Eugene Zelenko7855e772018-04-03 00:11:50 +00005025 if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00005026 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
Chandler Carruth607f38e2009-12-29 07:16:59 +00005027 }
5028
Eugene Zelenko7855e772018-04-03 00:11:50 +00005029 if (const auto *VAT = dyn_cast<VariableArrayType>(AT)) {
John McCall6c9dd522011-01-18 07:41:22 +00005030 return getVariableArrayType(unqualElementType,
John McCallc3007a22010-10-26 07:05:15 +00005031 VAT->getSizeExpr(),
Douglas Gregor3b05bdb2010-05-17 18:45:21 +00005032 VAT->getSizeModifier(),
5033 VAT->getIndexTypeCVRQualifiers(),
5034 VAT->getBracketsRange());
5035 }
5036
Eugene Zelenko7855e772018-04-03 00:11:50 +00005037 const auto *DSAT = cast<DependentSizedArrayType>(AT);
John McCall6c9dd522011-01-18 07:41:22 +00005038 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
Chandler Carruth607f38e2009-12-29 07:16:59 +00005039 DSAT->getSizeModifier(), 0,
5040 SourceRange());
5041}
5042
Richard Smitha3405ff2018-07-11 00:19:19 +00005043/// Attempt to unwrap two types that may both be array types with the same bound
5044/// (or both be array types of unknown bound) for the purpose of comparing the
5045/// cv-decomposition of two types per C++ [conv.qual].
Richard Smith5407d4f2018-07-18 20:13:36 +00005046bool ASTContext::UnwrapSimilarArrayTypes(QualType &T1, QualType &T2) {
5047 bool UnwrappedAny = false;
Richard Smitha3405ff2018-07-11 00:19:19 +00005048 while (true) {
Richard Smith5407d4f2018-07-18 20:13:36 +00005049 auto *AT1 = getAsArrayType(T1);
5050 if (!AT1) return UnwrappedAny;
Richard Smitha3405ff2018-07-11 00:19:19 +00005051
Richard Smith5407d4f2018-07-18 20:13:36 +00005052 auto *AT2 = getAsArrayType(T2);
5053 if (!AT2) return UnwrappedAny;
Richard Smitha3405ff2018-07-11 00:19:19 +00005054
5055 // If we don't have two array types with the same constant bound nor two
5056 // incomplete array types, we've unwrapped everything we can.
5057 if (auto *CAT1 = dyn_cast<ConstantArrayType>(AT1)) {
5058 auto *CAT2 = dyn_cast<ConstantArrayType>(AT2);
5059 if (!CAT2 || CAT1->getSize() != CAT2->getSize())
Richard Smith5407d4f2018-07-18 20:13:36 +00005060 return UnwrappedAny;
Richard Smitha3405ff2018-07-11 00:19:19 +00005061 } else if (!isa<IncompleteArrayType>(AT1) ||
5062 !isa<IncompleteArrayType>(AT2)) {
Richard Smith5407d4f2018-07-18 20:13:36 +00005063 return UnwrappedAny;
Richard Smitha3405ff2018-07-11 00:19:19 +00005064 }
5065
5066 T1 = AT1->getElementType();
5067 T2 = AT2->getElementType();
Richard Smith5407d4f2018-07-18 20:13:36 +00005068 UnwrappedAny = true;
Richard Smitha3405ff2018-07-11 00:19:19 +00005069 }
5070}
5071
5072/// Attempt to unwrap two types that may be similar (C++ [conv.qual]).
5073///
5074/// If T1 and T2 are both pointer types of the same kind, or both array types
5075/// with the same bound, unwraps layers from T1 and T2 until a pointer type is
5076/// unwrapped. Top-level qualifiers on T1 and T2 are ignored.
5077///
5078/// This function will typically be called in a loop that successively
5079/// "unwraps" pointer and pointer-to-member types to compare them at each
5080/// level.
5081///
5082/// \return \c true if a pointer type was unwrapped, \c false if we reached a
5083/// pair of types that can't be unwrapped further.
5084bool ASTContext::UnwrapSimilarTypes(QualType &T1, QualType &T2) {
Richard Smith5407d4f2018-07-18 20:13:36 +00005085 UnwrapSimilarArrayTypes(T1, T2);
Richard Smitha3405ff2018-07-11 00:19:19 +00005086
Eugene Zelenko7855e772018-04-03 00:11:50 +00005087 const auto *T1PtrType = T1->getAs<PointerType>();
5088 const auto *T2PtrType = T2->getAs<PointerType>();
Douglas Gregor1fc3d662010-06-09 03:53:18 +00005089 if (T1PtrType && T2PtrType) {
5090 T1 = T1PtrType->getPointeeType();
5091 T2 = T2PtrType->getPointeeType();
5092 return true;
5093 }
Richard Smith5407d4f2018-07-18 20:13:36 +00005094
Eugene Zelenko7855e772018-04-03 00:11:50 +00005095 const auto *T1MPType = T1->getAs<MemberPointerType>();
5096 const auto *T2MPType = T2->getAs<MemberPointerType>();
Fangrui Song6907ce22018-07-30 19:24:48 +00005097 if (T1MPType && T2MPType &&
5098 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
Douglas Gregor1fc3d662010-06-09 03:53:18 +00005099 QualType(T2MPType->getClass(), 0))) {
5100 T1 = T1MPType->getPointeeType();
5101 T2 = T2MPType->getPointeeType();
5102 return true;
5103 }
Fangrui Song6907ce22018-07-30 19:24:48 +00005104
David Blaikiebbafb8a2012-03-11 07:00:24 +00005105 if (getLangOpts().ObjC1) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00005106 const auto *T1OPType = T1->getAs<ObjCObjectPointerType>();
5107 const auto *T2OPType = T2->getAs<ObjCObjectPointerType>();
Douglas Gregor1fc3d662010-06-09 03:53:18 +00005108 if (T1OPType && T2OPType) {
5109 T1 = T1OPType->getPointeeType();
5110 T2 = T2OPType->getPointeeType();
5111 return true;
5112 }
5113 }
Fangrui Song6907ce22018-07-30 19:24:48 +00005114
Douglas Gregor1fc3d662010-06-09 03:53:18 +00005115 // FIXME: Block pointers, too?
Fangrui Song6907ce22018-07-30 19:24:48 +00005116
Douglas Gregor1fc3d662010-06-09 03:53:18 +00005117 return false;
5118}
5119
Richard Smitha3405ff2018-07-11 00:19:19 +00005120bool ASTContext::hasSimilarType(QualType T1, QualType T2) {
5121 while (true) {
5122 Qualifiers Quals;
5123 T1 = getUnqualifiedArrayType(T1, Quals);
5124 T2 = getUnqualifiedArrayType(T2, Quals);
5125 if (hasSameType(T1, T2))
5126 return true;
5127 if (!UnwrapSimilarTypes(T1, T2))
5128 return false;
5129 }
5130}
5131
5132bool ASTContext::hasCvrSimilarType(QualType T1, QualType T2) {
5133 while (true) {
5134 Qualifiers Quals1, Quals2;
5135 T1 = getUnqualifiedArrayType(T1, Quals1);
5136 T2 = getUnqualifiedArrayType(T2, Quals2);
5137
5138 Quals1.removeCVRQualifiers();
5139 Quals2.removeCVRQualifiers();
5140 if (Quals1 != Quals2)
5141 return false;
5142
5143 if (hasSameType(T1, T2))
5144 return true;
5145
5146 if (!UnwrapSimilarTypes(T1, T2))
5147 return false;
5148 }
5149}
5150
Jay Foad39c79802011-01-12 09:06:06 +00005151DeclarationNameInfo
5152ASTContext::getNameForTemplate(TemplateName Name,
5153 SourceLocation NameLoc) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00005154 switch (Name.getKind()) {
5155 case TemplateName::QualifiedTemplate:
5156 case TemplateName::Template:
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005157 // DNInfo work in progress: CHECKME: what about DNLoc?
John McCalld9dfe3a2011-06-30 08:33:18 +00005158 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
5159 NameLoc);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005160
John McCalld9dfe3a2011-06-30 08:33:18 +00005161 case TemplateName::OverloadedTemplate: {
5162 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
5163 // DNInfo work in progress: CHECKME: what about DNLoc?
5164 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
5165 }
5166
5167 case TemplateName::DependentTemplate: {
5168 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005169 DeclarationName DName;
John McCall847e2a12009-11-24 18:42:40 +00005170 if (DTN->isIdentifier()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005171 DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
5172 return DeclarationNameInfo(DName, NameLoc);
John McCall847e2a12009-11-24 18:42:40 +00005173 } else {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005174 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
5175 // DNInfo work in progress: FIXME: source locations?
5176 DeclarationNameLoc DNLoc;
5177 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
5178 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
5179 return DeclarationNameInfo(DName, NameLoc, DNLoc);
John McCall847e2a12009-11-24 18:42:40 +00005180 }
5181 }
5182
John McCalld9dfe3a2011-06-30 08:33:18 +00005183 case TemplateName::SubstTemplateTemplateParm: {
5184 SubstTemplateTemplateParmStorage *subst
5185 = Name.getAsSubstTemplateTemplateParm();
5186 return DeclarationNameInfo(subst->getParameter()->getDeclName(),
5187 NameLoc);
5188 }
5189
5190 case TemplateName::SubstTemplateTemplateParmPack: {
5191 SubstTemplateTemplateParmPackStorage *subst
5192 = Name.getAsSubstTemplateTemplateParmPack();
5193 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
5194 NameLoc);
5195 }
5196 }
5197
5198 llvm_unreachable("bad template name kind!");
John McCall847e2a12009-11-24 18:42:40 +00005199}
5200
Jay Foad39c79802011-01-12 09:06:06 +00005201TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
John McCalld9dfe3a2011-06-30 08:33:18 +00005202 switch (Name.getKind()) {
5203 case TemplateName::QualifiedTemplate:
5204 case TemplateName::Template: {
5205 TemplateDecl *Template = Name.getAsTemplateDecl();
Eugene Zelenko7855e772018-04-03 00:11:50 +00005206 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Template))
Douglas Gregor7dbfb462010-06-16 21:09:37 +00005207 Template = getCanonicalTemplateTemplateParmDecl(TTP);
Fangrui Song6907ce22018-07-30 19:24:48 +00005208
Douglas Gregor7dbfb462010-06-16 21:09:37 +00005209 // The canonical template name is the canonical template declaration.
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00005210 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
Douglas Gregor7dbfb462010-06-16 21:09:37 +00005211 }
Douglas Gregor6bc50582009-05-07 06:41:52 +00005212
John McCalld9dfe3a2011-06-30 08:33:18 +00005213 case TemplateName::OverloadedTemplate:
5214 llvm_unreachable("cannot canonicalize overloaded template");
Mike Stump11289f42009-09-09 15:08:12 +00005215
John McCalld9dfe3a2011-06-30 08:33:18 +00005216 case TemplateName::DependentTemplate: {
5217 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
5218 assert(DTN && "Non-dependent template names must refer to template decls.");
5219 return DTN->CanonicalTemplateName;
5220 }
5221
5222 case TemplateName::SubstTemplateTemplateParm: {
5223 SubstTemplateTemplateParmStorage *subst
5224 = Name.getAsSubstTemplateTemplateParm();
5225 return getCanonicalTemplateName(subst->getReplacement());
5226 }
5227
5228 case TemplateName::SubstTemplateTemplateParmPack: {
5229 SubstTemplateTemplateParmPackStorage *subst
5230 = Name.getAsSubstTemplateTemplateParmPack();
5231 TemplateTemplateParmDecl *canonParameter
5232 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
5233 TemplateArgument canonArgPack
5234 = getCanonicalTemplateArgument(subst->getArgumentPack());
5235 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
5236 }
5237 }
5238
5239 llvm_unreachable("bad template name!");
Douglas Gregor6bc50582009-05-07 06:41:52 +00005240}
5241
Douglas Gregoradee3e32009-11-11 23:06:43 +00005242bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
5243 X = getCanonicalTemplateName(X);
5244 Y = getCanonicalTemplateName(Y);
5245 return X.getAsVoidPointer() == Y.getAsVoidPointer();
5246}
5247
Mike Stump11289f42009-09-09 15:08:12 +00005248TemplateArgument
Jay Foad39c79802011-01-12 09:06:06 +00005249ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
Douglas Gregora8e02e72009-07-28 23:00:59 +00005250 switch (Arg.getKind()) {
5251 case TemplateArgument::Null:
5252 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00005253
Douglas Gregora8e02e72009-07-28 23:00:59 +00005254 case TemplateArgument::Expression:
Douglas Gregora8e02e72009-07-28 23:00:59 +00005255 return Arg;
Mike Stump11289f42009-09-09 15:08:12 +00005256
Douglas Gregor31f55dc2012-04-06 22:40:38 +00005257 case TemplateArgument::Declaration: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00005258 auto *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
David Blaikie952a9b12014-10-17 18:00:12 +00005259 return TemplateArgument(D, Arg.getParamTypeForDecl());
Douglas Gregor31f55dc2012-04-06 22:40:38 +00005260 }
Mike Stump11289f42009-09-09 15:08:12 +00005261
Eli Friedmanb826a002012-09-26 02:36:12 +00005262 case TemplateArgument::NullPtr:
5263 return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
5264 /*isNullPtr*/true);
5265
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005266 case TemplateArgument::Template:
5267 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
Douglas Gregore4ff4b52011-01-05 18:58:31 +00005268
5269 case TemplateArgument::TemplateExpansion:
5270 return TemplateArgument(getCanonicalTemplateName(
5271 Arg.getAsTemplateOrTemplatePattern()),
Douglas Gregore1d60df2011-01-14 23:41:42 +00005272 Arg.getNumTemplateExpansions());
Douglas Gregore4ff4b52011-01-05 18:58:31 +00005273
Douglas Gregora8e02e72009-07-28 23:00:59 +00005274 case TemplateArgument::Integral:
Benjamin Kramer6003ad52012-06-07 15:09:51 +00005275 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
Mike Stump11289f42009-09-09 15:08:12 +00005276
Douglas Gregora8e02e72009-07-28 23:00:59 +00005277 case TemplateArgument::Type:
John McCall0ad16662009-10-29 08:12:44 +00005278 return TemplateArgument(getCanonicalType(Arg.getAsType()));
Mike Stump11289f42009-09-09 15:08:12 +00005279
Douglas Gregora8e02e72009-07-28 23:00:59 +00005280 case TemplateArgument::Pack: {
Douglas Gregor0192c232010-12-20 16:52:59 +00005281 if (Arg.pack_size() == 0)
5282 return Arg;
Fangrui Song6907ce22018-07-30 19:24:48 +00005283
Eugene Zelenko7855e772018-04-03 00:11:50 +00005284 auto *CanonArgs = new (*this) TemplateArgument[Arg.pack_size()];
Douglas Gregora8e02e72009-07-28 23:00:59 +00005285 unsigned Idx = 0;
Mike Stump11289f42009-09-09 15:08:12 +00005286 for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
Douglas Gregora8e02e72009-07-28 23:00:59 +00005287 AEnd = Arg.pack_end();
5288 A != AEnd; (void)++A, ++Idx)
5289 CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
Mike Stump11289f42009-09-09 15:08:12 +00005290
Benjamin Kramercce63472015-08-05 09:40:22 +00005291 return TemplateArgument(llvm::makeArrayRef(CanonArgs, Arg.pack_size()));
Douglas Gregora8e02e72009-07-28 23:00:59 +00005292 }
5293 }
5294
5295 // Silence GCC warning
David Blaikie83d382b2011-09-23 05:06:16 +00005296 llvm_unreachable("Unhandled template argument kind");
Douglas Gregora8e02e72009-07-28 23:00:59 +00005297}
5298
Douglas Gregor333489b2009-03-27 23:10:48 +00005299NestedNameSpecifier *
Jay Foad39c79802011-01-12 09:06:06 +00005300ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
Mike Stump11289f42009-09-09 15:08:12 +00005301 if (!NNS)
Craig Topper36250ad2014-05-12 05:36:57 +00005302 return nullptr;
Douglas Gregor333489b2009-03-27 23:10:48 +00005303
5304 switch (NNS->getKind()) {
5305 case NestedNameSpecifier::Identifier:
5306 // Canonicalize the prefix but keep the identifier the same.
Mike Stump11289f42009-09-09 15:08:12 +00005307 return NestedNameSpecifier::Create(*this,
Douglas Gregor333489b2009-03-27 23:10:48 +00005308 getCanonicalNestedNameSpecifier(NNS->getPrefix()),
5309 NNS->getAsIdentifier());
5310
5311 case NestedNameSpecifier::Namespace:
5312 // A namespace is canonical; build a nested-name-specifier with
5313 // this namespace and no prefix.
Craig Topper36250ad2014-05-12 05:36:57 +00005314 return NestedNameSpecifier::Create(*this, nullptr,
Douglas Gregor7b26ff92011-02-24 02:36:08 +00005315 NNS->getAsNamespace()->getOriginalNamespace());
5316
5317 case NestedNameSpecifier::NamespaceAlias:
5318 // A namespace is canonical; build a nested-name-specifier with
5319 // this namespace and no prefix.
Craig Topper36250ad2014-05-12 05:36:57 +00005320 return NestedNameSpecifier::Create(*this, nullptr,
Douglas Gregor7b26ff92011-02-24 02:36:08 +00005321 NNS->getAsNamespaceAlias()->getNamespace()
5322 ->getOriginalNamespace());
Douglas Gregor333489b2009-03-27 23:10:48 +00005323
5324 case NestedNameSpecifier::TypeSpec:
5325 case NestedNameSpecifier::TypeSpecWithTemplate: {
5326 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
Fangrui Song6907ce22018-07-30 19:24:48 +00005327
Douglas Gregor3ade5702010-11-04 00:09:33 +00005328 // If we have some kind of dependent-named type (e.g., "typename T::type"),
5329 // break it apart into its prefix and identifier, then reconsititute those
5330 // as the canonical nested-name-specifier. This is required to canonicalize
5331 // a dependent nested-name-specifier involving typedefs of dependent-name
5332 // types, e.g.,
5333 // typedef typename T::type T1;
5334 // typedef typename T1::type T2;
Eugene Zelenko7855e772018-04-03 00:11:50 +00005335 if (const auto *DNT = T->getAs<DependentNameType>())
Fangrui Song6907ce22018-07-30 19:24:48 +00005336 return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
Douglas Gregor3ade5702010-11-04 00:09:33 +00005337 const_cast<IdentifierInfo *>(DNT->getIdentifier()));
Douglas Gregor3ade5702010-11-04 00:09:33 +00005338
Eli Friedman5358a0a2012-03-03 04:09:56 +00005339 // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
5340 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
5341 // first place?
Craig Topper36250ad2014-05-12 05:36:57 +00005342 return NestedNameSpecifier::Create(*this, nullptr, false,
5343 const_cast<Type *>(T.getTypePtr()));
Douglas Gregor333489b2009-03-27 23:10:48 +00005344 }
5345
5346 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +00005347 case NestedNameSpecifier::Super:
5348 // The global specifier and __super specifer are canonical and unique.
Douglas Gregor333489b2009-03-27 23:10:48 +00005349 return NNS;
5350 }
5351
David Blaikie8a40f702012-01-17 06:56:22 +00005352 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
Douglas Gregor333489b2009-03-27 23:10:48 +00005353}
5354
Jay Foad39c79802011-01-12 09:06:06 +00005355const ArrayType *ASTContext::getAsArrayType(QualType T) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00005356 // Handle the non-qualified case efficiently.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00005357 if (!T.hasLocalQualifiers()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00005358 // Handle the common positive case fast.
Eugene Zelenko7855e772018-04-03 00:11:50 +00005359 if (const auto *AT = dyn_cast<ArrayType>(T))
Chris Lattner7adf0762008-08-04 07:31:14 +00005360 return AT;
5361 }
Mike Stump11289f42009-09-09 15:08:12 +00005362
John McCall8ccfcb52009-09-24 19:53:00 +00005363 // Handle the common negative case fast.
John McCall33ddac02011-01-19 10:06:00 +00005364 if (!isa<ArrayType>(T.getCanonicalType()))
Craig Topper36250ad2014-05-12 05:36:57 +00005365 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00005366
John McCall8ccfcb52009-09-24 19:53:00 +00005367 // Apply any qualifiers from the array type to the element type. This
Chris Lattner7adf0762008-08-04 07:31:14 +00005368 // implements C99 6.7.3p8: "If the specification of an array type includes
5369 // any type qualifiers, the element type is so qualified, not the array type."
Mike Stump11289f42009-09-09 15:08:12 +00005370
Chris Lattner7adf0762008-08-04 07:31:14 +00005371 // If we get here, we either have type qualifiers on the type, or we have
5372 // sugar such as a typedef in the way. If we have type qualifiers on the type
Douglas Gregor2211d342009-08-05 05:36:45 +00005373 // we must propagate them down into the element type.
Mike Stump11289f42009-09-09 15:08:12 +00005374
John McCall33ddac02011-01-19 10:06:00 +00005375 SplitQualType split = T.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00005376 Qualifiers qs = split.Quals;
Mike Stump11289f42009-09-09 15:08:12 +00005377
Chris Lattner7adf0762008-08-04 07:31:14 +00005378 // If we have a simple case, just return now.
Eugene Zelenko7855e772018-04-03 00:11:50 +00005379 const auto *ATy = dyn_cast<ArrayType>(split.Ty);
Craig Topper36250ad2014-05-12 05:36:57 +00005380 if (!ATy || qs.empty())
Chris Lattner7adf0762008-08-04 07:31:14 +00005381 return ATy;
Mike Stump11289f42009-09-09 15:08:12 +00005382
Chris Lattner7adf0762008-08-04 07:31:14 +00005383 // Otherwise, we have an array and we have qualifiers on it. Push the
5384 // qualifiers into the array element type and return a new array type.
John McCall33ddac02011-01-19 10:06:00 +00005385 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
Mike Stump11289f42009-09-09 15:08:12 +00005386
Eugene Zelenko7855e772018-04-03 00:11:50 +00005387 if (const auto *CAT = dyn_cast<ConstantArrayType>(ATy))
Chris Lattner7adf0762008-08-04 07:31:14 +00005388 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
5389 CAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00005390 CAT->getIndexTypeCVRQualifiers()));
Eugene Zelenko7855e772018-04-03 00:11:50 +00005391 if (const auto *IAT = dyn_cast<IncompleteArrayType>(ATy))
Chris Lattner7adf0762008-08-04 07:31:14 +00005392 return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
5393 IAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00005394 IAT->getIndexTypeCVRQualifiers()));
Douglas Gregor4619e432008-12-05 23:32:09 +00005395
Eugene Zelenko7855e772018-04-03 00:11:50 +00005396 if (const auto *DSAT = dyn_cast<DependentSizedArrayType>(ATy))
Douglas Gregor4619e432008-12-05 23:32:09 +00005397 return cast<ArrayType>(
Mike Stump11289f42009-09-09 15:08:12 +00005398 getDependentSizedArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00005399 DSAT->getSizeExpr(),
Douglas Gregor4619e432008-12-05 23:32:09 +00005400 DSAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00005401 DSAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00005402 DSAT->getBracketsRange()));
Mike Stump11289f42009-09-09 15:08:12 +00005403
Eugene Zelenko7855e772018-04-03 00:11:50 +00005404 const auto *VAT = cast<VariableArrayType>(ATy);
Douglas Gregor04318252009-07-06 15:59:29 +00005405 return cast<ArrayType>(getVariableArrayType(NewEltTy,
John McCallc3007a22010-10-26 07:05:15 +00005406 VAT->getSizeExpr(),
Chris Lattner7adf0762008-08-04 07:31:14 +00005407 VAT->getSizeModifier(),
John McCall8ccfcb52009-09-24 19:53:00 +00005408 VAT->getIndexTypeCVRQualifiers(),
Douglas Gregor04318252009-07-06 15:59:29 +00005409 VAT->getBracketsRange()));
Chris Lattnered0d0792008-04-06 22:41:35 +00005410}
5411
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00005412QualType ASTContext::getAdjustedParameterType(QualType T) const {
Reid Kleckner8a365022013-06-24 17:51:48 +00005413 if (T->isArrayType() || T->isFunctionType())
5414 return getDecayedType(T);
5415 return T;
Douglas Gregor84280642011-07-12 04:42:08 +00005416}
5417
Abramo Bagnarae1decdf2012-05-17 12:44:05 +00005418QualType ASTContext::getSignatureParameterType(QualType T) const {
Douglas Gregor84280642011-07-12 04:42:08 +00005419 T = getVariableArrayDecayedType(T);
5420 T = getAdjustedParameterType(T);
5421 return T.getUnqualifiedType();
5422}
5423
David Majnemerd09a51c2015-03-03 01:50:05 +00005424QualType ASTContext::getExceptionObjectType(QualType T) const {
5425 // C++ [except.throw]p3:
5426 // A throw-expression initializes a temporary object, called the exception
5427 // object, the type of which is determined by removing any top-level
5428 // cv-qualifiers from the static type of the operand of throw and adjusting
5429 // the type from "array of T" or "function returning T" to "pointer to T"
5430 // or "pointer to function returning T", [...]
5431 T = getVariableArrayDecayedType(T);
5432 if (T->isArrayType() || T->isFunctionType())
5433 T = getDecayedType(T);
5434 return T.getUnqualifiedType();
5435}
5436
Chris Lattnera21ad802008-04-02 05:18:44 +00005437/// getArrayDecayedType - Return the properly qualified result of decaying the
5438/// specified array type to a pointer. This operation is non-trivial when
5439/// handling typedefs etc. The canonical type of "T" must be an array type,
5440/// this returns a pointer to a properly qualified element of the array.
5441///
5442/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
Jay Foad39c79802011-01-12 09:06:06 +00005443QualType ASTContext::getArrayDecayedType(QualType Ty) const {
Chris Lattner7adf0762008-08-04 07:31:14 +00005444 // Get the element type with 'getAsArrayType' so that we don't lose any
5445 // typedefs in the element type of the array. This also handles propagation
5446 // of type qualifiers from the array type into the element type if present
5447 // (C99 6.7.3p8).
5448 const ArrayType *PrettyArrayType = getAsArrayType(Ty);
5449 assert(PrettyArrayType && "Not an array type!");
Mike Stump11289f42009-09-09 15:08:12 +00005450
Chris Lattner7adf0762008-08-04 07:31:14 +00005451 QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
Chris Lattnera21ad802008-04-02 05:18:44 +00005452
5453 // int x[restrict 4] -> int *restrict
Jordan Rose303e2f12016-11-10 23:28:17 +00005454 QualType Result = getQualifiedType(PtrTy,
5455 PrettyArrayType->getIndexTypeQualifiers());
5456
5457 // int x[_Nullable] -> int * _Nullable
5458 if (auto Nullability = Ty->getNullability(*this)) {
5459 Result = const_cast<ASTContext *>(this)->getAttributedType(
5460 AttributedType::getNullabilityAttrKind(*Nullability), Result, Result);
5461 }
5462 return Result;
Chris Lattnera21ad802008-04-02 05:18:44 +00005463}
5464
John McCall33ddac02011-01-19 10:06:00 +00005465QualType ASTContext::getBaseElementType(const ArrayType *array) const {
5466 return getBaseElementType(array->getElementType());
Douglas Gregor79f83ed2009-07-23 23:49:00 +00005467}
5468
John McCall33ddac02011-01-19 10:06:00 +00005469QualType ASTContext::getBaseElementType(QualType type) const {
5470 Qualifiers qs;
5471 while (true) {
5472 SplitQualType split = type.getSplitDesugaredType();
John McCall18ce25e2012-02-08 00:46:36 +00005473 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
John McCall33ddac02011-01-19 10:06:00 +00005474 if (!array) break;
Mike Stump11289f42009-09-09 15:08:12 +00005475
John McCall33ddac02011-01-19 10:06:00 +00005476 type = array->getElementType();
John McCall18ce25e2012-02-08 00:46:36 +00005477 qs.addConsistentQualifiers(split.Quals);
John McCall33ddac02011-01-19 10:06:00 +00005478 }
Mike Stump11289f42009-09-09 15:08:12 +00005479
John McCall33ddac02011-01-19 10:06:00 +00005480 return getQualifiedType(type, qs);
Anders Carlssone0808df2008-12-21 03:44:36 +00005481}
5482
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00005483/// getConstantArrayElementCount - Returns number of constant array elements.
Mike Stump11289f42009-09-09 15:08:12 +00005484uint64_t
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00005485ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
5486 uint64_t ElementCount = 1;
5487 do {
5488 ElementCount *= CA->getSize().getZExtValue();
Richard Smith7808c6a2012-12-06 03:04:50 +00005489 CA = dyn_cast_or_null<ConstantArrayType>(
5490 CA->getElementType()->getAsArrayTypeUnsafe());
Fariborz Jahanian6c9e5a22009-08-21 16:31:06 +00005491 } while (CA);
5492 return ElementCount;
5493}
5494
Steve Naroff0af91202007-04-27 21:51:21 +00005495/// getFloatingRank - Return a relative rank for floating point types.
5496/// This routine will assert if passed a built-in type that isn't a float.
Chris Lattnerb90739d2008-04-06 23:38:49 +00005497static FloatingRank getFloatingRank(QualType T) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00005498 if (const auto *CT = T->getAs<ComplexType>())
Chris Lattnerc6395932007-06-22 20:56:16 +00005499 return getFloatingRank(CT->getElementType());
Chris Lattnerb90739d2008-04-06 23:38:49 +00005500
John McCall9dd450b2009-09-21 23:43:11 +00005501 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
5502 switch (T->getAs<BuiltinType>()->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00005503 default: llvm_unreachable("getFloatingRank(): not a floating type");
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00005504 case BuiltinType::Float16: return Float16Rank;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00005505 case BuiltinType::Half: return HalfRank;
Chris Lattnerc6395932007-06-22 20:56:16 +00005506 case BuiltinType::Float: return FloatRank;
5507 case BuiltinType::Double: return DoubleRank;
5508 case BuiltinType::LongDouble: return LongDoubleRank;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00005509 case BuiltinType::Float128: return Float128Rank;
Steve Naroffe4718892007-04-27 18:30:00 +00005510 }
5511}
5512
Mike Stump11289f42009-09-09 15:08:12 +00005513/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
5514/// point or a complex type (based on typeDomain/typeSize).
Steve Narofffc6ffa22007-08-27 01:41:48 +00005515/// 'typeDomain' is a real floating point or complex type.
5516/// 'typeSize' is a real floating point or complex type.
Chris Lattnerb9dfb032008-04-06 23:58:54 +00005517QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
5518 QualType Domain) const {
5519 FloatingRank EltRank = getFloatingRank(Size);
5520 if (Domain->isComplexType()) {
5521 switch (EltRank) {
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00005522 case Float16Rank:
David Blaikief47fa302012-01-17 02:30:50 +00005523 case HalfRank: llvm_unreachable("Complex half is not supported");
Steve Naroff9091ef72007-08-27 01:27:54 +00005524 case FloatRank: return FloatComplexTy;
5525 case DoubleRank: return DoubleComplexTy;
5526 case LongDoubleRank: return LongDoubleComplexTy;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00005527 case Float128Rank: return Float128ComplexTy;
Steve Naroff9091ef72007-08-27 01:27:54 +00005528 }
Steve Naroff0af91202007-04-27 21:51:21 +00005529 }
Chris Lattnerb9dfb032008-04-06 23:58:54 +00005530
5531 assert(Domain->isRealFloatingType() && "Unknown domain!");
5532 switch (EltRank) {
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00005533 case Float16Rank: return HalfTy;
Joey Goulydd7f4562013-01-23 11:56:20 +00005534 case HalfRank: return HalfTy;
Chris Lattnerb9dfb032008-04-06 23:58:54 +00005535 case FloatRank: return FloatTy;
5536 case DoubleRank: return DoubleTy;
5537 case LongDoubleRank: return LongDoubleTy;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00005538 case Float128Rank: return Float128Ty;
Steve Naroff9091ef72007-08-27 01:27:54 +00005539 }
David Blaikief47fa302012-01-17 02:30:50 +00005540 llvm_unreachable("getFloatingRank(): illegal value for rank");
Steve Naroffe4718892007-04-27 18:30:00 +00005541}
5542
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005543/// getFloatingTypeOrder - Compare the rank of the two specified floating
5544/// point types, ignoring the domain of the type (i.e. 'double' ==
5545/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00005546/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00005547int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
Chris Lattnerb90739d2008-04-06 23:38:49 +00005548 FloatingRank LHSR = getFloatingRank(LHS);
5549 FloatingRank RHSR = getFloatingRank(RHS);
Mike Stump11289f42009-09-09 15:08:12 +00005550
Chris Lattnerb90739d2008-04-06 23:38:49 +00005551 if (LHSR == RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00005552 return 0;
Chris Lattnerb90739d2008-04-06 23:38:49 +00005553 if (LHSR > RHSR)
Steve Naroff7af82d42007-08-27 15:30:22 +00005554 return 1;
5555 return -1;
Steve Naroffe4718892007-04-27 18:30:00 +00005556}
5557
Chris Lattner76a00cf2008-04-06 22:59:24 +00005558/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
5559/// routine will assert if passed a built-in type that isn't an integer or enum,
5560/// or if it is not canonicalized.
John McCall424cec92011-01-19 06:33:43 +00005561unsigned ASTContext::getIntegerRank(const Type *T) const {
John McCallb692a092009-10-22 20:10:53 +00005562 assert(T->isCanonicalUnqualified() && "T should be canonicalized");
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00005563
Chris Lattner76a00cf2008-04-06 22:59:24 +00005564 switch (cast<BuiltinType>(T)->getKind()) {
David Blaikie83d382b2011-09-23 05:06:16 +00005565 default: llvm_unreachable("getIntegerRank(): not a built-in integer");
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005566 case BuiltinType::Bool:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005567 return 1 + (getIntWidth(BoolTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005568 case BuiltinType::Char_S:
5569 case BuiltinType::Char_U:
5570 case BuiltinType::SChar:
5571 case BuiltinType::UChar:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005572 return 2 + (getIntWidth(CharTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005573 case BuiltinType::Short:
5574 case BuiltinType::UShort:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005575 return 3 + (getIntWidth(ShortTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005576 case BuiltinType::Int:
5577 case BuiltinType::UInt:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005578 return 4 + (getIntWidth(IntTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005579 case BuiltinType::Long:
5580 case BuiltinType::ULong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005581 return 5 + (getIntWidth(LongTy) << 3);
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005582 case BuiltinType::LongLong:
5583 case BuiltinType::ULongLong:
Eli Friedman1efaaea2009-02-13 02:31:07 +00005584 return 6 + (getIntWidth(LongLongTy) << 3);
Chris Lattnerf122cef2009-04-30 02:43:43 +00005585 case BuiltinType::Int128:
5586 case BuiltinType::UInt128:
5587 return 7 + (getIntWidth(Int128Ty) << 3);
Chris Lattner76a00cf2008-04-06 22:59:24 +00005588 }
5589}
5590
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005591/// Whether this is a promotable bitfield reference according
Eli Friedman629ffb92009-08-20 04:21:42 +00005592/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
5593///
5594/// \returns the type this bit-field will promote to, or NULL if no
5595/// promotion occurs.
Jay Foad39c79802011-01-12 09:06:06 +00005596QualType ASTContext::isPromotableBitField(Expr *E) const {
Douglas Gregore05d3cb2010-05-24 20:13:53 +00005597 if (E->isTypeDependent() || E->isValueDependent())
Eugene Zelenko7855e772018-04-03 00:11:50 +00005598 return {};
Richard Smith5b571672014-09-24 23:55:00 +00005599
Richard Smithaadb2542018-06-28 21:17:55 +00005600 // C++ [conv.prom]p5:
5601 // If the bit-field has an enumerated type, it is treated as any other
5602 // value of that type for promotion purposes.
5603 if (getLangOpts().CPlusPlus && E->getType()->isEnumeralType())
5604 return {};
5605
Richard Smith5b571672014-09-24 23:55:00 +00005606 // FIXME: We should not do this unless E->refersToBitField() is true. This
5607 // matters in C where getSourceBitField() will find bit-fields for various
5608 // cases where the source expression is not a bit-field designator.
5609
John McCalld25db7e2013-05-06 21:39:12 +00005610 FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
Eli Friedman629ffb92009-08-20 04:21:42 +00005611 if (!Field)
Eugene Zelenko7855e772018-04-03 00:11:50 +00005612 return {};
Eli Friedman629ffb92009-08-20 04:21:42 +00005613
5614 QualType FT = Field->getType();
5615
Richard Smithcaf33902011-10-10 18:28:20 +00005616 uint64_t BitWidth = Field->getBitWidthValue(*this);
Eli Friedman629ffb92009-08-20 04:21:42 +00005617 uint64_t IntSize = getTypeSize(IntTy);
Richard Smith5b571672014-09-24 23:55:00 +00005618 // C++ [conv.prom]p5:
5619 // A prvalue for an integral bit-field can be converted to a prvalue of type
5620 // int if int can represent all the values of the bit-field; otherwise, it
5621 // can be converted to unsigned int if unsigned int can represent all the
5622 // values of the bit-field. If the bit-field is larger yet, no integral
5623 // promotion applies to it.
5624 // C11 6.3.1.1/2:
5625 // [For a bit-field of type _Bool, int, signed int, or unsigned int:]
5626 // If an int can represent all values of the original type (as restricted by
5627 // the width, for a bit-field), the value is converted to an int; otherwise,
5628 // it is converted to an unsigned int.
5629 //
5630 // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
5631 // We perform that promotion here to match GCC and C++.
Richard Smithaadb2542018-06-28 21:17:55 +00005632 // FIXME: C does not permit promotion of an enum bit-field whose rank is
5633 // greater than that of 'int'. We perform that promotion to match GCC.
Eli Friedman629ffb92009-08-20 04:21:42 +00005634 if (BitWidth < IntSize)
5635 return IntTy;
5636
5637 if (BitWidth == IntSize)
5638 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
5639
Richard Smithaadb2542018-06-28 21:17:55 +00005640 // Bit-fields wider than int are not subject to promotions, and therefore act
Richard Smith5b571672014-09-24 23:55:00 +00005641 // like the base type. GCC has some weird bugs in this area that we
5642 // deliberately do not follow (GCC follows a pre-standard resolution to
5643 // C's DR315 which treats bit-width as being part of the type, and this leaks
5644 // into their semantics in some cases).
Eugene Zelenko7855e772018-04-03 00:11:50 +00005645 return {};
Eli Friedman629ffb92009-08-20 04:21:42 +00005646}
5647
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005648/// getPromotedIntegerType - Returns the type that Promotable will
5649/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
5650/// integer type.
Jay Foad39c79802011-01-12 09:06:06 +00005651QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005652 assert(!Promotable.isNull());
5653 assert(Promotable->isPromotableIntegerType());
Eugene Zelenko7855e772018-04-03 00:11:50 +00005654 if (const auto *ET = Promotable->getAs<EnumType>())
John McCall56774992009-12-09 09:09:27 +00005655 return ET->getDecl()->getPromotionType();
Eli Friedman3f37c1c2011-10-26 07:22:48 +00005656
Eugene Zelenko7855e772018-04-03 00:11:50 +00005657 if (const auto *BT = Promotable->getAs<BuiltinType>()) {
Eli Friedman3f37c1c2011-10-26 07:22:48 +00005658 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
5659 // (3.9.1) can be converted to a prvalue of the first of the following
5660 // types that can represent all the values of its underlying type:
5661 // int, unsigned int, long int, unsigned long int, long long int, or
5662 // unsigned long long int [...]
5663 // FIXME: Is there some better way to compute this?
5664 if (BT->getKind() == BuiltinType::WChar_S ||
5665 BT->getKind() == BuiltinType::WChar_U ||
Richard Smith3a8244d2018-05-01 05:02:45 +00005666 BT->getKind() == BuiltinType::Char8 ||
Eli Friedman3f37c1c2011-10-26 07:22:48 +00005667 BT->getKind() == BuiltinType::Char16 ||
5668 BT->getKind() == BuiltinType::Char32) {
5669 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
5670 uint64_t FromSize = getTypeSize(BT);
5671 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
5672 LongLongTy, UnsignedLongLongTy };
5673 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
5674 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
5675 if (FromSize < ToSize ||
5676 (FromSize == ToSize &&
5677 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
5678 return PromoteTypes[Idx];
5679 }
5680 llvm_unreachable("char type should fit into long long");
5681 }
5682 }
5683
5684 // At this point, we should have a signed or unsigned integer type.
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005685 if (Promotable->isSignedIntegerType())
5686 return IntTy;
Eli Friedman6745c3b2012-11-15 01:21:59 +00005687 uint64_t PromotableSize = getIntWidth(Promotable);
5688 uint64_t IntSize = getIntWidth(IntTy);
Eli Friedman5ae98ee2009-08-19 07:44:53 +00005689 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
5690 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
5691}
5692
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005693/// Recurses in pointer/array types until it finds an objc retainable
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00005694/// type and returns its ownership.
5695Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
5696 while (!T.isNull()) {
5697 if (T.getObjCLifetime() != Qualifiers::OCL_None)
5698 return T.getObjCLifetime();
5699 if (T->isArrayType())
5700 T = getBaseElementType(T);
Eugene Zelenko7855e772018-04-03 00:11:50 +00005701 else if (const auto *PT = T->getAs<PointerType>())
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00005702 T = PT->getPointeeType();
Eugene Zelenko7855e772018-04-03 00:11:50 +00005703 else if (const auto *RT = T->getAs<ReferenceType>())
Argyrios Kyrtzidis8e252532011-07-01 23:01:46 +00005704 T = RT->getPointeeType();
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00005705 else
5706 break;
5707 }
5708
5709 return Qualifiers::OCL_None;
5710}
5711
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00005712static const Type *getIntegerTypeForEnum(const EnumType *ET) {
5713 // Incomplete enum types are not treated as integer types.
5714 // FIXME: In C++, enum types are never integer types.
5715 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
5716 return ET->getDecl()->getIntegerType().getTypePtr();
Craig Topper36250ad2014-05-12 05:36:57 +00005717 return nullptr;
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00005718}
5719
Mike Stump11289f42009-09-09 15:08:12 +00005720/// getIntegerTypeOrder - Returns the highest ranked integer type:
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005721/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
Mike Stump11289f42009-09-09 15:08:12 +00005722/// LHS < RHS, return -1.
Jay Foad39c79802011-01-12 09:06:06 +00005723int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
John McCall424cec92011-01-19 06:33:43 +00005724 const Type *LHSC = getCanonicalType(LHS).getTypePtr();
5725 const Type *RHSC = getCanonicalType(RHS).getTypePtr();
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00005726
5727 // Unwrap enums to their underlying type.
Eugene Zelenko7855e772018-04-03 00:11:50 +00005728 if (const auto *ET = dyn_cast<EnumType>(LHSC))
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00005729 LHSC = getIntegerTypeForEnum(ET);
Eugene Zelenko7855e772018-04-03 00:11:50 +00005730 if (const auto *ET = dyn_cast<EnumType>(RHSC))
Ted Kremeneke65ab9e2013-10-10 00:54:01 +00005731 RHSC = getIntegerTypeForEnum(ET);
5732
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005733 if (LHSC == RHSC) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00005734
Chris Lattner76a00cf2008-04-06 22:59:24 +00005735 bool LHSUnsigned = LHSC->isUnsignedIntegerType();
5736 bool RHSUnsigned = RHSC->isUnsignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +00005737
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005738 unsigned LHSRank = getIntegerRank(LHSC);
5739 unsigned RHSRank = getIntegerRank(RHSC);
Mike Stump11289f42009-09-09 15:08:12 +00005740
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005741 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
5742 if (LHSRank == RHSRank) return 0;
5743 return LHSRank > RHSRank ? 1 : -1;
5744 }
Mike Stump11289f42009-09-09 15:08:12 +00005745
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005746 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
5747 if (LHSUnsigned) {
5748 // If the unsigned [LHS] type is larger, return it.
5749 if (LHSRank >= RHSRank)
5750 return 1;
Mike Stump11289f42009-09-09 15:08:12 +00005751
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005752 // If the signed type can represent all values of the unsigned type, it
5753 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00005754 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005755 return -1;
5756 }
Chris Lattner76a00cf2008-04-06 22:59:24 +00005757
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005758 // If the unsigned [RHS] type is larger, return it.
5759 if (RHSRank >= LHSRank)
5760 return -1;
Mike Stump11289f42009-09-09 15:08:12 +00005761
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005762 // If the signed type can represent all values of the unsigned type, it
5763 // wins. Because we are dealing with 2's complement and types that are
Mike Stump11289f42009-09-09 15:08:12 +00005764 // powers of two larger than each other, this is always safe.
Chris Lattnerd4bacd62008-04-06 23:55:33 +00005765 return 1;
Steve Naroffe4718892007-04-27 18:30:00 +00005766}
Anders Carlsson98f07902007-08-17 05:31:46 +00005767
Ben Langmuirf5416742016-02-04 00:55:24 +00005768TypedefDecl *ASTContext::getCFConstantStringDecl() const {
Anders Carlsson98f07902007-08-17 05:31:46 +00005769 if (!CFConstantStringTypeDecl) {
Ben Langmuirf5416742016-02-04 00:55:24 +00005770 assert(!CFConstantStringTagDecl &&
5771 "tag and typedef should be initialized together");
5772 CFConstantStringTagDecl = buildImplicitRecord("__NSConstantString_tag");
5773 CFConstantStringTagDecl->startDefinition();
Anders Carlsson6d417272009-11-14 21:45:58 +00005774
Anders Carlsson9c1011c2007-11-19 00:25:30 +00005775 QualType FieldTypes[4];
Ben Langmuir4791a802016-02-25 16:36:26 +00005776 const char *FieldNames[4];
Mike Stump11289f42009-09-09 15:08:12 +00005777
Anders Carlsson98f07902007-08-17 05:31:46 +00005778 // const int *isa;
John McCall8ccfcb52009-09-24 19:53:00 +00005779 FieldTypes[0] = getPointerType(IntTy.withConst());
Ben Langmuir4791a802016-02-25 16:36:26 +00005780 FieldNames[0] = "isa";
Anders Carlsson9c1011c2007-11-19 00:25:30 +00005781 // int flags;
5782 FieldTypes[1] = IntTy;
Ben Langmuir4791a802016-02-25 16:36:26 +00005783 FieldNames[1] = "flags";
Anders Carlsson98f07902007-08-17 05:31:46 +00005784 // const char *str;
John McCall8ccfcb52009-09-24 19:53:00 +00005785 FieldTypes[2] = getPointerType(CharTy.withConst());
Ben Langmuir4791a802016-02-25 16:36:26 +00005786 FieldNames[2] = "str";
Anders Carlsson98f07902007-08-17 05:31:46 +00005787 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00005788 FieldTypes[3] = LongTy;
Ben Langmuir4791a802016-02-25 16:36:26 +00005789 FieldNames[3] = "length";
Mike Stump11289f42009-09-09 15:08:12 +00005790
Anders Carlsson98f07902007-08-17 05:31:46 +00005791 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00005792 for (unsigned i = 0; i < 4; ++i) {
Ben Langmuirf5416742016-02-04 00:55:24 +00005793 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTagDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00005794 SourceLocation(),
Ben Langmuir4791a802016-02-25 16:36:26 +00005795 SourceLocation(),
5796 &Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00005797 FieldTypes[i], /*TInfo=*/nullptr,
5798 /*BitWidth=*/nullptr,
Richard Smith938f40b2011-06-11 17:19:42 +00005799 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00005800 ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00005801 Field->setAccess(AS_public);
Ben Langmuirf5416742016-02-04 00:55:24 +00005802 CFConstantStringTagDecl->addDecl(Field);
Douglas Gregor91f84212008-12-11 16:49:14 +00005803 }
5804
Ben Langmuirf5416742016-02-04 00:55:24 +00005805 CFConstantStringTagDecl->completeDefinition();
5806 // This type is designed to be compatible with NSConstantString, but cannot
5807 // use the same name, since NSConstantString is an interface.
5808 auto tagType = getTagDeclType(CFConstantStringTagDecl);
5809 CFConstantStringTypeDecl =
5810 buildImplicitTypedef(tagType, "__NSConstantString");
Anders Carlsson98f07902007-08-17 05:31:46 +00005811 }
Mike Stump11289f42009-09-09 15:08:12 +00005812
Quentin Colombet043406b2016-02-03 22:41:00 +00005813 return CFConstantStringTypeDecl;
5814}
5815
Ben Langmuirf5416742016-02-04 00:55:24 +00005816RecordDecl *ASTContext::getCFConstantStringTagDecl() const {
5817 if (!CFConstantStringTagDecl)
5818 getCFConstantStringDecl(); // Build the tag and the typedef.
5819 return CFConstantStringTagDecl;
5820}
5821
Quentin Colombet043406b2016-02-03 22:41:00 +00005822// getCFConstantStringType - Return the type used for constant CFStrings.
5823QualType ASTContext::getCFConstantStringType() const {
Ben Langmuirf5416742016-02-04 00:55:24 +00005824 return getTypedefType(getCFConstantStringDecl());
Gabor Greif412af032007-09-11 15:32:40 +00005825}
Anders Carlsson87c149b2007-10-11 01:00:40 +00005826
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00005827QualType ASTContext::getObjCSuperType() const {
5828 if (ObjCSuperType.isNull()) {
Alp Toker2dea15b2013-12-17 01:22:38 +00005829 RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00005830 TUDecl->addDecl(ObjCSuperTypeDecl);
5831 ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
5832 }
5833 return ObjCSuperType;
5834}
5835
Douglas Gregor512b0772009-04-23 22:29:11 +00005836void ASTContext::setCFConstantStringType(QualType T) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00005837 const auto *TD = T->getAs<TypedefType>();
Ben Langmuirf5416742016-02-04 00:55:24 +00005838 assert(TD && "Invalid CFConstantStringType");
5839 CFConstantStringTypeDecl = cast<TypedefDecl>(TD->getDecl());
Eugene Zelenko7855e772018-04-03 00:11:50 +00005840 const auto *TagType =
Ben Langmuirf5416742016-02-04 00:55:24 +00005841 CFConstantStringTypeDecl->getUnderlyingType()->getAs<RecordType>();
5842 assert(TagType && "Invalid CFConstantStringType");
5843 CFConstantStringTagDecl = TagType->getDecl();
Douglas Gregor512b0772009-04-23 22:29:11 +00005844}
5845
Jay Foad39c79802011-01-12 09:06:06 +00005846QualType ASTContext::getBlockDescriptorType() const {
Mike Stumpd0153282009-10-20 02:12:22 +00005847 if (BlockDescriptorType)
5848 return getTagDeclType(BlockDescriptorType);
5849
Alp Toker2dea15b2013-12-17 01:22:38 +00005850 RecordDecl *RD;
Mike Stumpd0153282009-10-20 02:12:22 +00005851 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00005852 RD = buildImplicitRecord("__block_descriptor");
5853 RD->startDefinition();
5854
Mike Stumpd0153282009-10-20 02:12:22 +00005855 QualType FieldTypes[] = {
5856 UnsignedLongTy,
5857 UnsignedLongTy,
5858 };
5859
Craig Topperd6d31ac2013-07-15 08:24:27 +00005860 static const char *const FieldNames[] = {
Mike Stumpd0153282009-10-20 02:12:22 +00005861 "reserved",
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005862 "Size"
Mike Stumpd0153282009-10-20 02:12:22 +00005863 };
5864
5865 for (size_t i = 0; i < 2; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00005866 FieldDecl *Field = FieldDecl::Create(
5867 *this, RD, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00005868 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
5869 /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00005870 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00005871 RD->addDecl(Field);
Mike Stumpd0153282009-10-20 02:12:22 +00005872 }
5873
Alp Toker2dea15b2013-12-17 01:22:38 +00005874 RD->completeDefinition();
Mike Stumpd0153282009-10-20 02:12:22 +00005875
Alp Toker2dea15b2013-12-17 01:22:38 +00005876 BlockDescriptorType = RD;
Mike Stumpd0153282009-10-20 02:12:22 +00005877
5878 return getTagDeclType(BlockDescriptorType);
5879}
5880
Jay Foad39c79802011-01-12 09:06:06 +00005881QualType ASTContext::getBlockDescriptorExtendedType() const {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005882 if (BlockDescriptorExtendedType)
5883 return getTagDeclType(BlockDescriptorExtendedType);
5884
Alp Toker2dea15b2013-12-17 01:22:38 +00005885 RecordDecl *RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005886 // FIXME: Needs the FlagAppleBlock bit.
Alp Toker2dea15b2013-12-17 01:22:38 +00005887 RD = buildImplicitRecord("__block_descriptor_withcopydispose");
5888 RD->startDefinition();
5889
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005890 QualType FieldTypes[] = {
5891 UnsignedLongTy,
5892 UnsignedLongTy,
5893 getPointerType(VoidPtrTy),
5894 getPointerType(VoidPtrTy)
5895 };
5896
Craig Topperd6d31ac2013-07-15 08:24:27 +00005897 static const char *const FieldNames[] = {
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005898 "reserved",
5899 "Size",
5900 "CopyFuncPtr",
5901 "DestroyFuncPtr"
5902 };
5903
5904 for (size_t i = 0; i < 4; ++i) {
Alp Toker2dea15b2013-12-17 01:22:38 +00005905 FieldDecl *Field = FieldDecl::Create(
5906 *this, RD, SourceLocation(), SourceLocation(),
Craig Topper36250ad2014-05-12 05:36:57 +00005907 &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
5908 /*BitWidth=*/nullptr,
Alp Toker2dea15b2013-12-17 01:22:38 +00005909 /*Mutable=*/false, ICIS_NoInit);
John McCall4d4dcc82010-04-30 21:35:41 +00005910 Field->setAccess(AS_public);
Alp Toker2dea15b2013-12-17 01:22:38 +00005911 RD->addDecl(Field);
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005912 }
5913
Alp Toker2dea15b2013-12-17 01:22:38 +00005914 RD->completeDefinition();
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005915
Alp Toker2dea15b2013-12-17 01:22:38 +00005916 BlockDescriptorExtendedType = RD;
Mike Stumpe1b19ba2009-10-22 00:49:09 +00005917 return getTagDeclType(BlockDescriptorExtendedType);
5918}
5919
Sven van Haastregt3bb7eaf2017-12-06 10:11:28 +00005920TargetInfo::OpenCLTypeKind ASTContext::getOpenCLTypeKind(const Type *T) const {
Eugene Zelenko7855e772018-04-03 00:11:50 +00005921 const auto *BT = dyn_cast<BuiltinType>(T);
Sven van Haastregt3bb7eaf2017-12-06 10:11:28 +00005922
5923 if (!BT) {
5924 if (isa<PipeType>(T))
5925 return TargetInfo::OCLTK_Pipe;
5926
5927 return TargetInfo::OCLTK_Default;
5928 }
5929
5930 switch (BT->getKind()) {
5931#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
5932 case BuiltinType::Id: \
5933 return TargetInfo::OCLTK_Image;
5934#include "clang/Basic/OpenCLImageTypes.def"
5935
5936 case BuiltinType::OCLClkEvent:
5937 return TargetInfo::OCLTK_ClkEvent;
5938
5939 case BuiltinType::OCLEvent:
5940 return TargetInfo::OCLTK_Event;
5941
5942 case BuiltinType::OCLQueue:
5943 return TargetInfo::OCLTK_Queue;
5944
5945 case BuiltinType::OCLReserveID:
5946 return TargetInfo::OCLTK_ReserveID;
5947
5948 case BuiltinType::OCLSampler:
5949 return TargetInfo::OCLTK_Sampler;
5950
5951 default:
5952 return TargetInfo::OCLTK_Default;
5953 }
5954}
5955
5956LangAS ASTContext::getOpenCLTypeAddrSpace(const Type *T) const {
5957 return Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T));
5958}
5959
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00005960/// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
5961/// requires copy/dispose. Note that this must match the logic
5962/// in buildByrefHelpers.
5963bool ASTContext::BlockRequiresCopying(QualType Ty,
5964 const VarDecl *D) {
5965 if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
Akira Hatanaka9978da32018-08-10 15:09:24 +00005966 const Expr *copyExpr = getBlockVarCopyInit(D).getCopyExpr();
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00005967 if (!copyExpr && record->hasTrivialDestructor()) return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00005968
Mike Stump94967902009-10-21 18:16:27 +00005969 return true;
Fariborz Jahaniana00076c2010-11-17 00:21:28 +00005970 }
Fangrui Song6907ce22018-07-30 19:24:48 +00005971
Akira Hatanaka7275da02018-02-28 07:15:55 +00005972 // The block needs copy/destroy helpers if Ty is non-trivial to destructively
5973 // move or destroy.
5974 if (Ty.isNonTrivialToPrimitiveDestructiveMove() || Ty.isDestructedType())
5975 return true;
5976
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00005977 if (!Ty->isObjCRetainableType()) return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00005978
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00005979 Qualifiers qs = Ty.getQualifiers();
Fangrui Song6907ce22018-07-30 19:24:48 +00005980
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00005981 // If we have lifetime, that dominates.
5982 if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00005983 switch (lifetime) {
5984 case Qualifiers::OCL_None: llvm_unreachable("impossible");
Fangrui Song6907ce22018-07-30 19:24:48 +00005985
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00005986 // These are just bits as far as the runtime is concerned.
5987 case Qualifiers::OCL_ExplicitNone:
5988 case Qualifiers::OCL_Autoreleasing:
5989 return false;
Akira Hatanaka7275da02018-02-28 07:15:55 +00005990
5991 // These cases should have been taken care of when checking the type's
5992 // non-triviality.
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00005993 case Qualifiers::OCL_Weak:
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00005994 case Qualifiers::OCL_Strong:
Akira Hatanaka7275da02018-02-28 07:15:55 +00005995 llvm_unreachable("impossible");
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00005996 }
5997 llvm_unreachable("fell out of lifetime switch!");
5998 }
5999 return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
6000 Ty->isObjCObjectPointerType());
Mike Stump94967902009-10-21 18:16:27 +00006001}
6002
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00006003bool ASTContext::getByrefLifetime(QualType Ty,
6004 Qualifiers::ObjCLifetime &LifeTime,
6005 bool &HasByrefExtendedLayout) const {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00006006 if (!getLangOpts().ObjC1 ||
6007 getLangOpts().getGC() != LangOptions::NonGC)
6008 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00006009
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00006010 HasByrefExtendedLayout = false;
Fariborz Jahanianf762b722012-12-11 19:58:01 +00006011 if (Ty->isRecordType()) {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00006012 HasByrefExtendedLayout = true;
6013 LifeTime = Qualifiers::OCL_None;
John McCall460ce582015-10-22 18:38:17 +00006014 } else if ((LifeTime = Ty.getObjCLifetime())) {
6015 // Honor the ARC qualifiers.
6016 } else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) {
6017 // The MRR rule.
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00006018 LifeTime = Qualifiers::OCL_ExplicitNone;
John McCall460ce582015-10-22 18:38:17 +00006019 } else {
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00006020 LifeTime = Qualifiers::OCL_None;
John McCall460ce582015-10-22 18:38:17 +00006021 }
Fariborz Jahaniana9d44642012-11-14 17:15:51 +00006022 return true;
6023}
6024
Douglas Gregorbab8a962011-09-08 01:46:34 +00006025TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
6026 if (!ObjCInstanceTypeDecl)
Alp Toker56b5cc92013-12-15 10:36:26 +00006027 ObjCInstanceTypeDecl =
6028 buildImplicitTypedef(getObjCIdType(), "instancetype");
Douglas Gregorbab8a962011-09-08 01:46:34 +00006029 return ObjCInstanceTypeDecl;
6030}
6031
Anders Carlsson18acd442007-10-29 06:33:42 +00006032// This returns true if a type has been typedefed to BOOL:
6033// typedef <type> BOOL;
Chris Lattnere0218992007-10-30 20:27:44 +00006034static bool isTypeTypedefedAsBOOL(QualType T) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006035 if (const auto *TT = dyn_cast<TypedefType>(T))
Chris Lattner9b1f2792008-11-24 03:52:59 +00006036 if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
6037 return II->isStr("BOOL");
Mike Stump11289f42009-09-09 15:08:12 +00006038
Anders Carlssond8499822007-10-29 05:01:08 +00006039 return false;
6040}
6041
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006042/// getObjCEncodingTypeSize returns size of type for objective-c encoding
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006043/// purpose.
Jay Foad39c79802011-01-12 09:06:06 +00006044CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
Douglas Gregora9d84932011-05-27 01:19:52 +00006045 if (!type->isIncompleteArrayType() && type->isIncompleteType())
6046 return CharUnits::Zero();
Fangrui Song6907ce22018-07-30 19:24:48 +00006047
Ken Dyck40775002010-01-11 17:06:35 +00006048 CharUnits sz = getTypeSizeInChars(type);
Mike Stump11289f42009-09-09 15:08:12 +00006049
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006050 // Make all integer and enum types at least as large as an int
Douglas Gregorb90df602010-06-16 00:17:44 +00006051 if (sz.isPositive() && type->isIntegralOrEnumerationType())
Ken Dyck40775002010-01-11 17:06:35 +00006052 sz = std::max(sz, getTypeSizeInChars(IntTy));
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006053 // Treat arrays as pointers, since that's how they're passed in.
6054 else if (type->isArrayType())
Ken Dyck40775002010-01-11 17:06:35 +00006055 sz = getTypeSizeInChars(VoidPtrTy);
Ken Dyckde37a672010-01-11 19:19:56 +00006056 return sz;
Ken Dyck40775002010-01-11 17:06:35 +00006057}
6058
Hans Wennborg56fc62b2014-07-17 20:25:23 +00006059bool ASTContext::isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const {
David Majnemer3f021502015-10-08 04:53:31 +00006060 return getTargetInfo().getCXXABI().isMicrosoft() &&
6061 VD->isStaticDataMember() &&
Hans Wennborgb18da9b2018-02-20 12:43:02 +00006062 VD->getType()->isIntegralOrEnumerationType() &&
David Majnemerfac52432015-10-19 23:22:49 +00006063 !VD->getFirstDecl()->isOutOfLine() && VD->getFirstDecl()->hasInit();
Hans Wennborg56fc62b2014-07-17 20:25:23 +00006064}
6065
Richard Smithd9b90092016-07-02 01:32:16 +00006066ASTContext::InlineVariableDefinitionKind
6067ASTContext::getInlineVariableDefinitionKind(const VarDecl *VD) const {
6068 if (!VD->isInline())
6069 return InlineVariableDefinitionKind::None;
6070
6071 // In almost all cases, it's a weak definition.
6072 auto *First = VD->getFirstDecl();
Richard Smith8910fe62017-10-23 03:58:34 +00006073 if (First->isInlineSpecified() || !First->isStaticDataMember())
Richard Smithd9b90092016-07-02 01:32:16 +00006074 return InlineVariableDefinitionKind::Weak;
6075
6076 // If there's a file-context declaration in this translation unit, it's a
6077 // non-discardable definition.
6078 for (auto *D : VD->redecls())
Richard Smith8910fe62017-10-23 03:58:34 +00006079 if (D->getLexicalDeclContext()->isFileContext() &&
6080 !D->isInlineSpecified() && (D->isConstexpr() || First->isConstexpr()))
Richard Smithd9b90092016-07-02 01:32:16 +00006081 return InlineVariableDefinitionKind::Strong;
6082
6083 // If we've not seen one yet, we don't know.
6084 return InlineVariableDefinitionKind::WeakUnknown;
6085}
6086
Eugene Zelenko7855e772018-04-03 00:11:50 +00006087static std::string charUnitsToString(const CharUnits &CU) {
Ken Dyck40775002010-01-11 17:06:35 +00006088 return llvm::itostr(CU.getQuantity());
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006089}
6090
John McCall351762c2011-02-07 10:33:21 +00006091/// getObjCEncodingForBlock - Return the encoded type for this block
David Chisnall950a9512009-11-17 19:33:30 +00006092/// declaration.
John McCall351762c2011-02-07 10:33:21 +00006093std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
6094 std::string S;
6095
David Chisnall950a9512009-11-17 19:33:30 +00006096 const BlockDecl *Decl = Expr->getBlockDecl();
6097 QualType BlockTy =
6098 Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
6099 // Encode result type.
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00006100 if (getLangOpts().EncodeExtendedBlockSig)
Alp Toker314cc812014-01-25 16:55:45 +00006101 getObjCEncodingForMethodParameter(
6102 Decl::OBJC_TQ_None, BlockTy->getAs<FunctionType>()->getReturnType(), S,
6103 true /*Extended*/);
Fariborz Jahanian64223e62012-11-14 23:11:38 +00006104 else
Alp Toker314cc812014-01-25 16:55:45 +00006105 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getReturnType(), S);
David Chisnall950a9512009-11-17 19:33:30 +00006106 // Compute size of all parameters.
6107 // Start with computing size of a pointer in number of bytes.
6108 // FIXME: There might(should) be a better way of doing this computation!
Ken Dyck40775002010-01-11 17:06:35 +00006109 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
6110 CharUnits ParmOffset = PtrSize;
David Majnemer59f77922016-06-24 04:05:48 +00006111 for (auto PI : Decl->parameters()) {
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +00006112 QualType PType = PI->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00006113 CharUnits sz = getObjCEncodingTypeSize(PType);
Fariborz Jahaniand4879412012-06-30 00:48:59 +00006114 if (sz.isZero())
6115 continue;
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00006116 assert(sz.isPositive() && "BlockExpr - Incomplete param type");
David Chisnall950a9512009-11-17 19:33:30 +00006117 ParmOffset += sz;
6118 }
6119 // Size of the argument frame
Ken Dyck40775002010-01-11 17:06:35 +00006120 S += charUnitsToString(ParmOffset);
David Chisnall950a9512009-11-17 19:33:30 +00006121 // Block pointer and offset.
6122 S += "@?0";
Fangrui Song6907ce22018-07-30 19:24:48 +00006123
David Chisnall950a9512009-11-17 19:33:30 +00006124 // Argument types.
6125 ParmOffset = PtrSize;
David Majnemer59f77922016-06-24 04:05:48 +00006126 for (auto PVDecl : Decl->parameters()) {
Fangrui Song6907ce22018-07-30 19:24:48 +00006127 QualType PType = PVDecl->getOriginalType();
Eugene Zelenko7855e772018-04-03 00:11:50 +00006128 if (const auto *AT =
6129 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
David Chisnall950a9512009-11-17 19:33:30 +00006130 // Use array's original type only if it has known number of
6131 // elements.
6132 if (!isa<ConstantArrayType>(AT))
6133 PType = PVDecl->getType();
6134 } else if (PType->isFunctionType())
6135 PType = PVDecl->getType();
Fariborz Jahanian0e3043b2012-11-15 19:02:45 +00006136 if (getLangOpts().EncodeExtendedBlockSig)
Fariborz Jahanian64223e62012-11-14 23:11:38 +00006137 getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
6138 S, true /*Extended*/);
6139 else
6140 getObjCEncodingForType(PType, S);
Ken Dyck40775002010-01-11 17:06:35 +00006141 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00006142 ParmOffset += getObjCEncodingTypeSize(PType);
David Chisnall950a9512009-11-17 19:33:30 +00006143 }
John McCall351762c2011-02-07 10:33:21 +00006144
6145 return S;
David Chisnall950a9512009-11-17 19:33:30 +00006146}
6147
John McCall843dfcc2016-11-29 21:57:00 +00006148std::string
6149ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl) const {
6150 std::string S;
David Chisnall50e4eba2010-12-30 14:05:53 +00006151 // Encode result type.
Alp Toker314cc812014-01-25 16:55:45 +00006152 getObjCEncodingForType(Decl->getReturnType(), S);
David Chisnall50e4eba2010-12-30 14:05:53 +00006153 CharUnits ParmOffset;
6154 // Compute size of all parameters.
David Majnemer59f77922016-06-24 04:05:48 +00006155 for (auto PI : Decl->parameters()) {
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00006156 QualType PType = PI->getType();
David Chisnall50e4eba2010-12-30 14:05:53 +00006157 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00006158 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00006159 continue;
Fangrui Song6907ce22018-07-30 19:24:48 +00006160
6161 assert(sz.isPositive() &&
John McCall843dfcc2016-11-29 21:57:00 +00006162 "getObjCEncodingForFunctionDecl - Incomplete param type");
David Chisnall50e4eba2010-12-30 14:05:53 +00006163 ParmOffset += sz;
6164 }
6165 S += charUnitsToString(ParmOffset);
6166 ParmOffset = CharUnits::Zero();
6167
6168 // Argument types.
David Majnemer59f77922016-06-24 04:05:48 +00006169 for (auto PVDecl : Decl->parameters()) {
David Chisnall50e4eba2010-12-30 14:05:53 +00006170 QualType PType = PVDecl->getOriginalType();
Eugene Zelenko7855e772018-04-03 00:11:50 +00006171 if (const auto *AT =
6172 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
David Chisnall50e4eba2010-12-30 14:05:53 +00006173 // Use array's original type only if it has known number of
6174 // elements.
6175 if (!isa<ConstantArrayType>(AT))
6176 PType = PVDecl->getType();
6177 } else if (PType->isFunctionType())
6178 PType = PVDecl->getType();
6179 getObjCEncodingForType(PType, S);
6180 S += charUnitsToString(ParmOffset);
6181 ParmOffset += getObjCEncodingTypeSize(PType);
6182 }
Fangrui Song6907ce22018-07-30 19:24:48 +00006183
John McCall843dfcc2016-11-29 21:57:00 +00006184 return S;
David Chisnall50e4eba2010-12-30 14:05:53 +00006185}
6186
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006187/// getObjCEncodingForMethodParameter - Return the encoded type for a single
Fangrui Song6907ce22018-07-30 19:24:48 +00006188/// method parameter or return type. If Extended, include class names and
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006189/// block object types.
6190void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
6191 QualType T, std::string& S,
6192 bool Extended) const {
6193 // Encode type qualifer, 'in', 'inout', etc. for the parameter.
6194 getObjCEncodingForTypeQualifier(QT, S);
6195 // Encode parameter type.
Craig Topper36250ad2014-05-12 05:36:57 +00006196 getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006197 true /*OutermostType*/,
Fangrui Song6907ce22018-07-30 19:24:48 +00006198 false /*EncodingProperty*/,
6199 false /*StructField*/,
6200 Extended /*EncodeBlockParameters*/,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006201 Extended /*EncodeClassNames*/);
6202}
6203
Ted Kremenek1b0ea822008-01-07 19:49:32 +00006204/// getObjCEncodingForMethodDecl - Return the encoded type for this method
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006205/// declaration.
John McCall843dfcc2016-11-29 21:57:00 +00006206std::string ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
6207 bool Extended) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00006208 // FIXME: This is not very efficient.
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006209 // Encode return type.
John McCall843dfcc2016-11-29 21:57:00 +00006210 std::string S;
Alp Toker314cc812014-01-25 16:55:45 +00006211 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
6212 Decl->getReturnType(), S, Extended);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006213 // Compute size of all parameters.
6214 // Start with computing size of a pointer in number of bytes.
6215 // FIXME: There might(should) be a better way of doing this computation!
Ken Dyck40775002010-01-11 17:06:35 +00006216 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006217 // The first two arguments (self and _cmd) are pointers; account for
6218 // their size.
Ken Dyck40775002010-01-11 17:06:35 +00006219 CharUnits ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00006220 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00006221 E = Decl->sel_param_end(); PI != E; ++PI) {
Chris Lattnera4997152009-02-20 18:43:26 +00006222 QualType PType = (*PI)->getType();
Ken Dyckde37a672010-01-11 19:19:56 +00006223 CharUnits sz = getObjCEncodingTypeSize(PType);
Douglas Gregora9d84932011-05-27 01:19:52 +00006224 if (sz.isZero())
Fariborz Jahanian271b8d42012-06-29 22:54:56 +00006225 continue;
Fangrui Song6907ce22018-07-30 19:24:48 +00006226
6227 assert(sz.isPositive() &&
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00006228 "getObjCEncodingForMethodDecl - Incomplete param type");
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006229 ParmOffset += sz;
6230 }
Ken Dyck40775002010-01-11 17:06:35 +00006231 S += charUnitsToString(ParmOffset);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006232 S += "@0:";
Ken Dyck40775002010-01-11 17:06:35 +00006233 S += charUnitsToString(PtrSize);
Mike Stump11289f42009-09-09 15:08:12 +00006234
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006235 // Argument types.
6236 ParmOffset = 2 * PtrSize;
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00006237 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
Fariborz Jahaniand9235db2010-04-08 21:29:11 +00006238 E = Decl->sel_param_end(); PI != E; ++PI) {
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00006239 const ParmVarDecl *PVDecl = *PI;
Mike Stump11289f42009-09-09 15:08:12 +00006240 QualType PType = PVDecl->getOriginalType();
Eugene Zelenko7855e772018-04-03 00:11:50 +00006241 if (const auto *AT =
6242 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
Steve Naroffe4e55d22009-04-14 00:03:58 +00006243 // Use array's original type only if it has known number of
6244 // elements.
Steve Naroff323827e2009-04-14 00:40:09 +00006245 if (!isa<ConstantArrayType>(AT))
Steve Naroffe4e55d22009-04-14 00:03:58 +00006246 PType = PVDecl->getType();
6247 } else if (PType->isFunctionType())
6248 PType = PVDecl->getType();
Fangrui Song6907ce22018-07-30 19:24:48 +00006249 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006250 PType, S, Extended);
Ken Dyck40775002010-01-11 17:06:35 +00006251 S += charUnitsToString(ParmOffset);
Ken Dyckde37a672010-01-11 19:19:56 +00006252 ParmOffset += getObjCEncodingTypeSize(PType);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006253 }
Fangrui Song6907ce22018-07-30 19:24:48 +00006254
John McCall843dfcc2016-11-29 21:57:00 +00006255 return S;
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00006256}
6257
Fariborz Jahaniandad96302014-01-22 19:02:20 +00006258ObjCPropertyImplDecl *
6259ASTContext::getObjCPropertyImplDeclForPropertyDecl(
6260 const ObjCPropertyDecl *PD,
6261 const Decl *Container) const {
6262 if (!Container)
Craig Topper36250ad2014-05-12 05:36:57 +00006263 return nullptr;
Eugene Zelenko7855e772018-04-03 00:11:50 +00006264 if (const auto *CID = dyn_cast<ObjCCategoryImplDecl>(Container)) {
Aaron Ballmand85eff42014-03-14 15:02:45 +00006265 for (auto *PID : CID->property_impls())
6266 if (PID->getPropertyDecl() == PD)
6267 return PID;
Craig Topper36250ad2014-05-12 05:36:57 +00006268 } else {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006269 const auto *OID = cast<ObjCImplementationDecl>(Container);
Craig Topper36250ad2014-05-12 05:36:57 +00006270 for (auto *PID : OID->property_impls())
6271 if (PID->getPropertyDecl() == PD)
6272 return PID;
6273 }
6274 return nullptr;
Fariborz Jahaniandad96302014-01-22 19:02:20 +00006275}
6276
Daniel Dunbar4932b362008-08-28 04:38:10 +00006277/// getObjCEncodingForPropertyDecl - Return the encoded type for this
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00006278/// property declaration. If non-NULL, Container must be either an
Daniel Dunbar4932b362008-08-28 04:38:10 +00006279/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
6280/// NULL when getting encodings for protocol properties.
Mike Stump11289f42009-09-09 15:08:12 +00006281/// Property attributes are stored as a comma-delimited C string. The simple
6282/// attributes readonly and bycopy are encoded as single characters. The
6283/// parametrized attributes, getter=name, setter=name, and ivar=name, are
6284/// encoded as single characters, followed by an identifier. Property types
6285/// are also encoded as a parametrized attribute. The characters used to encode
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00006286/// these attributes are defined by the following enumeration:
6287/// @code
6288/// enum PropertyAttributes {
6289/// kPropertyReadOnly = 'R', // property is read-only.
6290/// kPropertyBycopy = 'C', // property is a copy of the value last assigned
6291/// kPropertyByref = '&', // property is a reference to the value last assigned
6292/// kPropertyDynamic = 'D', // property is dynamic
6293/// kPropertyGetter = 'G', // followed by getter selector name
6294/// kPropertySetter = 'S', // followed by setter selector name
6295/// kPropertyInstanceVariable = 'V' // followed by instance variable name
Bob Wilson8cf61852012-03-22 17:48:02 +00006296/// kPropertyType = 'T' // followed by old-style type encoding.
Fariborz Jahanian2f85a642009-01-20 20:04:12 +00006297/// kPropertyWeak = 'W' // 'weak' property
6298/// kPropertyStrong = 'P' // property GC'able
6299/// kPropertyNonAtomic = 'N' // property non-atomic
6300/// };
6301/// @endcode
John McCall843dfcc2016-11-29 21:57:00 +00006302std::string
6303ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
6304 const Decl *Container) const {
Daniel Dunbar4932b362008-08-28 04:38:10 +00006305 // Collect information from the property implementation decl(s).
6306 bool Dynamic = false;
Craig Topper36250ad2014-05-12 05:36:57 +00006307 ObjCPropertyImplDecl *SynthesizePID = nullptr;
Daniel Dunbar4932b362008-08-28 04:38:10 +00006308
Fariborz Jahaniandad96302014-01-22 19:02:20 +00006309 if (ObjCPropertyImplDecl *PropertyImpDecl =
6310 getObjCPropertyImplDeclForPropertyDecl(PD, Container)) {
6311 if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
6312 Dynamic = true;
6313 else
6314 SynthesizePID = PropertyImpDecl;
Daniel Dunbar4932b362008-08-28 04:38:10 +00006315 }
6316
6317 // FIXME: This is not very efficient.
John McCall843dfcc2016-11-29 21:57:00 +00006318 std::string S = "T";
Daniel Dunbar4932b362008-08-28 04:38:10 +00006319
6320 // Encode result type.
Fariborz Jahanian218c6302009-01-20 19:14:18 +00006321 // GCC has some special rules regarding encoding of properties which
6322 // closely resembles encoding of ivars.
Joe Groff98ac7d22014-07-07 22:25:15 +00006323 getObjCEncodingForPropertyType(PD->getType(), S);
Daniel Dunbar4932b362008-08-28 04:38:10 +00006324
6325 if (PD->isReadOnly()) {
6326 S += ",R";
Nico Weber4e8626f2013-05-08 23:47:40 +00006327 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy)
6328 S += ",C";
6329 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain)
6330 S += ",&";
Fariborz Jahanian33079ee2014-04-02 22:49:42 +00006331 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak)
6332 S += ",W";
Daniel Dunbar4932b362008-08-28 04:38:10 +00006333 } else {
6334 switch (PD->getSetterKind()) {
6335 case ObjCPropertyDecl::Assign: break;
6336 case ObjCPropertyDecl::Copy: S += ",C"; break;
Mike Stump11289f42009-09-09 15:08:12 +00006337 case ObjCPropertyDecl::Retain: S += ",&"; break;
Fariborz Jahanian70a315c2011-08-12 20:47:08 +00006338 case ObjCPropertyDecl::Weak: S += ",W"; break;
Daniel Dunbar4932b362008-08-28 04:38:10 +00006339 }
6340 }
6341
6342 // It really isn't clear at all what this means, since properties
6343 // are "dynamic by default".
6344 if (Dynamic)
6345 S += ",D";
6346
Fariborz Jahanian218c6302009-01-20 19:14:18 +00006347 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
6348 S += ",N";
Mike Stump11289f42009-09-09 15:08:12 +00006349
Daniel Dunbar4932b362008-08-28 04:38:10 +00006350 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
6351 S += ",G";
Chris Lattnere4b95692008-11-24 03:33:13 +00006352 S += PD->getGetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00006353 }
6354
6355 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
6356 S += ",S";
Chris Lattnere4b95692008-11-24 03:33:13 +00006357 S += PD->getSetterName().getAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00006358 }
6359
6360 if (SynthesizePID) {
6361 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
6362 S += ",V";
Chris Lattner1cbaacc2008-11-24 04:00:27 +00006363 S += OID->getNameAsString();
Daniel Dunbar4932b362008-08-28 04:38:10 +00006364 }
6365
6366 // FIXME: OBJCGC: weak & strong
John McCall843dfcc2016-11-29 21:57:00 +00006367 return S;
Daniel Dunbar4932b362008-08-28 04:38:10 +00006368}
6369
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006370/// getLegacyIntegralTypeEncoding -
Mike Stump11289f42009-09-09 15:08:12 +00006371/// Another legacy compatibility encoding: 32-bit longs are encoded as
6372/// 'l' or 'L' , but not always. For typedefs, we need to use
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006373/// 'i' or 'I' instead if encoding a struct field, or a pointer!
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006374void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
Mike Stump212005c2009-07-22 18:58:19 +00006375 if (isa<TypedefType>(PointeeTy.getTypePtr())) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006376 if (const auto *BT = PointeeTy->getAs<BuiltinType>()) {
Jay Foad39c79802011-01-12 09:06:06 +00006377 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006378 PointeeTy = UnsignedIntTy;
Mike Stump11289f42009-09-09 15:08:12 +00006379 else
Jay Foad39c79802011-01-12 09:06:06 +00006380 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006381 PointeeTy = IntTy;
6382 }
6383 }
6384}
6385
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00006386void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006387 const FieldDecl *Field,
6388 QualType *NotEncodedT) const {
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00006389 // We follow the behavior of gcc, expanding structures which are
6390 // directly pointed to, and expanding embedded structures. Note that
6391 // these rules are sufficient to prevent recursive encoding of the
6392 // same type.
Mike Stump11289f42009-09-09 15:08:12 +00006393 getObjCEncodingForTypeImpl(T, S, true, true, Field,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006394 true /* outermost type */, false, false,
6395 false, false, false, NotEncodedT);
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00006396}
6397
Joe Groff98ac7d22014-07-07 22:25:15 +00006398void ASTContext::getObjCEncodingForPropertyType(QualType T,
6399 std::string& S) const {
6400 // Encode result type.
6401 // GCC has some special rules regarding encoding of properties which
6402 // closely resembles encoding of ivars.
6403 getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
6404 true /* outermost type */,
6405 true /* encoding property */);
6406}
6407
John McCall393a78d2012-12-20 02:45:14 +00006408static char getObjCEncodingForPrimitiveKind(const ASTContext *C,
6409 BuiltinType::Kind kind) {
6410 switch (kind) {
David Chisnallb190a2c2010-06-04 01:10:52 +00006411 case BuiltinType::Void: return 'v';
6412 case BuiltinType::Bool: return 'B';
Richard Smith3a8244d2018-05-01 05:02:45 +00006413 case BuiltinType::Char8:
David Chisnallb190a2c2010-06-04 01:10:52 +00006414 case BuiltinType::Char_U:
6415 case BuiltinType::UChar: return 'C';
John McCall393a78d2012-12-20 02:45:14 +00006416 case BuiltinType::Char16:
David Chisnallb190a2c2010-06-04 01:10:52 +00006417 case BuiltinType::UShort: return 'S';
John McCall393a78d2012-12-20 02:45:14 +00006418 case BuiltinType::Char32:
David Chisnallb190a2c2010-06-04 01:10:52 +00006419 case BuiltinType::UInt: return 'I';
6420 case BuiltinType::ULong:
John McCall393a78d2012-12-20 02:45:14 +00006421 return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
David Chisnallb190a2c2010-06-04 01:10:52 +00006422 case BuiltinType::UInt128: return 'T';
6423 case BuiltinType::ULongLong: return 'Q';
6424 case BuiltinType::Char_S:
6425 case BuiltinType::SChar: return 'c';
6426 case BuiltinType::Short: return 's';
Chris Lattnerad3467e2010-12-25 23:25:43 +00006427 case BuiltinType::WChar_S:
6428 case BuiltinType::WChar_U:
David Chisnallb190a2c2010-06-04 01:10:52 +00006429 case BuiltinType::Int: return 'i';
6430 case BuiltinType::Long:
John McCall393a78d2012-12-20 02:45:14 +00006431 return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
David Chisnallb190a2c2010-06-04 01:10:52 +00006432 case BuiltinType::LongLong: return 'q';
6433 case BuiltinType::Int128: return 't';
6434 case BuiltinType::Float: return 'f';
6435 case BuiltinType::Double: return 'd';
Daniel Dunbar7cba5a72010-10-11 21:13:48 +00006436 case BuiltinType::LongDouble: return 'D';
John McCall393a78d2012-12-20 02:45:14 +00006437 case BuiltinType::NullPtr: return '*'; // like char*
6438
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00006439 case BuiltinType::Float16:
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00006440 case BuiltinType::Float128:
John McCall393a78d2012-12-20 02:45:14 +00006441 case BuiltinType::Half:
Leonard Chanf921d852018-06-04 16:07:52 +00006442 case BuiltinType::ShortAccum:
6443 case BuiltinType::Accum:
6444 case BuiltinType::LongAccum:
6445 case BuiltinType::UShortAccum:
6446 case BuiltinType::UAccum:
6447 case BuiltinType::ULongAccum:
Leonard Chanab80f3c2018-06-14 14:53:51 +00006448 case BuiltinType::ShortFract:
6449 case BuiltinType::Fract:
6450 case BuiltinType::LongFract:
6451 case BuiltinType::UShortFract:
6452 case BuiltinType::UFract:
6453 case BuiltinType::ULongFract:
6454 case BuiltinType::SatShortAccum:
6455 case BuiltinType::SatAccum:
6456 case BuiltinType::SatLongAccum:
6457 case BuiltinType::SatUShortAccum:
6458 case BuiltinType::SatUAccum:
6459 case BuiltinType::SatULongAccum:
6460 case BuiltinType::SatShortFract:
6461 case BuiltinType::SatFract:
6462 case BuiltinType::SatLongFract:
6463 case BuiltinType::SatUShortFract:
6464 case BuiltinType::SatUFract:
6465 case BuiltinType::SatULongFract:
John McCall393a78d2012-12-20 02:45:14 +00006466 // FIXME: potentially need @encodes for these!
6467 return ' ';
6468
6469 case BuiltinType::ObjCId:
6470 case BuiltinType::ObjCClass:
6471 case BuiltinType::ObjCSel:
6472 llvm_unreachable("@encoding ObjC primitive type");
6473
6474 // OpenCL and placeholder types don't need @encodings.
Alexey Bader954ba212016-04-08 13:40:33 +00006475#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6476 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00006477#include "clang/Basic/OpenCLImageTypes.def"
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00006478 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +00006479 case BuiltinType::OCLClkEvent:
6480 case BuiltinType::OCLQueue:
Alexey Bader9c8453f2015-09-15 11:18:52 +00006481 case BuiltinType::OCLReserveID:
Guy Benyei61054192013-02-07 10:55:47 +00006482 case BuiltinType::OCLSampler:
John McCall393a78d2012-12-20 02:45:14 +00006483 case BuiltinType::Dependent:
6484#define BUILTIN_TYPE(KIND, ID)
6485#define PLACEHOLDER_TYPE(KIND, ID) \
6486 case BuiltinType::KIND:
6487#include "clang/AST/BuiltinTypes.def"
6488 llvm_unreachable("invalid builtin type for @encode");
David Chisnallb190a2c2010-06-04 01:10:52 +00006489 }
David Blaikie5a6a0202013-01-09 17:48:41 +00006490 llvm_unreachable("invalid BuiltinType::Kind value");
David Chisnallb190a2c2010-06-04 01:10:52 +00006491}
6492
Douglas Gregor8b7d4032011-09-08 17:18:35 +00006493static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
6494 EnumDecl *Enum = ET->getDecl();
Fangrui Song6907ce22018-07-30 19:24:48 +00006495
Douglas Gregor8b7d4032011-09-08 17:18:35 +00006496 // The encoding of an non-fixed enum type is always 'i', regardless of size.
6497 if (!Enum->isFixed())
6498 return 'i';
Fangrui Song6907ce22018-07-30 19:24:48 +00006499
Douglas Gregor8b7d4032011-09-08 17:18:35 +00006500 // The encoding of a fixed enum type matches its fixed underlying type.
Eugene Zelenko7855e772018-04-03 00:11:50 +00006501 const auto *BT = Enum->getIntegerType()->castAs<BuiltinType>();
John McCall393a78d2012-12-20 02:45:14 +00006502 return getObjCEncodingForPrimitiveKind(C, BT->getKind());
Douglas Gregor8b7d4032011-09-08 17:18:35 +00006503}
6504
Jay Foad39c79802011-01-12 09:06:06 +00006505static void EncodeBitField(const ASTContext *Ctx, std::string& S,
David Chisnallb190a2c2010-06-04 01:10:52 +00006506 QualType T, const FieldDecl *FD) {
Richard Smithcaf33902011-10-10 18:28:20 +00006507 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
Fariborz Jahanian5c767722009-01-13 01:18:13 +00006508 S += 'b';
David Chisnallb190a2c2010-06-04 01:10:52 +00006509 // The NeXT runtime encodes bit fields as b followed by the number of bits.
6510 // The GNU runtime requires more information; bitfields are encoded as b,
6511 // then the offset (in bits) of the first element, then the type of the
6512 // bitfield, then the size in bits. For example, in this structure:
6513 //
6514 // struct
6515 // {
6516 // int integer;
6517 // int flags:2;
6518 // };
6519 // On a 32-bit system, the encoding for flags would be b2 for the NeXT
6520 // runtime, but b32i2 for the GNU runtime. The reason for this extra
6521 // information is not especially sensible, but we're stuck with it for
6522 // compatibility with GCC, although providing it breaks anything that
6523 // actually uses runtime introspection and wants to work on both runtimes...
John McCall5fb5df92012-06-20 06:18:46 +00006524 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
Akira Hatanaka4b1c4842017-06-27 04:34:04 +00006525 uint64_t Offset;
6526
6527 if (const auto *IVD = dyn_cast<ObjCIvarDecl>(FD)) {
6528 Offset = Ctx->lookupFieldBitOffset(IVD->getContainingInterface(), nullptr,
6529 IVD);
6530 } else {
6531 const RecordDecl *RD = FD->getParent();
6532 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
6533 Offset = RL.getFieldOffset(FD->getFieldIndex());
6534 }
6535
6536 S += llvm::utostr(Offset);
6537
Eugene Zelenko7855e772018-04-03 00:11:50 +00006538 if (const auto *ET = T->getAs<EnumType>())
Douglas Gregor8b7d4032011-09-08 17:18:35 +00006539 S += ObjCEncodingForEnumType(Ctx, ET);
John McCall393a78d2012-12-20 02:45:14 +00006540 else {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006541 const auto *BT = T->castAs<BuiltinType>();
John McCall393a78d2012-12-20 02:45:14 +00006542 S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind());
6543 }
David Chisnallb190a2c2010-06-04 01:10:52 +00006544 }
Richard Smithcaf33902011-10-10 18:28:20 +00006545 S += llvm::utostr(FD->getBitWidthValue(*Ctx));
Fariborz Jahanian5c767722009-01-13 01:18:13 +00006546}
6547
Daniel Dunbar07d07852009-10-18 21:17:35 +00006548// FIXME: Use SmallString for accumulating string.
Daniel Dunbar3cd9a292008-10-17 07:30:50 +00006549void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
6550 bool ExpandPointedToStructures,
6551 bool ExpandStructures,
Daniel Dunbarc040ce42009-04-20 06:37:24 +00006552 const FieldDecl *FD,
Fariborz Jahanian218c6302009-01-20 19:14:18 +00006553 bool OutermostType,
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006554 bool EncodingProperty,
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006555 bool StructField,
6556 bool EncodeBlockParameters,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00006557 bool EncodeClassNames,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006558 bool EncodePointerToObjCTypedef,
6559 QualType *NotEncodedT) const {
John McCall393a78d2012-12-20 02:45:14 +00006560 CanQualType CT = getCanonicalType(T);
6561 switch (CT->getTypeClass()) {
6562 case Type::Builtin:
6563 case Type::Enum:
Chris Lattnere7cabb92009-07-13 00:10:46 +00006564 if (FD && FD->isBitField())
David Chisnallb190a2c2010-06-04 01:10:52 +00006565 return EncodeBitField(this, S, T, FD);
Eugene Zelenko7855e772018-04-03 00:11:50 +00006566 if (const auto *BT = dyn_cast<BuiltinType>(CT))
John McCall393a78d2012-12-20 02:45:14 +00006567 S += getObjCEncodingForPrimitiveKind(this, BT->getKind());
6568 else
6569 S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
Chris Lattnere7cabb92009-07-13 00:10:46 +00006570 return;
Mike Stump11289f42009-09-09 15:08:12 +00006571
John McCall393a78d2012-12-20 02:45:14 +00006572 case Type::Complex: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006573 const auto *CT = T->castAs<ComplexType>();
Anders Carlsson39b2e132009-04-09 21:55:45 +00006574 S += 'j';
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006575 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, nullptr);
Chris Lattnere7cabb92009-07-13 00:10:46 +00006576 return;
6577 }
John McCall393a78d2012-12-20 02:45:14 +00006578
6579 case Type::Atomic: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006580 const auto *AT = T->castAs<AtomicType>();
John McCall393a78d2012-12-20 02:45:14 +00006581 S += 'A';
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006582 getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, nullptr);
John McCall393a78d2012-12-20 02:45:14 +00006583 return;
Fariborz Jahanian9ffd7062010-04-13 23:45:47 +00006584 }
John McCall393a78d2012-12-20 02:45:14 +00006585
6586 // encoding for pointer or reference types.
6587 case Type::Pointer:
6588 case Type::LValueReference:
6589 case Type::RValueReference: {
6590 QualType PointeeTy;
6591 if (isa<PointerType>(CT)) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006592 const auto *PT = T->castAs<PointerType>();
John McCall393a78d2012-12-20 02:45:14 +00006593 if (PT->isObjCSelType()) {
6594 S += ':';
6595 return;
6596 }
6597 PointeeTy = PT->getPointeeType();
6598 } else {
6599 PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
6600 }
6601
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006602 bool isReadOnly = false;
6603 // For historical/compatibility reasons, the read-only qualifier of the
6604 // pointee gets emitted _before_ the '^'. The read-only qualifier of
6605 // the pointer itself gets ignored, _unless_ we are looking at a typedef!
Mike Stump11289f42009-09-09 15:08:12 +00006606 // Also, do not emit the 'r' for anything but the outermost type!
Mike Stump212005c2009-07-22 18:58:19 +00006607 if (isa<TypedefType>(T.getTypePtr())) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006608 if (OutermostType && T.isConstQualified()) {
6609 isReadOnly = true;
6610 S += 'r';
6611 }
Mike Stumpe9c6ffc2009-07-31 02:02:20 +00006612 } else if (OutermostType) {
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006613 QualType P = PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006614 while (P->getAs<PointerType>())
6615 P = P->getAs<PointerType>()->getPointeeType();
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006616 if (P.isConstQualified()) {
6617 isReadOnly = true;
6618 S += 'r';
6619 }
6620 }
6621 if (isReadOnly) {
6622 // Another legacy compatibility encoding. Some ObjC qualifier and type
6623 // combinations need to be rearranged.
6624 // Rewrite "in const" from "nr" to "rn"
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006625 if (StringRef(S).endswith("nr"))
Benjamin Kramer2e3197e2010-04-27 17:12:11 +00006626 S.replace(S.end()-2, S.end(), "rn");
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006627 }
Mike Stump11289f42009-09-09 15:08:12 +00006628
Anders Carlssond8499822007-10-29 05:01:08 +00006629 if (PointeeTy->isCharType()) {
6630 // char pointer types should be encoded as '*' unless it is a
6631 // type that has been typedef'd to 'BOOL'.
Anders Carlsson18acd442007-10-29 06:33:42 +00006632 if (!isTypeTypedefedAsBOOL(PointeeTy)) {
Anders Carlssond8499822007-10-29 05:01:08 +00006633 S += '*';
6634 return;
6635 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00006636 } else if (const auto *RTy = PointeeTy->getAs<RecordType>()) {
Steve Naroff3de6b702009-07-22 17:14:51 +00006637 // GCC binary compat: Need to convert "struct objc_class *" to "#".
6638 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
6639 S += '#';
6640 return;
6641 }
6642 // GCC binary compat: Need to convert "struct objc_object *" to "@".
6643 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
6644 S += '@';
6645 return;
6646 }
6647 // fall through...
Anders Carlssond8499822007-10-29 05:01:08 +00006648 }
Anders Carlssond8499822007-10-29 05:01:08 +00006649 S += '^';
Fariborz Jahanian0f66a6c2008-12-23 19:56:47 +00006650 getLegacyIntegralTypeEncoding(PointeeTy);
6651
Mike Stump11289f42009-09-09 15:08:12 +00006652 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006653 nullptr, false, false, false, false, false, false,
6654 NotEncodedT);
Chris Lattnere7cabb92009-07-13 00:10:46 +00006655 return;
6656 }
John McCall393a78d2012-12-20 02:45:14 +00006657
6658 case Type::ConstantArray:
6659 case Type::IncompleteArray:
6660 case Type::VariableArray: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006661 const auto *AT = cast<ArrayType>(CT);
John McCall393a78d2012-12-20 02:45:14 +00006662
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006663 if (isa<IncompleteArrayType>(AT) && !StructField) {
Anders Carlssond05f44b2009-02-22 01:38:57 +00006664 // Incomplete arrays are encoded as a pointer to the array element.
6665 S += '^';
6666
Mike Stump11289f42009-09-09 15:08:12 +00006667 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Anders Carlssond05f44b2009-02-22 01:38:57 +00006668 false, ExpandStructures, FD);
6669 } else {
6670 S += '[';
Mike Stump11289f42009-09-09 15:08:12 +00006671
Eugene Zelenko7855e772018-04-03 00:11:50 +00006672 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
Fariborz Jahanianf0dc11a2013-06-04 16:04:37 +00006673 S += llvm::utostr(CAT->getSize().getZExtValue());
6674 else {
Anders Carlssond05f44b2009-02-22 01:38:57 +00006675 //Variable length arrays are encoded as a regular array with 0 elements.
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006676 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
6677 "Unknown array type!");
Anders Carlssond05f44b2009-02-22 01:38:57 +00006678 S += '0';
6679 }
Mike Stump11289f42009-09-09 15:08:12 +00006680
6681 getObjCEncodingForTypeImpl(AT->getElementType(), S,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006682 false, ExpandStructures, FD,
6683 false, false, false, false, false, false,
6684 NotEncodedT);
Anders Carlssond05f44b2009-02-22 01:38:57 +00006685 S += ']';
6686 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00006687 return;
6688 }
Mike Stump11289f42009-09-09 15:08:12 +00006689
John McCall393a78d2012-12-20 02:45:14 +00006690 case Type::FunctionNoProto:
6691 case Type::FunctionProto:
Anders Carlssondf4cc612007-10-30 00:06:20 +00006692 S += '?';
Chris Lattnere7cabb92009-07-13 00:10:46 +00006693 return;
Mike Stump11289f42009-09-09 15:08:12 +00006694
John McCall393a78d2012-12-20 02:45:14 +00006695 case Type::Record: {
6696 RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
Daniel Dunbarff3c6742008-10-17 16:17:37 +00006697 S += RDecl->isUnion() ? '(' : '{';
Daniel Dunbar40cac772008-10-17 06:22:57 +00006698 // Anonymous structures print as '?'
6699 if (const IdentifierInfo *II = RDecl->getIdentifier()) {
6700 S += II->getName();
Eugene Zelenko7855e772018-04-03 00:11:50 +00006701 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
Fariborz Jahanianc5158202010-05-07 00:28:49 +00006702 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
Benjamin Kramer9170e912013-02-22 15:46:01 +00006703 llvm::raw_string_ostream OS(S);
Serge Pavlov03e672c2017-11-28 16:14:14 +00006704 printTemplateArgumentList(OS, TemplateArgs.asArray(),
6705 getPrintingPolicy());
Fariborz Jahanianc5158202010-05-07 00:28:49 +00006706 }
Daniel Dunbar40cac772008-10-17 06:22:57 +00006707 } else {
6708 S += '?';
6709 }
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00006710 if (ExpandStructures) {
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00006711 S += '=';
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006712 if (!RDecl->isUnion()) {
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006713 getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006714 } else {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006715 for (const auto *Field : RDecl->fields()) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006716 if (FD) {
6717 S += '"';
6718 S += Field->getNameAsString();
6719 S += '"';
6720 }
Mike Stump11289f42009-09-09 15:08:12 +00006721
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006722 // Special case bit-fields.
6723 if (Field->isBitField()) {
6724 getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006725 Field);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006726 } else {
6727 QualType qt = Field->getType();
6728 getLegacyIntegralTypeEncoding(qt);
6729 getObjCEncodingForTypeImpl(qt, S, false, true,
6730 FD, /*OutermostType*/false,
6731 /*EncodingProperty*/false,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006732 /*StructField*/true,
6733 false, false, false, NotEncodedT);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006734 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00006735 }
Fariborz Jahanian0a71ad22008-01-22 22:44:46 +00006736 }
Fariborz Jahanianbc92fd72007-11-13 23:21:38 +00006737 }
Daniel Dunbarff3c6742008-10-17 16:17:37 +00006738 S += RDecl->isUnion() ? ')' : '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00006739 return;
6740 }
Mike Stump11289f42009-09-09 15:08:12 +00006741
John McCall393a78d2012-12-20 02:45:14 +00006742 case Type::BlockPointer: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006743 const auto *BT = T->castAs<BlockPointerType>();
Steve Naroff49140cb2009-02-02 18:24:29 +00006744 S += "@?"; // Unlike a pointer-to-function, which is "^?".
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006745 if (EncodeBlockParameters) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006746 const auto *FT = BT->getPointeeType()->castAs<FunctionType>();
Fangrui Song6907ce22018-07-30 19:24:48 +00006747
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006748 S += '<';
6749 // Block return type
Alp Toker314cc812014-01-25 16:55:45 +00006750 getObjCEncodingForTypeImpl(
6751 FT->getReturnType(), S, ExpandPointedToStructures, ExpandStructures,
6752 FD, false /* OutermostType */, EncodingProperty,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006753 false /* StructField */, EncodeBlockParameters, EncodeClassNames, false,
6754 NotEncodedT);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006755 // Block self
6756 S += "@?";
6757 // Block parameters
Eugene Zelenko7855e772018-04-03 00:11:50 +00006758 if (const auto *FPT = dyn_cast<FunctionProtoType>(FT)) {
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00006759 for (const auto &I : FPT->param_types())
6760 getObjCEncodingForTypeImpl(
6761 I, S, ExpandPointedToStructures, ExpandStructures, FD,
6762 false /* OutermostType */, EncodingProperty,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006763 false /* StructField */, EncodeBlockParameters, EncodeClassNames,
6764 false, NotEncodedT);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006765 }
6766 S += '>';
6767 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00006768 return;
6769 }
Mike Stump11289f42009-09-09 15:08:12 +00006770
Fariborz Jahanian33fa9622014-01-28 20:41:15 +00006771 case Type::ObjCObject: {
6772 // hack to match legacy encoding of *id and *Class
6773 QualType Ty = getObjCObjectPointerType(CT);
6774 if (Ty->isObjCIdType()) {
6775 S += "{objc_object=}";
6776 return;
6777 }
6778 else if (Ty->isObjCClassType()) {
6779 S += "{objc_class=}";
6780 return;
6781 }
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00006782 // TODO: Double check to make sure this intentionally falls through.
Galina Kistanovaf87496d2017-06-03 06:31:42 +00006783 LLVM_FALLTHROUGH;
Fariborz Jahanian33fa9622014-01-28 20:41:15 +00006784 }
Fangrui Song6907ce22018-07-30 19:24:48 +00006785
John McCall393a78d2012-12-20 02:45:14 +00006786 case Type::ObjCInterface: {
6787 // Ignore protocol qualifiers when mangling at this level.
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00006788 // @encode(class_name)
Douglas Gregorc5e07f52015-07-07 03:58:01 +00006789 ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface();
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00006790 S += '{';
Douglas Gregorb32684e2015-06-16 21:04:55 +00006791 S += OI->getObjCRuntimeNameAsString();
Akira Hatanakafd0fb202016-08-17 19:42:22 +00006792 if (ExpandStructures) {
6793 S += '=';
6794 SmallVector<const ObjCIvarDecl*, 32> Ivars;
6795 DeepCollectObjCIvars(OI, true, Ivars);
6796 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
George Burgess IV00f70bd2018-03-01 05:43:23 +00006797 const FieldDecl *Field = Ivars[i];
Akira Hatanakafd0fb202016-08-17 19:42:22 +00006798 if (Field->isBitField())
6799 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
6800 else
6801 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD,
6802 false, false, false, false, false,
6803 EncodePointerToObjCTypedef,
6804 NotEncodedT);
6805 }
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00006806 }
6807 S += '}';
Chris Lattnere7cabb92009-07-13 00:10:46 +00006808 return;
Fariborz Jahanian1d35f122008-12-19 23:34:38 +00006809 }
Mike Stump11289f42009-09-09 15:08:12 +00006810
John McCall393a78d2012-12-20 02:45:14 +00006811 case Type::ObjCObjectPointer: {
Eugene Zelenko7855e772018-04-03 00:11:50 +00006812 const auto *OPT = T->castAs<ObjCObjectPointerType>();
Steve Naroff7cae42b2009-07-10 23:34:53 +00006813 if (OPT->isObjCIdType()) {
6814 S += '@';
6815 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00006816 }
Mike Stump11289f42009-09-09 15:08:12 +00006817
Steve Narofff0c86112009-10-28 22:03:49 +00006818 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
6819 // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
6820 // Since this is a binary compatibility issue, need to consult with runtime
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00006821 // folks. Fortunately, this is a *very* obscure construct.
Steve Naroff7cae42b2009-07-10 23:34:53 +00006822 S += '#';
6823 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00006824 }
Mike Stump11289f42009-09-09 15:08:12 +00006825
Chris Lattnere7cabb92009-07-13 00:10:46 +00006826 if (OPT->isObjCQualifiedIdType()) {
Mike Stump11289f42009-09-09 15:08:12 +00006827 getObjCEncodingForTypeImpl(getObjCIdType(), S,
Steve Naroff7cae42b2009-07-10 23:34:53 +00006828 ExpandPointedToStructures,
6829 ExpandStructures, FD);
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006830 if (FD || EncodingProperty || EncodeClassNames) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00006831 // Note that we do extended encoding of protocol qualifer list
6832 // Only when doing ivar or property encoding.
Steve Naroff7cae42b2009-07-10 23:34:53 +00006833 S += '"';
Aaron Ballman83731462014-03-17 16:14:00 +00006834 for (const auto *I : OPT->quals()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00006835 S += '<';
Douglas Gregorb32684e2015-06-16 21:04:55 +00006836 S += I->getObjCRuntimeNameAsString();
Steve Naroff7cae42b2009-07-10 23:34:53 +00006837 S += '>';
6838 }
6839 S += '"';
6840 }
6841 return;
Chris Lattnere7cabb92009-07-13 00:10:46 +00006842 }
Mike Stump11289f42009-09-09 15:08:12 +00006843
Chris Lattnere7cabb92009-07-13 00:10:46 +00006844 QualType PointeeTy = OPT->getPointeeType();
6845 if (!EncodingProperty &&
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00006846 isa<TypedefType>(PointeeTy.getTypePtr()) &&
6847 !EncodePointerToObjCTypedef) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00006848 // Another historical/compatibility reason.
Mike Stump11289f42009-09-09 15:08:12 +00006849 // We encode the underlying type which comes out as
Chris Lattnere7cabb92009-07-13 00:10:46 +00006850 // {...};
6851 S += '^';
Fariborz Jahanian88890e72013-07-12 16:19:11 +00006852 if (FD && OPT->getInterfaceDecl()) {
Fariborz Jahanianc682ef52013-07-12 16:41:56 +00006853 // Prevent recursive encoding of fields in some rare cases.
Fariborz Jahanian88890e72013-07-12 16:19:11 +00006854 ObjCInterfaceDecl *OI = OPT->getInterfaceDecl();
6855 SmallVector<const ObjCIvarDecl*, 32> Ivars;
6856 DeepCollectObjCIvars(OI, true, Ivars);
6857 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
George Burgess IV00f70bd2018-03-01 05:43:23 +00006858 if (Ivars[i] == FD) {
Fariborz Jahanian88890e72013-07-12 16:19:11 +00006859 S += '{';
Douglas Gregorb32684e2015-06-16 21:04:55 +00006860 S += OI->getObjCRuntimeNameAsString();
Fariborz Jahanian88890e72013-07-12 16:19:11 +00006861 S += '}';
6862 return;
6863 }
6864 }
6865 }
Mike Stump11289f42009-09-09 15:08:12 +00006866 getObjCEncodingForTypeImpl(PointeeTy, S,
6867 false, ExpandPointedToStructures,
Craig Topper36250ad2014-05-12 05:36:57 +00006868 nullptr,
Fariborz Jahaniand4c1a202013-02-15 21:14:50 +00006869 false, false, false, false, false,
6870 /*EncodePointerToObjCTypedef*/true);
Steve Naroff7cae42b2009-07-10 23:34:53 +00006871 return;
6872 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00006873
6874 S += '@';
Fangrui Song6907ce22018-07-30 19:24:48 +00006875 if (OPT->getInterfaceDecl() &&
Bob Wilson5f4e3a72011-11-30 01:57:58 +00006876 (FD || EncodingProperty || EncodeClassNames)) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00006877 S += '"';
Douglas Gregorb32684e2015-06-16 21:04:55 +00006878 S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString();
Aaron Ballman83731462014-03-17 16:14:00 +00006879 for (const auto *I : OPT->quals()) {
Chris Lattnere7cabb92009-07-13 00:10:46 +00006880 S += '<';
Douglas Gregorb32684e2015-06-16 21:04:55 +00006881 S += I->getObjCRuntimeNameAsString();
Chris Lattnere7cabb92009-07-13 00:10:46 +00006882 S += '>';
Mike Stump11289f42009-09-09 15:08:12 +00006883 }
Chris Lattnere7cabb92009-07-13 00:10:46 +00006884 S += '"';
6885 }
6886 return;
6887 }
Mike Stump11289f42009-09-09 15:08:12 +00006888
John McCalla9e6e8d2010-05-17 23:56:34 +00006889 // gcc just blithely ignores member pointers.
John McCall393a78d2012-12-20 02:45:14 +00006890 // FIXME: we shoul do better than that. 'M' is available.
6891 case Type::MemberPointer:
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006892 // This matches gcc's encoding, even though technically it is insufficient.
6893 //FIXME. We should do a better job than gcc.
John McCall393a78d2012-12-20 02:45:14 +00006894 case Type::Vector:
6895 case Type::ExtVector:
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006896 // Until we have a coherent encoding of these three types, issue warning.
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00006897 if (NotEncodedT)
6898 *NotEncodedT = T;
6899 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00006900
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006901 // We could see an undeduced auto type here during error recovery.
6902 // Just ignore it.
Richard Smith27d807c2013-04-30 13:56:41 +00006903 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00006904 case Type::DeducedTemplateSpecialization:
Richard Smith27d807c2013-04-30 13:56:41 +00006905 return;
6906
Xiuli Pan9c14e282016-01-09 12:53:17 +00006907 case Type::Pipe:
John McCall393a78d2012-12-20 02:45:14 +00006908#define ABSTRACT_TYPE(KIND, BASE)
6909#define TYPE(KIND, BASE)
6910#define DEPENDENT_TYPE(KIND, BASE) \
6911 case Type::KIND:
6912#define NON_CANONICAL_TYPE(KIND, BASE) \
6913 case Type::KIND:
6914#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
6915 case Type::KIND:
6916#include "clang/AST/TypeNodes.def"
6917 llvm_unreachable("@encode for dependent type!");
Fariborz Jahaniane0587be2010-10-07 21:25:25 +00006918 }
John McCall393a78d2012-12-20 02:45:14 +00006919 llvm_unreachable("bad type kind!");
Anders Carlssond8499822007-10-29 05:01:08 +00006920}
6921
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006922void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
6923 std::string &S,
6924 const FieldDecl *FD,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00006925 bool includeVBases,
6926 QualType *NotEncodedT) const {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006927 assert(RDecl && "Expected non-null RecordDecl");
6928 assert(!RDecl->isUnion() && "Should not be called for unions");
Argyrios Kyrtzidis785705b2016-01-16 00:20:02 +00006929 if (!RDecl->getDefinition() || RDecl->getDefinition()->isInvalidDecl())
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006930 return;
6931
Eugene Zelenko7855e772018-04-03 00:11:50 +00006932 const auto *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006933 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
6934 const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
6935
6936 if (CXXRec) {
Aaron Ballman574705e2014-03-13 15:41:46 +00006937 for (const auto &BI : CXXRec->bases()) {
6938 if (!BI.isVirtual()) {
6939 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00006940 if (base->isEmpty())
6941 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00006942 uint64_t offs = toBits(layout.getBaseClassOffset(base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006943 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
6944 std::make_pair(offs, base));
6945 }
6946 }
6947 }
Fangrui Song6907ce22018-07-30 19:24:48 +00006948
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006949 unsigned i = 0;
Hans Wennborga302cd92014-08-21 16:06:57 +00006950 for (auto *Field : RDecl->fields()) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006951 uint64_t offs = layout.getFieldOffset(i);
6952 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
Hans Wennborga302cd92014-08-21 16:06:57 +00006953 std::make_pair(offs, Field));
6954 ++i;
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006955 }
6956
6957 if (CXXRec && includeVBases) {
Aaron Ballman445a9392014-03-13 16:15:17 +00006958 for (const auto &BI : CXXRec->vbases()) {
6959 CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00006960 if (base->isEmpty())
6961 continue;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00006962 uint64_t offs = toBits(layout.getVBaseClassOffset(base));
Eli Friedman1d24af82013-09-18 01:59:16 +00006963 if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
6964 FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
Argyrios Kyrtzidis81c0b5c2011-09-26 18:14:24 +00006965 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
6966 std::make_pair(offs, base));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006967 }
6968 }
6969
6970 CharUnits size;
6971 if (CXXRec) {
6972 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
6973 } else {
6974 size = layout.getSize();
6975 }
6976
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006977#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006978 uint64_t CurOffs = 0;
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006979#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006980 std::multimap<uint64_t, NamedDecl *>::iterator
6981 CurLayObj = FieldOrBaseOffsets.begin();
6982
Douglas Gregorf5d6c742012-04-27 22:30:01 +00006983 if (CXXRec && CXXRec->isDynamicClass() &&
6984 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006985 if (FD) {
6986 S += "\"_vptr$";
6987 std::string recname = CXXRec->getNameAsString();
6988 if (recname.empty()) recname = "?";
6989 S += recname;
6990 S += '"';
6991 }
6992 S += "^^?";
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006993#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006994 CurOffs += getTypeSize(VoidPtrTy);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00006995#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00006996 }
6997
6998 if (!RDecl->hasFlexibleArrayMember()) {
6999 // Mark the end of the structure.
7000 uint64_t offs = toBits(size);
7001 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
Craig Topper36250ad2014-05-12 05:36:57 +00007002 std::make_pair(offs, nullptr));
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007003 }
7004
7005 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007006#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007007 assert(CurOffs <= CurLayObj->first);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007008 if (CurOffs < CurLayObj->first) {
Fangrui Song6907ce22018-07-30 19:24:48 +00007009 uint64_t padding = CurLayObj->first - CurOffs;
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007010 // FIXME: There doesn't seem to be a way to indicate in the encoding that
7011 // packing/alignment of members is different that normal, in which case
7012 // the encoding will be out-of-sync with the real layout.
7013 // If the runtime switches to just consider the size of types without
7014 // taking into account alignment, we could make padding explicit in the
7015 // encoding (e.g. using arrays of chars). The encoding strings would be
7016 // longer then though.
7017 CurOffs += padding;
7018 }
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007019#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007020
7021 NamedDecl *dcl = CurLayObj->second;
Craig Topper36250ad2014-05-12 05:36:57 +00007022 if (!dcl)
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007023 break; // reached end of structure.
7024
Eugene Zelenko7855e772018-04-03 00:11:50 +00007025 if (auto *base = dyn_cast<CXXRecordDecl>(dcl)) {
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007026 // We expand the bases without their virtual bases since those are going
7027 // in the initial structure. Note that this differs from gcc which
7028 // expands virtual bases each time one is encountered in the hierarchy,
7029 // making the encoding type bigger than it really is.
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00007030 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
7031 NotEncodedT);
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00007032 assert(!base->isEmpty());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007033#ifndef NDEBUG
Argyrios Kyrtzidis95a76f32011-06-17 23:19:38 +00007034 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007035#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007036 } else {
Eugene Zelenko7855e772018-04-03 00:11:50 +00007037 const auto *field = cast<FieldDecl>(dcl);
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007038 if (FD) {
7039 S += '"';
7040 S += field->getNameAsString();
7041 S += '"';
7042 }
7043
7044 if (field->isBitField()) {
7045 EncodeBitField(this, S, field->getType(), field);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007046#ifndef NDEBUG
Richard Smithcaf33902011-10-10 18:28:20 +00007047 CurOffs += field->getBitWidthValue(*this);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007048#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007049 } else {
7050 QualType qt = field->getType();
7051 getLegacyIntegralTypeEncoding(qt);
7052 getObjCEncodingForTypeImpl(qt, S, false, true, FD,
7053 /*OutermostType*/false,
7054 /*EncodingProperty*/false,
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00007055 /*StructField*/true,
7056 false, false, false, NotEncodedT);
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007057#ifndef NDEBUG
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007058 CurOffs += getTypeSize(field->getType());
Fariborz Jahanianf1a66de2014-01-07 01:02:50 +00007059#endif
Argyrios Kyrtzidis49b35de2011-05-17 00:46:38 +00007060 }
7061 }
7062 }
7063}
7064
Mike Stump11289f42009-09-09 15:08:12 +00007065void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
Fariborz Jahanianac73ff82007-11-01 17:18:37 +00007066 std::string& S) const {
7067 if (QT & Decl::OBJC_TQ_In)
7068 S += 'n';
7069 if (QT & Decl::OBJC_TQ_Inout)
7070 S += 'N';
7071 if (QT & Decl::OBJC_TQ_Out)
7072 S += 'o';
7073 if (QT & Decl::OBJC_TQ_Bycopy)
7074 S += 'O';
7075 if (QT & Decl::OBJC_TQ_Byref)
7076 S += 'R';
7077 if (QT & Decl::OBJC_TQ_Oneway)
7078 S += 'V';
7079}
7080
Douglas Gregor3ea72692011-08-12 05:46:01 +00007081TypedefDecl *ASTContext::getObjCIdDecl() const {
7082 if (!ObjCIdDecl) {
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00007083 QualType T = getObjCObjectType(ObjCBuiltinIdTy, {}, {});
Douglas Gregor3ea72692011-08-12 05:46:01 +00007084 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00007085 ObjCIdDecl = buildImplicitTypedef(T, "id");
Douglas Gregor3ea72692011-08-12 05:46:01 +00007086 }
Douglas Gregor3ea72692011-08-12 05:46:01 +00007087 return ObjCIdDecl;
Steve Naroff66e9f332007-10-15 14:41:52 +00007088}
7089
Douglas Gregor52e02802011-08-12 06:17:30 +00007090TypedefDecl *ASTContext::getObjCSelDecl() const {
7091 if (!ObjCSelDecl) {
Alp Toker56b5cc92013-12-15 10:36:26 +00007092 QualType T = getPointerType(ObjCBuiltinSelTy);
7093 ObjCSelDecl = buildImplicitTypedef(T, "SEL");
Douglas Gregor52e02802011-08-12 06:17:30 +00007094 }
7095 return ObjCSelDecl;
Fariborz Jahanian4bef4622007-10-16 20:40:23 +00007096}
7097
Douglas Gregor0a586182011-08-12 05:59:41 +00007098TypedefDecl *ASTContext::getObjCClassDecl() const {
7099 if (!ObjCClassDecl) {
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00007100 QualType T = getObjCObjectType(ObjCBuiltinClassTy, {}, {});
Douglas Gregor0a586182011-08-12 05:59:41 +00007101 T = getObjCObjectPointerType(T);
Alp Toker56b5cc92013-12-15 10:36:26 +00007102 ObjCClassDecl = buildImplicitTypedef(T, "Class");
Douglas Gregor0a586182011-08-12 05:59:41 +00007103 }
Douglas Gregor0a586182011-08-12 05:59:41 +00007104 return ObjCClassDecl;
Anders Carlssonf56a7ae2007-10-31 02:53:19 +00007105}
7106
Douglas Gregord53ae832012-01-17 18:09:05 +00007107ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
7108 if (!ObjCProtocolClassDecl) {
Fangrui Song6907ce22018-07-30 19:24:48 +00007109 ObjCProtocolClassDecl
7110 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
Douglas Gregord53ae832012-01-17 18:09:05 +00007111 SourceLocation(),
7112 &Idents.get("Protocol"),
Douglas Gregor85f3f952015-07-07 03:57:15 +00007113 /*typeParamList=*/nullptr,
Craig Topper36250ad2014-05-12 05:36:57 +00007114 /*PrevDecl=*/nullptr,
Fangrui Song6907ce22018-07-30 19:24:48 +00007115 SourceLocation(), true);
Douglas Gregord53ae832012-01-17 18:09:05 +00007116 }
Fangrui Song6907ce22018-07-30 19:24:48 +00007117
Douglas Gregord53ae832012-01-17 18:09:05 +00007118 return ObjCProtocolClassDecl;
7119}
7120
Meador Inge5d3fb222012-06-16 03:34:49 +00007121//===----------------------------------------------------------------------===//
7122// __builtin_va_list Construction Functions
7123//===----------------------------------------------------------------------===//
7124
Charles Davisc7d5c942015-09-17 20:55:33 +00007125static TypedefDecl *CreateCharPtrNamedVaListDecl(const ASTContext *Context,
7126 StringRef Name) {
7127 // typedef char* __builtin[_ms]_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00007128 QualType T = Context->getPointerType(Context->CharTy);
Charles Davisc7d5c942015-09-17 20:55:33 +00007129 return Context->buildImplicitTypedef(T, Name);
7130}
7131
7132static TypedefDecl *CreateMSVaListDecl(const ASTContext *Context) {
7133 return CreateCharPtrNamedVaListDecl(Context, "__builtin_ms_va_list");
7134}
7135
7136static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
7137 return CreateCharPtrNamedVaListDecl(Context, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00007138}
7139
7140static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
7141 // typedef void* __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00007142 QualType T = Context->getPointerType(Context->VoidTy);
7143 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00007144}
7145
Tim Northover9bb857a2013-01-31 12:13:10 +00007146static TypedefDecl *
7147CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00007148 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00007149 RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00007150 if (Context->getLangOpts().CPlusPlus) {
7151 // namespace std { struct __va_list {
7152 NamespaceDecl *NS;
7153 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
7154 Context->getTranslationUnitDecl(),
Craig Topper36250ad2014-05-12 05:36:57 +00007155 /*Inline*/ false, SourceLocation(),
Tim Northover9bb857a2013-01-31 12:13:10 +00007156 SourceLocation(), &Context->Idents.get("std"),
Craig Topper36250ad2014-05-12 05:36:57 +00007157 /*PrevDecl*/ nullptr);
Alp Toker56b5cc92013-12-15 10:36:26 +00007158 NS->setImplicit();
Tim Northover9bb857a2013-01-31 12:13:10 +00007159 VaListTagDecl->setDeclContext(NS);
Tim Northover9bb857a2013-01-31 12:13:10 +00007160 }
7161
7162 VaListTagDecl->startDefinition();
7163
7164 const size_t NumFields = 5;
7165 QualType FieldTypes[NumFields];
7166 const char *FieldNames[NumFields];
7167
7168 // void *__stack;
7169 FieldTypes[0] = Context->getPointerType(Context->VoidTy);
7170 FieldNames[0] = "__stack";
7171
7172 // void *__gr_top;
7173 FieldTypes[1] = Context->getPointerType(Context->VoidTy);
7174 FieldNames[1] = "__gr_top";
7175
7176 // void *__vr_top;
7177 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
7178 FieldNames[2] = "__vr_top";
7179
7180 // int __gr_offs;
7181 FieldTypes[3] = Context->IntTy;
7182 FieldNames[3] = "__gr_offs";
7183
7184 // int __vr_offs;
7185 FieldTypes[4] = Context->IntTy;
7186 FieldNames[4] = "__vr_offs";
7187
7188 // Create fields
7189 for (unsigned i = 0; i < NumFields; ++i) {
7190 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
7191 VaListTagDecl,
7192 SourceLocation(),
7193 SourceLocation(),
7194 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00007195 FieldTypes[i], /*TInfo=*/nullptr,
7196 /*BitWidth=*/nullptr,
Tim Northover9bb857a2013-01-31 12:13:10 +00007197 /*Mutable=*/false,
7198 ICIS_NoInit);
7199 Field->setAccess(AS_public);
7200 VaListTagDecl->addDecl(Field);
7201 }
7202 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00007203 Context->VaListTagDecl = VaListTagDecl;
Tim Northover9bb857a2013-01-31 12:13:10 +00007204 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Tim Northover9bb857a2013-01-31 12:13:10 +00007205
7206 // } __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00007207 return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
Tim Northover9bb857a2013-01-31 12:13:10 +00007208}
7209
Meador Inge5d3fb222012-06-16 03:34:49 +00007210static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
7211 // typedef struct __va_list_tag {
7212 RecordDecl *VaListTagDecl;
7213
Alp Toker2dea15b2013-12-17 01:22:38 +00007214 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00007215 VaListTagDecl->startDefinition();
7216
7217 const size_t NumFields = 5;
7218 QualType FieldTypes[NumFields];
7219 const char *FieldNames[NumFields];
7220
7221 // unsigned char gpr;
7222 FieldTypes[0] = Context->UnsignedCharTy;
7223 FieldNames[0] = "gpr";
7224
7225 // unsigned char fpr;
7226 FieldTypes[1] = Context->UnsignedCharTy;
7227 FieldNames[1] = "fpr";
7228
7229 // unsigned short reserved;
7230 FieldTypes[2] = Context->UnsignedShortTy;
7231 FieldNames[2] = "reserved";
7232
7233 // void* overflow_arg_area;
7234 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
7235 FieldNames[3] = "overflow_arg_area";
7236
7237 // void* reg_save_area;
7238 FieldTypes[4] = Context->getPointerType(Context->VoidTy);
7239 FieldNames[4] = "reg_save_area";
7240
7241 // Create fields
7242 for (unsigned i = 0; i < NumFields; ++i) {
7243 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
7244 SourceLocation(),
7245 SourceLocation(),
7246 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00007247 FieldTypes[i], /*TInfo=*/nullptr,
7248 /*BitWidth=*/nullptr,
Meador Inge5d3fb222012-06-16 03:34:49 +00007249 /*Mutable=*/false,
7250 ICIS_NoInit);
7251 Field->setAccess(AS_public);
7252 VaListTagDecl->addDecl(Field);
7253 }
7254 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00007255 Context->VaListTagDecl = VaListTagDecl;
Meador Inge5d3fb222012-06-16 03:34:49 +00007256 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
7257
7258 // } __va_list_tag;
Alp Toker56b5cc92013-12-15 10:36:26 +00007259 TypedefDecl *VaListTagTypedefDecl =
7260 Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
7261
Meador Inge5d3fb222012-06-16 03:34:49 +00007262 QualType VaListTagTypedefType =
7263 Context->getTypedefType(VaListTagTypedefDecl);
7264
7265 // typedef __va_list_tag __builtin_va_list[1];
7266 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
7267 QualType VaListTagArrayType
7268 = Context->getConstantArrayType(VaListTagTypedefType,
7269 Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00007270 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00007271}
7272
7273static TypedefDecl *
7274CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
Richard Smith9b88a4c2015-07-27 05:40:23 +00007275 // struct __va_list_tag {
Meador Inge5d3fb222012-06-16 03:34:49 +00007276 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00007277 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Meador Inge5d3fb222012-06-16 03:34:49 +00007278 VaListTagDecl->startDefinition();
7279
7280 const size_t NumFields = 4;
7281 QualType FieldTypes[NumFields];
7282 const char *FieldNames[NumFields];
7283
7284 // unsigned gp_offset;
7285 FieldTypes[0] = Context->UnsignedIntTy;
7286 FieldNames[0] = "gp_offset";
7287
7288 // unsigned fp_offset;
7289 FieldTypes[1] = Context->UnsignedIntTy;
7290 FieldNames[1] = "fp_offset";
7291
7292 // void* overflow_arg_area;
7293 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
7294 FieldNames[2] = "overflow_arg_area";
7295
7296 // void* reg_save_area;
7297 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
7298 FieldNames[3] = "reg_save_area";
7299
7300 // Create fields
7301 for (unsigned i = 0; i < NumFields; ++i) {
7302 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
7303 VaListTagDecl,
7304 SourceLocation(),
7305 SourceLocation(),
7306 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00007307 FieldTypes[i], /*TInfo=*/nullptr,
7308 /*BitWidth=*/nullptr,
Meador Inge5d3fb222012-06-16 03:34:49 +00007309 /*Mutable=*/false,
7310 ICIS_NoInit);
7311 Field->setAccess(AS_public);
7312 VaListTagDecl->addDecl(Field);
7313 }
7314 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00007315 Context->VaListTagDecl = VaListTagDecl;
Meador Inge5d3fb222012-06-16 03:34:49 +00007316 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
7317
Richard Smith9b88a4c2015-07-27 05:40:23 +00007318 // };
Alp Toker56b5cc92013-12-15 10:36:26 +00007319
Richard Smith9b88a4c2015-07-27 05:40:23 +00007320 // typedef struct __va_list_tag __builtin_va_list[1];
Meador Inge5d3fb222012-06-16 03:34:49 +00007321 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
Richard Smith9b88a4c2015-07-27 05:40:23 +00007322 QualType VaListTagArrayType =
7323 Context->getConstantArrayType(VaListTagType, Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00007324 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00007325}
7326
7327static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
7328 // typedef int __builtin_va_list[4];
7329 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
Yaron Kerene0bcdd42016-10-08 06:45:10 +00007330 QualType IntArrayType =
7331 Context->getConstantArrayType(Context->IntTy, Size, ArrayType::Normal, 0);
Alp Toker56b5cc92013-12-15 10:36:26 +00007332 return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list");
Meador Inge5d3fb222012-06-16 03:34:49 +00007333}
7334
Logan Chien57086ce2012-10-10 06:56:20 +00007335static TypedefDecl *
7336CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
Alp Toker56b5cc92013-12-15 10:36:26 +00007337 // struct __va_list
Alp Toker2dea15b2013-12-17 01:22:38 +00007338 RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00007339 if (Context->getLangOpts().CPlusPlus) {
7340 // namespace std { struct __va_list {
7341 NamespaceDecl *NS;
7342 NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
7343 Context->getTranslationUnitDecl(),
7344 /*Inline*/false, SourceLocation(),
7345 SourceLocation(), &Context->Idents.get("std"),
Craig Topper36250ad2014-05-12 05:36:57 +00007346 /*PrevDecl*/ nullptr);
Alp Toker56b5cc92013-12-15 10:36:26 +00007347 NS->setImplicit();
Logan Chien57086ce2012-10-10 06:56:20 +00007348 VaListDecl->setDeclContext(NS);
Logan Chien57086ce2012-10-10 06:56:20 +00007349 }
7350
7351 VaListDecl->startDefinition();
7352
7353 // void * __ap;
7354 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
7355 VaListDecl,
7356 SourceLocation(),
7357 SourceLocation(),
7358 &Context->Idents.get("__ap"),
7359 Context->getPointerType(Context->VoidTy),
Craig Topper36250ad2014-05-12 05:36:57 +00007360 /*TInfo=*/nullptr,
7361 /*BitWidth=*/nullptr,
Logan Chien57086ce2012-10-10 06:56:20 +00007362 /*Mutable=*/false,
7363 ICIS_NoInit);
7364 Field->setAccess(AS_public);
7365 VaListDecl->addDecl(Field);
7366
7367 // };
7368 VaListDecl->completeDefinition();
Oleg Ranevskyyb88d2472016-03-30 21:30:30 +00007369 Context->VaListTagDecl = VaListDecl;
Logan Chien57086ce2012-10-10 06:56:20 +00007370
7371 // typedef struct __va_list __builtin_va_list;
Alp Toker56b5cc92013-12-15 10:36:26 +00007372 QualType T = Context->getRecordType(VaListDecl);
7373 return Context->buildImplicitTypedef(T, "__builtin_va_list");
Logan Chien57086ce2012-10-10 06:56:20 +00007374}
7375
Ulrich Weigand47445072013-05-06 16:26:41 +00007376static TypedefDecl *
7377CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
Richard Smith9b88a4c2015-07-27 05:40:23 +00007378 // struct __va_list_tag {
Ulrich Weigand47445072013-05-06 16:26:41 +00007379 RecordDecl *VaListTagDecl;
Alp Toker2dea15b2013-12-17 01:22:38 +00007380 VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
Ulrich Weigand47445072013-05-06 16:26:41 +00007381 VaListTagDecl->startDefinition();
7382
7383 const size_t NumFields = 4;
7384 QualType FieldTypes[NumFields];
7385 const char *FieldNames[NumFields];
7386
7387 // long __gpr;
7388 FieldTypes[0] = Context->LongTy;
7389 FieldNames[0] = "__gpr";
7390
7391 // long __fpr;
7392 FieldTypes[1] = Context->LongTy;
7393 FieldNames[1] = "__fpr";
7394
7395 // void *__overflow_arg_area;
7396 FieldTypes[2] = Context->getPointerType(Context->VoidTy);
7397 FieldNames[2] = "__overflow_arg_area";
7398
7399 // void *__reg_save_area;
7400 FieldTypes[3] = Context->getPointerType(Context->VoidTy);
7401 FieldNames[3] = "__reg_save_area";
7402
7403 // Create fields
7404 for (unsigned i = 0; i < NumFields; ++i) {
7405 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
7406 VaListTagDecl,
7407 SourceLocation(),
7408 SourceLocation(),
7409 &Context->Idents.get(FieldNames[i]),
Craig Topper36250ad2014-05-12 05:36:57 +00007410 FieldTypes[i], /*TInfo=*/nullptr,
7411 /*BitWidth=*/nullptr,
Ulrich Weigand47445072013-05-06 16:26:41 +00007412 /*Mutable=*/false,
7413 ICIS_NoInit);
7414 Field->setAccess(AS_public);
7415 VaListTagDecl->addDecl(Field);
7416 }
7417 VaListTagDecl->completeDefinition();
Richard Smith9b88a4c2015-07-27 05:40:23 +00007418 Context->VaListTagDecl = VaListTagDecl;
Ulrich Weigand47445072013-05-06 16:26:41 +00007419 QualType VaListTagType = Context->getRecordType(VaListTagDecl);
Ulrich Weigand47445072013-05-06 16:26:41 +00007420
Richard Smith9b88a4c2015-07-27 05:40:23 +00007421 // };
Ulrich Weigand47445072013-05-06 16:26:41 +00007422
7423 // typedef __va_list_tag __builtin_va_list[1];
7424 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
Richard Smith9b88a4c2015-07-27 05:40:23 +00007425 QualType VaListTagArrayType =
7426 Context->getConstantArrayType(VaListTagType, Size, ArrayType::Normal, 0);
Ulrich Weigand47445072013-05-06 16:26:41 +00007427
Alp Toker56b5cc92013-12-15 10:36:26 +00007428 return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
Ulrich Weigand47445072013-05-06 16:26:41 +00007429}
7430
Meador Inge5d3fb222012-06-16 03:34:49 +00007431static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
7432 TargetInfo::BuiltinVaListKind Kind) {
7433 switch (Kind) {
7434 case TargetInfo::CharPtrBuiltinVaList:
7435 return CreateCharPtrBuiltinVaListDecl(Context);
7436 case TargetInfo::VoidPtrBuiltinVaList:
7437 return CreateVoidPtrBuiltinVaListDecl(Context);
Tim Northover9bb857a2013-01-31 12:13:10 +00007438 case TargetInfo::AArch64ABIBuiltinVaList:
7439 return CreateAArch64ABIBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00007440 case TargetInfo::PowerABIBuiltinVaList:
7441 return CreatePowerABIBuiltinVaListDecl(Context);
7442 case TargetInfo::X86_64ABIBuiltinVaList:
7443 return CreateX86_64ABIBuiltinVaListDecl(Context);
7444 case TargetInfo::PNaClABIBuiltinVaList:
7445 return CreatePNaClABIBuiltinVaListDecl(Context);
Logan Chien57086ce2012-10-10 06:56:20 +00007446 case TargetInfo::AAPCSABIBuiltinVaList:
7447 return CreateAAPCSABIBuiltinVaListDecl(Context);
Ulrich Weigand47445072013-05-06 16:26:41 +00007448 case TargetInfo::SystemZBuiltinVaList:
7449 return CreateSystemZBuiltinVaListDecl(Context);
Meador Inge5d3fb222012-06-16 03:34:49 +00007450 }
7451
7452 llvm_unreachable("Unhandled __builtin_va_list type kind");
7453}
7454
7455TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
Alp Toker56b5cc92013-12-15 10:36:26 +00007456 if (!BuiltinVaListDecl) {
Meador Inge5d3fb222012-06-16 03:34:49 +00007457 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
Alp Toker56b5cc92013-12-15 10:36:26 +00007458 assert(BuiltinVaListDecl->isImplicit());
7459 }
Meador Inge5d3fb222012-06-16 03:34:49 +00007460
7461 return BuiltinVaListDecl;
7462}
7463
Richard Smith9b88a4c2015-07-27 05:40:23 +00007464Decl *ASTContext::getVaListTagDecl() const {
7465 // Force the creation of VaListTagDecl by building the __builtin_va_list
Meador Ingecfb60902012-07-01 15:57:25 +00007466 // declaration.
Richard Smith9b88a4c2015-07-27 05:40:23 +00007467 if (!VaListTagDecl)
7468 (void)getBuiltinVaListDecl();
Meador Ingecfb60902012-07-01 15:57:25 +00007469
Richard Smith9b88a4c2015-07-27 05:40:23 +00007470 return VaListTagDecl;
Meador Ingecfb60902012-07-01 15:57:25 +00007471}
7472
Charles Davisc7d5c942015-09-17 20:55:33 +00007473TypedefDecl *ASTContext::getBuiltinMSVaListDecl() const {
7474 if (!BuiltinMSVaListDecl)
7475 BuiltinMSVaListDecl = CreateMSVaListDecl(this);
7476
7477 return BuiltinMSVaListDecl;
7478}
7479
Erich Keane41af9712018-04-16 21:30:08 +00007480bool ASTContext::canBuiltinBeRedeclared(const FunctionDecl *FD) const {
7481 return BuiltinInfo.canBeRedeclared(FD->getBuiltinID());
7482}
7483
Ted Kremenek1b0ea822008-01-07 19:49:32 +00007484void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
Mike Stump11289f42009-09-09 15:08:12 +00007485 assert(ObjCConstantStringType.isNull() &&
Steve Narofff73b7842007-10-15 23:35:17 +00007486 "'NSConstantString' type already set!");
Mike Stump11289f42009-09-09 15:08:12 +00007487
Ted Kremenek1b0ea822008-01-07 19:49:32 +00007488 ObjCConstantStringType = getObjCInterfaceType(Decl);
Steve Narofff73b7842007-10-15 23:35:17 +00007489}
7490
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007491/// Retrieve the template name that corresponds to a non-empty
John McCalld28ae272009-12-02 08:04:21 +00007492/// lookup.
Jay Foad39c79802011-01-12 09:06:06 +00007493TemplateName
7494ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
7495 UnresolvedSetIterator End) const {
John McCalld28ae272009-12-02 08:04:21 +00007496 unsigned size = End - Begin;
7497 assert(size > 1 && "set is not overloaded!");
7498
7499 void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
7500 size * sizeof(FunctionTemplateDecl*));
Eugene Zelenko7855e772018-04-03 00:11:50 +00007501 auto *OT = new (memory) OverloadedTemplateStorage(size);
John McCalld28ae272009-12-02 08:04:21 +00007502
7503 NamedDecl **Storage = OT->getStorage();
John McCallad371252010-01-20 00:46:10 +00007504 for (UnresolvedSetIterator I = Begin; I != End; ++I) {
John McCalld28ae272009-12-02 08:04:21 +00007505 NamedDecl *D = *I;
7506 assert(isa<FunctionTemplateDecl>(D) ||
Richard Smithef53a3e2018-06-06 16:36:56 +00007507 isa<UnresolvedUsingValueDecl>(D) ||
John McCalld28ae272009-12-02 08:04:21 +00007508 (isa<UsingShadowDecl>(D) &&
7509 isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
7510 *Storage++ = D;
7511 }
7512
7513 return TemplateName(OT);
7514}
7515
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007516/// Retrieve the template name that represents a qualified
Douglas Gregordc572a32009-03-30 22:58:21 +00007517/// template name such as \c std::vector.
Jay Foad39c79802011-01-12 09:06:06 +00007518TemplateName
7519ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
7520 bool TemplateKeyword,
7521 TemplateDecl *Template) const {
Douglas Gregore29139c2011-03-03 17:04:51 +00007522 assert(NNS && "Missing nested-name-specifier in qualified template name");
Fangrui Song6907ce22018-07-30 19:24:48 +00007523
Douglas Gregorc42075a2010-02-04 18:10:26 +00007524 // FIXME: Canonicalization?
Douglas Gregordc572a32009-03-30 22:58:21 +00007525 llvm::FoldingSetNodeID ID;
7526 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
7527
Craig Topper36250ad2014-05-12 05:36:57 +00007528 void *InsertPos = nullptr;
Douglas Gregordc572a32009-03-30 22:58:21 +00007529 QualifiedTemplateName *QTN =
7530 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7531 if (!QTN) {
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007532 QTN = new (*this, alignof(QualifiedTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00007533 QualifiedTemplateName(NNS, TemplateKeyword, Template);
Douglas Gregordc572a32009-03-30 22:58:21 +00007534 QualifiedTemplateNames.InsertNode(QTN, InsertPos);
7535 }
7536
7537 return TemplateName(QTN);
7538}
7539
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007540/// Retrieve the template name that represents a dependent
Douglas Gregordc572a32009-03-30 22:58:21 +00007541/// template name such as \c MetaFun::template apply.
Jay Foad39c79802011-01-12 09:06:06 +00007542TemplateName
7543ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
7544 const IdentifierInfo *Name) const {
Mike Stump11289f42009-09-09 15:08:12 +00007545 assert((!NNS || NNS->isDependent()) &&
Douglas Gregor308047d2009-09-09 00:23:06 +00007546 "Nested name specifier must be dependent");
Douglas Gregordc572a32009-03-30 22:58:21 +00007547
7548 llvm::FoldingSetNodeID ID;
7549 DependentTemplateName::Profile(ID, NNS, Name);
7550
Craig Topper36250ad2014-05-12 05:36:57 +00007551 void *InsertPos = nullptr;
Douglas Gregordc572a32009-03-30 22:58:21 +00007552 DependentTemplateName *QTN =
7553 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7554
7555 if (QTN)
7556 return TemplateName(QTN);
7557
7558 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
7559 if (CanonNNS == NNS) {
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007560 QTN = new (*this, alignof(DependentTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00007561 DependentTemplateName(NNS, Name);
Douglas Gregordc572a32009-03-30 22:58:21 +00007562 } else {
7563 TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007564 QTN = new (*this, alignof(DependentTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00007565 DependentTemplateName(NNS, Name, Canon);
Douglas Gregorc42075a2010-02-04 18:10:26 +00007566 DependentTemplateName *CheckQTN =
7567 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7568 assert(!CheckQTN && "Dependent type name canonicalization broken");
7569 (void)CheckQTN;
Douglas Gregordc572a32009-03-30 22:58:21 +00007570 }
7571
7572 DependentTemplateNames.InsertNode(QTN, InsertPos);
7573 return TemplateName(QTN);
7574}
7575
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007576/// Retrieve the template name that represents a dependent
Douglas Gregor71395fa2009-11-04 00:56:37 +00007577/// template name such as \c MetaFun::template operator+.
Fangrui Song6907ce22018-07-30 19:24:48 +00007578TemplateName
Douglas Gregor71395fa2009-11-04 00:56:37 +00007579ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
Jay Foad39c79802011-01-12 09:06:06 +00007580 OverloadedOperatorKind Operator) const {
Douglas Gregor71395fa2009-11-04 00:56:37 +00007581 assert((!NNS || NNS->isDependent()) &&
7582 "Nested name specifier must be dependent");
Fangrui Song6907ce22018-07-30 19:24:48 +00007583
Douglas Gregor71395fa2009-11-04 00:56:37 +00007584 llvm::FoldingSetNodeID ID;
7585 DependentTemplateName::Profile(ID, NNS, Operator);
Craig Topper36250ad2014-05-12 05:36:57 +00007586
7587 void *InsertPos = nullptr;
Douglas Gregorc42075a2010-02-04 18:10:26 +00007588 DependentTemplateName *QTN
7589 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
Fangrui Song6907ce22018-07-30 19:24:48 +00007590
Douglas Gregor71395fa2009-11-04 00:56:37 +00007591 if (QTN)
7592 return TemplateName(QTN);
Fangrui Song6907ce22018-07-30 19:24:48 +00007593
Douglas Gregor71395fa2009-11-04 00:56:37 +00007594 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
7595 if (CanonNNS == NNS) {
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007596 QTN = new (*this, alignof(DependentTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00007597 DependentTemplateName(NNS, Operator);
Douglas Gregor71395fa2009-11-04 00:56:37 +00007598 } else {
7599 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007600 QTN = new (*this, alignof(DependentTemplateName))
Richard Smitha5e69762012-08-16 01:19:31 +00007601 DependentTemplateName(NNS, Operator, Canon);
Benjamin Kramerc3f89252016-10-20 14:27:22 +00007602
Douglas Gregorc42075a2010-02-04 18:10:26 +00007603 DependentTemplateName *CheckQTN
7604 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
7605 assert(!CheckQTN && "Dependent template name canonicalization broken");
7606 (void)CheckQTN;
Douglas Gregor71395fa2009-11-04 00:56:37 +00007607 }
Fangrui Song6907ce22018-07-30 19:24:48 +00007608
Douglas Gregor71395fa2009-11-04 00:56:37 +00007609 DependentTemplateNames.InsertNode(QTN, InsertPos);
7610 return TemplateName(QTN);
7611}
7612
Fangrui Song6907ce22018-07-30 19:24:48 +00007613TemplateName
John McCalld9dfe3a2011-06-30 08:33:18 +00007614ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
7615 TemplateName replacement) const {
7616 llvm::FoldingSetNodeID ID;
7617 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
Craig Topper36250ad2014-05-12 05:36:57 +00007618
7619 void *insertPos = nullptr;
John McCalld9dfe3a2011-06-30 08:33:18 +00007620 SubstTemplateTemplateParmStorage *subst
7621 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
Fangrui Song6907ce22018-07-30 19:24:48 +00007622
John McCalld9dfe3a2011-06-30 08:33:18 +00007623 if (!subst) {
7624 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
7625 SubstTemplateTemplateParms.InsertNode(subst, insertPos);
7626 }
7627
7628 return TemplateName(subst);
7629}
7630
Fangrui Song6907ce22018-07-30 19:24:48 +00007631TemplateName
Douglas Gregor5590be02011-01-15 06:45:20 +00007632ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
7633 const TemplateArgument &ArgPack) const {
Eugene Zelenko7855e772018-04-03 00:11:50 +00007634 auto &Self = const_cast<ASTContext &>(*this);
Douglas Gregor5590be02011-01-15 06:45:20 +00007635 llvm::FoldingSetNodeID ID;
7636 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
Craig Topper36250ad2014-05-12 05:36:57 +00007637
7638 void *InsertPos = nullptr;
Douglas Gregor5590be02011-01-15 06:45:20 +00007639 SubstTemplateTemplateParmPackStorage *Subst
7640 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
Fangrui Song6907ce22018-07-30 19:24:48 +00007641
Douglas Gregor5590be02011-01-15 06:45:20 +00007642 if (!Subst) {
Fangrui Song6907ce22018-07-30 19:24:48 +00007643 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
Douglas Gregor5590be02011-01-15 06:45:20 +00007644 ArgPack.pack_size(),
7645 ArgPack.pack_begin());
7646 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
7647 }
7648
7649 return TemplateName(Subst);
7650}
7651
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00007652/// getFromTargetType - Given one of the integer types provided by
Douglas Gregorab138572008-11-03 15:57:00 +00007653/// TargetInfo, produce the corresponding type. The unsigned @p Type
7654/// is actually a value of type @c TargetInfo::IntType.
John McCall48f2d582009-10-23 23:03:21 +00007655CanQualType ASTContext::getFromTargetType(unsigned Type) const {
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00007656 switch (Type) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00007657 case TargetInfo::NoInt: return {};
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00007658 case TargetInfo::SignedChar: return SignedCharTy;
7659 case TargetInfo::UnsignedChar: return UnsignedCharTy;
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00007660 case TargetInfo::SignedShort: return ShortTy;
7661 case TargetInfo::UnsignedShort: return UnsignedShortTy;
7662 case TargetInfo::SignedInt: return IntTy;
7663 case TargetInfo::UnsignedInt: return UnsignedIntTy;
7664 case TargetInfo::SignedLong: return LongTy;
7665 case TargetInfo::UnsignedLong: return UnsignedLongTy;
7666 case TargetInfo::SignedLongLong: return LongLongTy;
7667 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
7668 }
7669
David Blaikie83d382b2011-09-23 05:06:16 +00007670 llvm_unreachable("Unhandled TargetInfo::IntType value");
Douglas Gregor8af6e6d2008-11-03 14:12:49 +00007671}
Ted Kremenek77c51b22008-07-24 23:58:27 +00007672
7673//===----------------------------------------------------------------------===//
7674// Type Predicates.
7675//===----------------------------------------------------------------------===//
7676
Fariborz Jahanian96207692009-02-18 21:49:28 +00007677/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
7678/// garbage collection attribute.
7679///
John McCall553d45a2011-01-12 00:34:59 +00007680Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +00007681 if (getLangOpts().getGC() == LangOptions::NonGC)
John McCall553d45a2011-01-12 00:34:59 +00007682 return Qualifiers::GCNone;
7683
David Blaikiebbafb8a2012-03-11 07:00:24 +00007684 assert(getLangOpts().ObjC1);
John McCall553d45a2011-01-12 00:34:59 +00007685 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
7686
7687 // Default behaviour under objective-C's gc is for ObjC pointers
7688 // (or pointers to them) be treated as though they were declared
7689 // as __strong.
7690 if (GCAttrs == Qualifiers::GCNone) {
7691 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
7692 return Qualifiers::Strong;
7693 else if (Ty->isPointerType())
7694 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
7695 } else {
7696 // It's not valid to set GC attributes on anything that isn't a
7697 // pointer.
7698#ifndef NDEBUG
7699 QualType CT = Ty->getCanonicalTypeInternal();
Eugene Zelenko7855e772018-04-03 00:11:50 +00007700 while (const auto *AT = dyn_cast<ArrayType>(CT))
John McCall553d45a2011-01-12 00:34:59 +00007701 CT = AT->getElementType();
7702 assert(CT->isAnyPointerType() || CT->isBlockPointerType());
7703#endif
Fariborz Jahanian96207692009-02-18 21:49:28 +00007704 }
Chris Lattnerd60183d2009-02-18 22:53:11 +00007705 return GCAttrs;
Fariborz Jahanian96207692009-02-18 21:49:28 +00007706}
7707
Chris Lattner49af6a42008-04-07 06:51:04 +00007708//===----------------------------------------------------------------------===//
7709// Type Compatibility Testing
7710//===----------------------------------------------------------------------===//
Chris Lattnerb338a6b2007-11-01 05:03:41 +00007711
Mike Stump11289f42009-09-09 15:08:12 +00007712/// areCompatVectorTypes - Return true if the two specified vector types are
Chris Lattner49af6a42008-04-07 06:51:04 +00007713/// compatible.
7714static bool areCompatVectorTypes(const VectorType *LHS,
7715 const VectorType *RHS) {
John McCallb692a092009-10-22 20:10:53 +00007716 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
Chris Lattner49af6a42008-04-07 06:51:04 +00007717 return LHS->getElementType() == RHS->getElementType() &&
Chris Lattner465fa322008-10-05 17:34:18 +00007718 LHS->getNumElements() == RHS->getNumElements();
Chris Lattner49af6a42008-04-07 06:51:04 +00007719}
7720
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00007721bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
7722 QualType SecondVec) {
7723 assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
7724 assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
7725
7726 if (hasSameUnqualifiedType(FirstVec, SecondVec))
7727 return true;
7728
Bob Wilsone6aeebb2010-11-12 17:24:54 +00007729 // Treat Neon vector types and most AltiVec vector types as if they are the
7730 // equivalent GCC vector types.
Eugene Zelenko7855e772018-04-03 00:11:50 +00007731 const auto *First = FirstVec->getAs<VectorType>();
7732 const auto *Second = SecondVec->getAs<VectorType>();
Bob Wilsone6aeebb2010-11-12 17:24:54 +00007733 if (First->getNumElements() == Second->getNumElements() &&
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00007734 hasSameType(First->getElementType(), Second->getElementType()) &&
Bob Wilsone6aeebb2010-11-12 17:24:54 +00007735 First->getVectorKind() != VectorType::AltiVecPixel &&
7736 First->getVectorKind() != VectorType::AltiVecBool &&
7737 Second->getVectorKind() != VectorType::AltiVecPixel &&
7738 Second->getVectorKind() != VectorType::AltiVecBool)
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00007739 return true;
7740
7741 return false;
7742}
7743
Steve Naroff8e6aee52009-07-23 01:01:38 +00007744//===----------------------------------------------------------------------===//
7745// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
7746//===----------------------------------------------------------------------===//
7747
7748/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
7749/// inheritance hierarchy of 'rProto'.
Jay Foad39c79802011-01-12 09:06:06 +00007750bool
7751ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
7752 ObjCProtocolDecl *rProto) const {
Douglas Gregor33b24292012-01-01 18:09:12 +00007753 if (declaresSameEntity(lProto, rProto))
Steve Naroff8e6aee52009-07-23 01:01:38 +00007754 return true;
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00007755 for (auto *PI : rProto->protocols())
7756 if (ProtocolCompatibleWithProtocol(lProto, PI))
Steve Naroff8e6aee52009-07-23 01:01:38 +00007757 return true;
7758 return false;
7759}
7760
Dmitri Gribenko4364fcf2012-08-28 02:49:14 +00007761/// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
7762/// Class<pr1, ...>.
Fangrui Song6907ce22018-07-30 19:24:48 +00007763bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00007764 QualType rhs) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00007765 const auto *lhsQID = lhs->getAs<ObjCObjectPointerType>();
7766 const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00007767 assert((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
Fangrui Song6907ce22018-07-30 19:24:48 +00007768
Aaron Ballman83731462014-03-17 16:14:00 +00007769 for (auto *lhsProto : lhsQID->quals()) {
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00007770 bool match = false;
Aaron Ballman83731462014-03-17 16:14:00 +00007771 for (auto *rhsProto : rhsOPT->quals()) {
Fariborz Jahanian3c7ebc32010-07-19 22:02:22 +00007772 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
7773 match = true;
7774 break;
7775 }
7776 }
7777 if (!match)
7778 return false;
7779 }
7780 return true;
7781}
7782
Steve Naroff8e6aee52009-07-23 01:01:38 +00007783/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
7784/// ObjCQualifiedIDType.
7785bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
7786 bool compare) {
7787 // Allow id<P..> and an 'id' or void* type in all cases.
Mike Stump11289f42009-09-09 15:08:12 +00007788 if (lhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00007789 lhs->isObjCIdType() || lhs->isObjCClassType())
7790 return true;
Mike Stump11289f42009-09-09 15:08:12 +00007791 else if (rhs->isVoidPointerType() ||
Steve Naroff8e6aee52009-07-23 01:01:38 +00007792 rhs->isObjCIdType() || rhs->isObjCClassType())
7793 return true;
7794
7795 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00007796 const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00007797
Steve Naroff8e6aee52009-07-23 01:01:38 +00007798 if (!rhsOPT) return false;
Mike Stump11289f42009-09-09 15:08:12 +00007799
Steve Naroff8e6aee52009-07-23 01:01:38 +00007800 if (rhsOPT->qual_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00007801 // If the RHS is a unqualified interface pointer "NSString*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00007802 // make sure we check the class hierarchy.
7803 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
Aaron Ballman83731462014-03-17 16:14:00 +00007804 for (auto *I : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007805 // when comparing an id<P> on lhs with a static type on rhs,
7806 // see if static class implements all of id's protocols, directly or
7807 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00007808 if (!rhsID->ClassImplementsProtocol(I, true))
Steve Naroff8e6aee52009-07-23 01:01:38 +00007809 return false;
7810 }
7811 }
7812 // If there are no qualifiers and no interface, we have an 'id'.
7813 return true;
7814 }
Mike Stump11289f42009-09-09 15:08:12 +00007815 // Both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00007816 for (auto *lhsProto : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007817 bool match = false;
7818
7819 // when comparing an id<P> on lhs with a static type on rhs,
7820 // see if static class implements all of id's protocols, directly or
7821 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00007822 for (auto *rhsProto : rhsOPT->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007823 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
7824 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
7825 match = true;
7826 break;
7827 }
7828 }
Mike Stump11289f42009-09-09 15:08:12 +00007829 // If the RHS is a qualified interface pointer "NSString<P>*",
Steve Naroff8e6aee52009-07-23 01:01:38 +00007830 // make sure we check the class hierarchy.
7831 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
Aaron Ballman83731462014-03-17 16:14:00 +00007832 for (auto *I : lhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007833 // when comparing an id<P> on lhs with a static type on rhs,
7834 // see if static class implements all of id's protocols, directly or
7835 // through its super class and categories.
Aaron Ballman83731462014-03-17 16:14:00 +00007836 if (rhsID->ClassImplementsProtocol(I, true)) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007837 match = true;
7838 break;
7839 }
7840 }
7841 }
7842 if (!match)
7843 return false;
7844 }
Mike Stump11289f42009-09-09 15:08:12 +00007845
Steve Naroff8e6aee52009-07-23 01:01:38 +00007846 return true;
7847 }
Mike Stump11289f42009-09-09 15:08:12 +00007848
Steve Naroff8e6aee52009-07-23 01:01:38 +00007849 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
7850 assert(rhsQID && "One of the LHS/RHS should be id<x>");
7851
Mike Stump11289f42009-09-09 15:08:12 +00007852 if (const ObjCObjectPointerType *lhsOPT =
Steve Naroff8e6aee52009-07-23 01:01:38 +00007853 lhs->getAsObjCInterfacePointerType()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007854 // If both the right and left sides have qualifiers.
Aaron Ballman83731462014-03-17 16:14:00 +00007855 for (auto *lhsProto : lhsOPT->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007856 bool match = false;
7857
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007858 // when comparing an id<P> on rhs with a static type on lhs,
Steve Naroff8e6aee52009-07-23 01:01:38 +00007859 // see if static class implements all of id's protocols, directly or
7860 // through its super class and categories.
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007861 // First, lhs protocols in the qualifier list must be found, direct
7862 // or indirect in rhs's qualifier list or it is a mismatch.
Aaron Ballman83731462014-03-17 16:14:00 +00007863 for (auto *rhsProto : rhsQID->quals()) {
Steve Naroff8e6aee52009-07-23 01:01:38 +00007864 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
7865 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
7866 match = true;
7867 break;
7868 }
7869 }
7870 if (!match)
7871 return false;
7872 }
Fangrui Song6907ce22018-07-30 19:24:48 +00007873
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007874 // Static class's protocols, or its super class or category protocols
7875 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
7876 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
7877 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
7878 CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
7879 // This is rather dubious but matches gcc's behavior. If lhs has
7880 // no type qualifier and its class has no static protocol(s)
7881 // assume that it is mismatch.
7882 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
7883 return false;
Aaron Ballman83731462014-03-17 16:14:00 +00007884 for (auto *lhsProto : LHSInheritedProtocols) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007885 bool match = false;
Aaron Ballman83731462014-03-17 16:14:00 +00007886 for (auto *rhsProto : rhsQID->quals()) {
Fariborz Jahanianeb7714c2010-11-01 20:47:16 +00007887 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
7888 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
7889 match = true;
7890 break;
7891 }
7892 }
7893 if (!match)
7894 return false;
7895 }
7896 }
Steve Naroff8e6aee52009-07-23 01:01:38 +00007897 return true;
7898 }
7899 return false;
7900}
7901
Eli Friedman47f77112008-08-22 00:56:42 +00007902/// canAssignObjCInterfaces - Return true if the two interface types are
Chris Lattner49af6a42008-04-07 06:51:04 +00007903/// compatible for assignment from RHS to LHS. This handles validation of any
7904/// protocol qualifiers on the LHS or RHS.
Steve Naroff7cae42b2009-07-10 23:34:53 +00007905bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
7906 const ObjCObjectPointerType *RHSOPT) {
John McCall8b07ec22010-05-15 11:32:37 +00007907 const ObjCObjectType* LHS = LHSOPT->getObjectType();
7908 const ObjCObjectType* RHS = RHSOPT->getObjectType();
7909
Steve Naroff1329fa02009-07-15 18:40:39 +00007910 // If either type represents the built-in 'id' or 'Class' types, return true.
John McCall8b07ec22010-05-15 11:32:37 +00007911 if (LHS->isObjCUnqualifiedIdOrClass() ||
7912 RHS->isObjCUnqualifiedIdOrClass())
Steve Naroff7cae42b2009-07-10 23:34:53 +00007913 return true;
7914
Douglas Gregorab209d82015-07-07 03:58:42 +00007915 // Function object that propagates a successful result or handles
7916 // __kindof types.
7917 auto finish = [&](bool succeeded) -> bool {
7918 if (succeeded)
7919 return true;
7920
7921 if (!RHS->isKindOfType())
7922 return false;
7923
7924 // Strip off __kindof and protocol qualifiers, then check whether
7925 // we can assign the other way.
7926 return canAssignObjCInterfaces(RHSOPT->stripObjCKindOfTypeAndQuals(*this),
7927 LHSOPT->stripObjCKindOfTypeAndQuals(*this));
7928 };
7929
7930 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) {
7931 return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
7932 QualType(RHSOPT,0),
7933 false));
7934 }
Fangrui Song6907ce22018-07-30 19:24:48 +00007935
Douglas Gregorab209d82015-07-07 03:58:42 +00007936 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) {
7937 return finish(ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
7938 QualType(RHSOPT,0)));
7939 }
Fangrui Song6907ce22018-07-30 19:24:48 +00007940
John McCall8b07ec22010-05-15 11:32:37 +00007941 // If we have 2 user-defined types, fall into that path.
Douglas Gregorab209d82015-07-07 03:58:42 +00007942 if (LHS->getInterface() && RHS->getInterface()) {
7943 return finish(canAssignObjCInterfaces(LHS, RHS));
7944 }
Mike Stump11289f42009-09-09 15:08:12 +00007945
Steve Naroff8e6aee52009-07-23 01:01:38 +00007946 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00007947}
7948
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007949/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
Fangrui Song6907ce22018-07-30 19:24:48 +00007950/// for providing type-safety for objective-c pointers used to pass/return
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007951/// arguments in block literals. When passed as arguments, passing 'A*' where
7952/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
7953/// not OK. For the return type, the opposite is not OK.
7954bool ASTContext::canAssignObjCInterfacesInBlockPointer(
7955 const ObjCObjectPointerType *LHSOPT,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00007956 const ObjCObjectPointerType *RHSOPT,
7957 bool BlockReturnType) {
Douglas Gregorab209d82015-07-07 03:58:42 +00007958
7959 // Function object that propagates a successful result or handles
7960 // __kindof types.
7961 auto finish = [&](bool succeeded) -> bool {
7962 if (succeeded)
7963 return true;
7964
7965 const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT;
7966 if (!Expected->isKindOfType())
7967 return false;
7968
7969 // Strip off __kindof and protocol qualifiers, then check whether
7970 // we can assign the other way.
7971 return canAssignObjCInterfacesInBlockPointer(
7972 RHSOPT->stripObjCKindOfTypeAndQuals(*this),
7973 LHSOPT->stripObjCKindOfTypeAndQuals(*this),
7974 BlockReturnType);
7975 };
7976
Fariborz Jahanian440a6832010-04-06 17:23:39 +00007977 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007978 return true;
Fangrui Song6907ce22018-07-30 19:24:48 +00007979
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007980 if (LHSOPT->isObjCBuiltinType()) {
Douglas Gregorab209d82015-07-07 03:58:42 +00007981 return finish(RHSOPT->isObjCBuiltinType() ||
7982 RHSOPT->isObjCQualifiedIdType());
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007983 }
Fangrui Song6907ce22018-07-30 19:24:48 +00007984
Fariborz Jahanian440a6832010-04-06 17:23:39 +00007985 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
Douglas Gregorab209d82015-07-07 03:58:42 +00007986 return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
7987 QualType(RHSOPT,0),
7988 false));
Fangrui Song6907ce22018-07-30 19:24:48 +00007989
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007990 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
7991 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
7992 if (LHS && RHS) { // We have 2 user-defined types.
7993 if (LHS != RHS) {
7994 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
Douglas Gregorab209d82015-07-07 03:58:42 +00007995 return finish(BlockReturnType);
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007996 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
Douglas Gregorab209d82015-07-07 03:58:42 +00007997 return finish(!BlockReturnType);
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00007998 }
7999 else
8000 return true;
8001 }
8002 return false;
8003}
8004
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008005/// Comparison routine for Objective-C protocols to be used with
8006/// llvm::array_pod_sort.
8007static int compareObjCProtocolsByName(ObjCProtocolDecl * const *lhs,
8008 ObjCProtocolDecl * const *rhs) {
8009 return (*lhs)->getName().compare((*rhs)->getName());
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008010}
8011
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00008012/// getIntersectionOfProtocols - This routine finds the intersection of set
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008013/// of protocols inherited from two distinct objective-c pointer objects with
8014/// the given common base.
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00008015/// It is used to build composite qualifier list of the composite type of
8016/// the conditional expression involving two objective-c pointer objects.
Fangrui Song6907ce22018-07-30 19:24:48 +00008017static
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00008018void getIntersectionOfProtocols(ASTContext &Context,
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008019 const ObjCInterfaceDecl *CommonBase,
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00008020 const ObjCObjectPointerType *LHSOPT,
8021 const ObjCObjectPointerType *RHSOPT,
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008022 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) {
Fangrui Song6907ce22018-07-30 19:24:48 +00008023
John McCall8b07ec22010-05-15 11:32:37 +00008024 const ObjCObjectType* LHS = LHSOPT->getObjectType();
8025 const ObjCObjectType* RHS = RHSOPT->getObjectType();
8026 assert(LHS->getInterface() && "LHS must have an interface base");
8027 assert(RHS->getInterface() && "RHS must have an interface base");
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008028
8029 // Add all of the protocols for the LHS.
8030 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSProtocolSet;
8031
8032 // Start with the protocol qualifiers.
8033 for (auto proto : LHS->quals()) {
8034 Context.CollectInheritedProtocols(proto, LHSProtocolSet);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00008035 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008036
8037 // Also add the protocols associated with the LHS interface.
8038 Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet);
8039
8040 // Add all of the protocls for the RHS.
8041 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSProtocolSet;
8042
8043 // Start with the protocol qualifiers.
8044 for (auto proto : RHS->quals()) {
8045 Context.CollectInheritedProtocols(proto, RHSProtocolSet);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00008046 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008047
8048 // Also add the protocols associated with the RHS interface.
8049 Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet);
8050
8051 // Compute the intersection of the collected protocol sets.
8052 for (auto proto : LHSProtocolSet) {
8053 if (RHSProtocolSet.count(proto))
8054 IntersectionSet.push_back(proto);
8055 }
8056
8057 // Compute the set of protocols that is implied by either the common type or
8058 // the protocols within the intersection.
8059 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ImpliedProtocols;
8060 Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols);
8061
8062 // Remove any implied protocols from the list of inherited protocols.
8063 if (!ImpliedProtocols.empty()) {
8064 IntersectionSet.erase(
8065 std::remove_if(IntersectionSet.begin(),
8066 IntersectionSet.end(),
8067 [&](ObjCProtocolDecl *proto) -> bool {
8068 return ImpliedProtocols.count(proto) > 0;
8069 }),
8070 IntersectionSet.end());
8071 }
8072
8073 // Sort the remaining protocols by name.
8074 llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(),
8075 compareObjCProtocolsByName);
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00008076}
8077
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008078/// Determine whether the first type is a subtype of the second.
8079static bool canAssignObjCObjectTypes(ASTContext &ctx, QualType lhs,
8080 QualType rhs) {
8081 // Common case: two object pointers.
Eugene Zelenko7855e772018-04-03 00:11:50 +00008082 const auto *lhsOPT = lhs->getAs<ObjCObjectPointerType>();
8083 const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008084 if (lhsOPT && rhsOPT)
8085 return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT);
8086
8087 // Two block pointers.
Eugene Zelenko7855e772018-04-03 00:11:50 +00008088 const auto *lhsBlock = lhs->getAs<BlockPointerType>();
8089 const auto *rhsBlock = rhs->getAs<BlockPointerType>();
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008090 if (lhsBlock && rhsBlock)
8091 return ctx.typesAreBlockPointerCompatible(lhs, rhs);
8092
8093 // If either is an unqualified 'id' and the other is a block, it's
8094 // acceptable.
8095 if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) ||
8096 (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock))
8097 return true;
8098
8099 return false;
8100}
8101
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008102// Check that the given Objective-C type argument lists are equivalent.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008103static bool sameObjCTypeArgs(ASTContext &ctx,
8104 const ObjCInterfaceDecl *iface,
8105 ArrayRef<QualType> lhsArgs,
Douglas Gregorab209d82015-07-07 03:58:42 +00008106 ArrayRef<QualType> rhsArgs,
8107 bool stripKindOf) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008108 if (lhsArgs.size() != rhsArgs.size())
8109 return false;
8110
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008111 ObjCTypeParamList *typeParams = iface->getTypeParamList();
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008112 for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) {
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008113 if (ctx.hasSameType(lhsArgs[i], rhsArgs[i]))
8114 continue;
8115
8116 switch (typeParams->begin()[i]->getVariance()) {
8117 case ObjCTypeParamVariance::Invariant:
Douglas Gregorab209d82015-07-07 03:58:42 +00008118 if (!stripKindOf ||
8119 !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx),
8120 rhsArgs[i].stripObjCKindOfType(ctx))) {
8121 return false;
8122 }
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008123 break;
8124
8125 case ObjCTypeParamVariance::Covariant:
8126 if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i]))
8127 return false;
8128 break;
8129
8130 case ObjCTypeParamVariance::Contravariant:
8131 if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i]))
8132 return false;
8133 break;
Douglas Gregorab209d82015-07-07 03:58:42 +00008134 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008135 }
8136
8137 return true;
8138}
8139
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00008140QualType ASTContext::areCommonBaseCompatible(
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008141 const ObjCObjectPointerType *Lptr,
8142 const ObjCObjectPointerType *Rptr) {
John McCall8b07ec22010-05-15 11:32:37 +00008143 const ObjCObjectType *LHS = Lptr->getObjectType();
8144 const ObjCObjectType *RHS = Rptr->getObjectType();
8145 const ObjCInterfaceDecl* LDecl = LHS->getInterface();
8146 const ObjCInterfaceDecl* RDecl = RHS->getInterface();
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008147
8148 if (!LDecl || !RDecl)
Eugene Zelenko7855e772018-04-03 00:11:50 +00008149 return {};
Douglas Gregore83b9562015-07-07 03:57:53 +00008150
Manman Renc46f7d12016-05-06 19:35:02 +00008151 // When either LHS or RHS is a kindof type, we should return a kindof type.
8152 // For example, for common base of kindof(ASub1) and kindof(ASub2), we return
8153 // kindof(A).
8154 bool anyKindOf = LHS->isKindOfType() || RHS->isKindOfType();
8155
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008156 // Follow the left-hand side up the class hierarchy until we either hit a
8157 // root or find the RHS. Record the ancestors in case we don't find it.
8158 llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4>
8159 LHSAncestors;
8160 while (true) {
8161 // Record this ancestor. We'll need this if the common type isn't in the
8162 // path from the LHS to the root.
8163 LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS;
Douglas Gregore83b9562015-07-07 03:57:53 +00008164
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008165 if (declaresSameEntity(LHS->getInterface(), RDecl)) {
8166 // Get the type arguments.
8167 ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten();
8168 bool anyChanges = false;
8169 if (LHS->isSpecialized() && RHS->isSpecialized()) {
8170 // Both have type arguments, compare them.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008171 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
8172 LHS->getTypeArgs(), RHS->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00008173 /*stripKindOf=*/true))
Eugene Zelenko7855e772018-04-03 00:11:50 +00008174 return {};
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008175 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
8176 // If only one has type arguments, the result will not have type
8177 // arguments.
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00008178 LHSTypeArgs = {};
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008179 anyChanges = true;
8180 }
8181
8182 // Compute the intersection of protocols.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008183 SmallVector<ObjCProtocolDecl *, 8> Protocols;
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008184 getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr,
8185 Protocols);
John McCall8b07ec22010-05-15 11:32:37 +00008186 if (!Protocols.empty())
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008187 anyChanges = true;
8188
8189 // If anything in the LHS will have changed, build a new result type.
Manman Renc46f7d12016-05-06 19:35:02 +00008190 // If we need to return a kindof type but LHS is not a kindof type, we
8191 // build a new result type.
8192 if (anyChanges || LHS->isKindOfType() != anyKindOf) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008193 QualType Result = getObjCInterfaceType(LHS->getInterface());
Douglas Gregorab209d82015-07-07 03:58:42 +00008194 Result = getObjCObjectType(Result, LHSTypeArgs, Protocols,
Manman Renc46f7d12016-05-06 19:35:02 +00008195 anyKindOf || LHS->isKindOfType());
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008196 return getObjCObjectPointerType(Result);
8197 }
8198
8199 return getObjCObjectPointerType(QualType(LHS, 0));
Fariborz Jahanian6c5a8e22009-10-30 01:13:23 +00008200 }
Douglas Gregore83b9562015-07-07 03:57:53 +00008201
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008202 // Find the superclass.
Douglas Gregore83b9562015-07-07 03:57:53 +00008203 QualType LHSSuperType = LHS->getSuperClassType();
8204 if (LHSSuperType.isNull())
8205 break;
8206
8207 LHS = LHSSuperType->castAs<ObjCObjectType>();
8208 }
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008209
8210 // We didn't find anything by following the LHS to its root; now check
8211 // the RHS against the cached set of ancestors.
8212 while (true) {
8213 auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl());
8214 if (KnownLHS != LHSAncestors.end()) {
8215 LHS = KnownLHS->second;
8216
8217 // Get the type arguments.
8218 ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten();
8219 bool anyChanges = false;
8220 if (LHS->isSpecialized() && RHS->isSpecialized()) {
8221 // Both have type arguments, compare them.
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008222 if (!sameObjCTypeArgs(*this, LHS->getInterface(),
8223 LHS->getTypeArgs(), RHS->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00008224 /*stripKindOf=*/true))
Eugene Zelenko7855e772018-04-03 00:11:50 +00008225 return {};
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008226 } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
8227 // If only one has type arguments, the result will not have type
8228 // arguments.
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00008229 RHSTypeArgs = {};
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008230 anyChanges = true;
8231 }
8232
8233 // Compute the intersection of protocols.
8234 SmallVector<ObjCProtocolDecl *, 8> Protocols;
8235 getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr,
8236 Protocols);
8237 if (!Protocols.empty())
8238 anyChanges = true;
8239
Manman Renc46f7d12016-05-06 19:35:02 +00008240 // If we need to return a kindof type but RHS is not a kindof type, we
8241 // build a new result type.
8242 if (anyChanges || RHS->isKindOfType() != anyKindOf) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008243 QualType Result = getObjCInterfaceType(RHS->getInterface());
Douglas Gregorab209d82015-07-07 03:58:42 +00008244 Result = getObjCObjectType(Result, RHSTypeArgs, Protocols,
Manman Renc46f7d12016-05-06 19:35:02 +00008245 anyKindOf || RHS->isKindOfType());
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008246 return getObjCObjectPointerType(Result);
8247 }
8248
8249 return getObjCObjectPointerType(QualType(RHS, 0));
8250 }
8251
8252 // Find the superclass of the RHS.
8253 QualType RHSSuperType = RHS->getSuperClassType();
8254 if (RHSSuperType.isNull())
8255 break;
8256
8257 RHS = RHSSuperType->castAs<ObjCObjectType>();
8258 }
8259
Eugene Zelenko7855e772018-04-03 00:11:50 +00008260 return {};
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00008261}
8262
John McCall8b07ec22010-05-15 11:32:37 +00008263bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
8264 const ObjCObjectType *RHS) {
8265 assert(LHS->getInterface() && "LHS is not an interface type");
8266 assert(RHS->getInterface() && "RHS is not an interface type");
8267
Chris Lattner49af6a42008-04-07 06:51:04 +00008268 // Verify that the base decls are compatible: the RHS must be a subclass of
8269 // the LHS.
Douglas Gregore83b9562015-07-07 03:57:53 +00008270 ObjCInterfaceDecl *LHSInterface = LHS->getInterface();
8271 bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface());
8272 if (!IsSuperClass)
Chris Lattner49af6a42008-04-07 06:51:04 +00008273 return false;
Mike Stump11289f42009-09-09 15:08:12 +00008274
Douglas Gregore83b9562015-07-07 03:57:53 +00008275 // If the LHS has protocol qualifiers, determine whether all of them are
8276 // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the
8277 // LHS).
8278 if (LHS->getNumProtocols() > 0) {
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00008279 // OK if conversion of LHS to SuperClass results in narrowing of types
8280 // ; i.e., SuperClass may implement at least one of the protocols
8281 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
8282 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
8283 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
8284 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
8285 // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
8286 // qualifiers.
8287 for (auto *RHSPI : RHS->quals())
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008288 CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols);
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00008289 // If there is no protocols associated with RHS, it is not a match.
8290 if (SuperClassInheritedProtocols.empty())
Steve Naroff114aecb2009-03-01 16:12:44 +00008291 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00008292
Fariborz Jahanian12f7ef32014-10-13 21:07:45 +00008293 for (const auto *LHSProto : LHS->quals()) {
8294 bool SuperImplementsProtocol = false;
8295 for (auto *SuperClassProto : SuperClassInheritedProtocols)
8296 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
8297 SuperImplementsProtocol = true;
8298 break;
8299 }
8300 if (!SuperImplementsProtocol)
8301 return false;
8302 }
Chris Lattner49af6a42008-04-07 06:51:04 +00008303 }
Douglas Gregore83b9562015-07-07 03:57:53 +00008304
8305 // If the LHS is specialized, we may need to check type arguments.
8306 if (LHS->isSpecialized()) {
8307 // Follow the superclass chain until we've matched the LHS class in the
8308 // hierarchy. This substitutes type arguments through.
8309 const ObjCObjectType *RHSSuper = RHS;
8310 while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface))
8311 RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>();
8312
8313 // If the RHS is specializd, compare type arguments.
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008314 if (RHSSuper->isSpecialized() &&
Douglas Gregor1ac1b632015-07-07 03:58:54 +00008315 !sameObjCTypeArgs(*this, LHS->getInterface(),
8316 LHS->getTypeArgs(), RHSSuper->getTypeArgs(),
Douglas Gregorab209d82015-07-07 03:58:42 +00008317 /*stripKindOf=*/true)) {
Douglas Gregorc5e07f52015-07-07 03:58:01 +00008318 return false;
Douglas Gregore83b9562015-07-07 03:57:53 +00008319 }
8320 }
8321
8322 return true;
Chris Lattner49af6a42008-04-07 06:51:04 +00008323}
8324
Steve Naroffb7605152009-02-12 17:52:19 +00008325bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
8326 // get the "pointed to" types
Eugene Zelenko7855e772018-04-03 00:11:50 +00008327 const auto *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
8328 const auto *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00008329
Steve Naroff7cae42b2009-07-10 23:34:53 +00008330 if (!LHSOPT || !RHSOPT)
Steve Naroffb7605152009-02-12 17:52:19 +00008331 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00008332
8333 return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
8334 canAssignObjCInterfaces(RHSOPT, LHSOPT);
Steve Naroffb7605152009-02-12 17:52:19 +00008335}
8336
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00008337bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
8338 return canAssignObjCInterfaces(
8339 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
8340 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
8341}
8342
Mike Stump11289f42009-09-09 15:08:12 +00008343/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
Steve Naroff32e44c02007-10-15 20:41:53 +00008344/// both shall have the identically qualified version of a compatible type.
Mike Stump11289f42009-09-09 15:08:12 +00008345/// C99 6.2.7p1: Two types have compatible types if their types are the
Steve Naroff32e44c02007-10-15 20:41:53 +00008346/// same. See 6.7.[2,3,5] for additional rules.
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008347bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
8348 bool CompareUnqualified) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00008349 if (getLangOpts().CPlusPlus)
Douglas Gregor21e771e2010-02-03 21:02:30 +00008350 return hasSameType(LHS, RHS);
Joey Gouly5788b782016-11-18 14:10:54 +00008351
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008352 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
Eli Friedman47f77112008-08-22 00:56:42 +00008353}
8354
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00008355bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
Fariborz Jahanianc87c8792011-07-12 23:20:13 +00008356 return typesAreCompatible(LHS, RHS);
Fariborz Jahanianc0f6af22011-07-12 22:05:16 +00008357}
8358
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008359bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
8360 return !mergeTypes(LHS, RHS, true).isNull();
8361}
8362
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00008363/// mergeTransparentUnionType - if T is a transparent union type and a member
8364/// of T is compatible with SubType, return the merged type, else return
8365/// QualType()
8366QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
8367 bool OfBlockPointer,
8368 bool Unqualified) {
8369 if (const RecordType *UT = T->getAsUnionType()) {
8370 RecordDecl *UD = UT->getDecl();
8371 if (UD->hasAttr<TransparentUnionAttr>()) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008372 for (const auto *I : UD->fields()) {
8373 QualType ET = I->getType().getUnqualifiedType();
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00008374 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
8375 if (!MT.isNull())
8376 return MT;
8377 }
8378 }
8379 }
8380
Eugene Zelenko7855e772018-04-03 00:11:50 +00008381 return {};
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00008382}
8383
Alp Toker9cacbab2014-01-20 20:26:09 +00008384/// mergeFunctionParameterTypes - merge two types which appear as function
8385/// parameter types
8386QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs,
8387 bool OfBlockPointer,
8388 bool Unqualified) {
Peter Collingbournea99fdcf2010-10-24 18:30:18 +00008389 // GNU extension: two types are compatible if they appear as a function
8390 // argument, one of the types is a transparent union type and the other
8391 // type is compatible with a union member
8392 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
8393 Unqualified);
8394 if (!lmerge.isNull())
8395 return lmerge;
8396
8397 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
8398 Unqualified);
8399 if (!rmerge.isNull())
8400 return rmerge;
8401
8402 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
8403}
8404
Fangrui Song6907ce22018-07-30 19:24:48 +00008405QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008406 bool OfBlockPointer,
8407 bool Unqualified) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00008408 const auto *lbase = lhs->getAs<FunctionType>();
8409 const auto *rbase = rhs->getAs<FunctionType>();
8410 const auto *lproto = dyn_cast<FunctionProtoType>(lbase);
8411 const auto *rproto = dyn_cast<FunctionProtoType>(rbase);
Eli Friedman47f77112008-08-22 00:56:42 +00008412 bool allLTypes = true;
8413 bool allRTypes = true;
8414
8415 // Check return type
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008416 QualType retType;
Fariborz Jahanian17825972011-02-11 18:46:17 +00008417 if (OfBlockPointer) {
Alp Toker314cc812014-01-25 16:55:45 +00008418 QualType RHS = rbase->getReturnType();
8419 QualType LHS = lbase->getReturnType();
Fariborz Jahanian17825972011-02-11 18:46:17 +00008420 bool UnqualifiedResult = Unqualified;
8421 if (!UnqualifiedResult)
8422 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
Fariborz Jahanian90186f82011-03-14 16:07:00 +00008423 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
Fariborz Jahanian17825972011-02-11 18:46:17 +00008424 }
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008425 else
Alp Toker314cc812014-01-25 16:55:45 +00008426 retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
John McCall8c6b56f2010-12-15 01:06:38 +00008427 Unqualified);
Eugene Zelenko7855e772018-04-03 00:11:50 +00008428 if (retType.isNull())
8429 return {};
Fangrui Song6907ce22018-07-30 19:24:48 +00008430
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008431 if (Unqualified)
8432 retType = retType.getUnqualifiedType();
8433
Alp Toker314cc812014-01-25 16:55:45 +00008434 CanQualType LRetType = getCanonicalType(lbase->getReturnType());
8435 CanQualType RRetType = getCanonicalType(rbase->getReturnType());
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008436 if (Unqualified) {
8437 LRetType = LRetType.getUnqualifiedType();
8438 RRetType = RRetType.getUnqualifiedType();
8439 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008440
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008441 if (getCanonicalType(retType) != LRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00008442 allLTypes = false;
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008443 if (getCanonicalType(retType) != RRetType)
Chris Lattner465fa322008-10-05 17:34:18 +00008444 allRTypes = false;
John McCall8c6b56f2010-12-15 01:06:38 +00008445
Daniel Dunbaredd5bae2010-04-28 16:20:58 +00008446 // FIXME: double check this
8447 // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
8448 // rbase->getRegParmAttr() != 0 &&
8449 // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
Rafael Espindolac50c27c2010-03-30 20:24:48 +00008450 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
8451 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
John McCall8c6b56f2010-12-15 01:06:38 +00008452
Douglas Gregor8c940862010-01-18 17:14:39 +00008453 // Compatible functions must have compatible calling conventions
Reid Kleckner78af0702013-08-27 23:08:25 +00008454 if (lbaseInfo.getCC() != rbaseInfo.getCC())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008455 return {};
Mike Stump11289f42009-09-09 15:08:12 +00008456
John McCall8c6b56f2010-12-15 01:06:38 +00008457 // Regparm is part of the calling convention.
Eli Friedmanc5b20b52011-04-09 08:18:08 +00008458 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008459 return {};
John McCall8c6b56f2010-12-15 01:06:38 +00008460 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008461 return {};
John McCall8c6b56f2010-12-15 01:06:38 +00008462
John McCall31168b02011-06-15 23:02:42 +00008463 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008464 return {};
Oren Ben Simhon318a6ea2017-04-27 12:01:00 +00008465 if (lbaseInfo.getNoCallerSavedRegs() != rbaseInfo.getNoCallerSavedRegs())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008466 return {};
Oren Ben Simhon220671a2018-03-17 13:31:35 +00008467 if (lbaseInfo.getNoCfCheck() != rbaseInfo.getNoCfCheck())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008468 return {};
John McCall31168b02011-06-15 23:02:42 +00008469
John McCall8c6b56f2010-12-15 01:06:38 +00008470 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
8471 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
John McCall8c6b56f2010-12-15 01:06:38 +00008472
Rafael Espindola8778c282012-11-29 16:09:03 +00008473 if (lbaseInfo.getNoReturn() != NoReturn)
8474 allLTypes = false;
8475 if (rbaseInfo.getNoReturn() != NoReturn)
8476 allRTypes = false;
8477
John McCall31168b02011-06-15 23:02:42 +00008478 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00008479
Eli Friedman47f77112008-08-22 00:56:42 +00008480 if (lproto && rproto) { // two C99 style function prototypes
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00008481 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
8482 "C++ shouldn't be here");
Alp Toker601b22c2014-01-21 23:35:24 +00008483 // Compatible functions must have the same number of parameters
8484 if (lproto->getNumParams() != rproto->getNumParams())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008485 return {};
Eli Friedman47f77112008-08-22 00:56:42 +00008486
8487 // Variadic and non-variadic functions aren't compatible
8488 if (lproto->isVariadic() != rproto->isVariadic())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008489 return {};
Eli Friedman47f77112008-08-22 00:56:42 +00008490
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00008491 if (lproto->getTypeQuals() != rproto->getTypeQuals())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008492 return {};
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00008493
Akira Hatanaka98a49332017-09-22 00:41:05 +00008494 SmallVector<FunctionProtoType::ExtParameterInfo, 4> newParamInfos;
8495 bool canUseLeft, canUseRight;
8496 if (!mergeExtParameterInfo(lproto, rproto, canUseLeft, canUseRight,
8497 newParamInfos))
Eugene Zelenko7855e772018-04-03 00:11:50 +00008498 return {};
Alp Toker601b22c2014-01-21 23:35:24 +00008499
Akira Hatanaka98a49332017-09-22 00:41:05 +00008500 if (!canUseLeft)
8501 allLTypes = false;
8502 if (!canUseRight)
8503 allRTypes = false;
8504
Alp Toker601b22c2014-01-21 23:35:24 +00008505 // Check parameter type compatibility
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008506 SmallVector<QualType, 10> types;
Alp Toker601b22c2014-01-21 23:35:24 +00008507 for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
8508 QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
8509 QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
8510 QualType paramType = mergeFunctionParameterTypes(
8511 lParamType, rParamType, OfBlockPointer, Unqualified);
8512 if (paramType.isNull())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008513 return {};
Alp Toker601b22c2014-01-21 23:35:24 +00008514
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008515 if (Unqualified)
Alp Toker601b22c2014-01-21 23:35:24 +00008516 paramType = paramType.getUnqualifiedType();
8517
8518 types.push_back(paramType);
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008519 if (Unqualified) {
Alp Toker601b22c2014-01-21 23:35:24 +00008520 lParamType = lParamType.getUnqualifiedType();
8521 rParamType = rParamType.getUnqualifiedType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008522 }
Alp Toker601b22c2014-01-21 23:35:24 +00008523
8524 if (getCanonicalType(paramType) != getCanonicalType(lParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00008525 allLTypes = false;
Alp Toker601b22c2014-01-21 23:35:24 +00008526 if (getCanonicalType(paramType) != getCanonicalType(rParamType))
Chris Lattner465fa322008-10-05 17:34:18 +00008527 allRTypes = false;
Eli Friedman47f77112008-08-22 00:56:42 +00008528 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008529
Eli Friedman47f77112008-08-22 00:56:42 +00008530 if (allLTypes) return lhs;
8531 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00008532
8533 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
8534 EPI.ExtInfo = einfo;
Akira Hatanaka98a49332017-09-22 00:41:05 +00008535 EPI.ExtParameterInfos =
8536 newParamInfos.empty() ? nullptr : newParamInfos.data();
Jordan Rose5c382722013-03-08 21:51:21 +00008537 return getFunctionType(retType, types, EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00008538 }
8539
8540 if (lproto) allRTypes = false;
8541 if (rproto) allLTypes = false;
8542
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008543 const FunctionProtoType *proto = lproto ? lproto : rproto;
Eli Friedman47f77112008-08-22 00:56:42 +00008544 if (proto) {
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00008545 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
Eugene Zelenko7855e772018-04-03 00:11:50 +00008546 if (proto->isVariadic())
8547 return {};
Eli Friedman47f77112008-08-22 00:56:42 +00008548 // Check that the types are compatible with the types that
8549 // would result from default argument promotions (C99 6.7.5.3p15).
8550 // The only types actually affected are promotable integer
8551 // types and floats, which would be passed as a different
8552 // type depending on whether the prototype is visible.
Alp Toker601b22c2014-01-21 23:35:24 +00008553 for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
8554 QualType paramTy = proto->getParamType(i);
Alp Toker9cacbab2014-01-20 20:26:09 +00008555
Eli Friedman448ce402012-08-30 00:44:15 +00008556 // Look at the converted type of enum types, since that is the type used
Douglas Gregor2973d402010-02-03 19:27:29 +00008557 // to pass enum values.
Eugene Zelenko7855e772018-04-03 00:11:50 +00008558 if (const auto *Enum = paramTy->getAs<EnumType>()) {
Alp Toker601b22c2014-01-21 23:35:24 +00008559 paramTy = Enum->getDecl()->getIntegerType();
8560 if (paramTy.isNull())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008561 return {};
Eli Friedman448ce402012-08-30 00:44:15 +00008562 }
Alp Toker601b22c2014-01-21 23:35:24 +00008563
8564 if (paramTy->isPromotableIntegerType() ||
8565 getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
Eugene Zelenko7855e772018-04-03 00:11:50 +00008566 return {};
Eli Friedman47f77112008-08-22 00:56:42 +00008567 }
8568
8569 if (allLTypes) return lhs;
8570 if (allRTypes) return rhs;
John McCalldb40c7f2010-12-14 08:05:40 +00008571
8572 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
8573 EPI.ExtInfo = einfo;
Alp Toker9cacbab2014-01-20 20:26:09 +00008574 return getFunctionType(retType, proto->getParamTypes(), EPI);
Eli Friedman47f77112008-08-22 00:56:42 +00008575 }
8576
8577 if (allLTypes) return lhs;
8578 if (allRTypes) return rhs;
John McCall8c6b56f2010-12-15 01:06:38 +00008579 return getFunctionNoProtoType(retType, einfo);
Eli Friedman47f77112008-08-22 00:56:42 +00008580}
8581
John McCall433c2e62013-03-21 00:10:07 +00008582/// Given that we have an enum type and a non-enum type, try to merge them.
8583static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
8584 QualType other, bool isBlockReturnType) {
8585 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
8586 // a signed integer type, or an unsigned integer type.
8587 // Compatibility is based on the underlying type, not the promotion
8588 // type.
8589 QualType underlyingType = ET->getDecl()->getIntegerType();
Eugene Zelenko7855e772018-04-03 00:11:50 +00008590 if (underlyingType.isNull())
8591 return {};
John McCall433c2e62013-03-21 00:10:07 +00008592 if (Context.hasSameType(underlyingType, other))
8593 return other;
8594
8595 // In block return types, we're more permissive and accept any
8596 // integral type of the same size.
8597 if (isBlockReturnType && other->isIntegerType() &&
8598 Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
8599 return other;
8600
Eugene Zelenko7855e772018-04-03 00:11:50 +00008601 return {};
John McCall433c2e62013-03-21 00:10:07 +00008602}
8603
Fangrui Song6907ce22018-07-30 19:24:48 +00008604QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008605 bool OfBlockPointer,
Fariborz Jahanian90186f82011-03-14 16:07:00 +00008606 bool Unqualified, bool BlockReturnType) {
Bill Wendlingdb4e3492007-12-03 07:33:35 +00008607 // C++ [expr]: If an expression initially has the type "reference to T", the
8608 // type is adjusted to "T" prior to any further analysis, the expression
8609 // designates the object or function denoted by the reference, and the
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00008610 // expression is an lvalue unless the reference is an rvalue reference and
8611 // the expression is a function call (possibly inside parentheses).
Douglas Gregor21e771e2010-02-03 21:02:30 +00008612 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
8613 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008614
8615 if (Unqualified) {
8616 LHS = LHS.getUnqualifiedType();
8617 RHS = RHS.getUnqualifiedType();
8618 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008619
Eli Friedman47f77112008-08-22 00:56:42 +00008620 QualType LHSCan = getCanonicalType(LHS),
8621 RHSCan = getCanonicalType(RHS);
8622
8623 // If two types are identical, they are compatible.
8624 if (LHSCan == RHSCan)
8625 return LHS;
8626
John McCall8ccfcb52009-09-24 19:53:00 +00008627 // If the qualifiers are different, the types aren't compatible... mostly.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00008628 Qualifiers LQuals = LHSCan.getLocalQualifiers();
8629 Qualifiers RQuals = RHSCan.getLocalQualifiers();
John McCall8ccfcb52009-09-24 19:53:00 +00008630 if (LQuals != RQuals) {
8631 // If any of these qualifiers are different, we have a type
8632 // mismatch.
8633 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
John McCall31168b02011-06-15 23:02:42 +00008634 LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
Roger Ferrer Ibanezd93add32017-02-24 08:41:09 +00008635 LQuals.getObjCLifetime() != RQuals.getObjCLifetime() ||
8636 LQuals.hasUnaligned() != RQuals.hasUnaligned())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008637 return {};
John McCall8ccfcb52009-09-24 19:53:00 +00008638
8639 // Exactly one GC qualifier difference is allowed: __strong is
8640 // okay if the other type has no GC qualifier but is an Objective
8641 // C object pointer (i.e. implicitly strong by default). We fix
8642 // this by pretending that the unqualified type was actually
8643 // qualified __strong.
8644 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
8645 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
8646 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
8647
8648 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
Eugene Zelenko7855e772018-04-03 00:11:50 +00008649 return {};
John McCall8ccfcb52009-09-24 19:53:00 +00008650
8651 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
8652 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
8653 }
8654 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
8655 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
8656 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00008657 return {};
John McCall8ccfcb52009-09-24 19:53:00 +00008658 }
8659
8660 // Okay, qualifiers are equal.
Eli Friedman47f77112008-08-22 00:56:42 +00008661
Eli Friedmandcca6332009-06-01 01:22:52 +00008662 Type::TypeClass LHSClass = LHSCan->getTypeClass();
8663 Type::TypeClass RHSClass = RHSCan->getTypeClass();
Eli Friedman47f77112008-08-22 00:56:42 +00008664
Chris Lattnerfd652912008-01-14 05:45:46 +00008665 // We want to consider the two function types to be the same for these
8666 // comparisons, just force one to the other.
8667 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
8668 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
Eli Friedman16f90962008-02-12 08:23:06 +00008669
8670 // Same as above for arrays
Chris Lattner95554662008-04-07 05:43:21 +00008671 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
8672 LHSClass = Type::ConstantArray;
8673 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
8674 RHSClass = Type::ConstantArray;
Mike Stump11289f42009-09-09 15:08:12 +00008675
John McCall8b07ec22010-05-15 11:32:37 +00008676 // ObjCInterfaces are just specialized ObjCObjects.
8677 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
8678 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
8679
Nate Begemance4d7fc2008-04-18 23:10:10 +00008680 // Canonicalize ExtVector -> Vector.
8681 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
8682 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
Mike Stump11289f42009-09-09 15:08:12 +00008683
Chris Lattner95554662008-04-07 05:43:21 +00008684 // If the canonical type classes don't match.
Chris Lattnerfd652912008-01-14 05:45:46 +00008685 if (LHSClass != RHSClass) {
John McCall433c2e62013-03-21 00:10:07 +00008686 // Note that we only have special rules for turning block enum
8687 // returns into block int returns, not vice-versa.
Eugene Zelenko7855e772018-04-03 00:11:50 +00008688 if (const auto *ETy = LHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00008689 return mergeEnumWithInteger(*this, ETy, RHS, false);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00008690 }
John McCall9dd450b2009-09-21 23:43:11 +00008691 if (const EnumType* ETy = RHS->getAs<EnumType>()) {
John McCall433c2e62013-03-21 00:10:07 +00008692 return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
Eli Friedmana7bf7ed2008-02-12 08:46:17 +00008693 }
Fariborz Jahanian26d83712012-01-26 00:45:38 +00008694 // allow block pointer type to match an 'id' type.
Fariborz Jahanian194904e2012-01-26 17:08:50 +00008695 if (OfBlockPointer && !BlockReturnType) {
8696 if (LHS->isObjCIdType() && RHS->isBlockPointerType())
8697 return LHS;
8698 if (RHS->isObjCIdType() && LHS->isBlockPointerType())
8699 return RHS;
8700 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008701
Eugene Zelenko7855e772018-04-03 00:11:50 +00008702 return {};
Steve Naroff32e44c02007-10-15 20:41:53 +00008703 }
Eli Friedman47f77112008-08-22 00:56:42 +00008704
Steve Naroffc6edcbd2008-01-09 22:43:08 +00008705 // The canonical type classes match.
Chris Lattnerfd652912008-01-14 05:45:46 +00008706 switch (LHSClass) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008707#define TYPE(Class, Base)
8708#define ABSTRACT_TYPE(Class, Base)
John McCallbd8d9bd2010-03-01 23:49:17 +00008709#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008710#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
8711#define DEPENDENT_TYPE(Class, Base) case Type::Class:
8712#include "clang/AST/TypeNodes.def"
David Blaikie83d382b2011-09-23 05:06:16 +00008713 llvm_unreachable("Non-canonical and dependent types shouldn't get here");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008714
Richard Smith27d807c2013-04-30 13:56:41 +00008715 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00008716 case Type::DeducedTemplateSpecialization:
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00008717 case Type::LValueReference:
8718 case Type::RValueReference:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008719 case Type::MemberPointer:
David Blaikie83d382b2011-09-23 05:06:16 +00008720 llvm_unreachable("C++ should never be in mergeTypes");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008721
John McCall8b07ec22010-05-15 11:32:37 +00008722 case Type::ObjCInterface:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008723 case Type::IncompleteArray:
8724 case Type::VariableArray:
8725 case Type::FunctionProto:
8726 case Type::ExtVector:
David Blaikie83d382b2011-09-23 05:06:16 +00008727 llvm_unreachable("Types are eliminated above");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008728
Chris Lattnerfd652912008-01-14 05:45:46 +00008729 case Type::Pointer:
Eli Friedman47f77112008-08-22 00:56:42 +00008730 {
8731 // Merge two pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00008732 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
8733 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008734 if (Unqualified) {
8735 LHSPointee = LHSPointee.getUnqualifiedType();
8736 RHSPointee = RHSPointee.getUnqualifiedType();
8737 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008738 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008739 Unqualified);
Eugene Zelenko7855e772018-04-03 00:11:50 +00008740 if (ResultType.isNull())
8741 return {};
Eli Friedman091a9ac2009-06-02 05:28:56 +00008742 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00008743 return LHS;
Eli Friedman091a9ac2009-06-02 05:28:56 +00008744 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
Chris Lattner465fa322008-10-05 17:34:18 +00008745 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00008746 return getPointerType(ResultType);
8747 }
Steve Naroff68e167d2008-12-10 17:49:55 +00008748 case Type::BlockPointer:
8749 {
8750 // Merge two block pointer types, while trying to preserve typedef info
Ted Kremenekc23c7e62009-07-29 21:53:49 +00008751 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
8752 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008753 if (Unqualified) {
8754 LHSPointee = LHSPointee.getUnqualifiedType();
8755 RHSPointee = RHSPointee.getUnqualifiedType();
8756 }
Anastasia Stulova81a25e352017-03-10 15:23:07 +00008757 if (getLangOpts().OpenCL) {
8758 Qualifiers LHSPteeQual = LHSPointee.getQualifiers();
8759 Qualifiers RHSPteeQual = RHSPointee.getQualifiers();
8760 // Blocks can't be an expression in a ternary operator (OpenCL v2.0
8761 // 6.12.5) thus the following check is asymmetric.
8762 if (!LHSPteeQual.isAddressSpaceSupersetOf(RHSPteeQual))
Eugene Zelenko7855e772018-04-03 00:11:50 +00008763 return {};
Anastasia Stulova81a25e352017-03-10 15:23:07 +00008764 LHSPteeQual.removeAddressSpace();
8765 RHSPteeQual.removeAddressSpace();
8766 LHSPointee =
8767 QualType(LHSPointee.getTypePtr(), LHSPteeQual.getAsOpaqueValue());
8768 RHSPointee =
8769 QualType(RHSPointee.getTypePtr(), RHSPteeQual.getAsOpaqueValue());
8770 }
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008771 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
8772 Unqualified);
Eugene Zelenko7855e772018-04-03 00:11:50 +00008773 if (ResultType.isNull())
8774 return {};
Steve Naroff68e167d2008-12-10 17:49:55 +00008775 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
8776 return LHS;
8777 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
8778 return RHS;
8779 return getBlockPointerType(ResultType);
8780 }
Eli Friedman0dfb8892011-10-06 23:00:33 +00008781 case Type::Atomic:
8782 {
8783 // Merge two pointer types, while trying to preserve typedef info
8784 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
8785 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
8786 if (Unqualified) {
8787 LHSValue = LHSValue.getUnqualifiedType();
8788 RHSValue = RHSValue.getUnqualifiedType();
8789 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008790 QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
Eli Friedman0dfb8892011-10-06 23:00:33 +00008791 Unqualified);
Eugene Zelenko7855e772018-04-03 00:11:50 +00008792 if (ResultType.isNull())
8793 return {};
Eli Friedman0dfb8892011-10-06 23:00:33 +00008794 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
8795 return LHS;
8796 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
8797 return RHS;
8798 return getAtomicType(ResultType);
8799 }
Chris Lattnerfd652912008-01-14 05:45:46 +00008800 case Type::ConstantArray:
Eli Friedman47f77112008-08-22 00:56:42 +00008801 {
8802 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
8803 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
8804 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008805 return {};
Eli Friedman47f77112008-08-22 00:56:42 +00008806
8807 QualType LHSElem = getAsArrayType(LHS)->getElementType();
8808 QualType RHSElem = getAsArrayType(RHS)->getElementType();
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008809 if (Unqualified) {
8810 LHSElem = LHSElem.getUnqualifiedType();
8811 RHSElem = RHSElem.getUnqualifiedType();
8812 }
Fangrui Song6907ce22018-07-30 19:24:48 +00008813
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008814 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
Eugene Zelenko7855e772018-04-03 00:11:50 +00008815 if (ResultType.isNull())
8816 return {};
Jeremy Morse8129c5c2018-06-05 09:18:26 +00008817
8818 const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
8819 const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
8820
8821 // If either side is a variable array, and both are complete, check whether
8822 // the current dimension is definite.
8823 if (LVAT || RVAT) {
8824 auto SizeFetch = [this](const VariableArrayType* VAT,
8825 const ConstantArrayType* CAT)
8826 -> std::pair<bool,llvm::APInt> {
8827 if (VAT) {
8828 llvm::APSInt TheInt;
8829 Expr *E = VAT->getSizeExpr();
8830 if (E && E->isIntegerConstantExpr(TheInt, *this))
8831 return std::make_pair(true, TheInt);
8832 else
8833 return std::make_pair(false, TheInt);
8834 } else if (CAT) {
8835 return std::make_pair(true, CAT->getSize());
8836 } else {
8837 return std::make_pair(false, llvm::APInt());
8838 }
8839 };
8840
8841 bool HaveLSize, HaveRSize;
8842 llvm::APInt LSize, RSize;
8843 std::tie(HaveLSize, LSize) = SizeFetch(LVAT, LCAT);
8844 std::tie(HaveRSize, RSize) = SizeFetch(RVAT, RCAT);
8845 if (HaveLSize && HaveRSize && !llvm::APInt::isSameValue(LSize, RSize))
8846 return {}; // Definite, but unequal, array dimension
8847 }
8848
Chris Lattner465fa322008-10-05 17:34:18 +00008849 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
8850 return LHS;
8851 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
8852 return RHS;
Eli Friedman3e62c212008-08-22 01:48:21 +00008853 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
8854 ArrayType::ArraySizeModifier(), 0);
8855 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
8856 ArrayType::ArraySizeModifier(), 0);
Chris Lattner465fa322008-10-05 17:34:18 +00008857 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
8858 return LHS;
8859 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
8860 return RHS;
Eli Friedman47f77112008-08-22 00:56:42 +00008861 if (LVAT) {
8862 // FIXME: This isn't correct! But tricky to implement because
8863 // the array's size has to be the size of LHS, but the type
8864 // has to be different.
8865 return LHS;
8866 }
8867 if (RVAT) {
8868 // FIXME: This isn't correct! But tricky to implement because
8869 // the array's size has to be the size of RHS, but the type
8870 // has to be different.
8871 return RHS;
8872 }
Eli Friedman3e62c212008-08-22 01:48:21 +00008873 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
8874 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
Douglas Gregor04318252009-07-06 15:59:29 +00008875 return getIncompleteArrayType(ResultType,
8876 ArrayType::ArraySizeModifier(), 0);
Eli Friedman47f77112008-08-22 00:56:42 +00008877 }
Chris Lattnerfd652912008-01-14 05:45:46 +00008878 case Type::FunctionNoProto:
Douglas Gregor17ea3f52010-07-29 15:18:02 +00008879 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008880 case Type::Record:
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008881 case Type::Enum:
Eugene Zelenko7855e772018-04-03 00:11:50 +00008882 return {};
Chris Lattnerfd652912008-01-14 05:45:46 +00008883 case Type::Builtin:
Chris Lattner7bbd3d72008-04-07 05:55:38 +00008884 // Only exactly equal builtin types are compatible, which is tested above.
Eugene Zelenko7855e772018-04-03 00:11:50 +00008885 return {};
Daniel Dunbar804c0442009-01-28 21:22:12 +00008886 case Type::Complex:
8887 // Distinct complex types are incompatible.
Eugene Zelenko7855e772018-04-03 00:11:50 +00008888 return {};
Chris Lattner7bbd3d72008-04-07 05:55:38 +00008889 case Type::Vector:
Eli Friedmancad96382009-02-27 23:04:43 +00008890 // FIXME: The merged type should be an ExtVector!
John McCall44c064b2010-03-12 23:14:13 +00008891 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
8892 RHSCan->getAs<VectorType>()))
Eli Friedman47f77112008-08-22 00:56:42 +00008893 return LHS;
Eugene Zelenko7855e772018-04-03 00:11:50 +00008894 return {};
John McCall8b07ec22010-05-15 11:32:37 +00008895 case Type::ObjCObject: {
8896 // Check if the types are assignment compatible.
Eli Friedmancad96382009-02-27 23:04:43 +00008897 // FIXME: This should be type compatibility, e.g. whether
8898 // "LHS x; RHS x;" at global scope is legal.
Eugene Zelenko7855e772018-04-03 00:11:50 +00008899 const auto *LHSIface = LHS->getAs<ObjCObjectType>();
8900 const auto *RHSIface = RHS->getAs<ObjCObjectType>();
John McCall8b07ec22010-05-15 11:32:37 +00008901 if (canAssignObjCInterfaces(LHSIface, RHSIface))
Steve Naroff7a7814c2009-02-21 16:18:07 +00008902 return LHS;
8903
Eugene Zelenko7855e772018-04-03 00:11:50 +00008904 return {};
Cedric Venet4fc88b72009-02-21 17:14:49 +00008905 }
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00008906 case Type::ObjCObjectPointer:
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008907 if (OfBlockPointer) {
8908 if (canAssignObjCInterfacesInBlockPointer(
8909 LHS->getAs<ObjCObjectPointerType>(),
Fariborz Jahanian90186f82011-03-14 16:07:00 +00008910 RHS->getAs<ObjCObjectPointerType>(),
8911 BlockReturnType))
David Blaikie8a40f702012-01-17 06:56:22 +00008912 return LHS;
Eugene Zelenko7855e772018-04-03 00:11:50 +00008913 return {};
Fariborz Jahanianb8b0ea32010-03-17 00:20:01 +00008914 }
John McCall9dd450b2009-09-21 23:43:11 +00008915 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
8916 RHS->getAs<ObjCObjectPointerType>()))
Steve Naroff7cae42b2009-07-10 23:34:53 +00008917 return LHS;
8918
Eugene Zelenko7855e772018-04-03 00:11:50 +00008919 return {};
Xiuli Pan9c14e282016-01-09 12:53:17 +00008920 case Type::Pipe:
Joey Goulye3c85de2016-12-01 11:30:49 +00008921 assert(LHS != RHS &&
8922 "Equivalent pipe types should have already been handled!");
Eugene Zelenko7855e772018-04-03 00:11:50 +00008923 return {};
Xiuli Pan9c14e282016-01-09 12:53:17 +00008924 }
Douglas Gregordeaad8c2009-02-26 23:50:07 +00008925
David Blaikie8a40f702012-01-17 06:56:22 +00008926 llvm_unreachable("Invalid Type::Class!");
Steve Naroff32e44c02007-10-15 20:41:53 +00008927}
Ted Kremenekfc581a92007-10-31 17:10:13 +00008928
Akira Hatanaka98a49332017-09-22 00:41:05 +00008929bool ASTContext::mergeExtParameterInfo(
8930 const FunctionProtoType *FirstFnType, const FunctionProtoType *SecondFnType,
8931 bool &CanUseFirst, bool &CanUseSecond,
8932 SmallVectorImpl<FunctionProtoType::ExtParameterInfo> &NewParamInfos) {
8933 assert(NewParamInfos.empty() && "param info list not empty");
8934 CanUseFirst = CanUseSecond = true;
8935 bool FirstHasInfo = FirstFnType->hasExtParameterInfos();
8936 bool SecondHasInfo = SecondFnType->hasExtParameterInfos();
8937
John McCall18afab72016-03-01 00:49:02 +00008938 // Fast path: if the first type doesn't have ext parameter infos,
Akira Hatanaka98a49332017-09-22 00:41:05 +00008939 // we match if and only if the second type also doesn't have them.
8940 if (!FirstHasInfo && !SecondHasInfo)
8941 return true;
John McCall18afab72016-03-01 00:49:02 +00008942
Akira Hatanaka98a49332017-09-22 00:41:05 +00008943 bool NeedParamInfo = false;
8944 size_t E = FirstHasInfo ? FirstFnType->getExtParameterInfos().size()
8945 : SecondFnType->getExtParameterInfos().size();
John McCall18afab72016-03-01 00:49:02 +00008946
Akira Hatanaka98a49332017-09-22 00:41:05 +00008947 for (size_t I = 0; I < E; ++I) {
8948 FunctionProtoType::ExtParameterInfo FirstParam, SecondParam;
8949 if (FirstHasInfo)
8950 FirstParam = FirstFnType->getExtParameterInfo(I);
8951 if (SecondHasInfo)
8952 SecondParam = SecondFnType->getExtParameterInfo(I);
John McCall18afab72016-03-01 00:49:02 +00008953
Akira Hatanaka98a49332017-09-22 00:41:05 +00008954 // Cannot merge unless everything except the noescape flag matches.
8955 if (FirstParam.withIsNoEscape(false) != SecondParam.withIsNoEscape(false))
John McCall18afab72016-03-01 00:49:02 +00008956 return false;
Akira Hatanaka98a49332017-09-22 00:41:05 +00008957
8958 bool FirstNoEscape = FirstParam.isNoEscape();
8959 bool SecondNoEscape = SecondParam.isNoEscape();
8960 bool IsNoEscape = FirstNoEscape && SecondNoEscape;
8961 NewParamInfos.push_back(FirstParam.withIsNoEscape(IsNoEscape));
8962 if (NewParamInfos.back().getOpaqueValue())
8963 NeedParamInfo = true;
8964 if (FirstNoEscape != IsNoEscape)
8965 CanUseFirst = false;
8966 if (SecondNoEscape != IsNoEscape)
8967 CanUseSecond = false;
John McCall18afab72016-03-01 00:49:02 +00008968 }
Akira Hatanaka98a49332017-09-22 00:41:05 +00008969
8970 if (!NeedParamInfo)
8971 NewParamInfos.clear();
8972
Fariborz Jahanian97676972011-09-28 21:52:05 +00008973 return true;
8974}
8975
Chandler Carruth21c90602015-12-30 03:24:14 +00008976void ASTContext::ResetObjCLayout(const ObjCContainerDecl *CD) {
8977 ObjCLayouts[CD] = nullptr;
8978}
8979
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00008980/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
8981/// 'RHS' attributes and returns the merged version; including for function
8982/// return types.
8983QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
8984 QualType LHSCan = getCanonicalType(LHS),
8985 RHSCan = getCanonicalType(RHS);
8986 // If two types are identical, they are compatible.
8987 if (LHSCan == RHSCan)
8988 return LHS;
8989 if (RHSCan->isFunctionType()) {
8990 if (!LHSCan->isFunctionType())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008991 return {};
Alp Toker314cc812014-01-25 16:55:45 +00008992 QualType OldReturnType =
8993 cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00008994 QualType NewReturnType =
Alp Toker314cc812014-01-25 16:55:45 +00008995 cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
Fangrui Song6907ce22018-07-30 19:24:48 +00008996 QualType ResReturnType =
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00008997 mergeObjCGCQualifiers(NewReturnType, OldReturnType);
8998 if (ResReturnType.isNull())
Eugene Zelenko7855e772018-04-03 00:11:50 +00008999 return {};
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009000 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
9001 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
9002 // In either case, use OldReturnType to build the new function type.
Eugene Zelenko7855e772018-04-03 00:11:50 +00009003 const auto *F = LHS->getAs<FunctionType>();
9004 if (const auto *FPT = cast<FunctionProtoType>(F)) {
John McCalldb40c7f2010-12-14 08:05:40 +00009005 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9006 EPI.ExtInfo = getFunctionExtInfo(LHS);
Reid Kleckner896b32f2013-06-10 20:51:09 +00009007 QualType ResultType =
Alp Toker9cacbab2014-01-20 20:26:09 +00009008 getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009009 return ResultType;
9010 }
9011 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00009012 return {};
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009013 }
Fangrui Song6907ce22018-07-30 19:24:48 +00009014
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009015 // If the qualifiers are different, the types can still be merged.
9016 Qualifiers LQuals = LHSCan.getLocalQualifiers();
9017 Qualifiers RQuals = RHSCan.getLocalQualifiers();
9018 if (LQuals != RQuals) {
9019 // If any of these qualifiers are different, we have a type mismatch.
9020 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
9021 LQuals.getAddressSpace() != RQuals.getAddressSpace())
Eugene Zelenko7855e772018-04-03 00:11:50 +00009022 return {};
Fangrui Song6907ce22018-07-30 19:24:48 +00009023
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009024 // Exactly one GC qualifier difference is allowed: __strong is
9025 // okay if the other type has no GC qualifier but is an Objective
9026 // C object pointer (i.e. implicitly strong by default). We fix
9027 // this by pretending that the unqualified type was actually
9028 // qualified __strong.
9029 Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
9030 Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
9031 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
Fangrui Song6907ce22018-07-30 19:24:48 +00009032
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009033 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
Eugene Zelenko7855e772018-04-03 00:11:50 +00009034 return {};
Fangrui Song6907ce22018-07-30 19:24:48 +00009035
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009036 if (GC_L == Qualifiers::Strong)
9037 return LHS;
9038 if (GC_R == Qualifiers::Strong)
9039 return RHS;
Eugene Zelenko7855e772018-04-03 00:11:50 +00009040 return {};
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009041 }
Fangrui Song6907ce22018-07-30 19:24:48 +00009042
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009043 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
9044 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
9045 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
9046 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
9047 if (ResQT == LHSBaseQT)
9048 return LHS;
9049 if (ResQT == RHSBaseQT)
9050 return RHS;
9051 }
Eugene Zelenko7855e772018-04-03 00:11:50 +00009052 return {};
Fariborz Jahanianf633ebd2010-05-19 21:37:30 +00009053}
9054
Chris Lattner4ba0cef2008-04-07 07:01:58 +00009055//===----------------------------------------------------------------------===//
Eli Friedman4f89ccb2008-06-28 06:23:08 +00009056// Integer Predicates
9057//===----------------------------------------------------------------------===//
Chris Lattner3c919712009-01-16 07:15:35 +00009058
Jay Foad39c79802011-01-12 09:06:06 +00009059unsigned ASTContext::getIntWidth(QualType T) const {
Eugene Zelenko7855e772018-04-03 00:11:50 +00009060 if (const auto *ET = T->getAs<EnumType>())
Eli Friedmanee275c82009-12-10 22:29:29 +00009061 T = ET->getDecl()->getIntegerType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00009062 if (T->isBooleanType())
9063 return 1;
Eli Friedman1efaaea2009-02-13 02:31:07 +00009064 // For builtin types, just use the standard type sizing method
Eli Friedman4f89ccb2008-06-28 06:23:08 +00009065 return (unsigned)getTypeSize(T);
9066}
9067
Abramo Bagnara13640492012-09-09 10:21:24 +00009068QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
Leonard Chanab80f3c2018-06-14 14:53:51 +00009069 assert((T->hasSignedIntegerRepresentation() || T->isSignedFixedPointType()) &&
9070 "Unexpected type");
Fangrui Song6907ce22018-07-30 19:24:48 +00009071
Chris Lattnerec3a1562009-10-17 20:33:28 +00009072 // Turn <4 x signed int> -> <4 x unsigned int>
Eugene Zelenko7855e772018-04-03 00:11:50 +00009073 if (const auto *VTy = T->getAs<VectorType>())
Chris Lattnerec3a1562009-10-17 20:33:28 +00009074 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
Bob Wilsonaeb56442010-11-10 21:56:12 +00009075 VTy->getNumElements(), VTy->getVectorKind());
Chris Lattnerec3a1562009-10-17 20:33:28 +00009076
9077 // For enums, we return the unsigned version of the base type.
Eugene Zelenko7855e772018-04-03 00:11:50 +00009078 if (const auto *ETy = T->getAs<EnumType>())
Eli Friedman4f89ccb2008-06-28 06:23:08 +00009079 T = ETy->getDecl()->getIntegerType();
Fangrui Song6907ce22018-07-30 19:24:48 +00009080
Eugene Zelenko7855e772018-04-03 00:11:50 +00009081 const auto *BTy = T->getAs<BuiltinType>();
Leonard Chanab80f3c2018-06-14 14:53:51 +00009082 assert(BTy && "Unexpected signed integer or fixed point type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00009083 switch (BTy->getKind()) {
9084 case BuiltinType::Char_S:
9085 case BuiltinType::SChar:
9086 return UnsignedCharTy;
9087 case BuiltinType::Short:
9088 return UnsignedShortTy;
9089 case BuiltinType::Int:
9090 return UnsignedIntTy;
9091 case BuiltinType::Long:
9092 return UnsignedLongTy;
9093 case BuiltinType::LongLong:
9094 return UnsignedLongLongTy;
Chris Lattnerf122cef2009-04-30 02:43:43 +00009095 case BuiltinType::Int128:
9096 return UnsignedInt128Ty;
Leonard Chanab80f3c2018-06-14 14:53:51 +00009097
9098 case BuiltinType::ShortAccum:
9099 return UnsignedShortAccumTy;
9100 case BuiltinType::Accum:
9101 return UnsignedAccumTy;
9102 case BuiltinType::LongAccum:
9103 return UnsignedLongAccumTy;
9104 case BuiltinType::SatShortAccum:
9105 return SatUnsignedShortAccumTy;
9106 case BuiltinType::SatAccum:
9107 return SatUnsignedAccumTy;
9108 case BuiltinType::SatLongAccum:
9109 return SatUnsignedLongAccumTy;
9110 case BuiltinType::ShortFract:
9111 return UnsignedShortFractTy;
9112 case BuiltinType::Fract:
9113 return UnsignedFractTy;
9114 case BuiltinType::LongFract:
9115 return UnsignedLongFractTy;
9116 case BuiltinType::SatShortFract:
9117 return SatUnsignedShortFractTy;
9118 case BuiltinType::SatFract:
9119 return SatUnsignedFractTy;
9120 case BuiltinType::SatLongFract:
9121 return SatUnsignedLongFractTy;
Eli Friedman4f89ccb2008-06-28 06:23:08 +00009122 default:
Leonard Chanab80f3c2018-06-14 14:53:51 +00009123 llvm_unreachable("Unexpected signed integer or fixed point type");
Eli Friedman4f89ccb2008-06-28 06:23:08 +00009124 }
9125}
9126
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00009127ASTMutationListener::~ASTMutationListener() = default;
Argyrios Kyrtzidis65ad5692010-10-24 17:26:36 +00009128
Richard Smith1fa5d642013-05-11 05:45:24 +00009129void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
9130 QualType ReturnType) {}
Chris Lattnerecd79c62009-06-14 00:45:47 +00009131
9132//===----------------------------------------------------------------------===//
9133// Builtin Type Computation
9134//===----------------------------------------------------------------------===//
9135
9136/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
Chris Lattnerdc226c22010-10-01 22:42:38 +00009137/// pointer over the consumed characters. This returns the resultant type. If
9138/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
9139/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
9140/// a vector of "i*".
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009141///
9142/// RequiresICE is filled in on return to indicate whether the value is required
9143/// to be an Integer Constant Expression.
Jay Foad39c79802011-01-12 09:06:06 +00009144static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
Chris Lattnerecd79c62009-06-14 00:45:47 +00009145 ASTContext::GetBuiltinTypeError &Error,
Chandler Carruth45bbe012017-03-24 09:11:57 +00009146 bool &RequiresICE,
Chris Lattnerdc226c22010-10-01 22:42:38 +00009147 bool AllowTypeModifiers) {
Chris Lattnerecd79c62009-06-14 00:45:47 +00009148 // Modifiers.
9149 int HowLong = 0;
9150 bool Signed = false, Unsigned = false;
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009151 RequiresICE = false;
Fangrui Song6907ce22018-07-30 19:24:48 +00009152
Chris Lattnerdc226c22010-10-01 22:42:38 +00009153 // Read the prefixed modifiers first.
Eric Christopher50daf5f2017-07-10 21:28:54 +00009154 bool Done = false;
9155 #ifndef NDEBUG
9156 bool IsSpecialLong = false;
9157 #endif
Chris Lattnerecd79c62009-06-14 00:45:47 +00009158 while (!Done) {
9159 switch (*Str++) {
Mike Stump11289f42009-09-09 15:08:12 +00009160 default: Done = true; --Str; break;
Chris Lattner84733392010-10-01 07:13:18 +00009161 case 'I':
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009162 RequiresICE = true;
Chris Lattner84733392010-10-01 07:13:18 +00009163 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009164 case 'S':
9165 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
9166 assert(!Signed && "Can't use 'S' modifier multiple times!");
9167 Signed = true;
9168 break;
9169 case 'U':
9170 assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
Sean Silva2a995142015-01-16 21:44:26 +00009171 assert(!Unsigned && "Can't use 'U' modifier multiple times!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00009172 Unsigned = true;
9173 break;
9174 case 'L':
Bruno Cardoso Lopesafa47c92017-06-21 02:20:46 +00009175 assert(!IsSpecialLong && "Can't use 'L' with 'W' or 'N' modifiers");
Chris Lattnerecd79c62009-06-14 00:45:47 +00009176 assert(HowLong <= 2 && "Can't have LLLL modifier");
9177 ++HowLong;
9178 break;
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00009179 case 'N':
Bruno Cardoso Lopesafa47c92017-06-21 02:20:46 +00009180 // 'N' behaves like 'L' for all non LP64 targets and 'int' otherwise.
9181 assert(!IsSpecialLong && "Can't use two 'N' or 'W' modifiers!");
9182 assert(HowLong == 0 && "Can't use both 'L' and 'N' modifiers!");
Eric Christopher50daf5f2017-07-10 21:28:54 +00009183 #ifndef NDEBUG
Bruno Cardoso Lopesafa47c92017-06-21 02:20:46 +00009184 IsSpecialLong = true;
Eric Christopher50daf5f2017-07-10 21:28:54 +00009185 #endif
Bruno Cardoso Lopesafa47c92017-06-21 02:20:46 +00009186 if (Context.getTargetInfo().getLongWidth() == 32)
9187 ++HowLong;
9188 break;
Kevin Qinad64f6d2014-02-24 02:45:03 +00009189 case 'W':
9190 // This modifier represents int64 type.
Bruno Cardoso Lopesafa47c92017-06-21 02:20:46 +00009191 assert(!IsSpecialLong && "Can't use two 'N' or 'W' modifiers!");
Kevin Qinad64f6d2014-02-24 02:45:03 +00009192 assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
Eric Christopher50daf5f2017-07-10 21:28:54 +00009193 #ifndef NDEBUG
Bruno Cardoso Lopesafa47c92017-06-21 02:20:46 +00009194 IsSpecialLong = true;
Eric Christopher50daf5f2017-07-10 21:28:54 +00009195 #endif
Kevin Qinad64f6d2014-02-24 02:45:03 +00009196 switch (Context.getTargetInfo().getInt64Type()) {
9197 default:
9198 llvm_unreachable("Unexpected integer type");
9199 case TargetInfo::SignedLong:
9200 HowLong = 1;
9201 break;
9202 case TargetInfo::SignedLongLong:
9203 HowLong = 2;
9204 break;
9205 }
Duncan P. N. Exon Smitheae8caa2017-06-14 21:26:31 +00009206 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009207 }
9208 }
9209
9210 QualType Type;
Mike Stump11289f42009-09-09 15:08:12 +00009211
Chris Lattnerecd79c62009-06-14 00:45:47 +00009212 // Read the base type.
9213 switch (*Str++) {
David Blaikie83d382b2011-09-23 05:06:16 +00009214 default: llvm_unreachable("Unknown builtin type letter!");
Chris Lattnerecd79c62009-06-14 00:45:47 +00009215 case 'v':
9216 assert(HowLong == 0 && !Signed && !Unsigned &&
9217 "Bad modifiers used with 'v'!");
9218 Type = Context.VoidTy;
9219 break;
Jack Carter24bef982013-08-15 15:16:57 +00009220 case 'h':
9221 assert(HowLong == 0 && !Signed && !Unsigned &&
Sean Silva2a995142015-01-16 21:44:26 +00009222 "Bad modifiers used with 'h'!");
Jack Carter24bef982013-08-15 15:16:57 +00009223 Type = Context.HalfTy;
9224 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009225 case 'f':
9226 assert(HowLong == 0 && !Signed && !Unsigned &&
9227 "Bad modifiers used with 'f'!");
9228 Type = Context.FloatTy;
9229 break;
9230 case 'd':
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00009231 assert(HowLong < 3 && !Signed && !Unsigned &&
Chris Lattnerecd79c62009-06-14 00:45:47 +00009232 "Bad modifiers used with 'd'!");
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00009233 if (HowLong == 1)
Chris Lattnerecd79c62009-06-14 00:45:47 +00009234 Type = Context.LongDoubleTy;
Benjamin Kramerdfecbe92018-01-06 21:49:54 +00009235 else if (HowLong == 2)
9236 Type = Context.Float128Ty;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009237 else
9238 Type = Context.DoubleTy;
9239 break;
9240 case 's':
9241 assert(HowLong == 0 && "Bad modifiers used with 's'!");
9242 if (Unsigned)
9243 Type = Context.UnsignedShortTy;
9244 else
9245 Type = Context.ShortTy;
9246 break;
9247 case 'i':
9248 if (HowLong == 3)
9249 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
9250 else if (HowLong == 2)
9251 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
9252 else if (HowLong == 1)
9253 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
9254 else
9255 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
9256 break;
9257 case 'c':
9258 assert(HowLong == 0 && "Bad modifiers used with 'c'!");
9259 if (Signed)
9260 Type = Context.SignedCharTy;
9261 else if (Unsigned)
9262 Type = Context.UnsignedCharTy;
9263 else
9264 Type = Context.CharTy;
9265 break;
9266 case 'b': // boolean
9267 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
9268 Type = Context.BoolTy;
9269 break;
9270 case 'z': // size_t.
9271 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
9272 Type = Context.getSizeType();
9273 break;
Richard Smith8110c9d2016-11-29 19:45:17 +00009274 case 'w': // wchar_t.
9275 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'w'!");
9276 Type = Context.getWideCharType();
9277 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009278 case 'F':
9279 Type = Context.getCFConstantStringType();
9280 break;
Fariborz Jahaniand11da7e2010-11-09 21:38:20 +00009281 case 'G':
9282 Type = Context.getObjCIdType();
9283 break;
9284 case 'H':
9285 Type = Context.getObjCSelType();
9286 break;
Fariborz Jahaniancb6c8672013-01-04 18:45:40 +00009287 case 'M':
9288 Type = Context.getObjCSuperType();
9289 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009290 case 'a':
9291 Type = Context.getBuiltinVaListType();
9292 assert(!Type.isNull() && "builtin va list type not initialized!");
9293 break;
9294 case 'A':
9295 // This is a "reference" to a va_list; however, what exactly
9296 // this means depends on how va_list is defined. There are two
9297 // different kinds of va_list: ones passed by value, and ones
9298 // passed by reference. An example of a by-value va_list is
9299 // x86, where va_list is a char*. An example of by-ref va_list
9300 // is x86-64, where va_list is a __va_list_tag[1]. For x86,
9301 // we want this argument to be a char*&; for x86-64, we want
9302 // it to be a __va_list_tag*.
9303 Type = Context.getBuiltinVaListType();
9304 assert(!Type.isNull() && "builtin va list type not initialized!");
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009305 if (Type->isArrayType())
Chris Lattnerecd79c62009-06-14 00:45:47 +00009306 Type = Context.getArrayDecayedType(Type);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009307 else
Chris Lattnerecd79c62009-06-14 00:45:47 +00009308 Type = Context.getLValueReferenceType(Type);
Chris Lattnerecd79c62009-06-14 00:45:47 +00009309 break;
9310 case 'V': {
9311 char *End;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009312 unsigned NumElements = strtoul(Str, &End, 10);
9313 assert(End != Str && "Missing vector size");
Chris Lattnerecd79c62009-06-14 00:45:47 +00009314 Str = End;
Mike Stump11289f42009-09-09 15:08:12 +00009315
Fangrui Song6907ce22018-07-30 19:24:48 +00009316 QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
Chandler Carruth45bbe012017-03-24 09:11:57 +00009317 RequiresICE, false);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009318 assert(!RequiresICE && "Can't require vector ICE");
Fangrui Song6907ce22018-07-30 19:24:48 +00009319
Chris Lattnerdc226c22010-10-01 22:42:38 +00009320 // TODO: No way to make AltiVec vectors in builtins yet.
Chris Lattner37141f42010-06-23 06:00:24 +00009321 Type = Context.getVectorType(ElementType, NumElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00009322 VectorType::GenericVector);
Chris Lattnerecd79c62009-06-14 00:45:47 +00009323 break;
9324 }
Douglas Gregorfed66992012-06-07 18:08:25 +00009325 case 'E': {
9326 char *End;
Fangrui Song6907ce22018-07-30 19:24:48 +00009327
Douglas Gregorfed66992012-06-07 18:08:25 +00009328 unsigned NumElements = strtoul(Str, &End, 10);
9329 assert(End != Str && "Missing vector size");
Fangrui Song6907ce22018-07-30 19:24:48 +00009330
Douglas Gregorfed66992012-06-07 18:08:25 +00009331 Str = End;
Fangrui Song6907ce22018-07-30 19:24:48 +00009332
Douglas Gregorfed66992012-06-07 18:08:25 +00009333 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
Chandler Carruth45bbe012017-03-24 09:11:57 +00009334 false);
Douglas Gregorfed66992012-06-07 18:08:25 +00009335 Type = Context.getExtVectorType(ElementType, NumElements);
Fangrui Song6907ce22018-07-30 19:24:48 +00009336 break;
Douglas Gregorfed66992012-06-07 18:08:25 +00009337 }
Douglas Gregor40ef7c52009-09-28 21:45:01 +00009338 case 'X': {
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009339 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
Chandler Carruth45bbe012017-03-24 09:11:57 +00009340 false);
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009341 assert(!RequiresICE && "Can't require complex ICE");
Douglas Gregor40ef7c52009-09-28 21:45:01 +00009342 Type = Context.getComplexType(ElementType);
9343 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00009344 }
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00009345 case 'Y':
Fariborz Jahanian73952fc2011-08-23 23:33:09 +00009346 Type = Context.getPointerDiffType();
9347 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00009348 case 'P':
Douglas Gregor27821ce2009-07-07 16:35:42 +00009349 Type = Context.getFILEType();
9350 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00009351 Error = ASTContext::GE_Missing_stdio;
Eugene Zelenko7855e772018-04-03 00:11:50 +00009352 return {};
Chris Lattnerecd79c62009-06-14 00:45:47 +00009353 }
Mike Stump2adb4da2009-07-28 23:47:15 +00009354 break;
Chris Lattnera58b3af2009-07-28 22:49:34 +00009355 case 'J':
Mike Stump93246cc2009-07-28 23:57:15 +00009356 if (Signed)
Mike Stumpa4de80b2009-07-28 02:25:19 +00009357 Type = Context.getsigjmp_bufType();
Mike Stump93246cc2009-07-28 23:57:15 +00009358 else
9359 Type = Context.getjmp_bufType();
9360
Mike Stump2adb4da2009-07-28 23:47:15 +00009361 if (Type.isNull()) {
Mike Stump93246cc2009-07-28 23:57:15 +00009362 Error = ASTContext::GE_Missing_setjmp;
Eugene Zelenko7855e772018-04-03 00:11:50 +00009363 return {};
Mike Stump2adb4da2009-07-28 23:47:15 +00009364 }
9365 break;
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00009366 case 'K':
9367 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
9368 Type = Context.getucontext_tType();
9369
9370 if (Type.isNull()) {
9371 Error = ASTContext::GE_Missing_ucontext;
Eugene Zelenko7855e772018-04-03 00:11:50 +00009372 return {};
Rafael Espindola6cfa82b2011-11-13 21:51:09 +00009373 }
9374 break;
Eli Friedman4e91899e2012-11-27 02:58:24 +00009375 case 'p':
9376 Type = Context.getProcessIDType();
9377 break;
Mike Stumpa4de80b2009-07-28 02:25:19 +00009378 }
Mike Stump11289f42009-09-09 15:08:12 +00009379
Chris Lattnerdc226c22010-10-01 22:42:38 +00009380 // If there are modifiers and if we're allowed to parse them, go for it.
9381 Done = !AllowTypeModifiers;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009382 while (!Done) {
John McCallb8b94662010-03-12 04:21:28 +00009383 switch (char c = *Str++) {
Chris Lattnerdc226c22010-10-01 22:42:38 +00009384 default: Done = true; --Str; break;
9385 case '*':
9386 case '&': {
9387 // Both pointers and references can have their pointee types
9388 // qualified with an address space.
9389 char *End;
9390 unsigned AddrSpace = strtoul(Str, &End, 10);
Matt Arsenaultc65f9662018-08-02 12:14:28 +00009391 if (End != Str) {
9392 // Note AddrSpace == 0 is not the same as an unspecified address space.
9393 Type = Context.getAddrSpaceQualType(
9394 Type,
9395 Context.getLangASForBuiltinAddressSpace(AddrSpace));
Chris Lattnerdc226c22010-10-01 22:42:38 +00009396 Str = End;
9397 }
9398 if (c == '*')
9399 Type = Context.getPointerType(Type);
9400 else
9401 Type = Context.getLValueReferenceType(Type);
9402 break;
9403 }
9404 // FIXME: There's no way to have a built-in with an rvalue ref arg.
9405 case 'C':
9406 Type = Type.withConst();
9407 break;
9408 case 'D':
9409 Type = Context.getVolatileType(Type);
9410 break;
Ted Kremenekf2a2f5f2012-01-20 21:40:12 +00009411 case 'R':
9412 Type = Type.withRestrict();
9413 break;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009414 }
9415 }
Fangrui Song6907ce22018-07-30 19:24:48 +00009416
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009417 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
Fangrui Song6907ce22018-07-30 19:24:48 +00009418 "Integer constant 'I' type must be an integer");
Mike Stump11289f42009-09-09 15:08:12 +00009419
Chris Lattnerecd79c62009-06-14 00:45:47 +00009420 return Type;
9421}
9422
9423/// GetBuiltinType - Return the type for the specified builtin.
Chandler Carruth45bbe012017-03-24 09:11:57 +00009424QualType ASTContext::GetBuiltinType(unsigned Id,
9425 GetBuiltinTypeError &Error,
9426 unsigned *IntegerConstantArgs) const {
Eric Christopher02d5d862015-08-06 01:01:12 +00009427 const char *TypeStr = BuiltinInfo.getTypeString(Id);
Mike Stump11289f42009-09-09 15:08:12 +00009428
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009429 SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00009430
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009431 bool RequiresICE = false;
Chris Lattnerecd79c62009-06-14 00:45:47 +00009432 Error = GE_None;
Chandler Carruth45bbe012017-03-24 09:11:57 +00009433 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
9434 RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00009435 if (Error != GE_None)
Eugene Zelenko7855e772018-04-03 00:11:50 +00009436 return {};
Fangrui Song6907ce22018-07-30 19:24:48 +00009437
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009438 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
Fangrui Song6907ce22018-07-30 19:24:48 +00009439
Chris Lattnerecd79c62009-06-14 00:45:47 +00009440 while (TypeStr[0] && TypeStr[0] != '.') {
Chandler Carruth45bbe012017-03-24 09:11:57 +00009441 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
Chris Lattnerecd79c62009-06-14 00:45:47 +00009442 if (Error != GE_None)
Eugene Zelenko7855e772018-04-03 00:11:50 +00009443 return {};
Chris Lattnerecd79c62009-06-14 00:45:47 +00009444
Chris Lattnerbd6e6932010-10-01 22:53:11 +00009445 // If this argument is required to be an IntegerConstantExpression and the
9446 // caller cares, fill in the bitmask we return.
9447 if (RequiresICE && IntegerConstantArgs)
9448 *IntegerConstantArgs |= 1 << ArgTypes.size();
Fangrui Song6907ce22018-07-30 19:24:48 +00009449
Chris Lattnerecd79c62009-06-14 00:45:47 +00009450 // Do array -> pointer decay. The builtin should use the decayed type.
9451 if (Ty->isArrayType())
9452 Ty = getArrayDecayedType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00009453
Chris Lattnerecd79c62009-06-14 00:45:47 +00009454 ArgTypes.push_back(Ty);
9455 }
9456
David Majnemerba3e5ec2015-03-13 18:26:17 +00009457 if (Id == Builtin::BI__GetExceptionInfo)
Eugene Zelenko7855e772018-04-03 00:11:50 +00009458 return {};
David Majnemerba3e5ec2015-03-13 18:26:17 +00009459
Chris Lattnerecd79c62009-06-14 00:45:47 +00009460 assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
9461 "'.' should only occur at end of builtin type list!");
9462
Reid Kleckner78af0702013-08-27 23:08:25 +00009463 FunctionType::ExtInfo EI(CC_C);
John McCall991eb4b2010-12-21 00:44:39 +00009464 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
9465
9466 bool Variadic = (TypeStr[0] == '.');
9467
Richard Smith836de6b2016-12-19 23:59:34 +00009468 // We really shouldn't be making a no-proto type here.
9469 if (ArgTypes.empty() && Variadic && !getLangOpts().CPlusPlus)
John McCall991eb4b2010-12-21 00:44:39 +00009470 return getFunctionNoProtoType(ResType, EI);
Douglas Gregor36c569f2010-02-21 22:15:06 +00009471
John McCalldb40c7f2010-12-14 08:05:40 +00009472 FunctionProtoType::ExtProtoInfo EPI;
John McCall991eb4b2010-12-21 00:44:39 +00009473 EPI.ExtInfo = EI;
9474 EPI.Variadic = Variadic;
Richard Smith391fb862016-10-18 07:13:55 +00009475 if (getLangOpts().CPlusPlus && BuiltinInfo.isNoThrow(Id))
9476 EPI.ExceptionSpec.Type =
9477 getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone;
John McCalldb40c7f2010-12-14 08:05:40 +00009478
Jordan Rose5c382722013-03-08 21:51:21 +00009479 return getFunctionType(ResType, ArgTypes, EPI);
Chris Lattnerecd79c62009-06-14 00:45:47 +00009480}
Eli Friedman5ae98ee2009-08-19 07:44:53 +00009481
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009482static GVALinkage basicGVALinkageForFunction(const ASTContext &Context,
9483 const FunctionDecl *FD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00009484 if (!FD->isExternallyVisible())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009485 return GVA_Internal;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009486
Richard Smithe2467b72017-11-16 23:54:56 +00009487 // Non-user-provided functions get emitted as weak definitions with every
9488 // use, no matter whether they've been explicitly instantiated etc.
Eugene Zelenko7855e772018-04-03 00:11:50 +00009489 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
Richard Smithe2467b72017-11-16 23:54:56 +00009490 if (!MD->isUserProvided())
9491 return GVA_DiscardableODR;
9492
Yaron Keren4cd211b2017-02-22 14:32:39 +00009493 GVALinkage External;
Rafael Espindola3ae00052013-05-13 00:12:11 +00009494 switch (FD->getTemplateSpecializationKind()) {
9495 case TSK_Undeclared:
9496 case TSK_ExplicitSpecialization:
9497 External = GVA_StrongExternal;
9498 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009499
Rafael Espindola3ae00052013-05-13 00:12:11 +00009500 case TSK_ExplicitInstantiationDefinition:
David Majnemer54e3ba52014-04-02 23:17:29 +00009501 return GVA_StrongODR;
Rafael Espindola3ae00052013-05-13 00:12:11 +00009502
David Majnemerc3d07332014-05-15 06:25:57 +00009503 // C++11 [temp.explicit]p10:
9504 // [ Note: The intent is that an inline function that is the subject of
9505 // an explicit instantiation declaration will still be implicitly
9506 // instantiated when used so that the body can be considered for
9507 // inlining, but that no out-of-line copy of the inline function would be
9508 // generated in the translation unit. -- end note ]
Rafael Espindola3ae00052013-05-13 00:12:11 +00009509 case TSK_ExplicitInstantiationDeclaration:
David Majnemer27d69db2014-04-28 22:17:59 +00009510 return GVA_AvailableExternally;
9511
Rafael Espindola3ae00052013-05-13 00:12:11 +00009512 case TSK_ImplicitInstantiation:
David Majnemer27d69db2014-04-28 22:17:59 +00009513 External = GVA_DiscardableODR;
Rafael Espindola3ae00052013-05-13 00:12:11 +00009514 break;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009515 }
9516
9517 if (!FD->isInlined())
9518 return External;
David Majnemer62f0ffd2013-08-01 17:26:42 +00009519
David Majnemer3f021502015-10-08 04:53:31 +00009520 if ((!Context.getLangOpts().CPlusPlus &&
9521 !Context.getTargetInfo().getCXXABI().isMicrosoft() &&
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009522 !FD->hasAttr<DLLExportAttr>()) ||
David Majnemer62f0ffd2013-08-01 17:26:42 +00009523 FD->hasAttr<GNUInlineAttr>()) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009524 // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
9525
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009526 // GNU or C99 inline semantics. Determine whether this symbol should be
9527 // externally visible.
9528 if (FD->isInlineDefinitionExternallyVisible())
9529 return External;
9530
9531 // C99 inline semantics, where the symbol is not externally visible.
David Majnemer27d69db2014-04-28 22:17:59 +00009532 return GVA_AvailableExternally;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009533 }
9534
David Majnemer54e3ba52014-04-02 23:17:29 +00009535 // Functions specified with extern and inline in -fms-compatibility mode
9536 // forcibly get emitted. While the body of the function cannot be later
9537 // replaced, the function definition cannot be discarded.
David Majnemer73768702015-03-20 00:02:27 +00009538 if (FD->isMSExternInline())
David Majnemer54e3ba52014-04-02 23:17:29 +00009539 return GVA_StrongODR;
9540
David Majnemer27d69db2014-04-28 22:17:59 +00009541 return GVA_DiscardableODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009542}
9543
Artem Belevichca2b9512016-05-02 20:30:03 +00009544static GVALinkage adjustGVALinkageForAttributes(const ASTContext &Context,
Richard Smitha4653622017-09-06 20:01:14 +00009545 const Decl *D, GVALinkage L) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009546 // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
9547 // dllexport/dllimport on inline functions.
9548 if (D->hasAttr<DLLImportAttr>()) {
9549 if (L == GVA_DiscardableODR || L == GVA_StrongODR)
9550 return GVA_AvailableExternally;
Artem Belevichca2b9512016-05-02 20:30:03 +00009551 } else if (D->hasAttr<DLLExportAttr>()) {
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009552 if (L == GVA_DiscardableODR)
9553 return GVA_StrongODR;
Artem Belevichca2b9512016-05-02 20:30:03 +00009554 } else if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice &&
9555 D->hasAttr<CUDAGlobalAttr>()) {
9556 // Device-side functions with __global__ attribute must always be
9557 // visible externally so they can be launched from host.
9558 if (L == GVA_DiscardableODR || L == GVA_Internal)
9559 return GVA_StrongODR;
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009560 }
9561 return L;
9562}
9563
Richard Smitha4653622017-09-06 20:01:14 +00009564/// Adjust the GVALinkage for a declaration based on what an external AST source
9565/// knows about whether there can be other definitions of this declaration.
9566static GVALinkage
9567adjustGVALinkageForExternalDefinitionKind(const ASTContext &Ctx, const Decl *D,
9568 GVALinkage L) {
9569 ExternalASTSource *Source = Ctx.getExternalSource();
9570 if (!Source)
9571 return L;
9572
9573 switch (Source->hasExternalDefinitions(D)) {
David Blaikie9ffe5a32017-01-30 05:00:26 +00009574 case ExternalASTSource::EK_Never:
Richard Smitha4653622017-09-06 20:01:14 +00009575 // Other translation units rely on us to provide the definition.
David Blaikie9ffe5a32017-01-30 05:00:26 +00009576 if (L == GVA_DiscardableODR)
9577 return GVA_StrongODR;
9578 break;
Richard Smitha4653622017-09-06 20:01:14 +00009579
David Blaikie9ffe5a32017-01-30 05:00:26 +00009580 case ExternalASTSource::EK_Always:
9581 return GVA_AvailableExternally;
Richard Smitha4653622017-09-06 20:01:14 +00009582
David Blaikie9ffe5a32017-01-30 05:00:26 +00009583 case ExternalASTSource::EK_ReplyHazy:
9584 break;
9585 }
9586 return L;
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009587}
9588
Richard Smitha4653622017-09-06 20:01:14 +00009589GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) const {
9590 return adjustGVALinkageForExternalDefinitionKind(*this, FD,
9591 adjustGVALinkageForAttributes(*this, FD,
9592 basicGVALinkageForFunction(*this, FD)));
9593}
9594
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009595static GVALinkage basicGVALinkageForVariable(const ASTContext &Context,
9596 const VarDecl *VD) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00009597 if (!VD->isExternallyVisible())
9598 return GVA_Internal;
9599
David Majnemer27d69db2014-04-28 22:17:59 +00009600 if (VD->isStaticLocal()) {
David Majnemer27d69db2014-04-28 22:17:59 +00009601 const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
9602 while (LexicalContext && !isa<FunctionDecl>(LexicalContext))
9603 LexicalContext = LexicalContext->getLexicalParent();
9604
David Blaikieeb210012017-01-27 23:11:10 +00009605 // ObjC Blocks can create local variables that don't have a FunctionDecl
9606 // LexicalContext.
9607 if (!LexicalContext)
9608 return GVA_DiscardableODR;
David Majnemer27d69db2014-04-28 22:17:59 +00009609
David Blaikieeb210012017-01-27 23:11:10 +00009610 // Otherwise, let the static local variable inherit its linkage from the
9611 // nearest enclosing function.
9612 auto StaticLocalLinkage =
9613 Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext));
9614
9615 // Itanium ABI 5.2.2: "Each COMDAT group [for a static local variable] must
9616 // be emitted in any object with references to the symbol for the object it
9617 // contains, whether inline or out-of-line."
9618 // Similar behavior is observed with MSVC. An alternative ABI could use
9619 // StrongODR/AvailableExternally to match the function, but none are
9620 // known/supported currently.
9621 if (StaticLocalLinkage == GVA_StrongODR ||
9622 StaticLocalLinkage == GVA_AvailableExternally)
9623 return GVA_DiscardableODR;
9624 return StaticLocalLinkage;
David Majnemer27d69db2014-04-28 22:17:59 +00009625 }
9626
Hans Wennborg56fc62b2014-07-17 20:25:23 +00009627 // MSVC treats in-class initialized static data members as definitions.
9628 // By giving them non-strong linkage, out-of-line definitions won't
9629 // cause link errors.
9630 if (Context.isMSStaticDataMemberInlineDefinition(VD))
9631 return GVA_DiscardableODR;
9632
Richard Smithd9b90092016-07-02 01:32:16 +00009633 // Most non-template variables have strong linkage; inline variables are
9634 // linkonce_odr or (occasionally, for compatibility) weak_odr.
9635 GVALinkage StrongLinkage;
9636 switch (Context.getInlineVariableDefinitionKind(VD)) {
9637 case ASTContext::InlineVariableDefinitionKind::None:
9638 StrongLinkage = GVA_StrongExternal;
9639 break;
9640 case ASTContext::InlineVariableDefinitionKind::Weak:
9641 case ASTContext::InlineVariableDefinitionKind::WeakUnknown:
Richard Smith62f19e72016-06-25 00:15:56 +00009642 StrongLinkage = GVA_DiscardableODR;
Richard Smithd9b90092016-07-02 01:32:16 +00009643 break;
9644 case ASTContext::InlineVariableDefinitionKind::Strong:
9645 StrongLinkage = GVA_StrongODR;
9646 break;
9647 }
Richard Smith62f19e72016-06-25 00:15:56 +00009648
Richard Smith8809a0c2013-09-27 20:14:12 +00009649 switch (VD->getTemplateSpecializationKind()) {
Rafael Espindola3ae00052013-05-13 00:12:11 +00009650 case TSK_Undeclared:
Richard Smith62f19e72016-06-25 00:15:56 +00009651 return StrongLinkage;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009652
David Majnemer6d1780c2015-07-17 23:36:49 +00009653 case TSK_ExplicitSpecialization:
David Majnemer3f021502015-10-08 04:53:31 +00009654 return Context.getTargetInfo().getCXXABI().isMicrosoft() &&
9655 VD->isStaticDataMember()
David Majnemer6d1780c2015-07-17 23:36:49 +00009656 ? GVA_StrongODR
Richard Smith62f19e72016-06-25 00:15:56 +00009657 : StrongLinkage;
David Majnemer6d1780c2015-07-17 23:36:49 +00009658
Rafael Espindola3ae00052013-05-13 00:12:11 +00009659 case TSK_ExplicitInstantiationDefinition:
David Majnemer54e3ba52014-04-02 23:17:29 +00009660 return GVA_StrongODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009661
David Majnemer27d69db2014-04-28 22:17:59 +00009662 case TSK_ExplicitInstantiationDeclaration:
9663 return GVA_AvailableExternally;
9664
Rafael Espindola3ae00052013-05-13 00:12:11 +00009665 case TSK_ImplicitInstantiation:
David Majnemer27d69db2014-04-28 22:17:59 +00009666 return GVA_DiscardableODR;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009667 }
Rafael Espindola27699c82013-05-13 14:05:53 +00009668
9669 llvm_unreachable("Invalid Linkage!");
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009670}
9671
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009672GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
Richard Smitha4653622017-09-06 20:01:14 +00009673 return adjustGVALinkageForExternalDefinitionKind(*this, VD,
9674 adjustGVALinkageForAttributes(*this, VD,
9675 basicGVALinkageForVariable(*this, VD)));
Hans Wennborgb0f2f142014-05-15 22:07:49 +00009676}
9677
David Blaikiee6b7c282017-04-11 20:46:34 +00009678bool ASTContext::DeclMustBeEmitted(const Decl *D) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00009679 if (const auto *VD = dyn_cast<VarDecl>(D)) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009680 if (!VD->isFileVarDecl())
9681 return false;
Renato Golin9258aa52014-05-21 10:40:27 +00009682 // Global named register variables (GNU extension) are never emitted.
9683 if (VD->getStorageClass() == SC_Register)
9684 return false;
Richard Smith7747ce22015-08-19 20:49:38 +00009685 if (VD->getDescribedVarTemplate() ||
9686 isa<VarTemplatePartialSpecializationDecl>(VD))
9687 return false;
Eugene Zelenko7855e772018-04-03 00:11:50 +00009688 } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
Richard Smith5205a8c2013-04-01 20:22:16 +00009689 // We never need to emit an uninstantiated function template.
9690 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
9691 return false;
Nico Weber66220292016-03-02 17:28:48 +00009692 } else if (isa<PragmaCommentDecl>(D))
9693 return true;
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00009694 else if (isa<OMPThreadPrivateDecl>(D))
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00009695 return true;
Nico Webercbbaeb12016-03-02 19:28:54 +00009696 else if (isa<PragmaDetectMismatchDecl>(D))
9697 return true;
Nico Weber66220292016-03-02 17:28:48 +00009698 else if (isa<OMPThreadPrivateDecl>(D))
Alexey Bataevc5b1d322016-03-04 09:22:22 +00009699 return !D->getDeclContext()->isDependentContext();
9700 else if (isa<OMPDeclareReductionDecl>(D))
9701 return !D->getDeclContext()->isDependentContext();
Richard Smithdc1f0422016-07-20 19:10:16 +00009702 else if (isa<ImportDecl>(D))
9703 return true;
Alexey Bataev97720002014-11-11 04:05:39 +00009704 else
Richard Smith5205a8c2013-04-01 20:22:16 +00009705 return false;
9706
Hans Wennborg08c5a7b2018-06-25 13:23:49 +00009707 if (D->isFromASTFile() && !LangOpts.BuildingPCHWithObjectFile) {
9708 assert(getExternalSource() && "It's from an AST file; must have a source.");
9709 // On Windows, PCH files are built together with an object file. If this
9710 // declaration comes from such a PCH and DeclMustBeEmitted would return
9711 // true, it would have returned true and the decl would have been emitted
9712 // into that object file, so it doesn't need to be emitted here.
9713 // Note that decls are still emitted if they're referenced, as usual;
9714 // DeclMustBeEmitted is used to decide whether a decl must be emitted even
9715 // if it's not referenced.
9716 //
9717 // Explicit template instantiation definitions are tricky. If there was an
9718 // explicit template instantiation decl in the PCH before, it will look like
9719 // the definition comes from there, even if that was just the declaration.
9720 // (Explicit instantiation defs of variable templates always get emitted.)
9721 bool IsExpInstDef =
9722 isa<FunctionDecl>(D) &&
9723 cast<FunctionDecl>(D)->getTemplateSpecializationKind() ==
9724 TSK_ExplicitInstantiationDefinition;
9725
Hans Wennborgb51a7032018-09-14 15:18:30 +00009726 // Implicit member function definitions, such as operator= might not be
9727 // marked as template specializations, since they're not coming from a
9728 // template but synthesized directly on the class.
9729 IsExpInstDef |=
9730 isa<CXXMethodDecl>(D) &&
9731 cast<CXXMethodDecl>(D)->getParent()->getTemplateSpecializationKind() ==
9732 TSK_ExplicitInstantiationDefinition;
9733
Hans Wennborg08c5a7b2018-06-25 13:23:49 +00009734 if (getExternalSource()->DeclIsFromPCHWithObjectFile(D) && !IsExpInstDef)
9735 return false;
9736 }
9737
Richard Smith5205a8c2013-04-01 20:22:16 +00009738 // If this is a member of a class template, we do not need to emit it.
9739 if (D->getDeclContext()->isDependentContext())
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009740 return false;
9741
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00009742 // Weak references don't produce any output by themselves.
9743 if (D->hasAttr<WeakRefAttr>())
9744 return false;
9745
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009746 // Aliases and used decls are required.
9747 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
9748 return true;
9749
Eugene Zelenko7855e772018-04-03 00:11:50 +00009750 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009751 // Forward declarations aren't required.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00009752 if (!FD->doesThisDeclarationHaveABody())
Nick Lewycky26da4dd2011-07-18 05:26:13 +00009753 return FD->doesDeclarationForceExternallyVisibleDefinition();
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009754
9755 // Constructors and destructors are required.
9756 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
9757 return true;
Hans Wennborg08c5a7b2018-06-25 13:23:49 +00009758
John McCall6bd2a892013-01-25 22:31:03 +00009759 // The key function for a class is required. This rule only comes
9760 // into play when inline functions can be key functions, though.
9761 if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
Eugene Zelenko7855e772018-04-03 00:11:50 +00009762 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
John McCall6bd2a892013-01-25 22:31:03 +00009763 const CXXRecordDecl *RD = MD->getParent();
9764 if (MD->isOutOfLine() && RD->isDynamicClass()) {
9765 const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
9766 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
9767 return true;
9768 }
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009769 }
9770 }
9771
David Blaikie9ffe5a32017-01-30 05:00:26 +00009772 GVALinkage Linkage = GetGVALinkageForFunction(FD);
9773
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009774 // static, static inline, always_inline, and extern inline functions can
9775 // always be deferred. Normal inline functions can be deferred in C99/C++.
9776 // Implicit template instantiations can also be deferred in C++.
David Blaikie9ffe5a32017-01-30 05:00:26 +00009777 return !isDiscardableGVALinkage(Linkage);
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009778 }
Hans Wennborg08c5a7b2018-06-25 13:23:49 +00009779
Eugene Zelenko7855e772018-04-03 00:11:50 +00009780 const auto *VD = cast<VarDecl>(D);
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009781 assert(VD->isFileVarDecl() && "Expected file scoped var");
9782
Alexey Bataevd01b7492018-08-15 19:45:12 +00009783 // If the decl is marked as `declare target to`, it should be emitted for the
9784 // host and for the device.
9785 if (LangOpts.OpenMP &&
9786 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
9787 return true;
9788
Hans Wennborg56fc62b2014-07-17 20:25:23 +00009789 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
9790 !isMSStaticDataMemberInlineDefinition(VD))
Argyrios Kyrtzidis6e03a742010-07-29 20:07:52 +00009791 return false;
9792
Richard Smitha0e5e542012-11-12 21:38:00 +00009793 // Variables that can be needed in other TUs are required.
Richard Smitha4653622017-09-06 20:01:14 +00009794 auto Linkage = GetGVALinkageForVariable(VD);
9795 if (!isDiscardableGVALinkage(Linkage))
Richard Smitha0e5e542012-11-12 21:38:00 +00009796 return true;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009797
Richard Smitha4653622017-09-06 20:01:14 +00009798 // We never need to emit a variable that is available in another TU.
9799 if (Linkage == GVA_AvailableExternally)
9800 return false;
9801
Richard Smitha0e5e542012-11-12 21:38:00 +00009802 // Variables that have destruction with side-effects are required.
9803 if (VD->getType().isDestructedType())
9804 return true;
9805
9806 // Variables that have initialization with side-effects are required.
Richard Smith7747ce22015-08-19 20:49:38 +00009807 if (VD->getInit() && VD->getInit()->HasSideEffects(*this) &&
Richard Smith187ffb42017-01-20 01:19:46 +00009808 // We can get a value-dependent initializer during error recovery.
9809 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
Richard Smitha0e5e542012-11-12 21:38:00 +00009810 return true;
9811
Richard Smithda383632016-08-15 01:33:41 +00009812 // Likewise, variables with tuple-like bindings are required if their
9813 // bindings have side-effects.
Eugene Zelenko7855e772018-04-03 00:11:50 +00009814 if (const auto *DD = dyn_cast<DecompositionDecl>(VD))
9815 for (const auto *BD : DD->bindings())
9816 if (const auto *BindingVD = BD->getHoldingVar())
Richard Smithda383632016-08-15 01:33:41 +00009817 if (DeclMustBeEmitted(BindingVD))
9818 return true;
9819
Richard Smitha0e5e542012-11-12 21:38:00 +00009820 return false;
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00009821}
Charles Davis53c59df2010-08-16 03:33:14 +00009822
Erich Keane281d20b2018-01-08 21:34:17 +00009823void ASTContext::forEachMultiversionedFunctionVersion(
9824 const FunctionDecl *FD,
Erich Keane0fb16482018-08-13 18:33:20 +00009825 llvm::function_ref<void(FunctionDecl *)> Pred) const {
Erich Keane281d20b2018-01-08 21:34:17 +00009826 assert(FD->isMultiVersion() && "Only valid for multiversioned functions");
9827 llvm::SmallDenseSet<const FunctionDecl*, 4> SeenDecls;
9828 FD = FD->getCanonicalDecl();
9829 for (auto *CurDecl :
9830 FD->getDeclContext()->getRedeclContext()->lookup(FD->getDeclName())) {
9831 FunctionDecl *CurFD = CurDecl->getAsFunction()->getCanonicalDecl();
9832 if (CurFD && hasSameType(CurFD->getType(), FD->getType()) &&
9833 std::end(SeenDecls) == llvm::find(SeenDecls, CurFD)) {
9834 SeenDecls.insert(CurFD);
9835 Pred(CurFD);
9836 }
9837 }
9838}
9839
Reid Kleckner78af0702013-08-27 23:08:25 +00009840CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic,
9841 bool IsCXXMethod) const {
Charles Davis99202b32010-11-09 18:04:24 +00009842 // Pass through to the C++ ABI object
Reid Kleckner78af0702013-08-27 23:08:25 +00009843 if (IsCXXMethod)
9844 return ABI->getDefaultMethodCallConv(IsVariadic);
Timur Iskhodzhanovc5098ad2012-07-12 09:50:54 +00009845
Alexey Bataeva7547182016-05-18 09:06:38 +00009846 switch (LangOpts.getDefaultCallingConv()) {
9847 case LangOptions::DCC_None:
9848 break;
9849 case LangOptions::DCC_CDecl:
9850 return CC_C;
9851 case LangOptions::DCC_FastCall:
Erich Keane5759fa72017-10-24 23:12:01 +00009852 if (getTargetInfo().hasFeature("sse2") && !IsVariadic)
Alexey Bataeva7547182016-05-18 09:06:38 +00009853 return CC_X86FastCall;
9854 break;
9855 case LangOptions::DCC_StdCall:
9856 if (!IsVariadic)
9857 return CC_X86StdCall;
9858 break;
9859 case LangOptions::DCC_VectorCall:
9860 // __vectorcall cannot be applied to variadic functions.
9861 if (!IsVariadic)
9862 return CC_X86VectorCall;
9863 break;
Erich Keanea957ffb2017-11-02 21:08:00 +00009864 case LangOptions::DCC_RegCall:
9865 // __regcall cannot be applied to variadic functions.
9866 if (!IsVariadic)
9867 return CC_X86RegCall;
9868 break;
Alexey Bataeva7547182016-05-18 09:06:38 +00009869 }
Alexander Kornienko21de0ae2015-01-20 11:20:41 +00009870 return Target->getDefaultCallingConv(TargetInfo::CCMT_Unknown);
Charles Davis99202b32010-11-09 18:04:24 +00009871}
9872
Jay Foad39c79802011-01-12 09:06:06 +00009873bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
Anders Carlsson60a62632010-11-25 01:51:53 +00009874 // Pass through to the C++ ABI object
9875 return ABI->isNearlyEmpty(RD);
9876}
9877
Reid Kleckner96f8f932014-02-05 17:27:08 +00009878VTableContextBase *ASTContext::getVTableContext() {
9879 if (!VTContext.get()) {
9880 if (Target->getCXXABI().isMicrosoft())
9881 VTContext.reset(new MicrosoftVTableContext(*this));
9882 else
9883 VTContext.reset(new ItaniumVTableContext(*this));
9884 }
9885 return VTContext.get();
9886}
9887
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00009888MangleContext *ASTContext::createMangleContext() {
John McCall359b8852013-01-25 22:30:49 +00009889 switch (Target->getCXXABI().getKind()) {
Tim Northover9bb857a2013-01-31 12:13:10 +00009890 case TargetCXXABI::GenericAArch64:
John McCall359b8852013-01-25 22:30:49 +00009891 case TargetCXXABI::GenericItanium:
9892 case TargetCXXABI::GenericARM:
Zoran Jovanovic26a12162015-02-18 15:21:35 +00009893 case TargetCXXABI::GenericMIPS:
John McCall359b8852013-01-25 22:30:49 +00009894 case TargetCXXABI::iOS:
Tim Northovera2ee4332014-03-29 15:09:45 +00009895 case TargetCXXABI::iOS64:
Dan Gohmanc2853072015-09-03 22:51:53 +00009896 case TargetCXXABI::WebAssembly:
Tim Northover756447a2015-10-30 16:30:36 +00009897 case TargetCXXABI::WatchOS:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00009898 return ItaniumMangleContext::create(*this, getDiagnostics());
John McCall359b8852013-01-25 22:30:49 +00009899 case TargetCXXABI::Microsoft:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00009900 return MicrosoftMangleContext::create(*this, getDiagnostics());
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00009901 }
David Blaikie83d382b2011-09-23 05:06:16 +00009902 llvm_unreachable("Unsupported ABI");
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00009903}
9904
Eugene Zelenko5e5e5642017-11-23 01:20:07 +00009905CXXABI::~CXXABI() = default;
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00009906
9907size_t ASTContext::getSideTableAllocatedMemory() const {
Larisse Voufo39a1e502013-08-06 01:03:05 +00009908 return ASTRecordLayouts.getMemorySize() +
9909 llvm::capacity_in_bytes(ObjCLayouts) +
9910 llvm::capacity_in_bytes(KeyFunctions) +
9911 llvm::capacity_in_bytes(ObjCImpls) +
9912 llvm::capacity_in_bytes(BlockVarCopyInits) +
9913 llvm::capacity_in_bytes(DeclAttrs) +
9914 llvm::capacity_in_bytes(TemplateOrInstantiation) +
9915 llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
9916 llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
9917 llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
9918 llvm::capacity_in_bytes(OverriddenMethods) +
9919 llvm::capacity_in_bytes(Types) +
9920 llvm::capacity_in_bytes(VariableArrayTypes) +
9921 llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
Ted Kremenekf5df0ce2011-04-28 04:53:38 +00009922}
Ted Kremenek540017e2011-10-06 05:00:56 +00009923
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00009924/// getIntTypeForBitwidth -
9925/// sets integer QualTy according to specified details:
9926/// bitwidth, signed/unsigned.
9927/// Returns empty type if there is no appropriate target types.
9928QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth,
9929 unsigned Signed) const {
9930 TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed);
9931 CanQualType QualTy = getFromTargetType(Ty);
9932 if (!QualTy && DestWidth == 128)
9933 return Signed ? Int128Ty : UnsignedInt128Ty;
9934 return QualTy;
9935}
9936
9937/// getRealTypeForBitwidth -
9938/// sets floating point QualTy according to specified bitwidth.
9939/// Returns empty type if there is no appropriate target types.
9940QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth) const {
9941 TargetInfo::RealType Ty = getTargetInfo().getRealTypeByWidth(DestWidth);
9942 switch (Ty) {
9943 case TargetInfo::Float:
9944 return FloatTy;
9945 case TargetInfo::Double:
9946 return DoubleTy;
9947 case TargetInfo::LongDouble:
9948 return LongDoubleTy;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00009949 case TargetInfo::Float128:
9950 return Float128Ty;
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00009951 case TargetInfo::NoFloat:
Eugene Zelenko7855e772018-04-03 00:11:50 +00009952 return {};
Stepan Dyatkovskiy5a637922013-09-05 11:23:21 +00009953 }
9954
9955 llvm_unreachable("Unhandled TargetInfo::RealType value");
9956}
9957
Eli Friedman3b7d46c2013-07-10 00:30:46 +00009958void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
9959 if (Number > 1)
9960 MangleNumbers[ND] = Number;
David Blaikie095deba2012-11-14 01:52:05 +00009961}
9962
Eli Friedman3b7d46c2013-07-10 00:30:46 +00009963unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const {
Richard Smithe9b02d62016-03-21 22:33:02 +00009964 auto I = MangleNumbers.find(ND);
Eli Friedman3b7d46c2013-07-10 00:30:46 +00009965 return I != MangleNumbers.end() ? I->second : 1;
David Blaikie095deba2012-11-14 01:52:05 +00009966}
9967
David Majnemer2206bf52014-03-05 08:57:59 +00009968void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
9969 if (Number > 1)
9970 StaticLocalNumbers[VD] = Number;
9971}
9972
9973unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const {
Richard Smithe9b02d62016-03-21 22:33:02 +00009974 auto I = StaticLocalNumbers.find(VD);
David Majnemer2206bf52014-03-05 08:57:59 +00009975 return I != StaticLocalNumbers.end() ? I->second : 1;
9976}
9977
Eli Friedman3b7d46c2013-07-10 00:30:46 +00009978MangleNumberingContext &
9979ASTContext::getManglingNumberContext(const DeclContext *DC) {
Reid Klecknerd8110b62013-09-10 20:14:30 +00009980 assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
Justin Lebar20ebffc2016-10-10 16:26:19 +00009981 std::unique_ptr<MangleNumberingContext> &MCtx = MangleNumberingContexts[DC];
Reid Klecknerd8110b62013-09-10 20:14:30 +00009982 if (!MCtx)
9983 MCtx = createMangleNumberingContext();
9984 return *MCtx;
9985}
9986
Justin Lebar20ebffc2016-10-10 16:26:19 +00009987std::unique_ptr<MangleNumberingContext>
9988ASTContext::createMangleNumberingContext() const {
Reid Klecknerd8110b62013-09-10 20:14:30 +00009989 return ABI->createMangleNumberingContext();
Douglas Gregor63798542012-02-20 19:44:39 +00009990}
9991
David Majnemere7a818f2015-03-06 18:53:55 +00009992const CXXConstructorDecl *
9993ASTContext::getCopyConstructorForExceptionObject(CXXRecordDecl *RD) {
9994 return ABI->getCopyConstructorForExceptionObject(
9995 cast<CXXRecordDecl>(RD->getFirstDecl()));
9996}
9997
9998void ASTContext::addCopyConstructorForExceptionObject(CXXRecordDecl *RD,
9999 CXXConstructorDecl *CD) {
10000 return ABI->addCopyConstructorForExceptionObject(
10001 cast<CXXRecordDecl>(RD->getFirstDecl()),
10002 cast<CXXConstructorDecl>(CD->getFirstDecl()));
10003}
10004
David Majnemer00350522015-08-31 18:48:39 +000010005void ASTContext::addTypedefNameForUnnamedTagDecl(TagDecl *TD,
10006 TypedefNameDecl *DD) {
10007 return ABI->addTypedefNameForUnnamedTagDecl(TD, DD);
10008}
10009
10010TypedefNameDecl *
10011ASTContext::getTypedefNameForUnnamedTagDecl(const TagDecl *TD) {
10012 return ABI->getTypedefNameForUnnamedTagDecl(TD);
10013}
10014
10015void ASTContext::addDeclaratorForUnnamedTagDecl(TagDecl *TD,
10016 DeclaratorDecl *DD) {
10017 return ABI->addDeclaratorForUnnamedTagDecl(TD, DD);
10018}
10019
10020DeclaratorDecl *ASTContext::getDeclaratorForUnnamedTagDecl(const TagDecl *TD) {
10021 return ABI->getDeclaratorForUnnamedTagDecl(TD);
10022}
10023
Ted Kremenek540017e2011-10-06 05:00:56 +000010024void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
10025 ParamIndices[D] = index;
10026}
10027
10028unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
10029 ParameterIndexTable::const_iterator I = ParamIndices.find(D);
Fangrui Song6907ce22018-07-30 19:24:48 +000010030 assert(I != ParamIndices.end() &&
Ted Kremenek540017e2011-10-06 05:00:56 +000010031 "ParmIndices lacks entry set by ParmVarDecl");
10032 return I->second;
10033}
Fariborz Jahanian615de762013-05-28 17:37:39 +000010034
Richard Smithe6c01442013-06-05 00:46:14 +000010035APValue *
10036ASTContext::getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E,
10037 bool MayCreate) {
10038 assert(E && E->getStorageDuration() == SD_Static &&
10039 "don't need to cache the computed value for this temporary");
David Majnemer2dcef9e2015-08-13 23:50:15 +000010040 if (MayCreate) {
10041 APValue *&MTVI = MaterializedTemporaryValues[E];
10042 if (!MTVI)
10043 MTVI = new (*this) APValue;
10044 return MTVI;
10045 }
Richard Smithe6c01442013-06-05 00:46:14 +000010046
David Majnemer2dcef9e2015-08-13 23:50:15 +000010047 return MaterializedTemporaryValues.lookup(E);
Richard Smithe6c01442013-06-05 00:46:14 +000010048}
10049
Fariborz Jahanian615de762013-05-28 17:37:39 +000010050bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
10051 const llvm::Triple &T = getTargetInfo().getTriple();
10052 if (!T.isOSDarwin())
10053 return false;
10054
Bob Wilson2c82c3d2013-11-02 23:27:49 +000010055 if (!(T.isiOS() && T.isOSVersionLT(7)) &&
10056 !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
10057 return false;
10058
Fariborz Jahanian615de762013-05-28 17:37:39 +000010059 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
10060 CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
10061 uint64_t Size = sizeChars.getQuantity();
10062 CharUnits alignChars = getTypeAlignInChars(AtomicTy);
10063 unsigned Align = alignChars.getQuantity();
10064 unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
10065 return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
10066}
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010067
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000010068static ast_type_traits::DynTypedNode getSingleDynTypedNodeFromParentMap(
Benjamin Kramer94355ae2015-10-23 09:04:55 +000010069 ASTContext::ParentMapPointers::mapped_type U) {
Benjamin Kramerfbfa7a12015-10-22 11:26:35 +000010070 if (const auto *D = U.dyn_cast<const Decl *>())
Benjamin Kramer8e4a1762015-10-22 11:21:40 +000010071 return ast_type_traits::DynTypedNode::create(*D);
Benjamin Kramerfbfa7a12015-10-22 11:26:35 +000010072 if (const auto *S = U.dyn_cast<const Stmt *>())
Benjamin Kramer8e4a1762015-10-22 11:21:40 +000010073 return ast_type_traits::DynTypedNode::create(*S);
Benjamin Kramerfbfa7a12015-10-22 11:26:35 +000010074 return *U.get<ast_type_traits::DynTypedNode *>();
Benjamin Kramer8e4a1762015-10-22 11:21:40 +000010075}
10076
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000010077namespace {
10078
Benjamin Kramer94355ae2015-10-23 09:04:55 +000010079/// Template specializations to abstract away from pointers and TypeLocs.
10080/// @{
10081template <typename T>
10082ast_type_traits::DynTypedNode createDynTypedNode(const T &Node) {
10083 return ast_type_traits::DynTypedNode::create(*Node);
10084}
10085template <>
10086ast_type_traits::DynTypedNode createDynTypedNode(const TypeLoc &Node) {
10087 return ast_type_traits::DynTypedNode::create(Node);
10088}
10089template <>
10090ast_type_traits::DynTypedNode
10091createDynTypedNode(const NestedNameSpecifierLoc &Node) {
10092 return ast_type_traits::DynTypedNode::create(Node);
10093}
10094/// @}
10095
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010096 /// A \c RecursiveASTVisitor that builds a map from nodes to their
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010097 /// parents as defined by the \c RecursiveASTVisitor.
10098 ///
10099 /// Note that the relationship described here is purely in terms of AST
10100 /// traversal - there are other relationships (for example declaration context)
10101 /// in the AST that are better modeled by special matchers.
10102 ///
Benjamin Kramere8c51fd2015-10-21 10:07:26 +000010103 /// FIXME: Currently only builds up the map using \c Stmt and \c Decl nodes.
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010104 class ParentMapASTVisitor : public RecursiveASTVisitor<ParentMapASTVisitor> {
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010105 public:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010106 /// Builds and returns the translation unit's parent map.
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010107 ///
10108 /// The caller takes ownership of the returned \c ParentMap.
Benjamin Kramer94355ae2015-10-23 09:04:55 +000010109 static std::pair<ASTContext::ParentMapPointers *,
10110 ASTContext::ParentMapOtherNodes *>
10111 buildMap(TranslationUnitDecl &TU) {
10112 ParentMapASTVisitor Visitor(new ASTContext::ParentMapPointers,
10113 new ASTContext::ParentMapOtherNodes);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010114 Visitor.TraverseDecl(&TU);
Benjamin Kramer94355ae2015-10-23 09:04:55 +000010115 return std::make_pair(Visitor.Parents, Visitor.OtherParents);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010116 }
10117
10118 private:
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000010119 friend class RecursiveASTVisitor<ParentMapASTVisitor>;
10120
10121 using VisitorBase = RecursiveASTVisitor<ParentMapASTVisitor>;
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010122
Benjamin Kramer94355ae2015-10-23 09:04:55 +000010123 ParentMapASTVisitor(ASTContext::ParentMapPointers *Parents,
10124 ASTContext::ParentMapOtherNodes *OtherParents)
10125 : Parents(Parents), OtherParents(OtherParents) {}
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010126
10127 bool shouldVisitTemplateInstantiations() const {
10128 return true;
10129 }
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000010130
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010131 bool shouldVisitImplicitCode() const {
10132 return true;
10133 }
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010134
Richard Smith85838722015-11-24 03:09:01 +000010135 template <typename T, typename MapNodeTy, typename BaseTraverseFn,
10136 typename MapTy>
Benjamin Kramer94355ae2015-10-23 09:04:55 +000010137 bool TraverseNode(T Node, MapNodeTy MapNode,
Richard Smith85838722015-11-24 03:09:01 +000010138 BaseTraverseFn BaseTraverse, MapTy *Parents) {
Craig Topper36250ad2014-05-12 05:36:57 +000010139 if (!Node)
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010140 return true;
Manuel Klimek95403e62014-05-21 13:28:59 +000010141 if (ParentStack.size() > 0) {
Benjamin Kramere8c51fd2015-10-21 10:07:26 +000010142 // FIXME: Currently we add the same parent multiple times, but only
10143 // when no memoization data is available for the type.
10144 // For example when we visit all subexpressions of template
10145 // instantiations; this is suboptimal, but benign: the only way to
10146 // visit those is with hasAncestor / hasParent, and those do not create
10147 // new matches.
10148 // The plan is to enable DynTypedNode to be storable in a map or hash
10149 // map. The main problem there is to implement hash functions /
10150 // comparison operators for all types that DynTypedNode supports that
10151 // do not have pointer identity.
Benjamin Kramer94355ae2015-10-23 09:04:55 +000010152 auto &NodeOrVector = (*Parents)[MapNode];
Manuel Klimek95403e62014-05-21 13:28:59 +000010153 if (NodeOrVector.isNull()) {
Benjamin Kramer8e4a1762015-10-22 11:21:40 +000010154 if (const auto *D = ParentStack.back().get<Decl>())
10155 NodeOrVector = D;
10156 else if (const auto *S = ParentStack.back().get<Stmt>())
10157 NodeOrVector = S;
10158 else
10159 NodeOrVector =
10160 new ast_type_traits::DynTypedNode(ParentStack.back());
Manuel Klimek95403e62014-05-21 13:28:59 +000010161 } else {
Benjamin Kramer8e4a1762015-10-22 11:21:40 +000010162 if (!NodeOrVector.template is<ASTContext::ParentVector *>()) {
10163 auto *Vector = new ASTContext::ParentVector(
10164 1, getSingleDynTypedNodeFromParentMap(NodeOrVector));
Gabor Horvath10a837a2017-04-19 15:11:10 +000010165 delete NodeOrVector
10166 .template dyn_cast<ast_type_traits::DynTypedNode *>();
Benjamin Kramer422b3ff2015-10-23 13:24:18 +000010167 NodeOrVector = Vector;
Samuel Benzaquen3ca0a7b2014-06-13 13:31:40 +000010168 }
Samuel Benzaquen3ca0a7b2014-06-13 13:31:40 +000010169
10170 auto *Vector =
10171 NodeOrVector.template get<ASTContext::ParentVector *>();
10172 // Skip duplicates for types that have memoization data.
10173 // We must check that the type has memoization data before calling
10174 // std::find() because DynTypedNode::operator== can't compare all
10175 // types.
10176 bool Found = ParentStack.back().getMemoizationData() &&
10177 std::find(Vector->begin(), Vector->end(),
10178 ParentStack.back()) != Vector->end();
10179 if (!Found)
10180 Vector->push_back(ParentStack.back());
Manuel Klimek95403e62014-05-21 13:28:59 +000010181 }
10182 }
Benjamin Kramer94355ae2015-10-23 09:04:55 +000010183 ParentStack.push_back(createDynTypedNode(Node));
Richard Smith85838722015-11-24 03:09:01 +000010184 bool Result = BaseTraverse();
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010185 ParentStack.pop_back();
10186 return Result;
10187 }
10188
10189 bool TraverseDecl(Decl *DeclNode) {
Richard Smith85838722015-11-24 03:09:01 +000010190 return TraverseNode(DeclNode, DeclNode,
10191 [&] { return VisitorBase::TraverseDecl(DeclNode); },
Benjamin Kramer94355ae2015-10-23 09:04:55 +000010192 Parents);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010193 }
10194
10195 bool TraverseStmt(Stmt *StmtNode) {
Richard Smith85838722015-11-24 03:09:01 +000010196 return TraverseNode(StmtNode, StmtNode,
10197 [&] { return VisitorBase::TraverseStmt(StmtNode); },
Benjamin Kramer94355ae2015-10-23 09:04:55 +000010198 Parents);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010199 }
10200
Benjamin Kramer94355ae2015-10-23 09:04:55 +000010201 bool TraverseTypeLoc(TypeLoc TypeLocNode) {
Richard Smith85838722015-11-24 03:09:01 +000010202 return TraverseNode(
10203 TypeLocNode, ast_type_traits::DynTypedNode::create(TypeLocNode),
10204 [&] { return VisitorBase::TraverseTypeLoc(TypeLocNode); },
10205 OtherParents);
Benjamin Kramer94355ae2015-10-23 09:04:55 +000010206 }
10207
10208 bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNSLocNode) {
10209 return TraverseNode(
10210 NNSLocNode, ast_type_traits::DynTypedNode::create(NNSLocNode),
Richard Smith85838722015-11-24 03:09:01 +000010211 [&] {
10212 return VisitorBase::TraverseNestedNameSpecifierLoc(NNSLocNode);
10213 },
10214 OtherParents);
Benjamin Kramer94355ae2015-10-23 09:04:55 +000010215 }
10216
10217 ASTContext::ParentMapPointers *Parents;
10218 ASTContext::ParentMapOtherNodes *OtherParents;
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010219 llvm::SmallVector<ast_type_traits::DynTypedNode, 16> ParentStack;
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010220 };
10221
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000010222} // namespace
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010223
Benjamin Kramer94355ae2015-10-23 09:04:55 +000010224template <typename NodeTy, typename MapTy>
10225static ASTContext::DynTypedNodeList getDynNodeFromMap(const NodeTy &Node,
10226 const MapTy &Map) {
10227 auto I = Map.find(Node);
10228 if (I == Map.end()) {
Benjamin Kramer8e4a1762015-10-22 11:21:40 +000010229 return llvm::ArrayRef<ast_type_traits::DynTypedNode>();
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010230 }
Eugene Zelenko7855e772018-04-03 00:11:50 +000010231 if (const auto *V =
10232 I->second.template dyn_cast<ASTContext::ParentVector *>()) {
Benjamin Kramer8e4a1762015-10-22 11:21:40 +000010233 return llvm::makeArrayRef(*V);
Manuel Klimek95403e62014-05-21 13:28:59 +000010234 }
Benjamin Kramer8e4a1762015-10-22 11:21:40 +000010235 return getSingleDynTypedNodeFromParentMap(I->second);
Reid Kleckner2ab0ac52013-06-17 12:56:08 +000010236}
Fariborz Jahaniand36150d2013-07-15 21:22:08 +000010237
Benjamin Kramer94355ae2015-10-23 09:04:55 +000010238ASTContext::DynTypedNodeList
10239ASTContext::getParents(const ast_type_traits::DynTypedNode &Node) {
10240 if (!PointerParents) {
10241 // We always need to run over the whole translation unit, as
10242 // hasAncestor can escape any subtree.
10243 auto Maps = ParentMapASTVisitor::buildMap(*getTranslationUnitDecl());
10244 PointerParents.reset(Maps.first);
10245 OtherParents.reset(Maps.second);
10246 }
10247 if (Node.getNodeKind().hasPointerIdentity())
10248 return getDynNodeFromMap(Node.getMemoizationData(), *PointerParents);
10249 return getDynNodeFromMap(Node, *OtherParents);
10250}
10251
Fariborz Jahaniand36150d2013-07-15 21:22:08 +000010252bool
10253ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
10254 const ObjCMethodDecl *MethodImpl) {
10255 // No point trying to match an unavailable/deprecated mothod.
10256 if (MethodDecl->hasAttr<UnavailableAttr>()
10257 || MethodDecl->hasAttr<DeprecatedAttr>())
10258 return false;
10259 if (MethodDecl->getObjCDeclQualifier() !=
10260 MethodImpl->getObjCDeclQualifier())
10261 return false;
Alp Toker314cc812014-01-25 16:55:45 +000010262 if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
Fariborz Jahaniand36150d2013-07-15 21:22:08 +000010263 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +000010264
Fariborz Jahaniand36150d2013-07-15 21:22:08 +000010265 if (MethodDecl->param_size() != MethodImpl->param_size())
10266 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +000010267
Fariborz Jahaniand36150d2013-07-15 21:22:08 +000010268 for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
10269 IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
10270 EF = MethodDecl->param_end();
10271 IM != EM && IF != EF; ++IM, ++IF) {
10272 const ParmVarDecl *DeclVar = (*IF);
10273 const ParmVarDecl *ImplVar = (*IM);
10274 if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
10275 return false;
10276 if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
10277 return false;
10278 }
Eugene Zelenko5e5e5642017-11-23 01:20:07 +000010279
Fariborz Jahaniand36150d2013-07-15 21:22:08 +000010280 return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
Fariborz Jahaniand36150d2013-07-15 21:22:08 +000010281}
Richard Smith053f6c62014-05-16 23:01:30 +000010282
Yaxun Liu402804b2016-12-15 08:09:08 +000010283uint64_t ASTContext::getTargetNullPointerValue(QualType QT) const {
Alexander Richardson6d989432017-10-15 18:48:14 +000010284 LangAS AS;
Yaxun Liu402804b2016-12-15 08:09:08 +000010285 if (QT->getUnqualifiedDesugaredType()->isNullPtrType())
Alexander Richardson6d989432017-10-15 18:48:14 +000010286 AS = LangAS::Default;
Yaxun Liu402804b2016-12-15 08:09:08 +000010287 else
10288 AS = QT->getPointeeType().getAddressSpace();
10289
10290 return getTargetInfo().getNullPointerValue(AS);
10291}
10292
Alexander Richardson6d989432017-10-15 18:48:14 +000010293unsigned ASTContext::getTargetAddressSpace(LangAS AS) const {
10294 if (isTargetAddressSpace(AS))
10295 return toTargetAddressSpace(AS);
Yaxun Liub34ec822017-04-11 17:24:23 +000010296 else
Alexander Richardson6d989432017-10-15 18:48:14 +000010297 return (*AddrSpaceMap)[(unsigned)AS];
Yaxun Liub34ec822017-04-11 17:24:23 +000010298}
10299
Leonard Chanab80f3c2018-06-14 14:53:51 +000010300QualType ASTContext::getCorrespondingSaturatedType(QualType Ty) const {
10301 assert(Ty->isFixedPointType());
10302
10303 if (Ty->isSaturatedFixedPointType()) return Ty;
10304
10305 const auto &BT = Ty->getAs<BuiltinType>();
10306 switch (BT->getKind()) {
10307 default:
10308 llvm_unreachable("Not a fixed point type!");
10309 case BuiltinType::ShortAccum:
10310 return SatShortAccumTy;
10311 case BuiltinType::Accum:
10312 return SatAccumTy;
10313 case BuiltinType::LongAccum:
10314 return SatLongAccumTy;
10315 case BuiltinType::UShortAccum:
10316 return SatUnsignedShortAccumTy;
10317 case BuiltinType::UAccum:
10318 return SatUnsignedAccumTy;
10319 case BuiltinType::ULongAccum:
10320 return SatUnsignedLongAccumTy;
10321 case BuiltinType::ShortFract:
10322 return SatShortFractTy;
10323 case BuiltinType::Fract:
10324 return SatFractTy;
10325 case BuiltinType::LongFract:
10326 return SatLongFractTy;
10327 case BuiltinType::UShortFract:
10328 return SatUnsignedShortFractTy;
10329 case BuiltinType::UFract:
10330 return SatUnsignedFractTy;
10331 case BuiltinType::ULongFract:
10332 return SatUnsignedLongFractTy;
10333 }
10334}
10335
Matt Arsenaultc65f9662018-08-02 12:14:28 +000010336LangAS ASTContext::getLangASForBuiltinAddressSpace(unsigned AS) const {
10337 if (LangOpts.OpenCL)
10338 return getTargetInfo().getOpenCLBuiltinAddressSpace(AS);
10339
10340 if (LangOpts.CUDA)
10341 return getTargetInfo().getCUDABuiltinAddressSpace(AS);
10342
10343 return getLangASFromTargetAS(AS);
10344}
10345
Richard Smith053f6c62014-05-16 23:01:30 +000010346// Explicitly instantiate this in case a Redeclarable<T> is used from a TU that
10347// doesn't include ASTContext.h
10348template
10349clang::LazyGenerationalUpdatePtr<
10350 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType
10351clang::LazyGenerationalUpdatePtr<
10352 const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue(
10353 const clang::ASTContext &Ctx, Decl *Value);
Leonard Chandb01c3a2018-06-20 17:19:40 +000010354
10355unsigned char ASTContext::getFixedPointScale(QualType Ty) const {
10356 assert(Ty->isFixedPointType());
10357
10358 const auto *BT = Ty->getAs<BuiltinType>();
10359 const TargetInfo &Target = getTargetInfo();
10360 switch (BT->getKind()) {
10361 default:
10362 llvm_unreachable("Not a fixed point type!");
10363 case BuiltinType::ShortAccum:
10364 case BuiltinType::SatShortAccum:
10365 return Target.getShortAccumScale();
10366 case BuiltinType::Accum:
10367 case BuiltinType::SatAccum:
10368 return Target.getAccumScale();
10369 case BuiltinType::LongAccum:
10370 case BuiltinType::SatLongAccum:
10371 return Target.getLongAccumScale();
10372 case BuiltinType::UShortAccum:
10373 case BuiltinType::SatUShortAccum:
10374 return Target.getUnsignedShortAccumScale();
10375 case BuiltinType::UAccum:
10376 case BuiltinType::SatUAccum:
10377 return Target.getUnsignedAccumScale();
10378 case BuiltinType::ULongAccum:
10379 case BuiltinType::SatULongAccum:
10380 return Target.getUnsignedLongAccumScale();
10381 case BuiltinType::ShortFract:
10382 case BuiltinType::SatShortFract:
10383 return Target.getShortFractScale();
10384 case BuiltinType::Fract:
10385 case BuiltinType::SatFract:
10386 return Target.getFractScale();
10387 case BuiltinType::LongFract:
10388 case BuiltinType::SatLongFract:
10389 return Target.getLongFractScale();
10390 case BuiltinType::UShortFract:
10391 case BuiltinType::SatUShortFract:
10392 return Target.getUnsignedShortFractScale();
10393 case BuiltinType::UFract:
10394 case BuiltinType::SatUFract:
10395 return Target.getUnsignedFractScale();
10396 case BuiltinType::ULongFract:
10397 case BuiltinType::SatULongFract:
10398 return Target.getUnsignedLongFractScale();
10399 }
10400}
10401
10402unsigned char ASTContext::getFixedPointIBits(QualType Ty) const {
10403 assert(Ty->isFixedPointType());
10404
10405 const auto *BT = Ty->getAs<BuiltinType>();
10406 const TargetInfo &Target = getTargetInfo();
10407 switch (BT->getKind()) {
10408 default:
10409 llvm_unreachable("Not a fixed point type!");
10410 case BuiltinType::ShortAccum:
10411 case BuiltinType::SatShortAccum:
10412 return Target.getShortAccumIBits();
10413 case BuiltinType::Accum:
10414 case BuiltinType::SatAccum:
10415 return Target.getAccumIBits();
10416 case BuiltinType::LongAccum:
10417 case BuiltinType::SatLongAccum:
10418 return Target.getLongAccumIBits();
10419 case BuiltinType::UShortAccum:
10420 case BuiltinType::SatUShortAccum:
10421 return Target.getUnsignedShortAccumIBits();
10422 case BuiltinType::UAccum:
10423 case BuiltinType::SatUAccum:
10424 return Target.getUnsignedAccumIBits();
10425 case BuiltinType::ULongAccum:
10426 case BuiltinType::SatULongAccum:
10427 return Target.getUnsignedLongAccumIBits();
10428 case BuiltinType::ShortFract:
10429 case BuiltinType::SatShortFract:
10430 case BuiltinType::Fract:
10431 case BuiltinType::SatFract:
10432 case BuiltinType::LongFract:
10433 case BuiltinType::SatLongFract:
10434 case BuiltinType::UShortFract:
10435 case BuiltinType::SatUShortFract:
10436 case BuiltinType::UFract:
10437 case BuiltinType::SatUFract:
10438 case BuiltinType::ULongFract:
10439 case BuiltinType::SatULongFract:
10440 return 0;
10441 }
10442}
Leonard Chana6779422018-08-06 16:42:37 +000010443
10444FixedPointSemantics ASTContext::getFixedPointSemantics(QualType Ty) const {
10445 assert(Ty->isFixedPointType());
10446 bool isSigned = Ty->isSignedFixedPointType();
10447 return FixedPointSemantics(
10448 static_cast<unsigned>(getTypeSize(Ty)), getFixedPointScale(Ty), isSigned,
10449 Ty->isSaturatedFixedPointType(),
10450 !isSigned && getTargetInfo().doUnsignedFixedPointTypesHavePadding());
10451}
10452
10453APFixedPoint ASTContext::getFixedPointMax(QualType Ty) const {
10454 assert(Ty->isFixedPointType());
10455 return APFixedPoint::getMax(getFixedPointSemantics(Ty));
10456}
10457
10458APFixedPoint ASTContext::getFixedPointMin(QualType Ty) const {
10459 assert(Ty->isFixedPointType());
10460 return APFixedPoint::getMin(getFixedPointSemantics(Ty));
10461}