blob: 9b23624a9a81f73bae7b212b00288c870638c919 [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
297 // a parameter of 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 Smith2589b9802012-07-25 03:56:55 +0000302 for (unsigned N = FunctionScopes.size(); N; --N) {
Richard Smith6eb9b9e2018-02-03 00:44:57 +0000303 sema::FunctionScopeInfo *Func = FunctionScopes[N-1];
304 // We do not permit pack expansion that would duplicate a statement
305 // expression, not even within a lambda.
306 // FIXME: We could probably support this for statement expressions that do
307 // not contain labels, and for pack expansions that expand both the stmt
308 // expr and the enclosing lambda.
309 if (std::any_of(
310 Func->CompoundScopes.begin(), Func->CompoundScopes.end(),
311 [](sema::CompoundScopeInfo &CSI) { return CSI.IsStmtExpr; }))
312 break;
313
314 if (auto *LSI = dyn_cast<sema::LambdaScopeInfo>(Func)) {
Richard Smithf26d5512017-08-15 22:58:45 +0000315 if (N == FunctionScopes.size()) {
Richard Smithb2997f52019-05-21 20:10:50 +0000316 for (auto &Pack : Unexpanded) {
317 auto *VD = dyn_cast_or_null<VarDecl>(
318 Pack.first.dyn_cast<NamedDecl *>());
319 if (VD && VD->getDeclContext() == LSI->CallOperator)
320 LambdaParamPackReferences.push_back(Pack);
Richard Smith78a07ba2017-08-15 19:11:21 +0000321 }
322 }
323
Richard Smithf26d5512017-08-15 22:58:45 +0000324 // If we have references to a parameter pack of the innermost enclosing
325 // lambda, only diagnose those ones. We don't know whether any other
326 // unexpanded parameters referenced herein are actually unexpanded;
327 // they might be expanded at an outer level.
328 if (!LambdaParamPackReferences.empty()) {
329 Unexpanded = LambdaParamPackReferences;
Richard Smith78a07ba2017-08-15 19:11:21 +0000330 break;
331 }
332
Richard Smith2589b9802012-07-25 03:56:55 +0000333 LSI->ContainsUnexpandedParameterPack = true;
334 return false;
335 }
336 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000337
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000338 SmallVector<SourceLocation, 4> Locations;
339 SmallVector<IdentifierInfo *, 4> Names;
Douglas Gregor1da294a2010-12-15 19:43:21 +0000340 llvm::SmallPtrSet<IdentifierInfo *, 4> NamesKnown;
341
342 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000343 IdentifierInfo *Name = nullptr;
Douglas Gregor1da294a2010-12-15 19:43:21 +0000344 if (const TemplateTypeParmType *TTP
345 = Unexpanded[I].first.dyn_cast<const TemplateTypeParmType *>())
Chandler Carruthdde65ea2011-05-01 01:05:51 +0000346 Name = TTP->getIdentifier();
Douglas Gregor1da294a2010-12-15 19:43:21 +0000347 else
348 Name = Unexpanded[I].first.get<NamedDecl *>()->getIdentifier();
349
David Blaikie82e95a32014-11-19 07:49:47 +0000350 if (Name && NamesKnown.insert(Name).second)
Douglas Gregor1da294a2010-12-15 19:43:21 +0000351 Names.push_back(Name);
352
353 if (Unexpanded[I].second.isValid())
354 Locations.push_back(Unexpanded[I].second);
355 }
356
Benjamin Kramer3a8650a2015-03-27 17:23:14 +0000357 DiagnosticBuilder DB = Diag(Loc, diag::err_unexpanded_parameter_pack)
358 << (int)UPPC << (int)Names.size();
359 for (size_t I = 0, E = std::min(Names.size(), (size_t)2); I != E; ++I)
360 DB << Names[I];
Douglas Gregor1da294a2010-12-15 19:43:21 +0000361
362 for (unsigned I = 0, N = Locations.size(); I != N; ++I)
363 DB << SourceRange(Locations[I]);
Richard Smith2589b9802012-07-25 03:56:55 +0000364 return true;
Douglas Gregor1da294a2010-12-15 19:43:21 +0000365}
366
Fangrui Song6907ce22018-07-30 19:24:48 +0000367bool Sema::DiagnoseUnexpandedParameterPack(SourceLocation Loc,
Douglas Gregorb55fdf82010-12-15 17:38:57 +0000368 TypeSourceInfo *T,
369 UnexpandedParameterPackContext UPPC) {
370 // C++0x [temp.variadic]p5:
Fangrui Song6907ce22018-07-30 19:24:48 +0000371 // An appearance of a name of a parameter pack that is not expanded is
Douglas Gregorb55fdf82010-12-15 17:38:57 +0000372 // ill-formed.
373 if (!T->getType()->containsUnexpandedParameterPack())
374 return false;
375
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000376 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
Douglas Gregor1da294a2010-12-15 19:43:21 +0000377 CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseTypeLoc(
378 T->getTypeLoc());
379 assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
Richard Smith2589b9802012-07-25 03:56:55 +0000380 return DiagnoseUnexpandedParameterPacks(Loc, UPPC, Unexpanded);
Douglas Gregorb55fdf82010-12-15 17:38:57 +0000381}
382
383bool Sema::DiagnoseUnexpandedParameterPack(Expr *E,
Douglas Gregorc4356532010-12-16 00:46:58 +0000384 UnexpandedParameterPackContext UPPC) {
Douglas Gregorb55fdf82010-12-15 17:38:57 +0000385 // C++0x [temp.variadic]p5:
Fangrui Song6907ce22018-07-30 19:24:48 +0000386 // An appearance of a name of a parameter pack that is not expanded is
Douglas Gregorb55fdf82010-12-15 17:38:57 +0000387 // ill-formed.
388 if (!E->containsUnexpandedParameterPack())
389 return false;
390
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000391 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
Douglas Gregor1da294a2010-12-15 19:43:21 +0000392 CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseStmt(E);
393 assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000394 return DiagnoseUnexpandedParameterPacks(E->getBeginLoc(), UPPC, Unexpanded);
Douglas Gregorb55fdf82010-12-15 17:38:57 +0000395}
Douglas Gregorc4356532010-12-16 00:46:58 +0000396
397bool Sema::DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS,
398 UnexpandedParameterPackContext UPPC) {
399 // 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 Gregorc4356532010-12-16 00:46:58 +0000401 // ill-formed.
Fangrui Song6907ce22018-07-30 19:24:48 +0000402 if (!SS.getScopeRep() ||
Douglas Gregorc4356532010-12-16 00:46:58 +0000403 !SS.getScopeRep()->containsUnexpandedParameterPack())
404 return false;
405
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000406 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
Douglas Gregorc4356532010-12-16 00:46:58 +0000407 CollectUnexpandedParameterPacksVisitor(Unexpanded)
408 .TraverseNestedNameSpecifier(SS.getScopeRep());
409 assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
Richard Smith2589b9802012-07-25 03:56:55 +0000410 return DiagnoseUnexpandedParameterPacks(SS.getRange().getBegin(),
411 UPPC, Unexpanded);
Douglas Gregorc4356532010-12-16 00:46:58 +0000412}
413
414bool Sema::DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo,
415 UnexpandedParameterPackContext UPPC) {
416 // C++0x [temp.variadic]p5:
Fangrui Song6907ce22018-07-30 19:24:48 +0000417 // An appearance of a name of a parameter pack that is not expanded is
Douglas Gregorc4356532010-12-16 00:46:58 +0000418 // ill-formed.
419 switch (NameInfo.getName().getNameKind()) {
420 case DeclarationName::Identifier:
421 case DeclarationName::ObjCZeroArgSelector:
422 case DeclarationName::ObjCOneArgSelector:
423 case DeclarationName::ObjCMultiArgSelector:
424 case DeclarationName::CXXOperatorName:
425 case DeclarationName::CXXLiteralOperatorName:
426 case DeclarationName::CXXUsingDirective:
Richard Smith35845152017-02-07 01:37:30 +0000427 case DeclarationName::CXXDeductionGuideName:
Douglas Gregorc4356532010-12-16 00:46:58 +0000428 return false;
429
430 case DeclarationName::CXXConstructorName:
431 case DeclarationName::CXXDestructorName:
432 case DeclarationName::CXXConversionFunctionName:
Douglas Gregor062ecac2010-12-16 17:19:19 +0000433 // FIXME: We shouldn't need this null check!
Douglas Gregor6ab34af2010-12-16 01:40:04 +0000434 if (TypeSourceInfo *TSInfo = NameInfo.getNamedTypeInfo())
435 return DiagnoseUnexpandedParameterPack(NameInfo.getLoc(), TSInfo, UPPC);
436
437 if (!NameInfo.getName().getCXXNameType()->containsUnexpandedParameterPack())
Douglas Gregorc4356532010-12-16 00:46:58 +0000438 return false;
Douglas Gregor6ab34af2010-12-16 01:40:04 +0000439
Douglas Gregorc4356532010-12-16 00:46:58 +0000440 break;
441 }
442
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000443 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
Douglas Gregorc4356532010-12-16 00:46:58 +0000444 CollectUnexpandedParameterPacksVisitor(Unexpanded)
Douglas Gregor6ab34af2010-12-16 01:40:04 +0000445 .TraverseType(NameInfo.getName().getCXXNameType());
Douglas Gregorc4356532010-12-16 00:46:58 +0000446 assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
Richard Smith2589b9802012-07-25 03:56:55 +0000447 return DiagnoseUnexpandedParameterPacks(NameInfo.getLoc(), UPPC, Unexpanded);
Douglas Gregorc4356532010-12-16 00:46:58 +0000448}
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000449
450bool Sema::DiagnoseUnexpandedParameterPack(SourceLocation Loc,
451 TemplateName Template,
452 UnexpandedParameterPackContext UPPC) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000453
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000454 if (Template.isNull() || !Template.containsUnexpandedParameterPack())
455 return false;
456
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000457 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000458 CollectUnexpandedParameterPacksVisitor(Unexpanded)
459 .TraverseTemplateName(Template);
460 assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
Richard Smith2589b9802012-07-25 03:56:55 +0000461 return DiagnoseUnexpandedParameterPacks(Loc, UPPC, Unexpanded);
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000462}
463
Douglas Gregor14406932011-01-03 20:35:03 +0000464bool Sema::DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg,
465 UnexpandedParameterPackContext UPPC) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000466 if (Arg.getArgument().isNull() ||
Douglas Gregor14406932011-01-03 20:35:03 +0000467 !Arg.getArgument().containsUnexpandedParameterPack())
468 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +0000469
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000470 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
Douglas Gregor14406932011-01-03 20:35:03 +0000471 CollectUnexpandedParameterPacksVisitor(Unexpanded)
472 .TraverseTemplateArgumentLoc(Arg);
473 assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
Richard Smith2589b9802012-07-25 03:56:55 +0000474 return DiagnoseUnexpandedParameterPacks(Arg.getLocation(), UPPC, Unexpanded);
Douglas Gregor14406932011-01-03 20:35:03 +0000475}
476
Douglas Gregor0f3feb42010-12-22 21:19:48 +0000477void Sema::collectUnexpandedParameterPacks(TemplateArgument Arg,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000478 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
Douglas Gregor0f3feb42010-12-22 21:19:48 +0000479 CollectUnexpandedParameterPacksVisitor(Unexpanded)
480 .TraverseTemplateArgument(Arg);
481}
482
Douglas Gregor840bd6c2010-12-20 22:05:00 +0000483void Sema::collectUnexpandedParameterPacks(TemplateArgumentLoc Arg,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000484 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
Douglas Gregor840bd6c2010-12-20 22:05:00 +0000485 CollectUnexpandedParameterPacksVisitor(Unexpanded)
486 .TraverseTemplateArgumentLoc(Arg);
487}
488
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000489void Sema::collectUnexpandedParameterPacks(QualType T,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000490 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000491 CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseType(T);
492}
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000493
Douglas Gregor752a5952011-01-03 22:36:02 +0000494void Sema::collectUnexpandedParameterPacks(TypeLoc TL,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000495 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000496 CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseTypeLoc(TL);
Richard Smith22a250c2016-12-19 04:08:53 +0000497}
498
Richard Smith151c4562016-12-20 21:35:28 +0000499void Sema::collectUnexpandedParameterPacks(
500 NestedNameSpecifierLoc NNS,
501 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
502 CollectUnexpandedParameterPacksVisitor(Unexpanded)
503 .TraverseNestedNameSpecifierLoc(NNS);
504}
505
506void Sema::collectUnexpandedParameterPacks(
507 const DeclarationNameInfo &NameInfo,
508 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
Douglas Gregor4a2a8f72011-10-25 03:44:56 +0000509 CollectUnexpandedParameterPacksVisitor(Unexpanded)
510 .TraverseDeclarationNameInfo(NameInfo);
511}
512
513
Fangrui Song6907ce22018-07-30 19:24:48 +0000514ParsedTemplateArgument
Douglas Gregord2fa7662010-12-20 02:24:11 +0000515Sema::ActOnPackExpansion(const ParsedTemplateArgument &Arg,
516 SourceLocation EllipsisLoc) {
517 if (Arg.isInvalid())
518 return Arg;
519
520 switch (Arg.getKind()) {
521 case ParsedTemplateArgument::Type: {
522 TypeResult Result = ActOnPackExpansion(Arg.getAsType(), EllipsisLoc);
523 if (Result.isInvalid())
524 return ParsedTemplateArgument();
525
Fangrui Song6907ce22018-07-30 19:24:48 +0000526 return ParsedTemplateArgument(Arg.getKind(), Result.get().getAsOpaquePtr(),
Douglas Gregord2fa7662010-12-20 02:24:11 +0000527 Arg.getLocation());
528 }
529
Douglas Gregore8e9dd62011-01-03 17:17:50 +0000530 case ParsedTemplateArgument::NonType: {
531 ExprResult Result = ActOnPackExpansion(Arg.getAsExpr(), EllipsisLoc);
532 if (Result.isInvalid())
533 return ParsedTemplateArgument();
Fangrui Song6907ce22018-07-30 19:24:48 +0000534
535 return ParsedTemplateArgument(Arg.getKind(), Result.get(),
Douglas Gregore8e9dd62011-01-03 17:17:50 +0000536 Arg.getLocation());
537 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000538
Douglas Gregord2fa7662010-12-20 02:24:11 +0000539 case ParsedTemplateArgument::Template:
Douglas Gregoreb29d182011-01-05 17:40:24 +0000540 if (!Arg.getAsTemplate().get().containsUnexpandedParameterPack()) {
541 SourceRange R(Arg.getLocation());
542 if (Arg.getScopeSpec().isValid())
543 R.setBegin(Arg.getScopeSpec().getBeginLoc());
544 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
545 << R;
546 return ParsedTemplateArgument();
547 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000548
Douglas Gregoreb29d182011-01-05 17:40:24 +0000549 return Arg.getTemplatePackExpansion(EllipsisLoc);
Douglas Gregord2fa7662010-12-20 02:24:11 +0000550 }
551 llvm_unreachable("Unhandled template argument kind?");
Douglas Gregord2fa7662010-12-20 02:24:11 +0000552}
553
Fangrui Song6907ce22018-07-30 19:24:48 +0000554TypeResult Sema::ActOnPackExpansion(ParsedType Type,
Douglas Gregord2fa7662010-12-20 02:24:11 +0000555 SourceLocation EllipsisLoc) {
556 TypeSourceInfo *TSInfo;
557 GetTypeFromParser(Type, &TSInfo);
558 if (!TSInfo)
559 return true;
560
David Blaikie7a30dc52013-02-21 01:47:18 +0000561 TypeSourceInfo *TSResult = CheckPackExpansion(TSInfo, EllipsisLoc, None);
Douglas Gregor840bd6c2010-12-20 22:05:00 +0000562 if (!TSResult)
563 return true;
Fangrui Song6907ce22018-07-30 19:24:48 +0000564
Douglas Gregor840bd6c2010-12-20 22:05:00 +0000565 return CreateParsedType(TSResult->getType(), TSResult);
566}
567
David Blaikie05785d12013-02-20 22:23:23 +0000568TypeSourceInfo *
569Sema::CheckPackExpansion(TypeSourceInfo *Pattern, SourceLocation EllipsisLoc,
570 Optional<unsigned> NumExpansions) {
Douglas Gregord2fa7662010-12-20 02:24:11 +0000571 // Create the pack expansion type and source-location information.
Fangrui Song6907ce22018-07-30 19:24:48 +0000572 QualType Result = CheckPackExpansion(Pattern->getType(),
Douglas Gregor822d0302011-01-12 17:07:58 +0000573 Pattern->getTypeLoc().getSourceRange(),
Douglas Gregor0dca5fd2011-01-14 17:04:44 +0000574 EllipsisLoc, NumExpansions);
Douglas Gregor822d0302011-01-12 17:07:58 +0000575 if (Result.isNull())
Craig Topperc3ec1492014-05-26 06:22:03 +0000576 return nullptr;
Eli Friedman7152fbe2013-06-07 20:31:48 +0000577
578 TypeLocBuilder TLB;
579 TLB.pushFullCopy(Pattern->getTypeLoc());
580 PackExpansionTypeLoc TL = TLB.push<PackExpansionTypeLoc>(Result);
Douglas Gregord2fa7662010-12-20 02:24:11 +0000581 TL.setEllipsisLoc(EllipsisLoc);
Eli Friedman7152fbe2013-06-07 20:31:48 +0000582
583 return TLB.getTypeSourceInfo(Context, Result);
Douglas Gregord2fa7662010-12-20 02:24:11 +0000584}
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000585
David Blaikie05785d12013-02-20 22:23:23 +0000586QualType Sema::CheckPackExpansion(QualType Pattern, SourceRange PatternRange,
Douglas Gregor0dca5fd2011-01-14 17:04:44 +0000587 SourceLocation EllipsisLoc,
David Blaikie05785d12013-02-20 22:23:23 +0000588 Optional<unsigned> NumExpansions) {
Richard Smithb2997f52019-05-21 20:10:50 +0000589 // C++11 [temp.variadic]p5:
Douglas Gregor822d0302011-01-12 17:07:58 +0000590 // The pattern of a pack expansion shall name one or more
591 // parameter packs that are not expanded by a nested pack
592 // expansion.
Richard Smithb2997f52019-05-21 20:10:50 +0000593 //
594 // A pattern containing a deduced type can't occur "naturally" but arises in
595 // the desugaring of an init-capture pack.
596 if (!Pattern->containsUnexpandedParameterPack() &&
597 !Pattern->getContainedDeducedType()) {
Douglas Gregor822d0302011-01-12 17:07:58 +0000598 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
599 << PatternRange;
600 return QualType();
601 }
602
Douglas Gregor0dca5fd2011-01-14 17:04:44 +0000603 return Context.getPackExpansionType(Pattern, NumExpansions);
Douglas Gregor822d0302011-01-12 17:07:58 +0000604}
605
Douglas Gregore8e9dd62011-01-03 17:17:50 +0000606ExprResult Sema::ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc) {
David Blaikie7a30dc52013-02-21 01:47:18 +0000607 return CheckPackExpansion(Pattern, EllipsisLoc, None);
Douglas Gregorb8840002011-01-14 21:20:45 +0000608}
609
610ExprResult Sema::CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
David Blaikie05785d12013-02-20 22:23:23 +0000611 Optional<unsigned> NumExpansions) {
Douglas Gregore8e9dd62011-01-03 17:17:50 +0000612 if (!Pattern)
613 return ExprError();
Fangrui Song6907ce22018-07-30 19:24:48 +0000614
Douglas Gregore8e9dd62011-01-03 17:17:50 +0000615 // C++0x [temp.variadic]p5:
616 // The pattern of a pack expansion shall name one or more
617 // parameter packs that are not expanded by a nested pack
618 // expansion.
619 if (!Pattern->containsUnexpandedParameterPack()) {
620 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
621 << Pattern->getSourceRange();
622 return ExprError();
623 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000624
Douglas Gregore8e9dd62011-01-03 17:17:50 +0000625 // Create the pack expansion expression and source-location information.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000626 return new (Context)
627 PackExpansionExpr(Context.DependentTy, Pattern, EllipsisLoc, NumExpansions);
Douglas Gregore8e9dd62011-01-03 17:17:50 +0000628}
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000629
David Blaikie05785d12013-02-20 22:23:23 +0000630bool Sema::CheckParameterPacksForExpansion(
631 SourceLocation EllipsisLoc, SourceRange PatternRange,
632 ArrayRef<UnexpandedParameterPack> Unexpanded,
633 const MultiLevelTemplateArgumentList &TemplateArgs, bool &ShouldExpand,
634 bool &RetainExpansion, Optional<unsigned> &NumExpansions) {
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000635 ShouldExpand = true;
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000636 RetainExpansion = false;
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000637 std::pair<IdentifierInfo *, SourceLocation> FirstPack;
638 bool HaveFirstPack = false;
Richard Smith4a8f3512018-07-19 19:00:37 +0000639 Optional<unsigned> NumPartialExpansions;
640 SourceLocation PartiallySubstitutedPackLoc;
641
David Blaikieb9c168a2011-09-22 02:34:54 +0000642 for (ArrayRef<UnexpandedParameterPack>::iterator i = Unexpanded.begin(),
643 end = Unexpanded.end();
644 i != end; ++i) {
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000645 // Compute the depth and index for this parameter pack.
Ted Kremenek582a0992011-01-23 17:04:59 +0000646 unsigned Depth = 0, Index = 0;
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000647 IdentifierInfo *Name;
Richard Smithb2997f52019-05-21 20:10:50 +0000648 bool IsVarDeclPack = false;
Fangrui Song6907ce22018-07-30 19:24:48 +0000649
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000650 if (const TemplateTypeParmType *TTP
David Blaikieb9c168a2011-09-22 02:34:54 +0000651 = i->first.dyn_cast<const TemplateTypeParmType *>()) {
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000652 Depth = TTP->getDepth();
653 Index = TTP->getIndex();
Chandler Carruthdde65ea2011-05-01 01:05:51 +0000654 Name = TTP->getIdentifier();
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000655 } else {
David Blaikieb9c168a2011-09-22 02:34:54 +0000656 NamedDecl *ND = i->first.get<NamedDecl *>();
Richard Smithb2997f52019-05-21 20:10:50 +0000657 if (isa<VarDecl>(ND))
658 IsVarDeclPack = true;
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000659 else
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000660 std::tie(Depth, Index) = getDepthAndIndex(ND);
661
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000662 Name = ND->getIdentifier();
663 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000664
Douglas Gregorf3010112011-01-07 16:43:16 +0000665 // Determine the size of this argument pack.
Fangrui Song6907ce22018-07-30 19:24:48 +0000666 unsigned NewPackSize;
Richard Smithb2997f52019-05-21 20:10:50 +0000667 if (IsVarDeclPack) {
Douglas Gregorf3010112011-01-07 16:43:16 +0000668 // Figure out whether we're instantiating to an argument pack or not.
669 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
Fangrui Song6907ce22018-07-30 19:24:48 +0000670
Douglas Gregorf3010112011-01-07 16:43:16 +0000671 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Instantiation
672 = CurrentInstantiationScope->findInstantiationOf(
David Blaikieb9c168a2011-09-22 02:34:54 +0000673 i->first.get<NamedDecl *>());
Chris Lattner15a776f2011-02-17 19:38:27 +0000674 if (Instantiation->is<DeclArgumentPack *>()) {
Douglas Gregorf3010112011-01-07 16:43:16 +0000675 // We could expand this function parameter pack.
676 NewPackSize = Instantiation->get<DeclArgumentPack *>()->size();
677 } else {
678 // We can't expand this function parameter pack, so we can't expand
679 // the pack expansion.
680 ShouldExpand = false;
681 continue;
682 }
683 } else {
Fangrui Song6907ce22018-07-30 19:24:48 +0000684 // If we don't have a template argument at this depth/index, then we
685 // cannot expand the pack expansion. Make a note of this, but we still
Douglas Gregorf3010112011-01-07 16:43:16 +0000686 // want to check any parameter packs we *do* have arguments for.
687 if (Depth >= TemplateArgs.getNumLevels() ||
688 !TemplateArgs.hasTemplateArgument(Depth, Index)) {
689 ShouldExpand = false;
690 continue;
691 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000692
Douglas Gregorf3010112011-01-07 16:43:16 +0000693 // Determine the size of the argument pack.
694 NewPackSize = TemplateArgs(Depth, Index).pack_size();
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000695 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000696
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000697 // C++0x [temp.arg.explicit]p9:
Fangrui Song6907ce22018-07-30 19:24:48 +0000698 // Template argument deduction can extend the sequence of template
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000699 // arguments corresponding to a template parameter pack, even when the
700 // sequence contains explicitly specified template arguments.
Richard Smithb2997f52019-05-21 20:10:50 +0000701 if (!IsVarDeclPack && CurrentInstantiationScope) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000702 if (NamedDecl *PartialPack
Douglas Gregor63dad4d2011-01-20 23:15:49 +0000703 = CurrentInstantiationScope->getPartiallySubstitutedPack()){
704 unsigned PartialDepth, PartialIndex;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000705 std::tie(PartialDepth, PartialIndex) = getDepthAndIndex(PartialPack);
Richard Smith4a8f3512018-07-19 19:00:37 +0000706 if (PartialDepth == Depth && PartialIndex == Index) {
Douglas Gregor63dad4d2011-01-20 23:15:49 +0000707 RetainExpansion = true;
Richard Smith4a8f3512018-07-19 19:00:37 +0000708 // We don't actually know the new pack size yet.
709 NumPartialExpansions = NewPackSize;
710 PartiallySubstitutedPackLoc = i->second;
711 continue;
712 }
Douglas Gregor63dad4d2011-01-20 23:15:49 +0000713 }
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000714 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000715
Douglas Gregor0dca5fd2011-01-14 17:04:44 +0000716 if (!NumExpansions) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000717 // The is the first pack we've seen for which we have an argument.
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000718 // Record it.
719 NumExpansions = NewPackSize;
720 FirstPack.first = Name;
David Blaikieb9c168a2011-09-22 02:34:54 +0000721 FirstPack.second = i->second;
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000722 HaveFirstPack = true;
723 continue;
724 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000725
Douglas Gregor0dca5fd2011-01-14 17:04:44 +0000726 if (NewPackSize != *NumExpansions) {
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000727 // C++0x [temp.variadic]p5:
Fangrui Song6907ce22018-07-30 19:24:48 +0000728 // All of the parameter packs expanded by a pack expansion shall have
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000729 // the same number of arguments specified.
Douglas Gregor0dca5fd2011-01-14 17:04:44 +0000730 if (HaveFirstPack)
731 Diag(EllipsisLoc, diag::err_pack_expansion_length_conflict)
732 << FirstPack.first << Name << *NumExpansions << NewPackSize
David Blaikieb9c168a2011-09-22 02:34:54 +0000733 << SourceRange(FirstPack.second) << SourceRange(i->second);
Douglas Gregor0dca5fd2011-01-14 17:04:44 +0000734 else
735 Diag(EllipsisLoc, diag::err_pack_expansion_length_conflict_multilevel)
736 << Name << *NumExpansions << NewPackSize
David Blaikieb9c168a2011-09-22 02:34:54 +0000737 << SourceRange(i->second);
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000738 return true;
739 }
740 }
Richard Smithc5452ed2016-10-19 22:18:42 +0000741
Richard Smith4a8f3512018-07-19 19:00:37 +0000742 // If we're performing a partial expansion but we also have a full expansion,
743 // expand to the number of common arguments. For example, given:
744 //
745 // template<typename ...T> struct A {
746 // template<typename ...U> void f(pair<T, U>...);
747 // };
748 //
749 // ... a call to 'A<int, int>().f<int>' should expand the pack once and
750 // retain an expansion.
751 if (NumPartialExpansions) {
752 if (NumExpansions && *NumExpansions < *NumPartialExpansions) {
753 NamedDecl *PartialPack =
754 CurrentInstantiationScope->getPartiallySubstitutedPack();
755 Diag(EllipsisLoc, diag::err_pack_expansion_length_conflict_partial)
756 << PartialPack << *NumPartialExpansions << *NumExpansions
757 << SourceRange(PartiallySubstitutedPackLoc);
758 return true;
759 }
760
761 NumExpansions = NumPartialExpansions;
762 }
763
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000764 return false;
765}
Douglas Gregor27b4c162010-12-23 22:44:42 +0000766
David Blaikie05785d12013-02-20 22:23:23 +0000767Optional<unsigned> Sema::getNumArgumentsInExpansion(QualType T,
Douglas Gregor5cde3862011-01-11 03:14:20 +0000768 const MultiLevelTemplateArgumentList &TemplateArgs) {
769 QualType Pattern = cast<PackExpansionType>(T)->getPattern();
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000770 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
Douglas Gregor5cde3862011-01-11 03:14:20 +0000771 CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseType(Pattern);
772
David Blaikie05785d12013-02-20 22:23:23 +0000773 Optional<unsigned> Result;
Douglas Gregor5cde3862011-01-11 03:14:20 +0000774 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
775 // Compute the depth and index for this parameter pack.
776 unsigned Depth;
777 unsigned Index;
Fangrui Song6907ce22018-07-30 19:24:48 +0000778
Douglas Gregor5cde3862011-01-11 03:14:20 +0000779 if (const TemplateTypeParmType *TTP
780 = Unexpanded[I].first.dyn_cast<const TemplateTypeParmType *>()) {
781 Depth = TTP->getDepth();
782 Index = TTP->getIndex();
Fangrui Song6907ce22018-07-30 19:24:48 +0000783 } else {
Douglas Gregor5cde3862011-01-11 03:14:20 +0000784 NamedDecl *ND = Unexpanded[I].first.get<NamedDecl *>();
Richard Smithb2997f52019-05-21 20:10:50 +0000785 if (isa<VarDecl>(ND)) {
786 // Function parameter pack or init-capture pack.
Douglas Gregor5cde3862011-01-11 03:14:20 +0000787 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
Fangrui Song6907ce22018-07-30 19:24:48 +0000788
Douglas Gregor5cde3862011-01-11 03:14:20 +0000789 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Instantiation
790 = CurrentInstantiationScope->findInstantiationOf(
791 Unexpanded[I].first.get<NamedDecl *>());
Richard Smith198223b2012-07-18 01:29:05 +0000792 if (Instantiation->is<Decl*>())
793 // The pattern refers to an unexpanded pack. We're not ready to expand
794 // this pack yet.
David Blaikie7a30dc52013-02-21 01:47:18 +0000795 return None;
Richard Smith198223b2012-07-18 01:29:05 +0000796
797 unsigned Size = Instantiation->get<DeclArgumentPack *>()->size();
798 assert((!Result || *Result == Size) && "inconsistent pack sizes");
799 Result = Size;
Douglas Gregor5cde3862011-01-11 03:14:20 +0000800 continue;
801 }
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000802
803 std::tie(Depth, Index) = getDepthAndIndex(ND);
Douglas Gregor5cde3862011-01-11 03:14:20 +0000804 }
805 if (Depth >= TemplateArgs.getNumLevels() ||
806 !TemplateArgs.hasTemplateArgument(Depth, Index))
Richard Smith198223b2012-07-18 01:29:05 +0000807 // The pattern refers to an unknown template argument. We're not ready to
808 // expand this pack yet.
David Blaikie7a30dc52013-02-21 01:47:18 +0000809 return None;
Fangrui Song6907ce22018-07-30 19:24:48 +0000810
Douglas Gregor5cde3862011-01-11 03:14:20 +0000811 // Determine the size of the argument pack.
Richard Smith198223b2012-07-18 01:29:05 +0000812 unsigned Size = TemplateArgs(Depth, Index).pack_size();
813 assert((!Result || *Result == Size) && "inconsistent pack sizes");
814 Result = Size;
Douglas Gregor5cde3862011-01-11 03:14:20 +0000815 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000816
Richard Smith198223b2012-07-18 01:29:05 +0000817 return Result;
Douglas Gregor5cde3862011-01-11 03:14:20 +0000818}
819
Douglas Gregor27b4c162010-12-23 22:44:42 +0000820bool Sema::containsUnexpandedParameterPacks(Declarator &D) {
821 const DeclSpec &DS = D.getDeclSpec();
822 switch (DS.getTypeSpecType()) {
Faisal Vali090da2d2018-01-01 18:23:28 +0000823 case TST_typename:
824 case TST_typeofType:
825 case TST_underlyingType:
826 case TST_atomic: {
Douglas Gregor27b4c162010-12-23 22:44:42 +0000827 QualType T = DS.getRepAsType().get();
828 if (!T.isNull() && T->containsUnexpandedParameterPack())
829 return true;
830 break;
831 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000832
Faisal Vali090da2d2018-01-01 18:23:28 +0000833 case TST_typeofExpr:
834 case TST_decltype:
Fangrui Song6907ce22018-07-30 19:24:48 +0000835 if (DS.getRepAsExpr() &&
Douglas Gregor27b4c162010-12-23 22:44:42 +0000836 DS.getRepAsExpr()->containsUnexpandedParameterPack())
837 return true;
838 break;
Fangrui Song6907ce22018-07-30 19:24:48 +0000839
Faisal Vali090da2d2018-01-01 18:23:28 +0000840 case TST_unspecified:
841 case TST_void:
842 case TST_char:
843 case TST_wchar:
Richard Smith3a8244d2018-05-01 05:02:45 +0000844 case TST_char8:
Faisal Vali090da2d2018-01-01 18:23:28 +0000845 case TST_char16:
846 case TST_char32:
847 case TST_int:
848 case TST_int128:
849 case TST_half:
850 case TST_float:
851 case TST_double:
Leonard Chanf921d852018-06-04 16:07:52 +0000852 case TST_Accum:
Leonard Chanab80f3c2018-06-14 14:53:51 +0000853 case TST_Fract:
Faisal Vali090da2d2018-01-01 18:23:28 +0000854 case TST_Float16:
855 case TST_float128:
856 case TST_bool:
857 case TST_decimal32:
858 case TST_decimal64:
859 case TST_decimal128:
860 case TST_enum:
861 case TST_union:
862 case TST_struct:
863 case TST_interface:
864 case TST_class:
865 case TST_auto:
866 case TST_auto_type:
867 case TST_decltype_auto:
868#define GENERIC_IMAGE_TYPE(ImgType, Id) case TST_##ImgType##_t:
Alexey Baderb62f1442016-04-13 08:33:41 +0000869#include "clang/Basic/OpenCLImageTypes.def"
Faisal Vali090da2d2018-01-01 18:23:28 +0000870 case TST_unknown_anytype:
871 case TST_error:
Douglas Gregor27b4c162010-12-23 22:44:42 +0000872 break;
873 }
Larisse Voufo2e846502014-08-29 21:08:16 +0000874
Douglas Gregor27b4c162010-12-23 22:44:42 +0000875 for (unsigned I = 0, N = D.getNumTypeObjects(); I != N; ++I) {
876 const DeclaratorChunk &Chunk = D.getTypeObject(I);
877 switch (Chunk.Kind) {
878 case DeclaratorChunk::Pointer:
879 case DeclaratorChunk::Reference:
880 case DeclaratorChunk::Paren:
Xiuli Pan9c14e282016-01-09 12:53:17 +0000881 case DeclaratorChunk::Pipe:
Larisse Voufo2e846502014-08-29 21:08:16 +0000882 case DeclaratorChunk::BlockPointer:
Douglas Gregor27b4c162010-12-23 22:44:42 +0000883 // These declarator chunks cannot contain any parameter packs.
884 break;
Fangrui Song6907ce22018-07-30 19:24:48 +0000885
Douglas Gregor27b4c162010-12-23 22:44:42 +0000886 case DeclaratorChunk::Array:
Larisse Voufo2e846502014-08-29 21:08:16 +0000887 if (Chunk.Arr.NumElts &&
888 Chunk.Arr.NumElts->containsUnexpandedParameterPack())
889 return true;
890 break;
Douglas Gregor27b4c162010-12-23 22:44:42 +0000891 case DeclaratorChunk::Function:
Larisse Voufo2e846502014-08-29 21:08:16 +0000892 for (unsigned i = 0, e = Chunk.Fun.NumParams; i != e; ++i) {
893 ParmVarDecl *Param = cast<ParmVarDecl>(Chunk.Fun.Params[i].Param);
894 QualType ParamTy = Param->getType();
895 assert(!ParamTy.isNull() && "Couldn't parse type?");
896 if (ParamTy->containsUnexpandedParameterPack()) return true;
897 }
898
899 if (Chunk.Fun.getExceptionSpecType() == EST_Dynamic) {
Reid Kleckner078aea92016-12-09 17:14:05 +0000900 for (unsigned i = 0; i != Chunk.Fun.getNumExceptions(); ++i) {
Larisse Voufo2e846502014-08-29 21:08:16 +0000901 if (Chunk.Fun.Exceptions[i]
902 .Ty.get()
903 ->containsUnexpandedParameterPack())
904 return true;
905 }
Richard Smitheaf11ad2018-05-03 03:58:32 +0000906 } else if (isComputedNoexcept(Chunk.Fun.getExceptionSpecType()) &&
Larisse Voufo2e846502014-08-29 21:08:16 +0000907 Chunk.Fun.NoexceptExpr->containsUnexpandedParameterPack())
908 return true;
909
Nico Weber8d26b722014-12-30 02:06:40 +0000910 if (Chunk.Fun.hasTrailingReturnType()) {
911 QualType T = Chunk.Fun.getTrailingReturnType().get();
Fangrui Song99337e22018-07-20 08:19:20 +0000912 if (!T.isNull() && T->containsUnexpandedParameterPack())
913 return true;
Nico Weber8d26b722014-12-30 02:06:40 +0000914 }
Larisse Voufo2e846502014-08-29 21:08:16 +0000915 break;
916
Douglas Gregor27b4c162010-12-23 22:44:42 +0000917 case DeclaratorChunk::MemberPointer:
918 if (Chunk.Mem.Scope().getScopeRep() &&
919 Chunk.Mem.Scope().getScopeRep()->containsUnexpandedParameterPack())
920 return true;
921 break;
922 }
923 }
Fangrui Song99337e22018-07-20 08:19:20 +0000924
Douglas Gregor27b4c162010-12-23 22:44:42 +0000925 return false;
926}
Douglas Gregor820ba7b2011-01-04 17:33:58 +0000927
Kaelyn Uhrain637b5b32012-01-13 23:10:36 +0000928namespace {
929
930// Callback to only accept typo corrections that refer to parameter packs.
Bruno Ricci70ad3962019-03-25 17:08:51 +0000931class ParameterPackValidatorCCC final : public CorrectionCandidateCallback {
Kaelyn Uhrain637b5b32012-01-13 23:10:36 +0000932 public:
Craig Toppere14c0f82014-03-12 04:55:44 +0000933 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhrain637b5b32012-01-13 23:10:36 +0000934 NamedDecl *ND = candidate.getCorrectionDecl();
935 return ND && ND->isParameterPack();
936 }
Bruno Ricci70ad3962019-03-25 17:08:51 +0000937
938 std::unique_ptr<CorrectionCandidateCallback> clone() override {
939 return llvm::make_unique<ParameterPackValidatorCCC>(*this);
940 }
Kaelyn Uhrain637b5b32012-01-13 23:10:36 +0000941};
942
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000943}
Kaelyn Uhrain637b5b32012-01-13 23:10:36 +0000944
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000945/// Called when an expression computing the size of a parameter pack
Douglas Gregor820ba7b2011-01-04 17:33:58 +0000946/// is parsed.
947///
948/// \code
949/// template<typename ...Types> struct count {
950/// static const unsigned value = sizeof...(Types);
951/// };
952/// \endcode
953///
954//
955/// \param OpLoc The location of the "sizeof" keyword.
956/// \param Name The name of the parameter pack whose size will be determined.
957/// \param NameLoc The source location of the name of the parameter pack.
958/// \param RParenLoc The location of the closing parentheses.
959ExprResult Sema::ActOnSizeofParameterPackExpr(Scope *S,
960 SourceLocation OpLoc,
961 IdentifierInfo &Name,
962 SourceLocation NameLoc,
963 SourceLocation RParenLoc) {
964 // C++0x [expr.sizeof]p5:
965 // The identifier in a sizeof... expression shall name a parameter pack.
Douglas Gregor820ba7b2011-01-04 17:33:58 +0000966 LookupResult R(*this, &Name, NameLoc, LookupOrdinaryName);
967 LookupName(R, S);
Craig Topperc3ec1492014-05-26 06:22:03 +0000968
969 NamedDecl *ParameterPack = nullptr;
Douglas Gregor820ba7b2011-01-04 17:33:58 +0000970 switch (R.getResultKind()) {
971 case LookupResult::Found:
972 ParameterPack = R.getFoundDecl();
973 break;
Fangrui Song6907ce22018-07-30 19:24:48 +0000974
Douglas Gregor820ba7b2011-01-04 17:33:58 +0000975 case LookupResult::NotFound:
Bruno Ricci70ad3962019-03-25 17:08:51 +0000976 case LookupResult::NotFoundInCurrentInstantiation: {
977 ParameterPackValidatorCCC CCC{};
Kaelyn Takata89c881b2014-10-27 18:07:29 +0000978 if (TypoCorrection Corrected =
979 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, nullptr,
Bruno Ricci70ad3962019-03-25 17:08:51 +0000980 CCC, CTK_ErrorRecovery)) {
Richard Smithf9b15102013-08-17 00:46:16 +0000981 diagnoseTypo(Corrected,
982 PDiag(diag::err_sizeof_pack_no_pack_name_suggest) << &Name,
983 PDiag(diag::note_parameter_pack_here));
Kaelyn Uhrain637b5b32012-01-13 23:10:36 +0000984 ParameterPack = Corrected.getCorrectionDecl();
Douglas Gregor820ba7b2011-01-04 17:33:58 +0000985 }
Reid Kleckner4dc0b1a2018-11-01 19:54:45 +0000986 break;
Bruno Ricci70ad3962019-03-25 17:08:51 +0000987 }
Douglas Gregor820ba7b2011-01-04 17:33:58 +0000988 case LookupResult::FoundOverloaded:
989 case LookupResult::FoundUnresolvedValue:
990 break;
Fangrui Song99337e22018-07-20 08:19:20 +0000991
Douglas Gregor820ba7b2011-01-04 17:33:58 +0000992 case LookupResult::Ambiguous:
993 DiagnoseAmbiguousLookup(R);
994 return ExprError();
995 }
Fangrui Song99337e22018-07-20 08:19:20 +0000996
Douglas Gregor3c6bd2a2011-01-05 21:11:38 +0000997 if (!ParameterPack || !ParameterPack->isParameterPack()) {
Douglas Gregor820ba7b2011-01-04 17:33:58 +0000998 Diag(NameLoc, diag::err_sizeof_pack_no_pack_name)
999 << &Name;
1000 return ExprError();
1001 }
1002
Nick Lewycky45b50522013-02-02 00:25:55 +00001003 MarkAnyDeclReferenced(OpLoc, ParameterPack, true);
Eli Friedman23b1be92012-03-01 21:32:56 +00001004
Richard Smithd784e682015-09-23 21:41:42 +00001005 return SizeOfPackExpr::Create(Context, OpLoc, ParameterPack, NameLoc,
1006 RParenLoc);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00001007}
Eli Friedman94e9eaa2013-06-20 04:11:21 +00001008
1009TemplateArgumentLoc
1010Sema::getTemplateArgumentPackExpansionPattern(
1011 TemplateArgumentLoc OrigLoc,
1012 SourceLocation &Ellipsis, Optional<unsigned> &NumExpansions) const {
1013 const TemplateArgument &Argument = OrigLoc.getArgument();
1014 assert(Argument.isPackExpansion());
1015 switch (Argument.getKind()) {
1016 case TemplateArgument::Type: {
1017 // FIXME: We shouldn't ever have to worry about missing
1018 // type-source info!
1019 TypeSourceInfo *ExpansionTSInfo = OrigLoc.getTypeSourceInfo();
1020 if (!ExpansionTSInfo)
1021 ExpansionTSInfo = Context.getTrivialTypeSourceInfo(Argument.getAsType(),
1022 Ellipsis);
1023 PackExpansionTypeLoc Expansion =
1024 ExpansionTSInfo->getTypeLoc().castAs<PackExpansionTypeLoc>();
1025 Ellipsis = Expansion.getEllipsisLoc();
1026
1027 TypeLoc Pattern = Expansion.getPatternLoc();
1028 NumExpansions = Expansion.getTypePtr()->getNumExpansions();
1029
1030 // We need to copy the TypeLoc because TemplateArgumentLocs store a
1031 // TypeSourceInfo.
1032 // FIXME: Find some way to avoid the copy?
1033 TypeLocBuilder TLB;
1034 TLB.pushFullCopy(Pattern);
1035 TypeSourceInfo *PatternTSInfo =
1036 TLB.getTypeSourceInfo(Context, Pattern.getType());
1037 return TemplateArgumentLoc(TemplateArgument(Pattern.getType()),
1038 PatternTSInfo);
1039 }
1040
1041 case TemplateArgument::Expression: {
1042 PackExpansionExpr *Expansion
1043 = cast<PackExpansionExpr>(Argument.getAsExpr());
1044 Expr *Pattern = Expansion->getPattern();
1045 Ellipsis = Expansion->getEllipsisLoc();
1046 NumExpansions = Expansion->getNumExpansions();
1047 return TemplateArgumentLoc(Pattern, Pattern);
1048 }
1049
1050 case TemplateArgument::TemplateExpansion:
1051 Ellipsis = OrigLoc.getTemplateEllipsisLoc();
1052 NumExpansions = Argument.getNumTemplateExpansions();
1053 return TemplateArgumentLoc(Argument.getPackExpansionPattern(),
1054 OrigLoc.getTemplateQualifierLoc(),
1055 OrigLoc.getTemplateNameLoc());
1056
1057 case TemplateArgument::Declaration:
1058 case TemplateArgument::NullPtr:
1059 case TemplateArgument::Template:
1060 case TemplateArgument::Integral:
1061 case TemplateArgument::Pack:
1062 case TemplateArgument::Null:
1063 return TemplateArgumentLoc();
1064 }
1065
1066 llvm_unreachable("Invalid TemplateArgument Kind!");
1067}
Richard Smith0f0af192014-11-08 05:07:16 +00001068
Richard Smithc5452ed2016-10-19 22:18:42 +00001069Optional<unsigned> Sema::getFullyPackExpandedSize(TemplateArgument Arg) {
1070 assert(Arg.containsUnexpandedParameterPack());
1071
1072 // If this is a substituted pack, grab that pack. If not, we don't know
1073 // the size yet.
1074 // FIXME: We could find a size in more cases by looking for a substituted
1075 // pack anywhere within this argument, but that's not necessary in the common
1076 // case for 'sizeof...(A)' handling.
1077 TemplateArgument Pack;
1078 switch (Arg.getKind()) {
1079 case TemplateArgument::Type:
1080 if (auto *Subst = Arg.getAsType()->getAs<SubstTemplateTypeParmPackType>())
1081 Pack = Subst->getArgumentPack();
1082 else
1083 return None;
1084 break;
1085
1086 case TemplateArgument::Expression:
1087 if (auto *Subst =
1088 dyn_cast<SubstNonTypeTemplateParmPackExpr>(Arg.getAsExpr()))
1089 Pack = Subst->getArgumentPack();
1090 else if (auto *Subst = dyn_cast<FunctionParmPackExpr>(Arg.getAsExpr())) {
Richard Smithb2997f52019-05-21 20:10:50 +00001091 for (VarDecl *PD : *Subst)
Richard Smithc5452ed2016-10-19 22:18:42 +00001092 if (PD->isParameterPack())
1093 return None;
1094 return Subst->getNumExpansions();
1095 } else
1096 return None;
1097 break;
1098
1099 case TemplateArgument::Template:
1100 if (SubstTemplateTemplateParmPackStorage *Subst =
1101 Arg.getAsTemplate().getAsSubstTemplateTemplateParmPack())
1102 Pack = Subst->getArgumentPack();
1103 else
1104 return None;
1105 break;
1106
1107 case TemplateArgument::Declaration:
1108 case TemplateArgument::NullPtr:
1109 case TemplateArgument::TemplateExpansion:
1110 case TemplateArgument::Integral:
1111 case TemplateArgument::Pack:
1112 case TemplateArgument::Null:
1113 return None;
1114 }
1115
1116 // Check that no argument in the pack is itself a pack expansion.
1117 for (TemplateArgument Elem : Pack.pack_elements()) {
1118 // There's no point recursing in this case; we would have already
1119 // expanded this pack expansion into the enclosing pack if we could.
1120 if (Elem.isPackExpansion())
1121 return None;
1122 }
1123 return Pack.pack_size();
1124}
1125
Richard Smith0f0af192014-11-08 05:07:16 +00001126static void CheckFoldOperand(Sema &S, Expr *E) {
1127 if (!E)
1128 return;
1129
1130 E = E->IgnoreImpCasts();
Richard Smith66094432016-10-20 00:55:15 +00001131 auto *OCE = dyn_cast<CXXOperatorCallExpr>(E);
1132 if ((OCE && OCE->isInfixBinaryOp()) || isa<BinaryOperator>(E) ||
1133 isa<AbstractConditionalOperator>(E)) {
Richard Smith0f0af192014-11-08 05:07:16 +00001134 S.Diag(E->getExprLoc(), diag::err_fold_expression_bad_operand)
1135 << E->getSourceRange()
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001136 << FixItHint::CreateInsertion(E->getBeginLoc(), "(")
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001137 << FixItHint::CreateInsertion(E->getEndLoc(), ")");
Richard Smith0f0af192014-11-08 05:07:16 +00001138 }
1139}
1140
1141ExprResult Sema::ActOnCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
1142 tok::TokenKind Operator,
1143 SourceLocation EllipsisLoc, Expr *RHS,
1144 SourceLocation RParenLoc) {
1145 // LHS and RHS must be cast-expressions. We allow an arbitrary expression
1146 // in the parser and reduce down to just cast-expressions here.
1147 CheckFoldOperand(*this, LHS);
1148 CheckFoldOperand(*this, RHS);
1149
Richard Smith90e043d2017-02-15 19:57:10 +00001150 auto DiscardOperands = [&] {
1151 CorrectDelayedTyposInExpr(LHS);
1152 CorrectDelayedTyposInExpr(RHS);
1153 };
1154
Richard Smith0f0af192014-11-08 05:07:16 +00001155 // [expr.prim.fold]p3:
1156 // In a binary fold, op1 and op2 shall be the same fold-operator, and
1157 // either e1 shall contain an unexpanded parameter pack or e2 shall contain
1158 // an unexpanded parameter pack, but not both.
1159 if (LHS && RHS &&
1160 LHS->containsUnexpandedParameterPack() ==
1161 RHS->containsUnexpandedParameterPack()) {
Richard Smith90e043d2017-02-15 19:57:10 +00001162 DiscardOperands();
Richard Smith0f0af192014-11-08 05:07:16 +00001163 return Diag(EllipsisLoc,
1164 LHS->containsUnexpandedParameterPack()
1165 ? diag::err_fold_expression_packs_both_sides
1166 : diag::err_pack_expansion_without_parameter_packs)
1167 << LHS->getSourceRange() << RHS->getSourceRange();
1168 }
1169
1170 // [expr.prim.fold]p2:
1171 // In a unary fold, the cast-expression shall contain an unexpanded
1172 // parameter pack.
1173 if (!LHS || !RHS) {
1174 Expr *Pack = LHS ? LHS : RHS;
1175 assert(Pack && "fold expression with neither LHS nor RHS");
Richard Smith90e043d2017-02-15 19:57:10 +00001176 DiscardOperands();
Richard Smith0f0af192014-11-08 05:07:16 +00001177 if (!Pack->containsUnexpandedParameterPack())
1178 return Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1179 << Pack->getSourceRange();
1180 }
1181
1182 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Operator);
Richard Smithc7214f62019-05-13 08:31:14 +00001183 return BuildCXXFoldExpr(LParenLoc, LHS, Opc, EllipsisLoc, RHS, RParenLoc,
1184 None);
Richard Smith0f0af192014-11-08 05:07:16 +00001185}
1186
1187ExprResult Sema::BuildCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
1188 BinaryOperatorKind Operator,
1189 SourceLocation EllipsisLoc, Expr *RHS,
Richard Smithc7214f62019-05-13 08:31:14 +00001190 SourceLocation RParenLoc,
1191 Optional<unsigned> NumExpansions) {
Richard Smith0f0af192014-11-08 05:07:16 +00001192 return new (Context) CXXFoldExpr(Context.DependentTy, LParenLoc, LHS,
Richard Smithc7214f62019-05-13 08:31:14 +00001193 Operator, EllipsisLoc, RHS, RParenLoc,
1194 NumExpansions);
Richard Smith0f0af192014-11-08 05:07:16 +00001195}
1196
1197ExprResult Sema::BuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc,
1198 BinaryOperatorKind Operator) {
1199 // [temp.variadic]p9:
1200 // If N is zero for a unary fold-expression, the value of the expression is
Richard Smith0f0af192014-11-08 05:07:16 +00001201 // && -> true
1202 // || -> false
1203 // , -> void()
1204 // if the operator is not listed [above], the instantiation is ill-formed.
1205 //
1206 // Note that we need to use something like int() here, not merely 0, to
1207 // prevent the result from being a null pointer constant.
1208 QualType ScalarType;
1209 switch (Operator) {
Richard Smith0f0af192014-11-08 05:07:16 +00001210 case BO_LOr:
1211 return ActOnCXXBoolLiteral(EllipsisLoc, tok::kw_false);
1212 case BO_LAnd:
1213 return ActOnCXXBoolLiteral(EllipsisLoc, tok::kw_true);
1214 case BO_Comma:
1215 ScalarType = Context.VoidTy;
1216 break;
1217
1218 default:
1219 return Diag(EllipsisLoc, diag::err_fold_expression_empty)
1220 << BinaryOperator::getOpcodeStr(Operator);
1221 }
1222
1223 return new (Context) CXXScalarValueInitExpr(
1224 ScalarType, Context.getTrivialTypeSourceInfo(ScalarType, EllipsisLoc),
1225 EllipsisLoc);
1226}