1//===------- SemaTemplateVariadic.cpp - C++ Variadic Templates ------------===/
2//
3// 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
6//===----------------------------------------------------------------------===/
7//
8// This file implements semantic analysis for C++0x variadic templates.
9//===----------------------------------------------------------------------===/
10
11#include "TypeLocBuilder.h"
12#include "clang/AST/DynamicRecursiveASTVisitor.h"
13#include "clang/AST/Expr.h"
14#include "clang/AST/ExprObjC.h"
15#include "clang/AST/TypeLoc.h"
16#include "clang/Sema/Lookup.h"
17#include "clang/Sema/ParsedAttr.h"
18#include "clang/Sema/ParsedTemplate.h"
19#include "clang/Sema/ScopeInfo.h"
20#include "clang/Sema/Sema.h"
21#include "clang/Sema/SemaInternal.h"
22#include "clang/Sema/Template.h"
23#include "llvm/Support/SaveAndRestore.h"
24#include <optional>
25
26using namespace clang;
27
28//----------------------------------------------------------------------------
29// Visitor that collects unexpanded parameter packs
30//----------------------------------------------------------------------------
31
32namespace {
33 /// A class that collects unexpanded parameter packs.
34class CollectUnexpandedParameterPacksVisitor
35 : public DynamicRecursiveASTVisitor {
36 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded;
37
38 bool InLambdaOrBlock = false;
39 unsigned DepthLimit = (unsigned)-1;
40
41#ifndef NDEBUG
42 bool ContainsIntermediatePacks = false;
43#endif
44
45 void addUnexpanded(NamedDecl *ND, SourceLocation Loc = SourceLocation()) {
46 if (auto *VD = dyn_cast<VarDecl>(Val: ND)) {
47 // For now, the only problematic case is a generic lambda's templated
48 // call operator, so we don't need to look for all the other ways we
49 // could have reached a dependent parameter pack.
50 auto *FD = dyn_cast<FunctionDecl>(Val: VD->getDeclContext());
51 auto *FTD = FD ? FD->getDescribedFunctionTemplate() : nullptr;
52 if (FTD && FTD->getTemplateParameters()->getDepth() >= DepthLimit)
53 return;
54 } else if (ND->isTemplateParameterPack() &&
55 getDepthAndIndex(ND).first >= DepthLimit) {
56 return;
57 }
58
59 Unexpanded.push_back(Elt: {ND, Loc});
60 }
61
62 void addUnexpanded(const TemplateTypeParmType *T,
63 SourceLocation Loc = SourceLocation()) {
64 if (T->getDepth() < DepthLimit)
65 Unexpanded.push_back(Elt: {T, Loc});
66 }
67
68 bool addUnexpanded(const SubstBuiltinTemplatePackType *T,
69 SourceLocation Loc = SourceLocation()) {
70 Unexpanded.push_back(Elt: {T, Loc});
71 return true;
72 }
73
74 bool addUnexpanded(const TemplateSpecializationType *T,
75 SourceLocation Loc = SourceLocation()) {
76 assert(T->isCanonicalUnqualified() &&
77 isPackProducingBuiltinTemplateName(T->getTemplateName()));
78 Unexpanded.push_back(Elt: {T, Loc});
79 return true;
80 }
81
82 /// Returns true iff it handled the traversal. On false, the callers must
83 /// traverse themselves.
84 bool
85 TryTraverseSpecializationProducingPacks(const TemplateSpecializationType *T,
86 SourceLocation Loc) {
87 if (!isPackProducingBuiltinTemplateName(N: T->getTemplateName()))
88 return false;
89 // Canonical types are inputs to the initial substitution. Report them and
90 // do not recurse any further.
91 if (T->isCanonicalUnqualified()) {
92 addUnexpanded(T, Loc);
93 return true;
94 }
95 // For sugared types, do not use the default traversal as it would be
96 // looking at (now irrelevant) template arguments. Instead, look at the
97 // result of substitution, it usually contains SubstPackType that needs to
98 // be expanded further.
99 DynamicRecursiveASTVisitor::TraverseType(T: T->desugar());
100 return true;
101 }
102
103 public:
104 explicit CollectUnexpandedParameterPacksVisitor(
105 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded)
106 : Unexpanded(Unexpanded) {
107 ShouldWalkTypesOfTypeLocs = false;
108
109 // We need this so we can find e.g. attributes on lambdas.
110 ShouldVisitImplicitCode = true;
111 }
112
113 //------------------------------------------------------------------------
114 // Recording occurrences of (unexpanded) parameter packs.
115 //------------------------------------------------------------------------
116
117 /// Record occurrences of template type parameter packs.
118 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) override {
119 if (TL.getTypePtr()->isParameterPack())
120 addUnexpanded(T: TL.getTypePtr(), Loc: TL.getNameLoc());
121 return true;
122 }
123
124 /// Record occurrences of template type parameter packs
125 /// when we don't have proper source-location information for
126 /// them.
127 ///
128 /// Ideally, this routine would never be used.
129 bool VisitTemplateTypeParmType(TemplateTypeParmType *T) override {
130 if (T->isParameterPack())
131 addUnexpanded(T);
132
133 return true;
134 }
135
136 /// Record occurrences of function and non-type template
137 /// parameter packs in an expression.
138 bool VisitDeclRefExpr(DeclRefExpr *E) override {
139 if (E->getDecl()->isParameterPack())
140 addUnexpanded(ND: E->getDecl(), Loc: E->getLocation());
141
142 return true;
143 }
144
145 /// Record occurrences of template template parameter packs.
146 bool TraverseTemplateName(TemplateName Template,
147 bool TraverseQualifier = true) override {
148
149 if (PackIndexingTemplateStorage *PI =
150 Template.getAsPackIndexingTemplate())
151 return DynamicRecursiveASTVisitor::TraverseStmt(S: PI->getIndexExpr());
152
153 if (auto *TTP = dyn_cast_or_null<TemplateTemplateParmDecl>(
154 Val: Template.getAsTemplateDecl())) {
155 if (TTP->isParameterPack())
156 addUnexpanded(ND: TTP);
157 }
158
159#ifndef NDEBUG
160 ContainsIntermediatePacks |=
161 (bool)Template.getAsSubstTemplateTemplateParmPack();
162#endif
163
164 return DynamicRecursiveASTVisitor::TraverseTemplateName(
165 Template, TraverseQualifier);
166 }
167
168 bool
169 TraverseTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc T,
170 bool TraverseQualifier) override {
171 if (TryTraverseSpecializationProducingPacks(T: T.getTypePtr(),
172 Loc: T.getBeginLoc()))
173 return true;
174 return DynamicRecursiveASTVisitor::TraverseTemplateSpecializationTypeLoc(
175 TL: T, TraverseQualifier);
176 }
177
178 bool TraverseTemplateSpecializationType(TemplateSpecializationType *T,
179 bool TraverseQualfier) override {
180 if (TryTraverseSpecializationProducingPacks(T, Loc: SourceLocation()))
181 return true;
182 return DynamicRecursiveASTVisitor::TraverseTemplateSpecializationType(T);
183 }
184
185 /// Suppress traversal into Objective-C container literal
186 /// elements that are pack expansions.
187 bool TraverseObjCDictionaryLiteral(ObjCDictionaryLiteral *E) override {
188 if (!E->containsUnexpandedParameterPack())
189 return true;
190
191 for (unsigned I = 0, N = E->getNumElements(); I != N; ++I) {
192 ObjCDictionaryElement Element = E->getKeyValueElement(Index: I);
193 if (Element.isPackExpansion())
194 continue;
195
196 TraverseStmt(S: Element.Key);
197 TraverseStmt(S: Element.Value);
198 }
199 return true;
200 }
201 //------------------------------------------------------------------------
202 // Pruning the search for unexpanded parameter packs.
203 //------------------------------------------------------------------------
204
205 /// Suppress traversal into statements and expressions that
206 /// do not contain unexpanded parameter packs.
207 bool TraverseStmt(Stmt *S) override {
208 Expr *E = dyn_cast_or_null<Expr>(Val: S);
209 if ((E && E->containsUnexpandedParameterPack()) || InLambdaOrBlock)
210 return DynamicRecursiveASTVisitor::TraverseStmt(S);
211
212 return true;
213 }
214
215 /// Suppress traversal into types that do not contain
216 /// unexpanded parameter packs.
217 bool TraverseType(QualType T, bool TraverseQualifier = true) override {
218 if ((!T.isNull() && T->containsUnexpandedParameterPack()) ||
219 InLambdaOrBlock)
220 return DynamicRecursiveASTVisitor::TraverseType(T, TraverseQualifier);
221
222 return true;
223 }
224
225 /// Suppress traversal into types with location information
226 /// that do not contain unexpanded parameter packs.
227 bool TraverseTypeLoc(TypeLoc TL, bool TraverseQualifier = true) override {
228 if ((!TL.getType().isNull() &&
229 TL.getType()->containsUnexpandedParameterPack()) ||
230 InLambdaOrBlock)
231 return DynamicRecursiveASTVisitor::TraverseTypeLoc(TL,
232 TraverseQualifier);
233
234 return true;
235 }
236
237 /// Suppress traversal of parameter packs.
238 bool TraverseDecl(Decl *D) override {
239 // A function parameter pack is a pack expansion, so cannot contain
240 // an unexpanded parameter pack. Likewise for a template parameter
241 // pack that contains any references to other packs.
242 if (D && D->isParameterPack())
243 return true;
244
245 return DynamicRecursiveASTVisitor::TraverseDecl(D);
246 }
247
248 /// Suppress traversal of pack-expanded attributes.
249 bool TraverseAttr(Attr *A) override {
250 if (A->isPackExpansion())
251 return true;
252
253 return DynamicRecursiveASTVisitor::TraverseAttr(At: A);
254 }
255
256 /// Suppress traversal of pack expansion expressions and types.
257 ///@{
258 bool TraversePackExpansionType(PackExpansionType *T,
259 bool TraverseQualifier) override {
260 return true;
261 }
262 bool TraversePackExpansionTypeLoc(PackExpansionTypeLoc TL,
263 bool TraverseQualifier) override {
264 return true;
265 }
266 bool TraversePackExpansionExpr(PackExpansionExpr *E) override {
267 return true;
268 }
269 bool TraverseCXXFoldExpr(CXXFoldExpr *E) override { return true; }
270 bool TraversePackIndexingExpr(PackIndexingExpr *E) override {
271 return DynamicRecursiveASTVisitor::TraverseStmt(S: E->getIndexExpr());
272 }
273 bool TraversePackIndexingType(PackIndexingType *E,
274 bool TraverseQualifier) override {
275 return DynamicRecursiveASTVisitor::TraverseStmt(S: E->getIndexExpr());
276 }
277 bool TraversePackIndexingTypeLoc(PackIndexingTypeLoc TL,
278 bool TraverseQualifier) override {
279 return DynamicRecursiveASTVisitor::TraverseStmt(S: TL.getIndexExpr());
280 }
281
282 ///@}
283
284 /// Suppress traversal of using-declaration pack expansion.
285 bool
286 TraverseUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) override {
287 if (D->isPackExpansion())
288 return true;
289
290 return DynamicRecursiveASTVisitor::TraverseUnresolvedUsingValueDecl(D);
291 }
292
293 /// Suppress traversal of using-declaration pack expansion.
294 bool TraverseUnresolvedUsingTypenameDecl(
295 UnresolvedUsingTypenameDecl *D) override {
296 if (D->isPackExpansion())
297 return true;
298
299 return DynamicRecursiveASTVisitor::TraverseUnresolvedUsingTypenameDecl(D);
300 }
301
302 /// Suppress traversal of template argument pack expansions.
303 bool TraverseTemplateArgument(const TemplateArgument &Arg) override {
304 if (Arg.isPackExpansion())
305 return true;
306
307 return DynamicRecursiveASTVisitor::TraverseTemplateArgument(Arg);
308 }
309
310 /// Suppress traversal of template argument pack expansions.
311 bool
312 TraverseTemplateArgumentLoc(const TemplateArgumentLoc &ArgLoc) override {
313 if (ArgLoc.getArgument().isPackExpansion())
314 return true;
315
316 return DynamicRecursiveASTVisitor::TraverseTemplateArgumentLoc(ArgLoc);
317 }
318
319 /// Suppress traversal of base specifier pack expansions.
320 bool TraverseCXXBaseSpecifier(const CXXBaseSpecifier &Base) override {
321 if (Base.isPackExpansion())
322 return true;
323
324 return DynamicRecursiveASTVisitor::TraverseCXXBaseSpecifier(Base);
325 }
326
327 /// Suppress traversal of mem-initializer pack expansions.
328 bool TraverseConstructorInitializer(CXXCtorInitializer *Init) override {
329 if (Init->isPackExpansion())
330 return true;
331
332 return DynamicRecursiveASTVisitor::TraverseConstructorInitializer(Init);
333 }
334
335 /// Note whether we're traversing a lambda containing an unexpanded
336 /// parameter pack. In this case, the unexpanded pack can occur anywhere,
337 /// including all the places where we normally wouldn't look. Within a
338 /// lambda, we don't propagate the 'contains unexpanded parameter pack' bit
339 /// outside an expression.
340 bool TraverseLambdaExpr(LambdaExpr *Lambda) override {
341 // The ContainsUnexpandedParameterPack bit on a lambda is always correct,
342 // even if it's contained within another lambda.
343 if (!Lambda->containsUnexpandedParameterPack())
344 return true;
345
346 SaveAndRestore _(InLambdaOrBlock, true);
347 unsigned OldDepthLimit = DepthLimit;
348
349 if (auto *TPL = Lambda->getTemplateParameterList())
350 DepthLimit = TPL->getDepth();
351
352 DynamicRecursiveASTVisitor::TraverseLambdaExpr(S: Lambda);
353
354 DepthLimit = OldDepthLimit;
355 return true;
356 }
357
358 /// Analogously for blocks.
359 bool TraverseBlockExpr(BlockExpr *Block) override {
360 if (!Block->containsUnexpandedParameterPack())
361 return true;
362
363 SaveAndRestore _(InLambdaOrBlock, true);
364 DynamicRecursiveASTVisitor::TraverseBlockExpr(S: Block);
365 return true;
366 }
367
368 /// Suppress traversal within pack expansions in lambda captures.
369 bool TraverseLambdaCapture(LambdaExpr *Lambda, const LambdaCapture *C,
370 Expr *Init) override {
371 if (C->isPackExpansion())
372 return true;
373
374 return DynamicRecursiveASTVisitor::TraverseLambdaCapture(LE: Lambda, C, Init);
375 }
376
377 bool TraverseUnresolvedLookupExpr(UnresolvedLookupExpr *E) override {
378 if (E->getNumDecls() == 1) {
379 NamedDecl *ND = *E->decls_begin();
380 if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Val: ND);
381 TTP && TTP->isParameterPack())
382 addUnexpanded(ND, Loc: E->getBeginLoc());
383 }
384 return DynamicRecursiveASTVisitor::TraverseUnresolvedLookupExpr(S: E);
385 }
386
387 bool TraverseSubstBuiltinTemplatePackType(SubstBuiltinTemplatePackType *T,
388 bool TraverseQualifier) override {
389 addUnexpanded(T);
390 // Do not call into base implementation to supress traversal of the
391 // substituted types.
392 return true;
393 }
394
395#ifndef NDEBUG
396 bool TraverseFunctionParmPackExpr(FunctionParmPackExpr *) override {
397 ContainsIntermediatePacks = true;
398 return true;
399 }
400
401 bool TraverseSubstNonTypeTemplateParmPackExpr(
402 SubstNonTypeTemplateParmPackExpr *) override {
403 ContainsIntermediatePacks = true;
404 return true;
405 }
406
407 bool VisitSubstTemplateTypeParmPackType(
408 SubstTemplateTypeParmPackType *) override {
409 ContainsIntermediatePacks = true;
410 return true;
411 }
412
413 bool VisitSubstTemplateTypeParmPackTypeLoc(
414 SubstTemplateTypeParmPackTypeLoc) override {
415 ContainsIntermediatePacks = true;
416 return true;
417 }
418
419 bool containsIntermediatePacks() const { return ContainsIntermediatePacks; }
420#endif
421};
422}
423
424/// Determine whether it's possible for an unexpanded parameter pack to
425/// be valid in this location. This only happens when we're in a declaration
426/// that is nested within an expression that could be expanded, such as a
427/// lambda-expression within a function call.
428///
429/// This is conservatively correct, but may claim that some unexpanded packs are
430/// permitted when they are not.
431bool Sema::isUnexpandedParameterPackPermitted() {
432 for (auto *SI : FunctionScopes)
433 if (isa<sema::LambdaScopeInfo>(Val: SI))
434 return true;
435 return false;
436}
437
438/// Diagnose all of the unexpanded parameter packs in the given
439/// vector.
440bool
441Sema::DiagnoseUnexpandedParameterPacks(SourceLocation Loc,
442 UnexpandedParameterPackContext UPPC,
443 ArrayRef<UnexpandedParameterPack> Unexpanded) {
444 if (Unexpanded.empty())
445 return false;
446
447 // If we are within a lambda expression and referencing a pack that is not
448 // declared within the lambda itself, that lambda contains an unexpanded
449 // parameter pack, and we are done. Analogously for blocks.
450 // FIXME: Store 'Unexpanded' on the lambda so we don't need to recompute it
451 // later.
452 SmallVector<UnexpandedParameterPack, 4> ParamPackReferences;
453 if (sema::CapturingScopeInfo *CSI = getEnclosingLambdaOrBlock()) {
454 for (auto &Pack : Unexpanded) {
455 auto DeclaresThisPack = [&](NamedDecl *LocalPack) {
456 if (auto *TTPT = Pack.first.dyn_cast<const TemplateTypeParmType *>()) {
457 auto *TTPD = dyn_cast<TemplateTypeParmDecl>(Val: LocalPack);
458 return TTPD && TTPD->getTypeForDecl() == TTPT;
459 }
460 return declaresSameEntity(D1: cast<NamedDecl *>(Val: Pack.first), D2: LocalPack);
461 };
462 if (llvm::any_of(Range&: CSI->LocalPacks, P: DeclaresThisPack))
463 ParamPackReferences.push_back(Elt: Pack);
464 }
465
466 if (ParamPackReferences.empty()) {
467 // Construct in lambda only references packs declared outside the lambda.
468 // That's OK for now, but the lambda itself is considered to contain an
469 // unexpanded pack in this case, which will require expansion outside the
470 // lambda.
471
472 // We do not permit pack expansion that would duplicate a statement
473 // expression, not even within a lambda.
474 // FIXME: We could probably support this for statement expressions that
475 // do not contain labels.
476 // FIXME: This is insufficient to detect this problem; consider
477 // f( ({ bad: 0; }) + pack ... );
478 bool EnclosingStmtExpr = false;
479 for (unsigned N = FunctionScopes.size(); N; --N) {
480 sema::FunctionScopeInfo *Func = FunctionScopes[N-1];
481 if (llvm::any_of(
482 Range&: Func->CompoundScopes,
483 P: [](sema::CompoundScopeInfo &CSI) { return CSI.IsStmtExpr; })) {
484 EnclosingStmtExpr = true;
485 break;
486 }
487 // Coumpound-statements outside the lambda are OK for now; we'll check
488 // for those when we finish handling the lambda.
489 if (Func == CSI)
490 break;
491 }
492
493 if (!EnclosingStmtExpr) {
494 CSI->ContainsUnexpandedParameterPack = true;
495 return false;
496 }
497 } else {
498 Unexpanded = ParamPackReferences;
499 }
500 }
501
502 SmallVector<SourceLocation, 4> Locations;
503 SmallVector<IdentifierInfo *, 4> Names;
504 llvm::SmallPtrSet<IdentifierInfo *, 4> NamesKnown;
505
506 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
507 IdentifierInfo *Name = nullptr;
508 if (const TemplateTypeParmType *TTP
509 = Unexpanded[I].first.dyn_cast<const TemplateTypeParmType *>())
510 Name = TTP->getIdentifier();
511 else if (NamedDecl *ND = Unexpanded[I].first.dyn_cast<NamedDecl *>())
512 Name = ND->getIdentifier();
513
514 if (Name && NamesKnown.insert(Ptr: Name).second)
515 Names.push_back(Elt: Name);
516
517 if (Unexpanded[I].second.isValid())
518 Locations.push_back(Elt: Unexpanded[I].second);
519 }
520
521 auto DB = Diag(Loc, DiagID: diag::err_unexpanded_parameter_pack)
522 << (int)UPPC << (int)Names.size();
523 for (size_t I = 0, E = std::min(a: Names.size(), b: (size_t)2); I != E; ++I)
524 DB << Names[I];
525
526 for (unsigned I = 0, N = Locations.size(); I != N; ++I)
527 DB << SourceRange(Locations[I]);
528 return true;
529}
530
531bool Sema::DiagnoseUnexpandedParameterPack(SourceLocation Loc,
532 TypeSourceInfo *T,
533 UnexpandedParameterPackContext UPPC) {
534 // C++0x [temp.variadic]p5:
535 // An appearance of a name of a parameter pack that is not expanded is
536 // ill-formed.
537 if (!T->getType()->containsUnexpandedParameterPack())
538 return false;
539
540 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
541 CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseTypeLoc(
542 TL: T->getTypeLoc());
543 assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
544 return DiagnoseUnexpandedParameterPacks(Loc, UPPC, Unexpanded);
545}
546
547bool Sema::DiagnoseUnexpandedParameterPack(Expr *E,
548 UnexpandedParameterPackContext UPPC) {
549 // C++0x [temp.variadic]p5:
550 // An appearance of a name of a parameter pack that is not expanded is
551 // ill-formed.
552 if (!E->containsUnexpandedParameterPack())
553 return false;
554
555 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
556 CollectUnexpandedParameterPacksVisitor Visitor(Unexpanded);
557 Visitor.TraverseStmt(S: E);
558#ifndef NDEBUG
559 // The expression might contain a type/subexpression that has been substituted
560 // but has the expansion held off, e.g. a FunctionParmPackExpr which a larger
561 // CXXFoldExpr would expand. It's only possible when expanding a lambda as a
562 // pattern of a fold expression, so don't fire on an empty result in that
563 // case.
564 bool LambdaReferencingOuterPacks =
565 getEnclosingLambdaOrBlock() && Visitor.containsIntermediatePacks();
566 assert((!Unexpanded.empty() || LambdaReferencingOuterPacks) &&
567 "Unable to find unexpanded parameter packs");
568#endif
569 return DiagnoseUnexpandedParameterPacks(Loc: E->getBeginLoc(), UPPC, Unexpanded);
570}
571
572bool Sema::DiagnoseUnexpandedParameterPackInRequiresExpr(RequiresExpr *RE) {
573 if (!RE->containsUnexpandedParameterPack())
574 return false;
575
576 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
577 CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseStmt(S: RE);
578 assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
579
580 // We only care about unexpanded references to the RequiresExpr's own
581 // parameter packs.
582 auto Parms = RE->getLocalParameters();
583 llvm::SmallPtrSet<NamedDecl *, 8> ParmSet(llvm::from_range, Parms);
584 SmallVector<UnexpandedParameterPack, 2> UnexpandedParms;
585 for (auto Parm : Unexpanded)
586 if (ParmSet.contains(Ptr: Parm.first.dyn_cast<NamedDecl *>()))
587 UnexpandedParms.push_back(Elt: Parm);
588 if (UnexpandedParms.empty())
589 return false;
590
591 return DiagnoseUnexpandedParameterPacks(Loc: RE->getBeginLoc(), UPPC: UPPC_Requirement,
592 Unexpanded: UnexpandedParms);
593}
594
595bool Sema::DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS,
596 UnexpandedParameterPackContext UPPC) {
597 // C++0x [temp.variadic]p5:
598 // An appearance of a name of a parameter pack that is not expanded is
599 // ill-formed.
600 if (!SS.getScopeRep().containsUnexpandedParameterPack())
601 return false;
602
603 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
604 CollectUnexpandedParameterPacksVisitor(Unexpanded)
605 .TraverseNestedNameSpecifier(NNS: SS.getScopeRep());
606 assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
607 return DiagnoseUnexpandedParameterPacks(Loc: SS.getRange().getBegin(),
608 UPPC, Unexpanded);
609}
610
611bool Sema::DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo,
612 UnexpandedParameterPackContext UPPC) {
613 // C++0x [temp.variadic]p5:
614 // An appearance of a name of a parameter pack that is not expanded is
615 // ill-formed.
616 switch (NameInfo.getName().getNameKind()) {
617 case DeclarationName::Identifier:
618 case DeclarationName::ObjCZeroArgSelector:
619 case DeclarationName::ObjCOneArgSelector:
620 case DeclarationName::ObjCMultiArgSelector:
621 case DeclarationName::CXXOperatorName:
622 case DeclarationName::CXXLiteralOperatorName:
623 case DeclarationName::CXXUsingDirective:
624 case DeclarationName::CXXDeductionGuideName:
625 return false;
626
627 case DeclarationName::CXXConstructorName:
628 case DeclarationName::CXXDestructorName:
629 case DeclarationName::CXXConversionFunctionName:
630 // FIXME: We shouldn't need this null check!
631 if (TypeSourceInfo *TSInfo = NameInfo.getNamedTypeInfo())
632 return DiagnoseUnexpandedParameterPack(Loc: NameInfo.getLoc(), T: TSInfo, UPPC);
633
634 if (!NameInfo.getName().getCXXNameType()->containsUnexpandedParameterPack())
635 return false;
636
637 break;
638 }
639
640 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
641 CollectUnexpandedParameterPacksVisitor(Unexpanded)
642 .TraverseType(T: NameInfo.getName().getCXXNameType());
643 assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
644 return DiagnoseUnexpandedParameterPacks(Loc: NameInfo.getLoc(), UPPC, Unexpanded);
645}
646
647bool Sema::DiagnoseUnexpandedParameterPack(SourceLocation Loc,
648 TemplateName Template,
649 UnexpandedParameterPackContext UPPC) {
650
651 if (Template.isNull() || !Template.containsUnexpandedParameterPack())
652 return false;
653
654 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
655 CollectUnexpandedParameterPacksVisitor(Unexpanded)
656 .TraverseTemplateName(Template);
657 assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
658 return DiagnoseUnexpandedParameterPacks(Loc, UPPC, Unexpanded);
659}
660
661bool Sema::DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg,
662 UnexpandedParameterPackContext UPPC) {
663 if (Arg.getArgument().isNull() ||
664 !Arg.getArgument().containsUnexpandedParameterPack())
665 return false;
666
667 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
668 CollectUnexpandedParameterPacksVisitor(Unexpanded)
669 .TraverseTemplateArgumentLoc(ArgLoc: Arg);
670 assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
671 return DiagnoseUnexpandedParameterPacks(Loc: Arg.getLocation(), UPPC, Unexpanded);
672}
673
674void Sema::collectUnexpandedParameterPacks(TemplateArgument Arg,
675 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
676 CollectUnexpandedParameterPacksVisitor(Unexpanded)
677 .TraverseTemplateArgument(Arg);
678}
679
680void Sema::collectUnexpandedParameterPacks(TemplateArgumentLoc Arg,
681 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
682 CollectUnexpandedParameterPacksVisitor(Unexpanded)
683 .TraverseTemplateArgumentLoc(ArgLoc: Arg);
684}
685
686void Sema::collectUnexpandedParameterPacks(QualType T,
687 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
688 CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseType(T);
689}
690
691void Sema::collectUnexpandedParameterPacks(
692 TemplateName Template,
693 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
694 CollectUnexpandedParameterPacksVisitor(Unexpanded)
695 .TraverseTemplateName(Template);
696}
697
698void Sema::collectUnexpandedParameterPacks(TypeLoc TL,
699 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
700 CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseTypeLoc(TL);
701}
702
703void Sema::collectUnexpandedParameterPacks(
704 NestedNameSpecifierLoc NNS,
705 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
706 CollectUnexpandedParameterPacksVisitor(Unexpanded)
707 .TraverseNestedNameSpecifierLoc(NNS);
708}
709
710void Sema::collectUnexpandedParameterPacks(
711 const DeclarationNameInfo &NameInfo,
712 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
713 CollectUnexpandedParameterPacksVisitor(Unexpanded)
714 .TraverseDeclarationNameInfo(NameInfo);
715}
716
717void Sema::collectUnexpandedParameterPacks(
718 Expr *E, SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
719 CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseStmt(S: E);
720}
721
722ParsedTemplateArgument
723Sema::ActOnTemplateTemplateArgument(const ParsedTemplateArgument &Arg) {
724 if (Arg.isInvalid())
725 return Arg;
726
727 // We do not allow to reference builtin templates that produce multiple
728 // values, they would not have a well-defined semantics outside template
729 // arguments.
730 auto *T = dyn_cast_or_null<BuiltinTemplateDecl>(
731 Val: Arg.getAsTemplate().get().getAsTemplateDecl());
732 if (T && T->isPackProducingBuiltinTemplate())
733 diagnoseMissingTemplateArguments(Name: Arg.getAsTemplate().get(),
734 Loc: Arg.getNameLoc());
735
736 return Arg;
737}
738
739ParsedTemplateArgument
740Sema::ActOnPackExpansion(const ParsedTemplateArgument &Arg,
741 SourceLocation EllipsisLoc) {
742 if (Arg.isInvalid())
743 return Arg;
744
745 switch (Arg.getKind()) {
746 case ParsedTemplateArgument::Type: {
747 TypeResult Result = ActOnPackExpansion(Type: Arg.getAsType(), EllipsisLoc);
748 if (Result.isInvalid())
749 return ParsedTemplateArgument();
750
751 return ParsedTemplateArgument(Arg.getKind(), Result.get().getAsOpaquePtr(),
752 Arg.getNameLoc());
753 }
754
755 case ParsedTemplateArgument::NonType: {
756 ExprResult Result = ActOnPackExpansion(Pattern: Arg.getAsExpr(), EllipsisLoc);
757 if (Result.isInvalid())
758 return ParsedTemplateArgument();
759
760 return ParsedTemplateArgument(Arg.getKind(), Result.get(),
761 Arg.getNameLoc());
762 }
763
764 case ParsedTemplateArgument::Template:
765 if (!Arg.getAsTemplate().get().containsUnexpandedParameterPack()) {
766 SourceRange R(Arg.getNameLoc());
767 if (Arg.getScopeSpec().isValid())
768 R.setBegin(Arg.getScopeSpec().getBeginLoc());
769 Diag(Loc: EllipsisLoc, DiagID: diag::err_pack_expansion_without_parameter_packs)
770 << R;
771 return ParsedTemplateArgument();
772 }
773
774 return Arg.getTemplatePackExpansion(EllipsisLoc);
775 }
776 llvm_unreachable("Unhandled template argument kind?");
777}
778
779TypeResult Sema::ActOnPackExpansion(ParsedType Type,
780 SourceLocation EllipsisLoc) {
781 TypeSourceInfo *TSInfo;
782 GetTypeFromParser(Ty: Type, TInfo: &TSInfo);
783 if (!TSInfo)
784 return true;
785
786 TypeSourceInfo *TSResult =
787 CheckPackExpansion(Pattern: TSInfo, EllipsisLoc, NumExpansions: std::nullopt);
788 if (!TSResult)
789 return true;
790
791 return CreateParsedType(T: TSResult->getType(), TInfo: TSResult);
792}
793
794TypeSourceInfo *Sema::CheckPackExpansion(TypeSourceInfo *Pattern,
795 SourceLocation EllipsisLoc,
796 UnsignedOrNone NumExpansions) {
797 // Create the pack expansion type and source-location information.
798 QualType Result = CheckPackExpansion(Pattern: Pattern->getType(),
799 PatternRange: Pattern->getTypeLoc().getSourceRange(),
800 EllipsisLoc, NumExpansions);
801 if (Result.isNull())
802 return nullptr;
803
804 TypeLocBuilder TLB;
805 TLB.pushFullCopy(L: Pattern->getTypeLoc());
806 PackExpansionTypeLoc TL = TLB.push<PackExpansionTypeLoc>(T: Result);
807 TL.setEllipsisLoc(EllipsisLoc);
808
809 return TLB.getTypeSourceInfo(Context, T: Result);
810}
811
812QualType Sema::CheckPackExpansion(QualType Pattern, SourceRange PatternRange,
813 SourceLocation EllipsisLoc,
814 UnsignedOrNone NumExpansions) {
815 // C++11 [temp.variadic]p5:
816 // The pattern of a pack expansion shall name one or more
817 // parameter packs that are not expanded by a nested pack
818 // expansion.
819 //
820 // A pattern containing a deduced type can't occur "naturally" but arises in
821 // the desugaring of an init-capture pack.
822 if (!Pattern->containsUnexpandedParameterPack() &&
823 !Pattern->getContainedDeducedType()) {
824 Diag(Loc: EllipsisLoc, DiagID: diag::err_pack_expansion_without_parameter_packs)
825 << PatternRange;
826 return QualType();
827 }
828
829 return Context.getPackExpansionType(Pattern, NumExpansions,
830 /*ExpectPackInType=*/false);
831}
832
833ExprResult Sema::ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc) {
834 return CheckPackExpansion(Pattern, EllipsisLoc, NumExpansions: std::nullopt);
835}
836
837ExprResult Sema::CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
838 UnsignedOrNone NumExpansions) {
839 if (!Pattern)
840 return ExprError();
841
842 // C++0x [temp.variadic]p5:
843 // The pattern of a pack expansion shall name one or more
844 // parameter packs that are not expanded by a nested pack
845 // expansion.
846 if (!Pattern->containsUnexpandedParameterPack()) {
847 Diag(Loc: EllipsisLoc, DiagID: diag::err_pack_expansion_without_parameter_packs)
848 << Pattern->getSourceRange();
849 return ExprError();
850 }
851
852 // Create the pack expansion expression and source-location information.
853 return new (Context) PackExpansionExpr(Pattern, EllipsisLoc, NumExpansions);
854}
855
856bool Sema::CheckParameterPacksForExpansion(
857 SourceLocation EllipsisLoc, SourceRange PatternRange,
858 ArrayRef<UnexpandedParameterPack> Unexpanded,
859 const MultiLevelTemplateArgumentList &TemplateArgs,
860 bool FailOnPackProducingTemplates, bool &ShouldExpand,
861 bool &RetainExpansion, UnsignedOrNone &NumExpansions, bool Diagnose) {
862 ShouldExpand = true;
863 RetainExpansion = false;
864 IdentifierLoc FirstPack;
865 bool HaveFirstPack = false;
866 UnsignedOrNone NumPartialExpansions = std::nullopt;
867 SourceLocation PartiallySubstitutedPackLoc;
868 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
869
870 for (UnexpandedParameterPack ParmPack : Unexpanded) {
871 // Compute the depth and index for this parameter pack.
872 unsigned Depth = 0, Index = 0;
873 IdentifierInfo *Name;
874 bool IsVarDeclPack = false;
875 FunctionParmPackExpr *BindingPack = nullptr;
876 std::optional<unsigned> NumPrecomputedArguments;
877
878 if (auto *TTP = ParmPack.first.dyn_cast<const TemplateTypeParmType *>()) {
879 Depth = TTP->getDepth();
880 Index = TTP->getIndex();
881 Name = TTP->getIdentifier();
882 } else if (auto *TST =
883 ParmPack.first
884 .dyn_cast<const TemplateSpecializationType *>()) {
885 assert(isPackProducingBuiltinTemplateName(TST->getTemplateName()));
886 // Delay expansion, substitution is required to know the size.
887 ShouldExpand = false;
888 if (!FailOnPackProducingTemplates)
889 continue;
890
891 if (!Diagnose)
892 return true;
893
894 // It is not yet supported in certain contexts.
895 return Diag(Loc: PatternRange.getBegin().isValid() ? PatternRange.getBegin()
896 : EllipsisLoc,
897 DiagID: diag::err_unsupported_builtin_template_pack_expansion)
898 << TST->getTemplateName();
899 } else if (auto *S =
900 ParmPack.first
901 .dyn_cast<const SubstBuiltinTemplatePackType *>()) {
902 Name = nullptr;
903 NumPrecomputedArguments = S->getNumArgs();
904 } else {
905 NamedDecl *ND = cast<NamedDecl *>(Val&: ParmPack.first);
906 if (isa<VarDecl>(Val: ND))
907 IsVarDeclPack = true;
908 else if (isa<BindingDecl>(Val: ND)) {
909 // Find the instantiated BindingDecl and check it for a resolved pack.
910 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Instantiation =
911 CurrentInstantiationScope->findInstantiationOf(D: ND);
912 Decl *B = cast<Decl *>(Val&: *Instantiation);
913 Expr *BindingExpr = cast<BindingDecl>(Val: B)->getBinding();
914 BindingPack = cast_if_present<FunctionParmPackExpr>(Val: BindingExpr);
915 if (!BindingPack) {
916 ShouldExpand = false;
917 continue;
918 }
919 } else
920 std::tie(args&: Depth, args&: Index) = getDepthAndIndex(ND);
921
922 Name = ND->getIdentifier();
923 }
924
925 // Determine the size of this argument pack.
926 unsigned NewPackSize, PendingPackExpansionSize = 0;
927 if (IsVarDeclPack) {
928 // Figure out whether we're instantiating to an argument pack or not.
929 //
930 // The instantiation may not exist; this can happen when instantiating an
931 // expansion statement that contains a pack (e.g.
932 // `template for (auto x : {{ts...}})`).
933 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Instantiation =
934 CurrentInstantiationScope->getInstantiationOfIfExists(
935 D: cast<NamedDecl *>(Val&: ParmPack.first));
936 if (Instantiation && isa<DeclArgumentPack *>(Val: *Instantiation)) {
937 // We could expand this function parameter pack.
938 NewPackSize = cast<DeclArgumentPack *>(Val&: *Instantiation)->size();
939 } else {
940 // We can't expand this function parameter pack, so we can't expand
941 // the pack expansion.
942 ShouldExpand = false;
943 continue;
944 }
945 } else if (BindingPack) {
946 NewPackSize = BindingPack->getNumExpansions();
947 } else if (NumPrecomputedArguments) {
948 NewPackSize = *NumPrecomputedArguments;
949 } else {
950 // If we don't have a template argument at this depth/index, then we
951 // cannot expand the pack expansion. Make a note of this, but we still
952 // want to check any parameter packs we *do* have arguments for.
953 if (Depth >= TemplateArgs.getNumLevels() ||
954 !TemplateArgs.hasTemplateArgument(Depth, Index)) {
955 ShouldExpand = false;
956 continue;
957 }
958
959 // Determine the size of the argument pack.
960 ArrayRef<TemplateArgument> Pack =
961 TemplateArgs(Depth, Index).getPackAsArray();
962 NewPackSize = Pack.size();
963 PendingPackExpansionSize =
964 llvm::count_if(Range&: Pack, P: [](const TemplateArgument &TA) {
965 if (!TA.isPackExpansion())
966 return false;
967
968 if (TA.getKind() == TemplateArgument::Type)
969 return !TA.getAsType()
970 ->castAs<PackExpansionType>()
971 ->getNumExpansions();
972
973 if (TA.getKind() == TemplateArgument::Expression)
974 return !cast<PackExpansionExpr>(Val: TA.getAsExpr())
975 ->getNumExpansions();
976
977 return !TA.getNumTemplateExpansions();
978 });
979 }
980
981 // C++0x [temp.arg.explicit]p9:
982 // Template argument deduction can extend the sequence of template
983 // arguments corresponding to a template parameter pack, even when the
984 // sequence contains explicitly specified template arguments.
985 if (!IsVarDeclPack && CurrentInstantiationScope) {
986 if (NamedDecl *PartialPack =
987 CurrentInstantiationScope->getPartiallySubstitutedPack()) {
988 unsigned PartialDepth, PartialIndex;
989 std::tie(args&: PartialDepth, args&: PartialIndex) = getDepthAndIndex(ND: PartialPack);
990 if (PartialDepth == Depth && PartialIndex == Index) {
991 RetainExpansion = true;
992 // We don't actually know the new pack size yet.
993 NumPartialExpansions = NewPackSize;
994 PartiallySubstitutedPackLoc = ParmPack.second;
995 continue;
996 }
997 }
998 }
999
1000 if (!NumExpansions) {
1001 // This is the first pack we've seen for which we have an argument.
1002 // Record it.
1003 NumExpansions = NewPackSize;
1004 FirstPack = IdentifierLoc(ParmPack.second, Name);
1005 HaveFirstPack = true;
1006 continue;
1007 }
1008
1009 if (NewPackSize != *NumExpansions) {
1010 // In some cases, we might be handling packs with unexpanded template
1011 // arguments. For example, this can occur when substituting into a type
1012 // alias declaration that uses its injected template parameters as
1013 // arguments:
1014 //
1015 // template <class... Outer> struct S {
1016 // template <class... Inner> using Alias = S<void(Outer, Inner)...>;
1017 // };
1018 //
1019 // Consider an instantiation attempt like 'S<int>::Alias<Pack...>', where
1020 // Pack comes from another template parameter. 'S<int>' is first
1021 // instantiated, expanding the outer pack 'Outer' to <int>. The alias
1022 // declaration is accordingly substituted, leaving the template arguments
1023 // as unexpanded
1024 // '<Pack...>'.
1025 //
1026 // Since we have no idea of the size of '<Pack...>' until its expansion,
1027 // we shouldn't assume its pack size for validation. However if we are
1028 // certain that there are extra arguments beyond unexpanded packs, in
1029 // which case the pack size is already larger than the previous expansion,
1030 // we can complain that before instantiation.
1031 unsigned LeastNewPackSize = NewPackSize - PendingPackExpansionSize;
1032 if (PendingPackExpansionSize && LeastNewPackSize <= *NumExpansions) {
1033 ShouldExpand = false;
1034 continue;
1035 }
1036 // C++0x [temp.variadic]p5:
1037 // All of the parameter packs expanded by a pack expansion shall have
1038 // the same number of arguments specified.
1039 if (!Diagnose)
1040 ;
1041 else if (HaveFirstPack)
1042 Diag(Loc: EllipsisLoc, DiagID: diag::err_pack_expansion_length_conflict)
1043 << FirstPack.getIdentifierInfo() << Name << *NumExpansions
1044 << (LeastNewPackSize != NewPackSize) << LeastNewPackSize
1045 << SourceRange(FirstPack.getLoc()) << SourceRange(ParmPack.second);
1046 else
1047 Diag(Loc: EllipsisLoc, DiagID: diag::err_pack_expansion_length_conflict_multilevel)
1048 << Name << *NumExpansions << (LeastNewPackSize != NewPackSize)
1049 << LeastNewPackSize << SourceRange(ParmPack.second);
1050 return true;
1051 }
1052 }
1053
1054 // If we're performing a partial expansion but we also have a full expansion,
1055 // expand to the number of common arguments. For example, given:
1056 //
1057 // template<typename ...T> struct A {
1058 // template<typename ...U> void f(pair<T, U>...);
1059 // };
1060 //
1061 // ... a call to 'A<int, int>().f<int>' should expand the pack once and
1062 // retain an expansion.
1063 if (NumPartialExpansions) {
1064 if (NumExpansions && *NumExpansions < *NumPartialExpansions) {
1065 NamedDecl *PartialPack =
1066 CurrentInstantiationScope->getPartiallySubstitutedPack();
1067 if (!Diagnose)
1068 return true;
1069 Diag(Loc: EllipsisLoc, DiagID: diag::err_pack_expansion_length_conflict_partial)
1070 << PartialPack << *NumPartialExpansions << *NumExpansions
1071 << SourceRange(PartiallySubstitutedPackLoc);
1072 return true;
1073 }
1074
1075 NumExpansions = NumPartialExpansions;
1076 }
1077
1078 return false;
1079}
1080
1081UnsignedOrNone Sema::getNumArgumentsInExpansionFromUnexpanded(
1082 llvm::ArrayRef<UnexpandedParameterPack> Unexpanded,
1083 const MultiLevelTemplateArgumentList &TemplateArgs) {
1084 UnsignedOrNone Result = std::nullopt;
1085 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
1086 // Compute the depth and index for this parameter pack.
1087 unsigned Depth;
1088 unsigned Index;
1089
1090 if (const TemplateTypeParmType *TTP =
1091 Unexpanded[I].first.dyn_cast<const TemplateTypeParmType *>()) {
1092 Depth = TTP->getDepth();
1093 Index = TTP->getIndex();
1094 } else if (auto *TST =
1095 Unexpanded[I]
1096 .first.dyn_cast<const TemplateSpecializationType *>()) {
1097 // This is a dependent pack, we are not ready to expand it yet.
1098 assert(isPackProducingBuiltinTemplateName(TST->getTemplateName()));
1099 (void)TST;
1100 return std::nullopt;
1101 } else if (auto *PST =
1102 Unexpanded[I]
1103 .first
1104 .dyn_cast<const SubstBuiltinTemplatePackType *>()) {
1105 assert((!Result || *Result == PST->getNumArgs()) &&
1106 "inconsistent pack sizes");
1107 Result = PST->getNumArgs();
1108 continue;
1109 } else {
1110 NamedDecl *ND = cast<NamedDecl *>(Val: Unexpanded[I].first);
1111 if (isa<VarDecl>(Val: ND)) {
1112 // Function parameter pack or init-capture pack.
1113 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
1114
1115 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Instantiation =
1116 CurrentInstantiationScope->findInstantiationOf(
1117 D: cast<NamedDecl *>(Val: Unexpanded[I].first));
1118 if (isa<Decl *>(Val: *Instantiation))
1119 // The pattern refers to an unexpanded pack. We're not ready to expand
1120 // this pack yet.
1121 return std::nullopt;
1122
1123 unsigned Size = cast<DeclArgumentPack *>(Val&: *Instantiation)->size();
1124 assert((!Result || *Result == Size) && "inconsistent pack sizes");
1125 Result = Size;
1126 continue;
1127 }
1128
1129 std::tie(args&: Depth, args&: Index) = getDepthAndIndex(ND);
1130 }
1131 if (Depth >= TemplateArgs.getNumLevels() ||
1132 !TemplateArgs.hasTemplateArgument(Depth, Index))
1133 // The pattern refers to an unknown template argument. We're not ready to
1134 // expand this pack yet.
1135 return std::nullopt;
1136
1137 // Determine the size of the argument pack.
1138 unsigned Size = TemplateArgs(Depth, Index).pack_size();
1139 assert((!Result || *Result == Size) && "inconsistent pack sizes");
1140 Result = Size;
1141 }
1142
1143 return Result;
1144}
1145
1146UnsignedOrNone Sema::getNumArgumentsInExpansion(
1147 QualType T, const MultiLevelTemplateArgumentList &TemplateArgs) {
1148 QualType Pattern = cast<PackExpansionType>(Val&: T)->getPattern();
1149 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
1150 CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseType(T: Pattern);
1151 return getNumArgumentsInExpansionFromUnexpanded(Unexpanded, TemplateArgs);
1152}
1153
1154bool Sema::containsUnexpandedParameterPacks(Declarator &D) {
1155 const DeclSpec &DS = D.getDeclSpec();
1156 switch (DS.getTypeSpecType()) {
1157 case TST_typename_pack_indexing:
1158 case TST_typename:
1159 case TST_typeof_unqualType:
1160 case TST_typeofType:
1161#define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case TST_##Trait:
1162#include "clang/Basic/BuiltinTraits.inc"
1163 case TST_atomic: {
1164 QualType T = DS.getRepAsType().get();
1165 if (!T.isNull() && T->containsUnexpandedParameterPack())
1166 return true;
1167 break;
1168 }
1169
1170 case TST_typeof_unqualExpr:
1171 case TST_typeofExpr:
1172 case TST_decltype:
1173 case TST_bitint:
1174 if (DS.getRepAsExpr() &&
1175 DS.getRepAsExpr()->containsUnexpandedParameterPack())
1176 return true;
1177 break;
1178
1179 case TST_unspecified:
1180 case TST_void:
1181 case TST_char:
1182 case TST_wchar:
1183 case TST_char8:
1184 case TST_char16:
1185 case TST_char32:
1186 case TST_int:
1187 case TST_int128:
1188 case TST_half:
1189 case TST_float:
1190 case TST_double:
1191 case TST_Accum:
1192 case TST_Fract:
1193 case TST_Float16:
1194 case TST_float128:
1195 case TST_ibm128:
1196 case TST_bool:
1197 case TST_decimal32:
1198 case TST_decimal64:
1199 case TST_decimal128:
1200 case TST_enum:
1201 case TST_union:
1202 case TST_struct:
1203 case TST_interface:
1204 case TST_class:
1205 case TST_auto:
1206 case TST_auto_type:
1207 case TST_decltype_auto:
1208 case TST_BFloat16:
1209#define GENERIC_IMAGE_TYPE(ImgType, Id) case TST_##ImgType##_t:
1210#include "clang/Basic/OpenCLImageTypes.def"
1211#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case TST_##Name:
1212#include "clang/Basic/HLSLIntangibleTypes.def"
1213 case TST_unknown_anytype:
1214 case TST_error:
1215 break;
1216 }
1217
1218 for (unsigned I = 0, N = D.getNumTypeObjects(); I != N; ++I) {
1219 const DeclaratorChunk &Chunk = D.getTypeObject(i: I);
1220 switch (Chunk.Kind) {
1221 case DeclaratorChunk::Pointer:
1222 case DeclaratorChunk::Reference:
1223 case DeclaratorChunk::Paren:
1224 case DeclaratorChunk::Pipe:
1225 case DeclaratorChunk::BlockPointer:
1226 // These declarator chunks cannot contain any parameter packs.
1227 break;
1228
1229 case DeclaratorChunk::Array:
1230 if (Chunk.Arr.NumElts &&
1231 Chunk.Arr.NumElts->containsUnexpandedParameterPack())
1232 return true;
1233 break;
1234 case DeclaratorChunk::Function:
1235 for (unsigned i = 0, e = Chunk.Fun.NumParams; i != e; ++i) {
1236 ParmVarDecl *Param = cast<ParmVarDecl>(Val: Chunk.Fun.Params[i].Param);
1237 QualType ParamTy = Param->getType();
1238 assert(!ParamTy.isNull() && "Couldn't parse type?");
1239 if (ParamTy->containsUnexpandedParameterPack()) return true;
1240 }
1241
1242 if (Chunk.Fun.getExceptionSpecType() == EST_Dynamic) {
1243 for (unsigned i = 0; i != Chunk.Fun.getNumExceptions(); ++i) {
1244 if (Chunk.Fun.Exceptions[i]
1245 .Ty.get()
1246 ->containsUnexpandedParameterPack())
1247 return true;
1248 }
1249 } else if (isComputedNoexcept(ESpecType: Chunk.Fun.getExceptionSpecType()) &&
1250 Chunk.Fun.NoexceptExpr->containsUnexpandedParameterPack())
1251 return true;
1252
1253 if (Chunk.Fun.hasTrailingReturnType()) {
1254 QualType T = Chunk.Fun.getTrailingReturnType().get();
1255 if (!T.isNull() && T->containsUnexpandedParameterPack())
1256 return true;
1257 }
1258 break;
1259
1260 case DeclaratorChunk::MemberPointer:
1261 if (Chunk.Mem.Scope().getScopeRep().containsUnexpandedParameterPack())
1262 return true;
1263 break;
1264 }
1265 }
1266
1267 if (Expr *TRC = D.getTrailingRequiresClause())
1268 if (TRC->containsUnexpandedParameterPack())
1269 return true;
1270
1271 return false;
1272}
1273
1274namespace {
1275
1276// Callback to only accept typo corrections that refer to parameter packs.
1277class ParameterPackValidatorCCC final : public CorrectionCandidateCallback {
1278 public:
1279 bool ValidateCandidate(const TypoCorrection &candidate) override {
1280 NamedDecl *ND = candidate.getCorrectionDecl();
1281 return ND && ND->isParameterPack();
1282 }
1283
1284 std::unique_ptr<CorrectionCandidateCallback> clone() override {
1285 return std::make_unique<ParameterPackValidatorCCC>(args&: *this);
1286 }
1287};
1288
1289}
1290
1291ExprResult Sema::ActOnSizeofParameterPackExpr(Scope *S,
1292 SourceLocation OpLoc,
1293 IdentifierInfo &Name,
1294 SourceLocation NameLoc,
1295 SourceLocation RParenLoc) {
1296 // C++0x [expr.sizeof]p5:
1297 // The identifier in a sizeof... expression shall name a parameter pack.
1298 LookupResult R(*this, &Name, NameLoc, LookupOrdinaryName);
1299 LookupName(R, S);
1300
1301 NamedDecl *ParameterPack = nullptr;
1302 switch (R.getResultKind()) {
1303 case LookupResultKind::Found:
1304 ParameterPack = R.getFoundDecl();
1305 break;
1306
1307 case LookupResultKind::NotFound:
1308 case LookupResultKind::NotFoundInCurrentInstantiation: {
1309 ParameterPackValidatorCCC CCC{};
1310 if (TypoCorrection Corrected =
1311 CorrectTypo(Typo: R.getLookupNameInfo(), LookupKind: R.getLookupKind(), S, SS: nullptr,
1312 CCC, Mode: CorrectTypoKind::ErrorRecovery)) {
1313 diagnoseTypo(Correction: Corrected,
1314 TypoDiag: PDiag(DiagID: diag::err_sizeof_pack_no_pack_name_suggest) << &Name,
1315 PrevNote: PDiag(DiagID: diag::note_parameter_pack_here));
1316 ParameterPack = Corrected.getCorrectionDecl();
1317 }
1318 break;
1319 }
1320 case LookupResultKind::FoundOverloaded:
1321 case LookupResultKind::FoundUnresolvedValue:
1322 break;
1323
1324 case LookupResultKind::Ambiguous:
1325 DiagnoseAmbiguousLookup(Result&: R);
1326 return ExprError();
1327 }
1328
1329 if (!ParameterPack || !ParameterPack->isParameterPack()) {
1330 Diag(Loc: NameLoc, DiagID: diag::err_expected_name_of_pack) << &Name;
1331 return ExprError();
1332 }
1333
1334 MarkAnyDeclReferenced(Loc: OpLoc, D: ParameterPack, MightBeOdrUse: true);
1335
1336 return SizeOfPackExpr::Create(Context, OperatorLoc: OpLoc, Pack: ParameterPack, PackLoc: NameLoc,
1337 RParenLoc);
1338}
1339
1340static bool isParameterPack(Expr *PackExpression) {
1341 if (auto *D = dyn_cast<DeclRefExpr>(Val: PackExpression); D) {
1342 ValueDecl *VD = D->getDecl();
1343 return VD->isParameterPack();
1344 }
1345 return false;
1346}
1347
1348ExprResult Sema::ActOnPackIndexingExpr(Scope *S, Expr *PackExpression,
1349 SourceLocation EllipsisLoc,
1350 SourceLocation LSquareLoc,
1351 Expr *IndexExpr,
1352 SourceLocation RSquareLoc) {
1353 bool isParameterPack = ::isParameterPack(PackExpression);
1354 if (!isParameterPack) {
1355 if (!PackExpression->containsErrors())
1356 Diag(Loc: PackExpression->getBeginLoc(), DiagID: diag::err_expected_name_of_pack)
1357 << PackExpression;
1358 return ExprError();
1359 }
1360 ExprResult Res =
1361 BuildPackIndexingExpr(PackExpression, EllipsisLoc, IndexExpr, RSquareLoc);
1362 if (!Res.isInvalid())
1363 Diag(Loc: Res.get()->getBeginLoc(), DiagID: getLangOpts().CPlusPlus26
1364 ? diag::warn_cxx23_pack_indexing
1365 : diag::ext_pack_indexing);
1366 return Res;
1367}
1368
1369ExprResult Sema::BuildPackIndexingExpr(Expr *PackExpression,
1370 SourceLocation EllipsisLoc,
1371 Expr *IndexExpr,
1372 SourceLocation RSquareLoc,
1373 ArrayRef<Expr *> ExpandedExprs,
1374 bool FullySubstituted) {
1375
1376 std::optional<uint64_t> Index;
1377 if (!IndexExpr->isInstantiationDependent()) {
1378 llvm::APSInt Value(Context.getIntWidth(T: Context.getSizeType()));
1379
1380 ExprResult Res = CheckConvertedConstantExpression(
1381 From: IndexExpr, T: Context.getSizeType(), Value, CCE: CCEKind::PackIndex);
1382 if (!Res.isUsable() || !Value.isRepresentableByInt64())
1383 return ExprError();
1384 Index = Value.getZExtValue();
1385 IndexExpr = Res.get();
1386 }
1387
1388 if (Index && FullySubstituted) {
1389 if (*Index >= ExpandedExprs.size()) {
1390 Diag(Loc: PackExpression->getBeginLoc(), DiagID: diag::err_pack_index_out_of_bound)
1391 << *Index << PackExpression << ExpandedExprs.size();
1392 return ExprError();
1393 }
1394 }
1395
1396 return PackIndexingExpr::Create(Context&: getASTContext(), EllipsisLoc, RSquareLoc,
1397 PackIdExpr: PackExpression, IndexExpr, Index,
1398 SubstitutedExprs: ExpandedExprs, FullySubstituted);
1399}
1400
1401TemplateName Sema::ActOnPackIndexingTemplateName(TemplateName Pattern,
1402 SourceLocation NameLoc,
1403 Expr *IndexExpr) {
1404 assert(!Pattern.isNull() && IndexExpr);
1405
1406 // C++29 [temp.names]p3:
1407 // The simple-template-name P in a pack-index-template-name shall denote a
1408 // pack.
1409 bool DenotesPack = Pattern.containsUnexpandedParameterPack();
1410 if (!DenotesPack)
1411 Diag(Loc: NameLoc, DiagID: diag::err_expected_name_of_pack) << Pattern;
1412
1413 TemplateName Name = BuildPackIndexingTemplateName(Pattern, IndexExpr);
1414 if (!Name.isNull() && DenotesPack)
1415 DiagCompat(Loc: NameLoc, CompatDiagId: diag_compat::pack_indexing_template);
1416 return Name;
1417}
1418
1419TemplateName
1420Sema::BuildPackIndexingTemplateName(TemplateName Pattern, Expr *IndexExpr,
1421 bool FullySubstituted,
1422 ArrayRef<TemplateName> Expansions) {
1423 if (!IndexExpr->isInstantiationDependent()) {
1424 llvm::APSInt Value(Context.getIntWidth(T: Context.getSizeType()));
1425 ExprResult Res = CheckConvertedConstantExpression(
1426 From: IndexExpr, T: Context.getSizeType(), Value, CCE: CCEKind::PackIndex);
1427 if (!Res.isUsable() || !Value.isRepresentableByInt64())
1428 return TemplateName();
1429
1430 IndexExpr = Res.get();
1431 uint64_t V = Value.getZExtValue();
1432 if (FullySubstituted && V >= Expansions.size()) {
1433 Diag(Loc: IndexExpr->getBeginLoc(), DiagID: diag::err_pack_index_out_of_bound)
1434 << V << Pattern << Expansions.size();
1435 return TemplateName();
1436 }
1437 }
1438
1439 return Context.getPackIndexingTemplateName(Pattern, IndexExpr,
1440 FullySubstituted, Expansions);
1441}
1442
1443TypeResult Sema::ActOnPackIndexingDeducedTemplateSpecializationType(
1444 TemplateName Name, SourceLocation NameLoc) {
1445
1446 QualType T = Context.getDeducedTemplateSpecializationType(
1447 DK: DeducedKind::Undeduced, DeducedAsType: QualType(), Keyword: ElaboratedTypeKeyword::None, Template: Name);
1448 TypeLocBuilder TLB;
1449 auto TL = TLB.push<DeducedTemplateSpecializationTypeLoc>(T);
1450 TL.setElaboratedKeywordLoc(SourceLocation());
1451 TL.setQualifierLoc(NestedNameSpecifierLoc());
1452 TL.setNameLoc(NameLoc);
1453 return CreateParsedType(T, TInfo: TLB.getTypeSourceInfo(Context, T));
1454}
1455
1456TemplateArgumentLoc Sema::getTemplateArgumentPackExpansionPattern(
1457 TemplateArgumentLoc OrigLoc, SourceLocation &Ellipsis,
1458 UnsignedOrNone &NumExpansions) const {
1459 const TemplateArgument &Argument = OrigLoc.getArgument();
1460 assert(Argument.isPackExpansion());
1461 switch (Argument.getKind()) {
1462 case TemplateArgument::Type: {
1463 // FIXME: We shouldn't ever have to worry about missing
1464 // type-source info!
1465 TypeSourceInfo *ExpansionTSInfo = OrigLoc.getTypeSourceInfo();
1466 if (!ExpansionTSInfo)
1467 ExpansionTSInfo = Context.getTrivialTypeSourceInfo(T: Argument.getAsType(),
1468 Loc: Ellipsis);
1469 PackExpansionTypeLoc Expansion =
1470 ExpansionTSInfo->getTypeLoc().castAs<PackExpansionTypeLoc>();
1471 Ellipsis = Expansion.getEllipsisLoc();
1472
1473 TypeLoc Pattern = Expansion.getPatternLoc();
1474 NumExpansions = Expansion.getTypePtr()->getNumExpansions();
1475
1476 // We need to copy the TypeLoc because TemplateArgumentLocs store a
1477 // TypeSourceInfo.
1478 // FIXME: Find some way to avoid the copy?
1479 TypeLocBuilder TLB;
1480 TLB.pushFullCopy(L: Pattern);
1481 TypeSourceInfo *PatternTSInfo =
1482 TLB.getTypeSourceInfo(Context, T: Pattern.getType());
1483 return TemplateArgumentLoc(TemplateArgument(Pattern.getType()),
1484 PatternTSInfo);
1485 }
1486
1487 case TemplateArgument::Expression: {
1488 PackExpansionExpr *Expansion
1489 = cast<PackExpansionExpr>(Val: Argument.getAsExpr());
1490 Expr *Pattern = Expansion->getPattern();
1491 Ellipsis = Expansion->getEllipsisLoc();
1492 NumExpansions = Expansion->getNumExpansions();
1493 return TemplateArgumentLoc(
1494 TemplateArgument(Pattern, Argument.isCanonicalExpr()), Pattern);
1495 }
1496
1497 case TemplateArgument::TemplateExpansion:
1498 Ellipsis = OrigLoc.getTemplateEllipsisLoc();
1499 NumExpansions = Argument.getNumTemplateExpansions();
1500 return TemplateArgumentLoc(
1501 Context, Argument.getPackExpansionPattern(), OrigLoc.getTemplateKWLoc(),
1502 OrigLoc.getTemplateQualifierLoc(), OrigLoc.getTemplateNameLoc());
1503
1504 case TemplateArgument::Declaration:
1505 case TemplateArgument::NullPtr:
1506 case TemplateArgument::Template:
1507 case TemplateArgument::Integral:
1508 case TemplateArgument::StructuralValue:
1509 case TemplateArgument::Pack:
1510 case TemplateArgument::Null:
1511 return TemplateArgumentLoc();
1512 }
1513
1514 llvm_unreachable("Invalid TemplateArgument Kind!");
1515}
1516
1517UnsignedOrNone Sema::getFullyPackExpandedSize(TemplateArgument Arg) {
1518 assert(Arg.containsUnexpandedParameterPack());
1519
1520 // If this is a substituted pack, grab that pack. If not, we don't know
1521 // the size yet.
1522 // FIXME: We could find a size in more cases by looking for a substituted
1523 // pack anywhere within this argument, but that's not necessary in the common
1524 // case for 'sizeof...(A)' handling.
1525 TemplateArgument Pack;
1526 switch (Arg.getKind()) {
1527 case TemplateArgument::Type:
1528 if (auto *Subst = Arg.getAsType()->getAs<SubstTemplateTypeParmPackType>())
1529 Pack = Subst->getArgumentPack();
1530 else
1531 return std::nullopt;
1532 break;
1533
1534 case TemplateArgument::Expression:
1535 if (auto *Subst =
1536 dyn_cast<SubstNonTypeTemplateParmPackExpr>(Val: Arg.getAsExpr()))
1537 Pack = Subst->getArgumentPack();
1538 else if (auto *Subst = dyn_cast<FunctionParmPackExpr>(Val: Arg.getAsExpr())) {
1539 for (ValueDecl *PD : *Subst)
1540 if (PD->isParameterPack())
1541 return std::nullopt;
1542 return Subst->getNumExpansions();
1543 } else
1544 return std::nullopt;
1545 break;
1546
1547 case TemplateArgument::Template:
1548 if (SubstTemplateTemplateParmPackStorage *Subst =
1549 Arg.getAsTemplate().getAsSubstTemplateTemplateParmPack())
1550 Pack = Subst->getArgumentPack();
1551 else
1552 return std::nullopt;
1553 break;
1554
1555 case TemplateArgument::Declaration:
1556 case TemplateArgument::NullPtr:
1557 case TemplateArgument::TemplateExpansion:
1558 case TemplateArgument::Integral:
1559 case TemplateArgument::StructuralValue:
1560 case TemplateArgument::Pack:
1561 case TemplateArgument::Null:
1562 return std::nullopt;
1563 }
1564
1565 // Check that no argument in the pack is itself a pack expansion.
1566 for (TemplateArgument Elem : Pack.pack_elements()) {
1567 // There's no point recursing in this case; we would have already
1568 // expanded this pack expansion into the enclosing pack if we could.
1569 if (Elem.isPackExpansion())
1570 return std::nullopt;
1571 // Don't guess the size of unexpanded packs. The pack within a template
1572 // argument may have yet to be of a PackExpansion type before we see the
1573 // ellipsis in the annotation stage.
1574 //
1575 // This doesn't mean we would invalidate the optimization: Arg can be an
1576 // unexpanded pack regardless of Elem's dependence. For instance,
1577 // A TemplateArgument that contains either a SubstTemplateTypeParmPackType
1578 // or SubstNonTypeTemplateParmPackExpr is always considered Unexpanded, but
1579 // the underlying TemplateArgument thereof may not.
1580 if (Elem.containsUnexpandedParameterPack())
1581 return std::nullopt;
1582 }
1583 return Pack.pack_size();
1584}
1585
1586static void CheckFoldOperand(Sema &S, Expr *E) {
1587 if (!E)
1588 return;
1589
1590 E = E->IgnoreImpCasts();
1591 auto *OCE = dyn_cast<CXXOperatorCallExpr>(Val: E);
1592 if ((OCE && OCE->isInfixBinaryOp()) || isa<BinaryOperator>(Val: E) ||
1593 isa<AbstractConditionalOperator>(Val: E)) {
1594 S.Diag(Loc: E->getExprLoc(), DiagID: diag::err_fold_expression_bad_operand)
1595 << E->getSourceRange()
1596 << FixItHint::CreateInsertion(InsertionLoc: E->getBeginLoc(), Code: "(")
1597 << FixItHint::CreateInsertion(InsertionLoc: S.getLocForEndOfToken(Loc: E->getEndLoc()),
1598 Code: ")");
1599 }
1600}
1601
1602ExprResult Sema::ActOnCXXFoldExpr(Scope *S, SourceLocation LParenLoc, Expr *LHS,
1603 tok::TokenKind Operator,
1604 SourceLocation EllipsisLoc, Expr *RHS,
1605 SourceLocation RParenLoc) {
1606 // LHS and RHS must be cast-expressions. We allow an arbitrary expression
1607 // in the parser and reduce down to just cast-expressions here.
1608 CheckFoldOperand(S&: *this, E: LHS);
1609 CheckFoldOperand(S&: *this, E: RHS);
1610
1611 // [expr.prim.fold]p3:
1612 // In a binary fold, op1 and op2 shall be the same fold-operator, and
1613 // either e1 shall contain an unexpanded parameter pack or e2 shall contain
1614 // an unexpanded parameter pack, but not both.
1615 if (LHS && RHS &&
1616 LHS->containsUnexpandedParameterPack() ==
1617 RHS->containsUnexpandedParameterPack()) {
1618 return Diag(Loc: EllipsisLoc,
1619 DiagID: LHS->containsUnexpandedParameterPack()
1620 ? diag::err_fold_expression_packs_both_sides
1621 : diag::err_pack_expansion_without_parameter_packs)
1622 << LHS->getSourceRange() << RHS->getSourceRange();
1623 }
1624
1625 // [expr.prim.fold]p2:
1626 // In a unary fold, the cast-expression shall contain an unexpanded
1627 // parameter pack.
1628 if (!LHS || !RHS) {
1629 Expr *Pack = LHS ? LHS : RHS;
1630 assert(Pack && "fold expression with neither LHS nor RHS");
1631 if (!Pack->containsUnexpandedParameterPack()) {
1632 return Diag(Loc: EllipsisLoc, DiagID: diag::err_pack_expansion_without_parameter_packs)
1633 << Pack->getSourceRange();
1634 }
1635 }
1636
1637 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind: Operator);
1638
1639 // Perform first-phase name lookup now.
1640 UnresolvedLookupExpr *ULE = nullptr;
1641 {
1642 UnresolvedSet<16> Functions;
1643 LookupBinOp(S, OpLoc: EllipsisLoc, Opc, Functions);
1644 if (!Functions.empty()) {
1645 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(
1646 Op: BinaryOperator::getOverloadedOperator(Opc));
1647 ExprResult Callee = CreateUnresolvedLookupExpr(
1648 /*NamingClass*/ nullptr, NNSLoc: NestedNameSpecifierLoc(),
1649 DNI: DeclarationNameInfo(OpName, EllipsisLoc), Fns: Functions);
1650 if (Callee.isInvalid())
1651 return ExprError();
1652 ULE = cast<UnresolvedLookupExpr>(Val: Callee.get());
1653 }
1654 }
1655
1656 return BuildCXXFoldExpr(Callee: ULE, LParenLoc, LHS, Operator: Opc, EllipsisLoc, RHS, RParenLoc,
1657 NumExpansions: std::nullopt);
1658}
1659
1660ExprResult Sema::BuildCXXFoldExpr(UnresolvedLookupExpr *Callee,
1661 SourceLocation LParenLoc, Expr *LHS,
1662 BinaryOperatorKind Operator,
1663 SourceLocation EllipsisLoc, Expr *RHS,
1664 SourceLocation RParenLoc,
1665 UnsignedOrNone NumExpansions) {
1666 return new (Context)
1667 CXXFoldExpr(Context.DependentTy, Callee, LParenLoc, LHS, Operator,
1668 EllipsisLoc, RHS, RParenLoc, NumExpansions);
1669}
1670
1671ExprResult Sema::BuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc,
1672 BinaryOperatorKind Operator) {
1673 // [temp.variadic]p9:
1674 // If N is zero for a unary fold-expression, the value of the expression is
1675 // && -> true
1676 // || -> false
1677 // , -> void()
1678 // if the operator is not listed [above], the instantiation is ill-formed.
1679 //
1680 // Note that we need to use something like int() here, not merely 0, to
1681 // prevent the result from being a null pointer constant.
1682 QualType ScalarType;
1683 switch (Operator) {
1684 case BO_LOr:
1685 return ActOnCXXBoolLiteral(OpLoc: EllipsisLoc, Kind: tok::kw_false);
1686 case BO_LAnd:
1687 return ActOnCXXBoolLiteral(OpLoc: EllipsisLoc, Kind: tok::kw_true);
1688 case BO_Comma:
1689 ScalarType = Context.VoidTy;
1690 break;
1691
1692 default:
1693 return Diag(Loc: EllipsisLoc, DiagID: diag::err_fold_expression_empty)
1694 << BinaryOperator::getOpcodeStr(Op: Operator);
1695 }
1696
1697 return new (Context) CXXScalarValueInitExpr(
1698 ScalarType, Context.getTrivialTypeSourceInfo(T: ScalarType, Loc: EllipsisLoc),
1699 EllipsisLoc);
1700}
1701