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

source code of clang/lib/Sema/SemaTemplateVariadic.cpp