blob: 466cb084e7c3da852ce4e57b21267c8d60c1b854 [file] [log] [blame]
Douglas Gregorb55fdf82010-12-15 17:38:57 +00001//===------- SemaTemplateVariadic.cpp - C++ Variadic Templates ------------===/
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Douglas Gregorb55fdf82010-12-15 17:38:57 +00006//===----------------------------------------------------------------------===/
7//
8// This file implements semantic analysis for C++0x variadic templates.
9//===----------------------------------------------------------------------===/
10
11#include "clang/Sema/Sema.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000012#include "TypeLocBuilder.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000013#include "clang/AST/Expr.h"
14#include "clang/AST/RecursiveASTVisitor.h"
15#include "clang/AST/TypeLoc.h"
Douglas Gregor820ba7b2011-01-04 17:33:58 +000016#include "clang/Sema/Lookup.h"
Douglas Gregord2fa7662010-12-20 02:24:11 +000017#include "clang/Sema/ParsedTemplate.h"
Richard Smith2589b9802012-07-25 03:56:55 +000018#include "clang/Sema/ScopeInfo.h"
Douglas Gregorb55fdf82010-12-15 17:38:57 +000019#include "clang/Sema/SemaInternal.h"
Douglas Gregor840bd6c2010-12-20 22:05:00 +000020#include "clang/Sema/Template.h"
Douglas Gregorb55fdf82010-12-15 17:38:57 +000021
22using namespace clang;
23
Douglas Gregor1da294a2010-12-15 19:43:21 +000024//----------------------------------------------------------------------------
25// Visitor that collects unexpanded parameter packs
26//----------------------------------------------------------------------------
27
Douglas Gregor1da294a2010-12-15 19:43:21 +000028namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000029 /// A class that collects unexpanded parameter packs.
Douglas Gregor1da294a2010-12-15 19:43:21 +000030 class CollectUnexpandedParameterPacksVisitor :
Fangrui Song6907ce22018-07-30 19:24:48 +000031 public RecursiveASTVisitor<CollectUnexpandedParameterPacksVisitor>
Douglas Gregor1da294a2010-12-15 19:43:21 +000032 {
33 typedef RecursiveASTVisitor<CollectUnexpandedParameterPacksVisitor>
34 inherited;
35
Chris Lattner0e62c1c2011-07-23 10:55:15 +000036 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded;
Douglas Gregor1da294a2010-12-15 19:43:21 +000037
Richard Smith78a07ba2017-08-15 19:11:21 +000038 bool InLambda = false;
39 unsigned DepthLimit = (unsigned)-1;
Richard Smith2589b9802012-07-25 03:56:55 +000040
Richard Smith78a07ba2017-08-15 19:11:21 +000041 void addUnexpanded(NamedDecl *ND, SourceLocation Loc = SourceLocation()) {
Richard Smithb2997f52019-05-21 20:10:50 +000042 if (auto *VD = dyn_cast<VarDecl>(ND)) {
Richard Smith78a07ba2017-08-15 19:11:21 +000043 // For now, the only problematic case is a generic lambda's templated
44 // call operator, so we don't need to look for all the other ways we
45 // could have reached a dependent parameter pack.
Richard Smithb2997f52019-05-21 20:10:50 +000046 auto *FD = dyn_cast<FunctionDecl>(VD->getDeclContext());
Richard Smith78a07ba2017-08-15 19:11:21 +000047 auto *FTD = FD ? FD->getDescribedFunctionTemplate() : nullptr;
48 if (FTD && FTD->getTemplateParameters()->getDepth() >= DepthLimit)
49 return;
50 } else if (getDepthAndIndex(ND).first >= DepthLimit)
51 return;
52
53 Unexpanded.push_back({ND, Loc});
54 }
55 void addUnexpanded(const TemplateTypeParmType *T,
56 SourceLocation Loc = SourceLocation()) {
57 if (T->getDepth() < DepthLimit)
58 Unexpanded.push_back({T, Loc});
59 }
Fangrui Song6907ce22018-07-30 19:24:48 +000060
Douglas Gregor1da294a2010-12-15 19:43:21 +000061 public:
62 explicit CollectUnexpandedParameterPacksVisitor(
Richard Smith78a07ba2017-08-15 19:11:21 +000063 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded)
64 : Unexpanded(Unexpanded) {}
Douglas Gregor1da294a2010-12-15 19:43:21 +000065
Douglas Gregor15b4ec22010-12-20 23:07:20 +000066 bool shouldWalkTypesOfTypeLocs() const { return false; }
Richard Smith78a07ba2017-08-15 19:11:21 +000067
Douglas Gregor1da294a2010-12-15 19:43:21 +000068 //------------------------------------------------------------------------
69 // Recording occurrences of (unexpanded) parameter packs.
70 //------------------------------------------------------------------------
71
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000072 /// Record occurrences of template type parameter packs.
Douglas Gregor1da294a2010-12-15 19:43:21 +000073 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
74 if (TL.getTypePtr()->isParameterPack())
Richard Smith78a07ba2017-08-15 19:11:21 +000075 addUnexpanded(TL.getTypePtr(), TL.getNameLoc());
Douglas Gregor1da294a2010-12-15 19:43:21 +000076 return true;
77 }
78
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000079 /// Record occurrences of template type parameter packs
Douglas Gregor1da294a2010-12-15 19:43:21 +000080 /// when we don't have proper source-location information for
81 /// them.
82 ///
83 /// Ideally, this routine would never be used.
84 bool VisitTemplateTypeParmType(TemplateTypeParmType *T) {
85 if (T->isParameterPack())
Richard Smith78a07ba2017-08-15 19:11:21 +000086 addUnexpanded(T);
Douglas Gregor1da294a2010-12-15 19:43:21 +000087
88 return true;
89 }
90
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000091 /// Record occurrences of function and non-type template
Douglas Gregorda3cc0d2010-12-23 23:51:58 +000092 /// parameter packs in an expression.
93 bool VisitDeclRefExpr(DeclRefExpr *E) {
Douglas Gregorf3010112011-01-07 16:43:16 +000094 if (E->getDecl()->isParameterPack())
Richard Smith78a07ba2017-08-15 19:11:21 +000095 addUnexpanded(E->getDecl(), E->getLocation());
Fangrui Song6907ce22018-07-30 19:24:48 +000096
Douglas Gregorda3cc0d2010-12-23 23:51:58 +000097 return true;
98 }
Fangrui Song6907ce22018-07-30 19:24:48 +000099
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000100 /// Record occurrences of template template parameter packs.
Douglas Gregorf5500772011-01-05 15:48:55 +0000101 bool TraverseTemplateName(TemplateName Template) {
Richard Smith78a07ba2017-08-15 19:11:21 +0000102 if (auto *TTP = dyn_cast_or_null<TemplateTemplateParmDecl>(
103 Template.getAsTemplateDecl())) {
Douglas Gregorf5500772011-01-05 15:48:55 +0000104 if (TTP->isParameterPack())
Richard Smith78a07ba2017-08-15 19:11:21 +0000105 addUnexpanded(TTP);
106 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000107
Douglas Gregorf5500772011-01-05 15:48:55 +0000108 return inherited::TraverseTemplateName(Template);
109 }
Douglas Gregor1da294a2010-12-15 19:43:21 +0000110
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000111 /// Suppress traversal into Objective-C container literal
Ted Kremeneke65b0862012-03-06 20:05:56 +0000112 /// elements that are pack expansions.
113 bool TraverseObjCDictionaryLiteral(ObjCDictionaryLiteral *E) {
114 if (!E->containsUnexpandedParameterPack())
115 return true;
116
117 for (unsigned I = 0, N = E->getNumElements(); I != N; ++I) {
118 ObjCDictionaryElement Element = E->getKeyValueElement(I);
119 if (Element.isPackExpansion())
120 continue;
121
122 TraverseStmt(Element.Key);
123 TraverseStmt(Element.Value);
124 }
125 return true;
126 }
Douglas Gregor1da294a2010-12-15 19:43:21 +0000127 //------------------------------------------------------------------------
128 // Pruning the search for unexpanded parameter packs.
129 //------------------------------------------------------------------------
130
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000131 /// Suppress traversal into statements and expressions that
Douglas Gregor1da294a2010-12-15 19:43:21 +0000132 /// do not contain unexpanded parameter packs.
Fangrui Song6907ce22018-07-30 19:24:48 +0000133 bool TraverseStmt(Stmt *S) {
Richard Smith2589b9802012-07-25 03:56:55 +0000134 Expr *E = dyn_cast_or_null<Expr>(S);
135 if ((E && E->containsUnexpandedParameterPack()) || InLambda)
136 return inherited::TraverseStmt(S);
Douglas Gregor1da294a2010-12-15 19:43:21 +0000137
Richard Smith2589b9802012-07-25 03:56:55 +0000138 return true;
Douglas Gregor1da294a2010-12-15 19:43:21 +0000139 }
140
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000141 /// Suppress traversal into types that do not contain
Douglas Gregor1da294a2010-12-15 19:43:21 +0000142 /// unexpanded parameter packs.
143 bool TraverseType(QualType T) {
Richard Smith2589b9802012-07-25 03:56:55 +0000144 if ((!T.isNull() && T->containsUnexpandedParameterPack()) || InLambda)
Douglas Gregor1da294a2010-12-15 19:43:21 +0000145 return inherited::TraverseType(T);
146
147 return true;
148 }
149
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000150 /// Suppress traversal into types with location information
Douglas Gregor1da294a2010-12-15 19:43:21 +0000151 /// that do not contain unexpanded parameter packs.
152 bool TraverseTypeLoc(TypeLoc TL) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000153 if ((!TL.getType().isNull() &&
Richard Smith2589b9802012-07-25 03:56:55 +0000154 TL.getType()->containsUnexpandedParameterPack()) ||
155 InLambda)
Douglas Gregor1da294a2010-12-15 19:43:21 +0000156 return inherited::TraverseTypeLoc(TL);
157
158 return true;
159 }
160
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000161 /// Suppress traversal of parameter packs.
Fangrui Song6907ce22018-07-30 19:24:48 +0000162 bool TraverseDecl(Decl *D) {
Richard Smith78a07ba2017-08-15 19:11:21 +0000163 // A function parameter pack is a pack expansion, so cannot contain
Richard Smithf26d5512017-08-15 22:58:45 +0000164 // an unexpanded parameter pack. Likewise for a template parameter
165 // pack that contains any references to other packs.
Brian Gesiak7dda73a2019-01-07 03:25:59 +0000166 if (D && D->isParameterPack())
Richard Smith78a07ba2017-08-15 19:11:21 +0000167 return true;
168
Richard Smithf26d5512017-08-15 22:58:45 +0000169 return inherited::TraverseDecl(D);
170 }
Douglas Gregora8461bb2010-12-15 21:57:59 +0000171
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000172 /// Suppress traversal of pack-expanded attributes.
Richard Smithf26d5512017-08-15 22:58:45 +0000173 bool TraverseAttr(Attr *A) {
174 if (A->isPackExpansion())
175 return true;
176
177 return inherited::TraverseAttr(A);
178 }
179
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000180 /// Suppress traversal of pack expansion expressions and types.
Richard Smithf26d5512017-08-15 22:58:45 +0000181 ///@{
182 bool TraversePackExpansionType(PackExpansionType *T) { return true; }
183 bool TraversePackExpansionTypeLoc(PackExpansionTypeLoc TL) { return true; }
184 bool TraversePackExpansionExpr(PackExpansionExpr *E) { return true; }
185 bool TraverseCXXFoldExpr(CXXFoldExpr *E) { return true; }
186
187 ///@}
188
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000189 /// Suppress traversal of using-declaration pack expansion.
Richard Smithf26d5512017-08-15 22:58:45 +0000190 bool TraverseUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
191 if (D->isPackExpansion())
192 return true;
193
194 return inherited::TraverseUnresolvedUsingValueDecl(D);
195 }
196
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000197 /// Suppress traversal of using-declaration pack expansion.
Richard Smithf26d5512017-08-15 22:58:45 +0000198 bool TraverseUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {
199 if (D->isPackExpansion())
200 return true;
201
202 return inherited::TraverseUnresolvedUsingTypenameDecl(D);
Douglas Gregora8461bb2010-12-15 21:57:59 +0000203 }
Douglas Gregoreb29d182011-01-05 17:40:24 +0000204
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000205 /// Suppress traversal of template argument pack expansions.
Douglas Gregoreb29d182011-01-05 17:40:24 +0000206 bool TraverseTemplateArgument(const TemplateArgument &Arg) {
207 if (Arg.isPackExpansion())
208 return true;
209
210 return inherited::TraverseTemplateArgument(Arg);
211 }
212
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000213 /// Suppress traversal of template argument pack expansions.
Douglas Gregoreb29d182011-01-05 17:40:24 +0000214 bool TraverseTemplateArgumentLoc(const TemplateArgumentLoc &ArgLoc) {
215 if (ArgLoc.getArgument().isPackExpansion())
216 return true;
Fangrui Song6907ce22018-07-30 19:24:48 +0000217
Douglas Gregoreb29d182011-01-05 17:40:24 +0000218 return inherited::TraverseTemplateArgumentLoc(ArgLoc);
219 }
Richard Smith2589b9802012-07-25 03:56:55 +0000220
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000221 /// Suppress traversal of base specifier pack expansions.
Richard Smithf26d5512017-08-15 22:58:45 +0000222 bool TraverseCXXBaseSpecifier(const CXXBaseSpecifier &Base) {
223 if (Base.isPackExpansion())
224 return true;
225
226 return inherited::TraverseCXXBaseSpecifier(Base);
227 }
228
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000229 /// Suppress traversal of mem-initializer pack expansions.
Richard Smithf26d5512017-08-15 22:58:45 +0000230 bool TraverseConstructorInitializer(CXXCtorInitializer *Init) {
231 if (Init->isPackExpansion())
232 return true;
233
234 return inherited::TraverseConstructorInitializer(Init);
235 }
236
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000237 /// Note whether we're traversing a lambda containing an unexpanded
Richard Smith2589b9802012-07-25 03:56:55 +0000238 /// parameter pack. In this case, the unexpanded pack can occur anywhere,
239 /// including all the places where we normally wouldn't look. Within a
240 /// lambda, we don't propagate the 'contains unexpanded parameter pack' bit
241 /// outside an expression.
242 bool TraverseLambdaExpr(LambdaExpr *Lambda) {
243 // The ContainsUnexpandedParameterPack bit on a lambda is always correct,
244 // even if it's contained within another lambda.
245 if (!Lambda->containsUnexpandedParameterPack())
246 return true;
247
248 bool WasInLambda = InLambda;
Richard Smith78a07ba2017-08-15 19:11:21 +0000249 unsigned OldDepthLimit = DepthLimit;
Richard Smith2589b9802012-07-25 03:56:55 +0000250
Richard Smith78a07ba2017-08-15 19:11:21 +0000251 InLambda = true;
252 if (auto *TPL = Lambda->getTemplateParameterList())
253 DepthLimit = TPL->getDepth();
Richard Smith2589b9802012-07-25 03:56:55 +0000254
255 inherited::TraverseLambdaExpr(Lambda);
256
257 InLambda = WasInLambda;
Richard Smith78a07ba2017-08-15 19:11:21 +0000258 DepthLimit = OldDepthLimit;
Richard Smith2589b9802012-07-25 03:56:55 +0000259 return true;
260 }
Richard Smith78a07ba2017-08-15 19:11:21 +0000261
262 /// Suppress traversal within pack expansions in lambda captures.
263 bool TraverseLambdaCapture(LambdaExpr *Lambda, const LambdaCapture *C,
264 Expr *Init) {
265 if (C->isPackExpansion())
266 return true;
Richard Smithf26d5512017-08-15 22:58:45 +0000267
Richard Smith78a07ba2017-08-15 19:11:21 +0000268 return inherited::TraverseLambdaCapture(Lambda, C, Init);
269 }
Douglas Gregor1da294a2010-12-15 19:43:21 +0000270 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000271}
Douglas Gregor1da294a2010-12-15 19:43:21 +0000272
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000273/// Determine whether it's possible for an unexpanded parameter pack to
Richard Smith36ee9fb2014-08-11 23:30:23 +0000274/// be valid in this location. This only happens when we're in a declaration
275/// that is nested within an expression that could be expanded, such as a
276/// lambda-expression within a function call.
277///
278/// This is conservatively correct, but may claim that some unexpanded packs are
279/// permitted when they are not.
280bool Sema::isUnexpandedParameterPackPermitted() {
281 for (auto *SI : FunctionScopes)
282 if (isa<sema::LambdaScopeInfo>(SI))
283 return true;
284 return false;
285}
286
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000287/// Diagnose all of the unexpanded parameter packs in the given
Douglas Gregor1da294a2010-12-15 19:43:21 +0000288/// vector.
Richard Smith2589b9802012-07-25 03:56:55 +0000289bool
Douglas Gregor4a2a8f72011-10-25 03:44:56 +0000290Sema::DiagnoseUnexpandedParameterPacks(SourceLocation Loc,
291 UnexpandedParameterPackContext UPPC,
Bill Wendling8ac06af2012-02-22 09:38:11 +0000292 ArrayRef<UnexpandedParameterPack> Unexpanded) {
Douglas Gregor4a2a8f72011-10-25 03:44:56 +0000293 if (Unexpanded.empty())
Richard Smith2589b9802012-07-25 03:56:55 +0000294 return false;
295
Richard Smith78a07ba2017-08-15 19:11:21 +0000296 // If we are within a lambda expression and referencing a pack that is not
Richard Smithb26bc342019-08-26 22:51:28 +0000297 // declared within the lambda itself, that lambda contains an unexpanded
Richard Smith2589b9802012-07-25 03:56:55 +0000298 // parameter pack, and we are done.
299 // FIXME: Store 'Unexpanded' on the lambda so we don't need to recompute it
300 // later.
Richard Smithf26d5512017-08-15 22:58:45 +0000301 SmallVector<UnexpandedParameterPack, 4> LambdaParamPackReferences;
Richard Smithb26bc342019-08-26 22:51:28 +0000302 if (auto *LSI = getEnclosingLambda()) {
303 for (auto &Pack : Unexpanded) {
304 auto DeclaresThisPack = [&](NamedDecl *LocalPack) {
305 if (auto *TTPT = Pack.first.dyn_cast<const TemplateTypeParmType *>()) {
306 auto *TTPD = dyn_cast<TemplateTypeParmDecl>(LocalPack);
307 return TTPD && TTPD->getTypeForDecl() == TTPT;
Richard Smith78a07ba2017-08-15 19:11:21 +0000308 }
Richard Smithb26bc342019-08-26 22:51:28 +0000309 return declaresSameEntity(Pack.first.get<NamedDecl *>(), LocalPack);
310 };
311 if (std::find_if(LSI->LocalPacks.begin(), LSI->LocalPacks.end(),
312 DeclaresThisPack) != LSI->LocalPacks.end())
313 LambdaParamPackReferences.push_back(Pack);
314 }
315
316 if (LambdaParamPackReferences.empty()) {
317 // Construct in lambda only references packs declared outside the lambda.
318 // That's OK for now, but the lambda itself is considered to contain an
319 // unexpanded pack in this case, which will require expansion outside the
320 // lambda.
321
322 // We do not permit pack expansion that would duplicate a statement
323 // expression, not even within a lambda.
324 // FIXME: We could probably support this for statement expressions that
325 // do not contain labels.
326 // FIXME: This is insufficient to detect this problem; consider
327 // f( ({ bad: 0; }) + pack ... );
328 bool EnclosingStmtExpr = false;
329 for (unsigned N = FunctionScopes.size(); N; --N) {
330 sema::FunctionScopeInfo *Func = FunctionScopes[N-1];
331 if (std::any_of(
332 Func->CompoundScopes.begin(), Func->CompoundScopes.end(),
333 [](sema::CompoundScopeInfo &CSI) { return CSI.IsStmtExpr; })) {
334 EnclosingStmtExpr = true;
335 break;
336 }
337 // Coumpound-statements outside the lambda are OK for now; we'll check
338 // for those when we finish handling the lambda.
339 if (Func == LSI)
340 break;
Richard Smith78a07ba2017-08-15 19:11:21 +0000341 }
342
Richard Smithb26bc342019-08-26 22:51:28 +0000343 if (!EnclosingStmtExpr) {
344 LSI->ContainsUnexpandedParameterPack = true;
345 return false;
Richard Smith78a07ba2017-08-15 19:11:21 +0000346 }
Richard Smithb26bc342019-08-26 22:51:28 +0000347 } else {
348 Unexpanded = LambdaParamPackReferences;
Richard Smith2589b9802012-07-25 03:56:55 +0000349 }
350 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000351
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000352 SmallVector<SourceLocation, 4> Locations;
353 SmallVector<IdentifierInfo *, 4> Names;
Douglas Gregor1da294a2010-12-15 19:43:21 +0000354 llvm::SmallPtrSet<IdentifierInfo *, 4> NamesKnown;
355
356 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000357 IdentifierInfo *Name = nullptr;
Douglas Gregor1da294a2010-12-15 19:43:21 +0000358 if (const TemplateTypeParmType *TTP
359 = Unexpanded[I].first.dyn_cast<const TemplateTypeParmType *>())
Chandler Carruthdde65ea2011-05-01 01:05:51 +0000360 Name = TTP->getIdentifier();
Douglas Gregor1da294a2010-12-15 19:43:21 +0000361 else
362 Name = Unexpanded[I].first.get<NamedDecl *>()->getIdentifier();
363
David Blaikie82e95a32014-11-19 07:49:47 +0000364 if (Name && NamesKnown.insert(Name).second)
Douglas Gregor1da294a2010-12-15 19:43:21 +0000365 Names.push_back(Name);
366
367 if (Unexpanded[I].second.isValid())
368 Locations.push_back(Unexpanded[I].second);
369 }
370
Benjamin Kramer3a8650a2015-03-27 17:23:14 +0000371 DiagnosticBuilder DB = Diag(Loc, diag::err_unexpanded_parameter_pack)
372 << (int)UPPC << (int)Names.size();
373 for (size_t I = 0, E = std::min(Names.size(), (size_t)2); I != E; ++I)
374 DB << Names[I];
Douglas Gregor1da294a2010-12-15 19:43:21 +0000375
376 for (unsigned I = 0, N = Locations.size(); I != N; ++I)
377 DB << SourceRange(Locations[I]);
Richard Smith2589b9802012-07-25 03:56:55 +0000378 return true;
Douglas Gregor1da294a2010-12-15 19:43:21 +0000379}
380
Fangrui Song6907ce22018-07-30 19:24:48 +0000381bool Sema::DiagnoseUnexpandedParameterPack(SourceLocation Loc,
Douglas Gregorb55fdf82010-12-15 17:38:57 +0000382 TypeSourceInfo *T,
383 UnexpandedParameterPackContext UPPC) {
384 // C++0x [temp.variadic]p5:
Fangrui Song6907ce22018-07-30 19:24:48 +0000385 // An appearance of a name of a parameter pack that is not expanded is
Douglas Gregorb55fdf82010-12-15 17:38:57 +0000386 // ill-formed.
387 if (!T->getType()->containsUnexpandedParameterPack())
388 return false;
389
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000390 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
Douglas Gregor1da294a2010-12-15 19:43:21 +0000391 CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseTypeLoc(
392 T->getTypeLoc());
393 assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
Richard Smith2589b9802012-07-25 03:56:55 +0000394 return DiagnoseUnexpandedParameterPacks(Loc, UPPC, Unexpanded);
Douglas Gregorb55fdf82010-12-15 17:38:57 +0000395}
396
397bool Sema::DiagnoseUnexpandedParameterPack(Expr *E,
Douglas Gregorc4356532010-12-16 00:46:58 +0000398 UnexpandedParameterPackContext UPPC) {
Douglas Gregorb55fdf82010-12-15 17:38:57 +0000399 // C++0x [temp.variadic]p5:
Fangrui Song6907ce22018-07-30 19:24:48 +0000400 // An appearance of a name of a parameter pack that is not expanded is
Douglas Gregorb55fdf82010-12-15 17:38:57 +0000401 // ill-formed.
402 if (!E->containsUnexpandedParameterPack())
403 return false;
404
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000405 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
Douglas Gregor1da294a2010-12-15 19:43:21 +0000406 CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseStmt(E);
407 assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000408 return DiagnoseUnexpandedParameterPacks(E->getBeginLoc(), UPPC, Unexpanded);
Douglas Gregorb55fdf82010-12-15 17:38:57 +0000409}
Douglas Gregorc4356532010-12-16 00:46:58 +0000410
411bool Sema::DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS,
412 UnexpandedParameterPackContext UPPC) {
413 // C++0x [temp.variadic]p5:
Fangrui Song6907ce22018-07-30 19:24:48 +0000414 // An appearance of a name of a parameter pack that is not expanded is
Douglas Gregorc4356532010-12-16 00:46:58 +0000415 // ill-formed.
Fangrui Song6907ce22018-07-30 19:24:48 +0000416 if (!SS.getScopeRep() ||
Douglas Gregorc4356532010-12-16 00:46:58 +0000417 !SS.getScopeRep()->containsUnexpandedParameterPack())
418 return false;
419
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000420 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
Douglas Gregorc4356532010-12-16 00:46:58 +0000421 CollectUnexpandedParameterPacksVisitor(Unexpanded)
422 .TraverseNestedNameSpecifier(SS.getScopeRep());
423 assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
Richard Smith2589b9802012-07-25 03:56:55 +0000424 return DiagnoseUnexpandedParameterPacks(SS.getRange().getBegin(),
425 UPPC, Unexpanded);
Douglas Gregorc4356532010-12-16 00:46:58 +0000426}
427
428bool Sema::DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo,
429 UnexpandedParameterPackContext UPPC) {
430 // C++0x [temp.variadic]p5:
Fangrui Song6907ce22018-07-30 19:24:48 +0000431 // An appearance of a name of a parameter pack that is not expanded is
Douglas Gregorc4356532010-12-16 00:46:58 +0000432 // ill-formed.
433 switch (NameInfo.getName().getNameKind()) {
434 case DeclarationName::Identifier:
435 case DeclarationName::ObjCZeroArgSelector:
436 case DeclarationName::ObjCOneArgSelector:
437 case DeclarationName::ObjCMultiArgSelector:
438 case DeclarationName::CXXOperatorName:
439 case DeclarationName::CXXLiteralOperatorName:
440 case DeclarationName::CXXUsingDirective:
Richard Smith35845152017-02-07 01:37:30 +0000441 case DeclarationName::CXXDeductionGuideName:
Douglas Gregorc4356532010-12-16 00:46:58 +0000442 return false;
443
444 case DeclarationName::CXXConstructorName:
445 case DeclarationName::CXXDestructorName:
446 case DeclarationName::CXXConversionFunctionName:
Douglas Gregor062ecac2010-12-16 17:19:19 +0000447 // FIXME: We shouldn't need this null check!
Douglas Gregor6ab34af2010-12-16 01:40:04 +0000448 if (TypeSourceInfo *TSInfo = NameInfo.getNamedTypeInfo())
449 return DiagnoseUnexpandedParameterPack(NameInfo.getLoc(), TSInfo, UPPC);
450
451 if (!NameInfo.getName().getCXXNameType()->containsUnexpandedParameterPack())
Douglas Gregorc4356532010-12-16 00:46:58 +0000452 return false;
Douglas Gregor6ab34af2010-12-16 01:40:04 +0000453
Douglas Gregorc4356532010-12-16 00:46:58 +0000454 break;
455 }
456
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000457 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
Douglas Gregorc4356532010-12-16 00:46:58 +0000458 CollectUnexpandedParameterPacksVisitor(Unexpanded)
Douglas Gregor6ab34af2010-12-16 01:40:04 +0000459 .TraverseType(NameInfo.getName().getCXXNameType());
Douglas Gregorc4356532010-12-16 00:46:58 +0000460 assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
Richard Smith2589b9802012-07-25 03:56:55 +0000461 return DiagnoseUnexpandedParameterPacks(NameInfo.getLoc(), UPPC, Unexpanded);
Douglas Gregorc4356532010-12-16 00:46:58 +0000462}
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000463
464bool Sema::DiagnoseUnexpandedParameterPack(SourceLocation Loc,
465 TemplateName Template,
466 UnexpandedParameterPackContext UPPC) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000467
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000468 if (Template.isNull() || !Template.containsUnexpandedParameterPack())
469 return false;
470
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000471 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000472 CollectUnexpandedParameterPacksVisitor(Unexpanded)
473 .TraverseTemplateName(Template);
474 assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
Richard Smith2589b9802012-07-25 03:56:55 +0000475 return DiagnoseUnexpandedParameterPacks(Loc, UPPC, Unexpanded);
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000476}
477
Douglas Gregor14406932011-01-03 20:35:03 +0000478bool Sema::DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg,
479 UnexpandedParameterPackContext UPPC) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000480 if (Arg.getArgument().isNull() ||
Douglas Gregor14406932011-01-03 20:35:03 +0000481 !Arg.getArgument().containsUnexpandedParameterPack())
482 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +0000483
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000484 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
Douglas Gregor14406932011-01-03 20:35:03 +0000485 CollectUnexpandedParameterPacksVisitor(Unexpanded)
486 .TraverseTemplateArgumentLoc(Arg);
487 assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
Richard Smith2589b9802012-07-25 03:56:55 +0000488 return DiagnoseUnexpandedParameterPacks(Arg.getLocation(), UPPC, Unexpanded);
Douglas Gregor14406932011-01-03 20:35:03 +0000489}
490
Douglas Gregor0f3feb42010-12-22 21:19:48 +0000491void Sema::collectUnexpandedParameterPacks(TemplateArgument Arg,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000492 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
Douglas Gregor0f3feb42010-12-22 21:19:48 +0000493 CollectUnexpandedParameterPacksVisitor(Unexpanded)
494 .TraverseTemplateArgument(Arg);
495}
496
Douglas Gregor840bd6c2010-12-20 22:05:00 +0000497void Sema::collectUnexpandedParameterPacks(TemplateArgumentLoc Arg,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000498 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
Douglas Gregor840bd6c2010-12-20 22:05:00 +0000499 CollectUnexpandedParameterPacksVisitor(Unexpanded)
500 .TraverseTemplateArgumentLoc(Arg);
501}
502
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000503void Sema::collectUnexpandedParameterPacks(QualType T,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000504 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000505 CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseType(T);
506}
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000507
Douglas Gregor752a5952011-01-03 22:36:02 +0000508void Sema::collectUnexpandedParameterPacks(TypeLoc TL,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000509 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000510 CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseTypeLoc(TL);
Richard Smith22a250c2016-12-19 04:08:53 +0000511}
512
Richard Smith151c4562016-12-20 21:35:28 +0000513void Sema::collectUnexpandedParameterPacks(
514 NestedNameSpecifierLoc NNS,
515 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
516 CollectUnexpandedParameterPacksVisitor(Unexpanded)
517 .TraverseNestedNameSpecifierLoc(NNS);
518}
519
520void Sema::collectUnexpandedParameterPacks(
521 const DeclarationNameInfo &NameInfo,
522 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
Douglas Gregor4a2a8f72011-10-25 03:44:56 +0000523 CollectUnexpandedParameterPacksVisitor(Unexpanded)
524 .TraverseDeclarationNameInfo(NameInfo);
525}
526
527
Fangrui Song6907ce22018-07-30 19:24:48 +0000528ParsedTemplateArgument
Douglas Gregord2fa7662010-12-20 02:24:11 +0000529Sema::ActOnPackExpansion(const ParsedTemplateArgument &Arg,
530 SourceLocation EllipsisLoc) {
531 if (Arg.isInvalid())
532 return Arg;
533
534 switch (Arg.getKind()) {
535 case ParsedTemplateArgument::Type: {
536 TypeResult Result = ActOnPackExpansion(Arg.getAsType(), EllipsisLoc);
537 if (Result.isInvalid())
538 return ParsedTemplateArgument();
539
Fangrui Song6907ce22018-07-30 19:24:48 +0000540 return ParsedTemplateArgument(Arg.getKind(), Result.get().getAsOpaquePtr(),
Douglas Gregord2fa7662010-12-20 02:24:11 +0000541 Arg.getLocation());
542 }
543
Douglas Gregore8e9dd62011-01-03 17:17:50 +0000544 case ParsedTemplateArgument::NonType: {
545 ExprResult Result = ActOnPackExpansion(Arg.getAsExpr(), EllipsisLoc);
546 if (Result.isInvalid())
547 return ParsedTemplateArgument();
Fangrui Song6907ce22018-07-30 19:24:48 +0000548
549 return ParsedTemplateArgument(Arg.getKind(), Result.get(),
Douglas Gregore8e9dd62011-01-03 17:17:50 +0000550 Arg.getLocation());
551 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000552
Douglas Gregord2fa7662010-12-20 02:24:11 +0000553 case ParsedTemplateArgument::Template:
Douglas Gregoreb29d182011-01-05 17:40:24 +0000554 if (!Arg.getAsTemplate().get().containsUnexpandedParameterPack()) {
555 SourceRange R(Arg.getLocation());
556 if (Arg.getScopeSpec().isValid())
557 R.setBegin(Arg.getScopeSpec().getBeginLoc());
558 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
559 << R;
560 return ParsedTemplateArgument();
561 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000562
Douglas Gregoreb29d182011-01-05 17:40:24 +0000563 return Arg.getTemplatePackExpansion(EllipsisLoc);
Douglas Gregord2fa7662010-12-20 02:24:11 +0000564 }
565 llvm_unreachable("Unhandled template argument kind?");
Douglas Gregord2fa7662010-12-20 02:24:11 +0000566}
567
Fangrui Song6907ce22018-07-30 19:24:48 +0000568TypeResult Sema::ActOnPackExpansion(ParsedType Type,
Douglas Gregord2fa7662010-12-20 02:24:11 +0000569 SourceLocation EllipsisLoc) {
570 TypeSourceInfo *TSInfo;
571 GetTypeFromParser(Type, &TSInfo);
572 if (!TSInfo)
573 return true;
574
David Blaikie7a30dc52013-02-21 01:47:18 +0000575 TypeSourceInfo *TSResult = CheckPackExpansion(TSInfo, EllipsisLoc, None);
Douglas Gregor840bd6c2010-12-20 22:05:00 +0000576 if (!TSResult)
577 return true;
Fangrui Song6907ce22018-07-30 19:24:48 +0000578
Douglas Gregor840bd6c2010-12-20 22:05:00 +0000579 return CreateParsedType(TSResult->getType(), TSResult);
580}
581
David Blaikie05785d12013-02-20 22:23:23 +0000582TypeSourceInfo *
583Sema::CheckPackExpansion(TypeSourceInfo *Pattern, SourceLocation EllipsisLoc,
584 Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +0000585 // Create the pack expansion type and source-location information.
Fangrui Song6907ce22018-07-30 19:24:48 +0000586 QualType Result = CheckPackExpansion(Pattern->getType(),
Douglas Gregor822d0302011-01-12 17:07:58 +0000587 Pattern->getTypeLoc().getSourceRange(),
Douglas Gregor0dca5fd2011-01-14 17:04:44 +0000588 EllipsisLoc, NumExpansions);
Douglas Gregor822d0302011-01-12 17:07:58 +0000589 if (Result.isNull())
Craig Topperc3ec1492014-05-26 06:22:03 +0000590 return nullptr;
Eli Friedman7152fbe2013-06-07 20:31:48 +0000591
592 TypeLocBuilder TLB;
593 TLB.pushFullCopy(Pattern->getTypeLoc());
594 PackExpansionTypeLoc TL = TLB.push<PackExpansionTypeLoc>(Result);
Douglas Gregord2fa7662010-12-20 02:24:11 +0000595 TL.setEllipsisLoc(EllipsisLoc);
Eli Friedman7152fbe2013-06-07 20:31:48 +0000596
597 return TLB.getTypeSourceInfo(Context, Result);
Douglas Gregord2fa7662010-12-20 02:24:11 +0000598}
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000599
David Blaikie05785d12013-02-20 22:23:23 +0000600QualType Sema::CheckPackExpansion(QualType Pattern, SourceRange PatternRange,
Douglas Gregor0dca5fd2011-01-14 17:04:44 +0000601 SourceLocation EllipsisLoc,
David Blaikie05785d12013-02-20 22:23:23 +0000602 Optional<unsigned> NumExpansions) {
Richard Smithb2997f52019-05-21 20:10:50 +0000603 // C++11 [temp.variadic]p5:
Douglas Gregor822d0302011-01-12 17:07:58 +0000604 // The pattern of a pack expansion shall name one or more
605 // parameter packs that are not expanded by a nested pack
606 // expansion.
Richard Smithb2997f52019-05-21 20:10:50 +0000607 //
608 // A pattern containing a deduced type can't occur "naturally" but arises in
609 // the desugaring of an init-capture pack.
610 if (!Pattern->containsUnexpandedParameterPack() &&
611 !Pattern->getContainedDeducedType()) {
Douglas Gregor822d0302011-01-12 17:07:58 +0000612 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
613 << PatternRange;
614 return QualType();
615 }
616
Douglas Gregor0dca5fd2011-01-14 17:04:44 +0000617 return Context.getPackExpansionType(Pattern, NumExpansions);
Douglas Gregor822d0302011-01-12 17:07:58 +0000618}
619
Douglas Gregore8e9dd62011-01-03 17:17:50 +0000620ExprResult Sema::ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc) {
David Blaikie7a30dc52013-02-21 01:47:18 +0000621 return CheckPackExpansion(Pattern, EllipsisLoc, None);
Douglas Gregorb8840002011-01-14 21:20:45 +0000622}
623
624ExprResult Sema::CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
David Blaikie05785d12013-02-20 22:23:23 +0000625 Optional<unsigned> NumExpansions) {
Douglas Gregore8e9dd62011-01-03 17:17:50 +0000626 if (!Pattern)
627 return ExprError();
Fangrui Song6907ce22018-07-30 19:24:48 +0000628
Douglas Gregore8e9dd62011-01-03 17:17:50 +0000629 // C++0x [temp.variadic]p5:
630 // The pattern of a pack expansion shall name one or more
631 // parameter packs that are not expanded by a nested pack
632 // expansion.
633 if (!Pattern->containsUnexpandedParameterPack()) {
634 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
635 << Pattern->getSourceRange();
Sam McCall0afffab2019-07-16 10:30:21 +0000636 CorrectDelayedTyposInExpr(Pattern);
Douglas Gregore8e9dd62011-01-03 17:17:50 +0000637 return ExprError();
638 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000639
Douglas Gregore8e9dd62011-01-03 17:17:50 +0000640 // Create the pack expansion expression and source-location information.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000641 return new (Context)
642 PackExpansionExpr(Context.DependentTy, Pattern, EllipsisLoc, NumExpansions);
Douglas Gregore8e9dd62011-01-03 17:17:50 +0000643}
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000644
David Blaikie05785d12013-02-20 22:23:23 +0000645bool Sema::CheckParameterPacksForExpansion(
646 SourceLocation EllipsisLoc, SourceRange PatternRange,
647 ArrayRef<UnexpandedParameterPack> Unexpanded,
648 const MultiLevelTemplateArgumentList &TemplateArgs, bool &ShouldExpand,
649 bool &RetainExpansion, Optional<unsigned> &NumExpansions) {
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000650 ShouldExpand = true;
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000651 RetainExpansion = false;
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000652 std::pair<IdentifierInfo *, SourceLocation> FirstPack;
653 bool HaveFirstPack = false;
Richard Smith4a8f3512018-07-19 19:00:37 +0000654 Optional<unsigned> NumPartialExpansions;
655 SourceLocation PartiallySubstitutedPackLoc;
656
David Blaikieb9c168a2011-09-22 02:34:54 +0000657 for (ArrayRef<UnexpandedParameterPack>::iterator i = Unexpanded.begin(),
658 end = Unexpanded.end();
659 i != end; ++i) {
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000660 // Compute the depth and index for this parameter pack.
Ted Kremenek582a0992011-01-23 17:04:59 +0000661 unsigned Depth = 0, Index = 0;
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000662 IdentifierInfo *Name;
Richard Smithb2997f52019-05-21 20:10:50 +0000663 bool IsVarDeclPack = false;
Fangrui Song6907ce22018-07-30 19:24:48 +0000664
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000665 if (const TemplateTypeParmType *TTP
David Blaikieb9c168a2011-09-22 02:34:54 +0000666 = i->first.dyn_cast<const TemplateTypeParmType *>()) {
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000667 Depth = TTP->getDepth();
668 Index = TTP->getIndex();
Chandler Carruthdde65ea2011-05-01 01:05:51 +0000669 Name = TTP->getIdentifier();
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000670 } else {
David Blaikieb9c168a2011-09-22 02:34:54 +0000671 NamedDecl *ND = i->first.get<NamedDecl *>();
Richard Smithb2997f52019-05-21 20:10:50 +0000672 if (isa<VarDecl>(ND))
673 IsVarDeclPack = true;
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000674 else
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000675 std::tie(Depth, Index) = getDepthAndIndex(ND);
676
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000677 Name = ND->getIdentifier();
678 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000679
Douglas Gregorf3010112011-01-07 16:43:16 +0000680 // Determine the size of this argument pack.
Fangrui Song6907ce22018-07-30 19:24:48 +0000681 unsigned NewPackSize;
Richard Smithb2997f52019-05-21 20:10:50 +0000682 if (IsVarDeclPack) {
Douglas Gregorf3010112011-01-07 16:43:16 +0000683 // Figure out whether we're instantiating to an argument pack or not.
684 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
Fangrui Song6907ce22018-07-30 19:24:48 +0000685
Douglas Gregorf3010112011-01-07 16:43:16 +0000686 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Instantiation
687 = CurrentInstantiationScope->findInstantiationOf(
David Blaikieb9c168a2011-09-22 02:34:54 +0000688 i->first.get<NamedDecl *>());
Chris Lattner15a776f2011-02-17 19:38:27 +0000689 if (Instantiation->is<DeclArgumentPack *>()) {
Douglas Gregorf3010112011-01-07 16:43:16 +0000690 // We could expand this function parameter pack.
691 NewPackSize = Instantiation->get<DeclArgumentPack *>()->size();
692 } else {
693 // We can't expand this function parameter pack, so we can't expand
694 // the pack expansion.
695 ShouldExpand = false;
696 continue;
697 }
698 } else {
Fangrui Song6907ce22018-07-30 19:24:48 +0000699 // If we don't have a template argument at this depth/index, then we
700 // cannot expand the pack expansion. Make a note of this, but we still
Douglas Gregorf3010112011-01-07 16:43:16 +0000701 // want to check any parameter packs we *do* have arguments for.
702 if (Depth >= TemplateArgs.getNumLevels() ||
703 !TemplateArgs.hasTemplateArgument(Depth, Index)) {
704 ShouldExpand = false;
705 continue;
706 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000707
Douglas Gregorf3010112011-01-07 16:43:16 +0000708 // Determine the size of the argument pack.
709 NewPackSize = TemplateArgs(Depth, Index).pack_size();
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000710 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000711
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000712 // C++0x [temp.arg.explicit]p9:
Fangrui Song6907ce22018-07-30 19:24:48 +0000713 // Template argument deduction can extend the sequence of template
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000714 // arguments corresponding to a template parameter pack, even when the
715 // sequence contains explicitly specified template arguments.
Richard Smithb2997f52019-05-21 20:10:50 +0000716 if (!IsVarDeclPack && CurrentInstantiationScope) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000717 if (NamedDecl *PartialPack
Douglas Gregor63dad4d2011-01-20 23:15:49 +0000718 = CurrentInstantiationScope->getPartiallySubstitutedPack()){
719 unsigned PartialDepth, PartialIndex;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000720 std::tie(PartialDepth, PartialIndex) = getDepthAndIndex(PartialPack);
Richard Smith4a8f3512018-07-19 19:00:37 +0000721 if (PartialDepth == Depth && PartialIndex == Index) {
Douglas Gregor63dad4d2011-01-20 23:15:49 +0000722 RetainExpansion = true;
Richard Smith4a8f3512018-07-19 19:00:37 +0000723 // We don't actually know the new pack size yet.
724 NumPartialExpansions = NewPackSize;
725 PartiallySubstitutedPackLoc = i->second;
726 continue;
727 }
Douglas Gregor63dad4d2011-01-20 23:15:49 +0000728 }
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000729 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000730
Douglas Gregor0dca5fd2011-01-14 17:04:44 +0000731 if (!NumExpansions) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000732 // The is the first pack we've seen for which we have an argument.
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000733 // Record it.
734 NumExpansions = NewPackSize;
735 FirstPack.first = Name;
David Blaikieb9c168a2011-09-22 02:34:54 +0000736 FirstPack.second = i->second;
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000737 HaveFirstPack = true;
738 continue;
739 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000740
Douglas Gregor0dca5fd2011-01-14 17:04:44 +0000741 if (NewPackSize != *NumExpansions) {
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000742 // C++0x [temp.variadic]p5:
Fangrui Song6907ce22018-07-30 19:24:48 +0000743 // All of the parameter packs expanded by a pack expansion shall have
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000744 // the same number of arguments specified.
Douglas Gregor0dca5fd2011-01-14 17:04:44 +0000745 if (HaveFirstPack)
746 Diag(EllipsisLoc, diag::err_pack_expansion_length_conflict)
747 << FirstPack.first << Name << *NumExpansions << NewPackSize
David Blaikieb9c168a2011-09-22 02:34:54 +0000748 << SourceRange(FirstPack.second) << SourceRange(i->second);
Douglas Gregor0dca5fd2011-01-14 17:04:44 +0000749 else
750 Diag(EllipsisLoc, diag::err_pack_expansion_length_conflict_multilevel)
751 << Name << *NumExpansions << NewPackSize
David Blaikieb9c168a2011-09-22 02:34:54 +0000752 << SourceRange(i->second);
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000753 return true;
754 }
755 }
Richard Smithc5452ed2016-10-19 22:18:42 +0000756
Richard Smith4a8f3512018-07-19 19:00:37 +0000757 // If we're performing a partial expansion but we also have a full expansion,
758 // expand to the number of common arguments. For example, given:
759 //
760 // template<typename ...T> struct A {
761 // template<typename ...U> void f(pair<T, U>...);
762 // };
763 //
764 // ... a call to 'A<int, int>().f<int>' should expand the pack once and
765 // retain an expansion.
766 if (NumPartialExpansions) {
767 if (NumExpansions && *NumExpansions < *NumPartialExpansions) {
768 NamedDecl *PartialPack =
769 CurrentInstantiationScope->getPartiallySubstitutedPack();
770 Diag(EllipsisLoc, diag::err_pack_expansion_length_conflict_partial)
771 << PartialPack << *NumPartialExpansions << *NumExpansions
772 << SourceRange(PartiallySubstitutedPackLoc);
773 return true;
774 }
775
776 NumExpansions = NumPartialExpansions;
777 }
778
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000779 return false;
780}
Douglas Gregor27b4c162010-12-23 22:44:42 +0000781
David Blaikie05785d12013-02-20 22:23:23 +0000782Optional<unsigned> Sema::getNumArgumentsInExpansion(QualType T,
Douglas Gregor5cde3862011-01-11 03:14:20 +0000783 const MultiLevelTemplateArgumentList &TemplateArgs) {
784 QualType Pattern = cast<PackExpansionType>(T)->getPattern();
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000785 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
Douglas Gregor5cde3862011-01-11 03:14:20 +0000786 CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseType(Pattern);
787
David Blaikie05785d12013-02-20 22:23:23 +0000788 Optional<unsigned> Result;
Douglas Gregor5cde3862011-01-11 03:14:20 +0000789 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
790 // Compute the depth and index for this parameter pack.
791 unsigned Depth;
792 unsigned Index;
Fangrui Song6907ce22018-07-30 19:24:48 +0000793
Douglas Gregor5cde3862011-01-11 03:14:20 +0000794 if (const TemplateTypeParmType *TTP
795 = Unexpanded[I].first.dyn_cast<const TemplateTypeParmType *>()) {
796 Depth = TTP->getDepth();
797 Index = TTP->getIndex();
Fangrui Song6907ce22018-07-30 19:24:48 +0000798 } else {
Douglas Gregor5cde3862011-01-11 03:14:20 +0000799 NamedDecl *ND = Unexpanded[I].first.get<NamedDecl *>();
Richard Smithb2997f52019-05-21 20:10:50 +0000800 if (isa<VarDecl>(ND)) {
801 // Function parameter pack or init-capture pack.
Douglas Gregor5cde3862011-01-11 03:14:20 +0000802 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
Fangrui Song6907ce22018-07-30 19:24:48 +0000803
Douglas Gregor5cde3862011-01-11 03:14:20 +0000804 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Instantiation
805 = CurrentInstantiationScope->findInstantiationOf(
806 Unexpanded[I].first.get<NamedDecl *>());
Richard Smith198223b2012-07-18 01:29:05 +0000807 if (Instantiation->is<Decl*>())
808 // The pattern refers to an unexpanded pack. We're not ready to expand
809 // this pack yet.
David Blaikie7a30dc52013-02-21 01:47:18 +0000810 return None;
Richard Smith198223b2012-07-18 01:29:05 +0000811
812 unsigned Size = Instantiation->get<DeclArgumentPack *>()->size();
813 assert((!Result || *Result == Size) && "inconsistent pack sizes");
814 Result = Size;
Douglas Gregor5cde3862011-01-11 03:14:20 +0000815 continue;
816 }
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000817
818 std::tie(Depth, Index) = getDepthAndIndex(ND);
Douglas Gregor5cde3862011-01-11 03:14:20 +0000819 }
820 if (Depth >= TemplateArgs.getNumLevels() ||
821 !TemplateArgs.hasTemplateArgument(Depth, Index))
Richard Smith198223b2012-07-18 01:29:05 +0000822 // The pattern refers to an unknown template argument. We're not ready to
823 // expand this pack yet.
David Blaikie7a30dc52013-02-21 01:47:18 +0000824 return None;
Fangrui Song6907ce22018-07-30 19:24:48 +0000825
Douglas Gregor5cde3862011-01-11 03:14:20 +0000826 // Determine the size of the argument pack.
Richard Smith198223b2012-07-18 01:29:05 +0000827 unsigned Size = TemplateArgs(Depth, Index).pack_size();
828 assert((!Result || *Result == Size) && "inconsistent pack sizes");
829 Result = Size;
Douglas Gregor5cde3862011-01-11 03:14:20 +0000830 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000831
Richard Smith198223b2012-07-18 01:29:05 +0000832 return Result;
Douglas Gregor5cde3862011-01-11 03:14:20 +0000833}
834
Douglas Gregor27b4c162010-12-23 22:44:42 +0000835bool Sema::containsUnexpandedParameterPacks(Declarator &D) {
836 const DeclSpec &DS = D.getDeclSpec();
837 switch (DS.getTypeSpecType()) {
Faisal Vali090da2d2018-01-01 18:23:28 +0000838 case TST_typename:
839 case TST_typeofType:
840 case TST_underlyingType:
841 case TST_atomic: {
Douglas Gregor27b4c162010-12-23 22:44:42 +0000842 QualType T = DS.getRepAsType().get();
843 if (!T.isNull() && T->containsUnexpandedParameterPack())
844 return true;
845 break;
846 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000847
Faisal Vali090da2d2018-01-01 18:23:28 +0000848 case TST_typeofExpr:
849 case TST_decltype:
Erich Keane5f0903e2020-04-17 10:44:19 -0700850 case TST_extint:
Fangrui Song6907ce22018-07-30 19:24:48 +0000851 if (DS.getRepAsExpr() &&
Douglas Gregor27b4c162010-12-23 22:44:42 +0000852 DS.getRepAsExpr()->containsUnexpandedParameterPack())
853 return true;
854 break;
Fangrui Song6907ce22018-07-30 19:24:48 +0000855
Faisal Vali090da2d2018-01-01 18:23:28 +0000856 case TST_unspecified:
857 case TST_void:
858 case TST_char:
859 case TST_wchar:
Richard Smith3a8244d2018-05-01 05:02:45 +0000860 case TST_char8:
Faisal Vali090da2d2018-01-01 18:23:28 +0000861 case TST_char16:
862 case TST_char32:
863 case TST_int:
864 case TST_int128:
865 case TST_half:
866 case TST_float:
867 case TST_double:
Leonard Chanf921d852018-06-04 16:07:52 +0000868 case TST_Accum:
Leonard Chanab80f3c2018-06-14 14:53:51 +0000869 case TST_Fract:
Faisal Vali090da2d2018-01-01 18:23:28 +0000870 case TST_Float16:
871 case TST_float128:
872 case TST_bool:
873 case TST_decimal32:
874 case TST_decimal64:
875 case TST_decimal128:
876 case TST_enum:
877 case TST_union:
878 case TST_struct:
879 case TST_interface:
880 case TST_class:
881 case TST_auto:
882 case TST_auto_type:
883 case TST_decltype_auto:
884#define GENERIC_IMAGE_TYPE(ImgType, Id) case TST_##ImgType##_t:
Alexey Baderb62f1442016-04-13 08:33:41 +0000885#include "clang/Basic/OpenCLImageTypes.def"
Faisal Vali090da2d2018-01-01 18:23:28 +0000886 case TST_unknown_anytype:
887 case TST_error:
Douglas Gregor27b4c162010-12-23 22:44:42 +0000888 break;
889 }
Larisse Voufo2e846502014-08-29 21:08:16 +0000890
Douglas Gregor27b4c162010-12-23 22:44:42 +0000891 for (unsigned I = 0, N = D.getNumTypeObjects(); I != N; ++I) {
892 const DeclaratorChunk &Chunk = D.getTypeObject(I);
893 switch (Chunk.Kind) {
894 case DeclaratorChunk::Pointer:
895 case DeclaratorChunk::Reference:
896 case DeclaratorChunk::Paren:
Xiuli Pan9c14e282016-01-09 12:53:17 +0000897 case DeclaratorChunk::Pipe:
Larisse Voufo2e846502014-08-29 21:08:16 +0000898 case DeclaratorChunk::BlockPointer:
Douglas Gregor27b4c162010-12-23 22:44:42 +0000899 // These declarator chunks cannot contain any parameter packs.
900 break;
Fangrui Song6907ce22018-07-30 19:24:48 +0000901
Douglas Gregor27b4c162010-12-23 22:44:42 +0000902 case DeclaratorChunk::Array:
Larisse Voufo2e846502014-08-29 21:08:16 +0000903 if (Chunk.Arr.NumElts &&
904 Chunk.Arr.NumElts->containsUnexpandedParameterPack())
905 return true;
906 break;
Douglas Gregor27b4c162010-12-23 22:44:42 +0000907 case DeclaratorChunk::Function:
Larisse Voufo2e846502014-08-29 21:08:16 +0000908 for (unsigned i = 0, e = Chunk.Fun.NumParams; i != e; ++i) {
909 ParmVarDecl *Param = cast<ParmVarDecl>(Chunk.Fun.Params[i].Param);
910 QualType ParamTy = Param->getType();
911 assert(!ParamTy.isNull() && "Couldn't parse type?");
912 if (ParamTy->containsUnexpandedParameterPack()) return true;
913 }
914
915 if (Chunk.Fun.getExceptionSpecType() == EST_Dynamic) {
Reid Kleckner078aea92016-12-09 17:14:05 +0000916 for (unsigned i = 0; i != Chunk.Fun.getNumExceptions(); ++i) {
Larisse Voufo2e846502014-08-29 21:08:16 +0000917 if (Chunk.Fun.Exceptions[i]
918 .Ty.get()
919 ->containsUnexpandedParameterPack())
920 return true;
921 }
Richard Smitheaf11ad2018-05-03 03:58:32 +0000922 } else if (isComputedNoexcept(Chunk.Fun.getExceptionSpecType()) &&
Larisse Voufo2e846502014-08-29 21:08:16 +0000923 Chunk.Fun.NoexceptExpr->containsUnexpandedParameterPack())
924 return true;
925
Nico Weber8d26b722014-12-30 02:06:40 +0000926 if (Chunk.Fun.hasTrailingReturnType()) {
927 QualType T = Chunk.Fun.getTrailingReturnType().get();
Fangrui Song99337e22018-07-20 08:19:20 +0000928 if (!T.isNull() && T->containsUnexpandedParameterPack())
929 return true;
Nico Weber8d26b722014-12-30 02:06:40 +0000930 }
Larisse Voufo2e846502014-08-29 21:08:16 +0000931 break;
932
Douglas Gregor27b4c162010-12-23 22:44:42 +0000933 case DeclaratorChunk::MemberPointer:
934 if (Chunk.Mem.Scope().getScopeRep() &&
935 Chunk.Mem.Scope().getScopeRep()->containsUnexpandedParameterPack())
936 return true;
937 break;
938 }
939 }
Fangrui Song99337e22018-07-20 08:19:20 +0000940
Saar Razb65b1f32020-01-09 15:07:51 +0200941 if (Expr *TRC = D.getTrailingRequiresClause())
942 if (TRC->containsUnexpandedParameterPack())
943 return true;
Jim Lin466f8842020-02-18 10:48:38 +0800944
Douglas Gregor27b4c162010-12-23 22:44:42 +0000945 return false;
946}
Douglas Gregor820ba7b2011-01-04 17:33:58 +0000947
Kaelyn Uhrain637b5b32012-01-13 23:10:36 +0000948namespace {
949
950// Callback to only accept typo corrections that refer to parameter packs.
Bruno Ricci70ad3962019-03-25 17:08:51 +0000951class ParameterPackValidatorCCC final : public CorrectionCandidateCallback {
Kaelyn Uhrain637b5b32012-01-13 23:10:36 +0000952 public:
Craig Toppere14c0f82014-03-12 04:55:44 +0000953 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhrain637b5b32012-01-13 23:10:36 +0000954 NamedDecl *ND = candidate.getCorrectionDecl();
955 return ND && ND->isParameterPack();
956 }
Bruno Ricci70ad3962019-03-25 17:08:51 +0000957
958 std::unique_ptr<CorrectionCandidateCallback> clone() override {
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +0000959 return std::make_unique<ParameterPackValidatorCCC>(*this);
Bruno Ricci70ad3962019-03-25 17:08:51 +0000960 }
Kaelyn Uhrain637b5b32012-01-13 23:10:36 +0000961};
962
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000963}
Kaelyn Uhrain637b5b32012-01-13 23:10:36 +0000964
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000965/// Called when an expression computing the size of a parameter pack
Douglas Gregor820ba7b2011-01-04 17:33:58 +0000966/// is parsed.
967///
968/// \code
969/// template<typename ...Types> struct count {
970/// static const unsigned value = sizeof...(Types);
971/// };
972/// \endcode
973///
974//
975/// \param OpLoc The location of the "sizeof" keyword.
976/// \param Name The name of the parameter pack whose size will be determined.
977/// \param NameLoc The source location of the name of the parameter pack.
978/// \param RParenLoc The location of the closing parentheses.
979ExprResult Sema::ActOnSizeofParameterPackExpr(Scope *S,
980 SourceLocation OpLoc,
981 IdentifierInfo &Name,
982 SourceLocation NameLoc,
983 SourceLocation RParenLoc) {
984 // C++0x [expr.sizeof]p5:
985 // The identifier in a sizeof... expression shall name a parameter pack.
Douglas Gregor820ba7b2011-01-04 17:33:58 +0000986 LookupResult R(*this, &Name, NameLoc, LookupOrdinaryName);
987 LookupName(R, S);
Craig Topperc3ec1492014-05-26 06:22:03 +0000988
989 NamedDecl *ParameterPack = nullptr;
Douglas Gregor820ba7b2011-01-04 17:33:58 +0000990 switch (R.getResultKind()) {
991 case LookupResult::Found:
992 ParameterPack = R.getFoundDecl();
993 break;
Fangrui Song6907ce22018-07-30 19:24:48 +0000994
Douglas Gregor820ba7b2011-01-04 17:33:58 +0000995 case LookupResult::NotFound:
Bruno Ricci70ad3962019-03-25 17:08:51 +0000996 case LookupResult::NotFoundInCurrentInstantiation: {
997 ParameterPackValidatorCCC CCC{};
Kaelyn Takata89c881b2014-10-27 18:07:29 +0000998 if (TypoCorrection Corrected =
999 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, nullptr,
Bruno Ricci70ad3962019-03-25 17:08:51 +00001000 CCC, CTK_ErrorRecovery)) {
Richard Smithf9b15102013-08-17 00:46:16 +00001001 diagnoseTypo(Corrected,
1002 PDiag(diag::err_sizeof_pack_no_pack_name_suggest) << &Name,
1003 PDiag(diag::note_parameter_pack_here));
Kaelyn Uhrain637b5b32012-01-13 23:10:36 +00001004 ParameterPack = Corrected.getCorrectionDecl();
Douglas Gregor820ba7b2011-01-04 17:33:58 +00001005 }
Reid Kleckner4dc0b1a2018-11-01 19:54:45 +00001006 break;
Bruno Ricci70ad3962019-03-25 17:08:51 +00001007 }
Douglas Gregor820ba7b2011-01-04 17:33:58 +00001008 case LookupResult::FoundOverloaded:
1009 case LookupResult::FoundUnresolvedValue:
1010 break;
Fangrui Song99337e22018-07-20 08:19:20 +00001011
Douglas Gregor820ba7b2011-01-04 17:33:58 +00001012 case LookupResult::Ambiguous:
1013 DiagnoseAmbiguousLookup(R);
1014 return ExprError();
1015 }
Fangrui Song99337e22018-07-20 08:19:20 +00001016
Douglas Gregor3c6bd2a2011-01-05 21:11:38 +00001017 if (!ParameterPack || !ParameterPack->isParameterPack()) {
Douglas Gregor820ba7b2011-01-04 17:33:58 +00001018 Diag(NameLoc, diag::err_sizeof_pack_no_pack_name)
1019 << &Name;
1020 return ExprError();
1021 }
1022
Nick Lewycky45b50522013-02-02 00:25:55 +00001023 MarkAnyDeclReferenced(OpLoc, ParameterPack, true);
Eli Friedman23b1be92012-03-01 21:32:56 +00001024
Richard Smithd784e682015-09-23 21:41:42 +00001025 return SizeOfPackExpr::Create(Context, OpLoc, ParameterPack, NameLoc,
1026 RParenLoc);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00001027}
Eli Friedman94e9eaa2013-06-20 04:11:21 +00001028
1029TemplateArgumentLoc
1030Sema::getTemplateArgumentPackExpansionPattern(
1031 TemplateArgumentLoc OrigLoc,
1032 SourceLocation &Ellipsis, Optional<unsigned> &NumExpansions) const {
1033 const TemplateArgument &Argument = OrigLoc.getArgument();
1034 assert(Argument.isPackExpansion());
1035 switch (Argument.getKind()) {
1036 case TemplateArgument::Type: {
1037 // FIXME: We shouldn't ever have to worry about missing
1038 // type-source info!
1039 TypeSourceInfo *ExpansionTSInfo = OrigLoc.getTypeSourceInfo();
1040 if (!ExpansionTSInfo)
1041 ExpansionTSInfo = Context.getTrivialTypeSourceInfo(Argument.getAsType(),
1042 Ellipsis);
1043 PackExpansionTypeLoc Expansion =
1044 ExpansionTSInfo->getTypeLoc().castAs<PackExpansionTypeLoc>();
1045 Ellipsis = Expansion.getEllipsisLoc();
1046
1047 TypeLoc Pattern = Expansion.getPatternLoc();
1048 NumExpansions = Expansion.getTypePtr()->getNumExpansions();
1049
1050 // We need to copy the TypeLoc because TemplateArgumentLocs store a
1051 // TypeSourceInfo.
1052 // FIXME: Find some way to avoid the copy?
1053 TypeLocBuilder TLB;
1054 TLB.pushFullCopy(Pattern);
1055 TypeSourceInfo *PatternTSInfo =
1056 TLB.getTypeSourceInfo(Context, Pattern.getType());
1057 return TemplateArgumentLoc(TemplateArgument(Pattern.getType()),
1058 PatternTSInfo);
1059 }
1060
1061 case TemplateArgument::Expression: {
1062 PackExpansionExpr *Expansion
1063 = cast<PackExpansionExpr>(Argument.getAsExpr());
1064 Expr *Pattern = Expansion->getPattern();
1065 Ellipsis = Expansion->getEllipsisLoc();
1066 NumExpansions = Expansion->getNumExpansions();
1067 return TemplateArgumentLoc(Pattern, Pattern);
1068 }
1069
1070 case TemplateArgument::TemplateExpansion:
1071 Ellipsis = OrigLoc.getTemplateEllipsisLoc();
1072 NumExpansions = Argument.getNumTemplateExpansions();
1073 return TemplateArgumentLoc(Argument.getPackExpansionPattern(),
1074 OrigLoc.getTemplateQualifierLoc(),
1075 OrigLoc.getTemplateNameLoc());
1076
1077 case TemplateArgument::Declaration:
1078 case TemplateArgument::NullPtr:
1079 case TemplateArgument::Template:
1080 case TemplateArgument::Integral:
1081 case TemplateArgument::Pack:
1082 case TemplateArgument::Null:
1083 return TemplateArgumentLoc();
1084 }
1085
1086 llvm_unreachable("Invalid TemplateArgument Kind!");
1087}
Richard Smith0f0af192014-11-08 05:07:16 +00001088
Richard Smithc5452ed2016-10-19 22:18:42 +00001089Optional<unsigned> Sema::getFullyPackExpandedSize(TemplateArgument Arg) {
1090 assert(Arg.containsUnexpandedParameterPack());
1091
1092 // If this is a substituted pack, grab that pack. If not, we don't know
1093 // the size yet.
1094 // FIXME: We could find a size in more cases by looking for a substituted
1095 // pack anywhere within this argument, but that's not necessary in the common
1096 // case for 'sizeof...(A)' handling.
1097 TemplateArgument Pack;
1098 switch (Arg.getKind()) {
1099 case TemplateArgument::Type:
1100 if (auto *Subst = Arg.getAsType()->getAs<SubstTemplateTypeParmPackType>())
1101 Pack = Subst->getArgumentPack();
1102 else
1103 return None;
1104 break;
1105
1106 case TemplateArgument::Expression:
1107 if (auto *Subst =
1108 dyn_cast<SubstNonTypeTemplateParmPackExpr>(Arg.getAsExpr()))
1109 Pack = Subst->getArgumentPack();
1110 else if (auto *Subst = dyn_cast<FunctionParmPackExpr>(Arg.getAsExpr())) {
Richard Smithb2997f52019-05-21 20:10:50 +00001111 for (VarDecl *PD : *Subst)
Richard Smithc5452ed2016-10-19 22:18:42 +00001112 if (PD->isParameterPack())
1113 return None;
1114 return Subst->getNumExpansions();
1115 } else
1116 return None;
1117 break;
1118
1119 case TemplateArgument::Template:
1120 if (SubstTemplateTemplateParmPackStorage *Subst =
1121 Arg.getAsTemplate().getAsSubstTemplateTemplateParmPack())
1122 Pack = Subst->getArgumentPack();
1123 else
1124 return None;
1125 break;
1126
1127 case TemplateArgument::Declaration:
1128 case TemplateArgument::NullPtr:
1129 case TemplateArgument::TemplateExpansion:
1130 case TemplateArgument::Integral:
1131 case TemplateArgument::Pack:
1132 case TemplateArgument::Null:
1133 return None;
1134 }
1135
1136 // Check that no argument in the pack is itself a pack expansion.
1137 for (TemplateArgument Elem : Pack.pack_elements()) {
1138 // There's no point recursing in this case; we would have already
1139 // expanded this pack expansion into the enclosing pack if we could.
1140 if (Elem.isPackExpansion())
1141 return None;
1142 }
1143 return Pack.pack_size();
1144}
1145
Richard Smith0f0af192014-11-08 05:07:16 +00001146static void CheckFoldOperand(Sema &S, Expr *E) {
1147 if (!E)
1148 return;
1149
1150 E = E->IgnoreImpCasts();
Richard Smith66094432016-10-20 00:55:15 +00001151 auto *OCE = dyn_cast<CXXOperatorCallExpr>(E);
1152 if ((OCE && OCE->isInfixBinaryOp()) || isa<BinaryOperator>(E) ||
1153 isa<AbstractConditionalOperator>(E)) {
Richard Smith0f0af192014-11-08 05:07:16 +00001154 S.Diag(E->getExprLoc(), diag::err_fold_expression_bad_operand)
1155 << E->getSourceRange()
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001156 << FixItHint::CreateInsertion(E->getBeginLoc(), "(")
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001157 << FixItHint::CreateInsertion(E->getEndLoc(), ")");
Richard Smith0f0af192014-11-08 05:07:16 +00001158 }
1159}
1160
1161ExprResult Sema::ActOnCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
1162 tok::TokenKind Operator,
1163 SourceLocation EllipsisLoc, Expr *RHS,
1164 SourceLocation RParenLoc) {
1165 // LHS and RHS must be cast-expressions. We allow an arbitrary expression
1166 // in the parser and reduce down to just cast-expressions here.
1167 CheckFoldOperand(*this, LHS);
1168 CheckFoldOperand(*this, RHS);
1169
Richard Smith90e043d2017-02-15 19:57:10 +00001170 auto DiscardOperands = [&] {
1171 CorrectDelayedTyposInExpr(LHS);
1172 CorrectDelayedTyposInExpr(RHS);
1173 };
1174
Richard Smith0f0af192014-11-08 05:07:16 +00001175 // [expr.prim.fold]p3:
1176 // In a binary fold, op1 and op2 shall be the same fold-operator, and
1177 // either e1 shall contain an unexpanded parameter pack or e2 shall contain
1178 // an unexpanded parameter pack, but not both.
1179 if (LHS && RHS &&
1180 LHS->containsUnexpandedParameterPack() ==
1181 RHS->containsUnexpandedParameterPack()) {
Richard Smith90e043d2017-02-15 19:57:10 +00001182 DiscardOperands();
Richard Smith0f0af192014-11-08 05:07:16 +00001183 return Diag(EllipsisLoc,
1184 LHS->containsUnexpandedParameterPack()
1185 ? diag::err_fold_expression_packs_both_sides
1186 : diag::err_pack_expansion_without_parameter_packs)
1187 << LHS->getSourceRange() << RHS->getSourceRange();
1188 }
1189
1190 // [expr.prim.fold]p2:
1191 // In a unary fold, the cast-expression shall contain an unexpanded
1192 // parameter pack.
1193 if (!LHS || !RHS) {
1194 Expr *Pack = LHS ? LHS : RHS;
1195 assert(Pack && "fold expression with neither LHS nor RHS");
Richard Smith90e043d2017-02-15 19:57:10 +00001196 DiscardOperands();
Richard Smith0f0af192014-11-08 05:07:16 +00001197 if (!Pack->containsUnexpandedParameterPack())
1198 return Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1199 << Pack->getSourceRange();
1200 }
1201
1202 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Operator);
Richard Smithc7214f62019-05-13 08:31:14 +00001203 return BuildCXXFoldExpr(LParenLoc, LHS, Opc, EllipsisLoc, RHS, RParenLoc,
1204 None);
Richard Smith0f0af192014-11-08 05:07:16 +00001205}
1206
1207ExprResult Sema::BuildCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
1208 BinaryOperatorKind Operator,
1209 SourceLocation EllipsisLoc, Expr *RHS,
Richard Smithc7214f62019-05-13 08:31:14 +00001210 SourceLocation RParenLoc,
1211 Optional<unsigned> NumExpansions) {
Richard Smith0f0af192014-11-08 05:07:16 +00001212 return new (Context) CXXFoldExpr(Context.DependentTy, LParenLoc, LHS,
Richard Smithc7214f62019-05-13 08:31:14 +00001213 Operator, EllipsisLoc, RHS, RParenLoc,
1214 NumExpansions);
Richard Smith0f0af192014-11-08 05:07:16 +00001215}
1216
1217ExprResult Sema::BuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc,
1218 BinaryOperatorKind Operator) {
1219 // [temp.variadic]p9:
1220 // If N is zero for a unary fold-expression, the value of the expression is
Richard Smith0f0af192014-11-08 05:07:16 +00001221 // && -> true
1222 // || -> false
1223 // , -> void()
1224 // if the operator is not listed [above], the instantiation is ill-formed.
1225 //
1226 // Note that we need to use something like int() here, not merely 0, to
1227 // prevent the result from being a null pointer constant.
1228 QualType ScalarType;
1229 switch (Operator) {
Richard Smith0f0af192014-11-08 05:07:16 +00001230 case BO_LOr:
1231 return ActOnCXXBoolLiteral(EllipsisLoc, tok::kw_false);
1232 case BO_LAnd:
1233 return ActOnCXXBoolLiteral(EllipsisLoc, tok::kw_true);
1234 case BO_Comma:
1235 ScalarType = Context.VoidTy;
1236 break;
1237
1238 default:
1239 return Diag(EllipsisLoc, diag::err_fold_expression_empty)
1240 << BinaryOperator::getOpcodeStr(Operator);
1241 }
1242
1243 return new (Context) CXXScalarValueInitExpr(
1244 ScalarType, Context.getTrivialTypeSourceInfo(ScalarType, EllipsisLoc),
1245 EllipsisLoc);
1246}