1 //===------- SemaTemplateVariadic.cpp - C++ Variadic Templates ------------===/
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 //===----------------------------------------------------------------------===/
8 // This file implements semantic analysis for C++0x variadic templates.
9 //===----------------------------------------------------------------------===/
11 #include "clang/Sema/Sema.h"
12 #include "TypeLocBuilder.h"
13 #include "clang/AST/Expr.h"
14 #include "clang/AST/RecursiveASTVisitor.h"
15 #include "clang/AST/TypeLoc.h"
16 #include "clang/Sema/Lookup.h"
17 #include "clang/Sema/ParsedTemplate.h"
18 #include "clang/Sema/ScopeInfo.h"
19 #include "clang/Sema/SemaInternal.h"
20 #include "clang/Sema/Template.h"
22 using namespace clang;
24 //----------------------------------------------------------------------------
25 // Visitor that collects unexpanded parameter packs
26 //----------------------------------------------------------------------------
29 /// A class that collects unexpanded parameter packs.
30 class CollectUnexpandedParameterPacksVisitor :
31 public RecursiveASTVisitor<CollectUnexpandedParameterPacksVisitor>
33 typedef RecursiveASTVisitor<CollectUnexpandedParameterPacksVisitor>
36 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded;
38 bool InLambda = false;
39 unsigned DepthLimit = (unsigned)-1;
41 void addUnexpanded(NamedDecl *ND, SourceLocation Loc = SourceLocation()) {
42 if (auto *VD = dyn_cast<VarDecl>(ND)) {
43 // For now, the only problematic case is a generic lambda's templated
44 // call operator, so we don't need to look for all the other ways we
45 // could have reached a dependent parameter pack.
46 auto *FD = dyn_cast<FunctionDecl>(VD->getDeclContext());
47 auto *FTD = FD ? FD->getDescribedFunctionTemplate() : nullptr;
48 if (FTD && FTD->getTemplateParameters()->getDepth() >= DepthLimit)
50 } else if (getDepthAndIndex(ND).first >= DepthLimit)
53 Unexpanded.push_back({ND, Loc});
55 void addUnexpanded(const TemplateTypeParmType *T,
56 SourceLocation Loc = SourceLocation()) {
57 if (T->getDepth() < DepthLimit)
58 Unexpanded.push_back({T, Loc});
62 explicit CollectUnexpandedParameterPacksVisitor(
63 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded)
64 : Unexpanded(Unexpanded) {}
66 bool shouldWalkTypesOfTypeLocs() const { return false; }
68 //------------------------------------------------------------------------
69 // Recording occurrences of (unexpanded) parameter packs.
70 //------------------------------------------------------------------------
72 /// Record occurrences of template type parameter packs.
73 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
74 if (TL.getTypePtr()->isParameterPack())
75 addUnexpanded(TL.getTypePtr(), TL.getNameLoc());
79 /// Record occurrences of template type parameter packs
80 /// when we don't have proper source-location information for
83 /// Ideally, this routine would never be used.
84 bool VisitTemplateTypeParmType(TemplateTypeParmType *T) {
85 if (T->isParameterPack())
91 /// Record occurrences of function and non-type template
92 /// parameter packs in an expression.
93 bool VisitDeclRefExpr(DeclRefExpr *E) {
94 if (E->getDecl()->isParameterPack())
95 addUnexpanded(E->getDecl(), E->getLocation());
100 /// Record occurrences of template template parameter packs.
101 bool TraverseTemplateName(TemplateName Template) {
102 if (auto *TTP = dyn_cast_or_null<TemplateTemplateParmDecl>(
103 Template.getAsTemplateDecl())) {
104 if (TTP->isParameterPack())
108 return inherited::TraverseTemplateName(Template);
111 /// Suppress traversal into Objective-C container literal
112 /// elements that are pack expansions.
113 bool TraverseObjCDictionaryLiteral(ObjCDictionaryLiteral *E) {
114 if (!E->containsUnexpandedParameterPack())
117 for (unsigned I = 0, N = E->getNumElements(); I != N; ++I) {
118 ObjCDictionaryElement Element = E->getKeyValueElement(I);
119 if (Element.isPackExpansion())
122 TraverseStmt(Element.Key);
123 TraverseStmt(Element.Value);
127 //------------------------------------------------------------------------
128 // Pruning the search for unexpanded parameter packs.
129 //------------------------------------------------------------------------
131 /// Suppress traversal into statements and expressions that
132 /// do not contain unexpanded parameter packs.
133 bool TraverseStmt(Stmt *S) {
134 Expr *E = dyn_cast_or_null<Expr>(S);
135 if ((E && E->containsUnexpandedParameterPack()) || InLambda)
136 return inherited::TraverseStmt(S);
141 /// Suppress traversal into types that do not contain
142 /// unexpanded parameter packs.
143 bool TraverseType(QualType T) {
144 if ((!T.isNull() && T->containsUnexpandedParameterPack()) || InLambda)
145 return inherited::TraverseType(T);
150 /// Suppress traversal into types with location information
151 /// that do not contain unexpanded parameter packs.
152 bool TraverseTypeLoc(TypeLoc TL) {
153 if ((!TL.getType().isNull() &&
154 TL.getType()->containsUnexpandedParameterPack()) ||
156 return inherited::TraverseTypeLoc(TL);
161 /// Suppress traversal of parameter packs.
162 bool TraverseDecl(Decl *D) {
163 // A function parameter pack is a pack expansion, so cannot contain
164 // an unexpanded parameter pack. Likewise for a template parameter
165 // pack that contains any references to other packs.
166 if (D && D->isParameterPack())
169 return inherited::TraverseDecl(D);
172 /// Suppress traversal of pack-expanded attributes.
173 bool TraverseAttr(Attr *A) {
174 if (A->isPackExpansion())
177 return inherited::TraverseAttr(A);
180 /// Suppress traversal of pack expansion expressions and types.
182 bool TraversePackExpansionType(PackExpansionType *T) { return true; }
183 bool TraversePackExpansionTypeLoc(PackExpansionTypeLoc TL) { return true; }
184 bool TraversePackExpansionExpr(PackExpansionExpr *E) { return true; }
185 bool TraverseCXXFoldExpr(CXXFoldExpr *E) { return true; }
189 /// Suppress traversal of using-declaration pack expansion.
190 bool TraverseUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
191 if (D->isPackExpansion())
194 return inherited::TraverseUnresolvedUsingValueDecl(D);
197 /// Suppress traversal of using-declaration pack expansion.
198 bool TraverseUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {
199 if (D->isPackExpansion())
202 return inherited::TraverseUnresolvedUsingTypenameDecl(D);
205 /// Suppress traversal of template argument pack expansions.
206 bool TraverseTemplateArgument(const TemplateArgument &Arg) {
207 if (Arg.isPackExpansion())
210 return inherited::TraverseTemplateArgument(Arg);
213 /// Suppress traversal of template argument pack expansions.
214 bool TraverseTemplateArgumentLoc(const TemplateArgumentLoc &ArgLoc) {
215 if (ArgLoc.getArgument().isPackExpansion())
218 return inherited::TraverseTemplateArgumentLoc(ArgLoc);
221 /// Suppress traversal of base specifier pack expansions.
222 bool TraverseCXXBaseSpecifier(const CXXBaseSpecifier &Base) {
223 if (Base.isPackExpansion())
226 return inherited::TraverseCXXBaseSpecifier(Base);
229 /// Suppress traversal of mem-initializer pack expansions.
230 bool TraverseConstructorInitializer(CXXCtorInitializer *Init) {
231 if (Init->isPackExpansion())
234 return inherited::TraverseConstructorInitializer(Init);
237 /// Note whether we're traversing a lambda containing an unexpanded
238 /// parameter pack. In this case, the unexpanded pack can occur anywhere,
239 /// including all the places where we normally wouldn't look. Within a
240 /// lambda, we don't propagate the 'contains unexpanded parameter pack' bit
241 /// outside an expression.
242 bool TraverseLambdaExpr(LambdaExpr *Lambda) {
243 // The ContainsUnexpandedParameterPack bit on a lambda is always correct,
244 // even if it's contained within another lambda.
245 if (!Lambda->containsUnexpandedParameterPack())
248 bool WasInLambda = InLambda;
249 unsigned OldDepthLimit = DepthLimit;
252 if (auto *TPL = Lambda->getTemplateParameterList())
253 DepthLimit = TPL->getDepth();
255 inherited::TraverseLambdaExpr(Lambda);
257 InLambda = WasInLambda;
258 DepthLimit = OldDepthLimit;
262 /// Suppress traversal within pack expansions in lambda captures.
263 bool TraverseLambdaCapture(LambdaExpr *Lambda, const LambdaCapture *C,
265 if (C->isPackExpansion())
268 return inherited::TraverseLambdaCapture(Lambda, C, Init);
273 /// Determine whether it's possible for an unexpanded parameter pack to
274 /// be valid in this location. This only happens when we're in a declaration
275 /// that is nested within an expression that could be expanded, such as a
276 /// lambda-expression within a function call.
278 /// This is conservatively correct, but may claim that some unexpanded packs are
279 /// permitted when they are not.
280 bool Sema::isUnexpandedParameterPackPermitted() {
281 for (auto *SI : FunctionScopes)
282 if (isa<sema::LambdaScopeInfo>(SI))
287 /// Diagnose all of the unexpanded parameter packs in the given
290 Sema::DiagnoseUnexpandedParameterPacks(SourceLocation Loc,
291 UnexpandedParameterPackContext UPPC,
292 ArrayRef<UnexpandedParameterPack> Unexpanded) {
293 if (Unexpanded.empty())
296 // If we are within a lambda expression and referencing a pack that is not
297 // a parameter of the lambda itself, that lambda contains an unexpanded
298 // parameter pack, and we are done.
299 // FIXME: Store 'Unexpanded' on the lambda so we don't need to recompute it
301 SmallVector<UnexpandedParameterPack, 4> LambdaParamPackReferences;
302 for (unsigned N = FunctionScopes.size(); N; --N) {
303 sema::FunctionScopeInfo *Func = FunctionScopes[N-1];
304 // We do not permit pack expansion that would duplicate a statement
305 // expression, not even within a lambda.
306 // FIXME: We could probably support this for statement expressions that do
307 // not contain labels, and for pack expansions that expand both the stmt
308 // expr and the enclosing lambda.
310 Func->CompoundScopes.begin(), Func->CompoundScopes.end(),
311 [](sema::CompoundScopeInfo &CSI) { return CSI.IsStmtExpr; }))
314 if (auto *LSI = dyn_cast<sema::LambdaScopeInfo>(Func)) {
315 if (N == FunctionScopes.size()) {
316 for (auto &Pack : Unexpanded) {
317 auto *VD = dyn_cast_or_null<VarDecl>(
318 Pack.first.dyn_cast<NamedDecl *>());
319 if (VD && VD->getDeclContext() == LSI->CallOperator)
320 LambdaParamPackReferences.push_back(Pack);
324 // If we have references to a parameter pack of the innermost enclosing
325 // lambda, only diagnose those ones. We don't know whether any other
326 // unexpanded parameters referenced herein are actually unexpanded;
327 // they might be expanded at an outer level.
328 if (!LambdaParamPackReferences.empty()) {
329 Unexpanded = LambdaParamPackReferences;
333 LSI->ContainsUnexpandedParameterPack = true;
338 SmallVector<SourceLocation, 4> Locations;
339 SmallVector<IdentifierInfo *, 4> Names;
340 llvm::SmallPtrSet<IdentifierInfo *, 4> NamesKnown;
342 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
343 IdentifierInfo *Name = nullptr;
344 if (const TemplateTypeParmType *TTP
345 = Unexpanded[I].first.dyn_cast<const TemplateTypeParmType *>())
346 Name = TTP->getIdentifier();
348 Name = Unexpanded[I].first.get<NamedDecl *>()->getIdentifier();
350 if (Name && NamesKnown.insert(Name).second)
351 Names.push_back(Name);
353 if (Unexpanded[I].second.isValid())
354 Locations.push_back(Unexpanded[I].second);
357 DiagnosticBuilder DB = Diag(Loc, diag::err_unexpanded_parameter_pack)
358 << (int)UPPC << (int)Names.size();
359 for (size_t I = 0, E = std::min(Names.size(), (size_t)2); I != E; ++I)
362 for (unsigned I = 0, N = Locations.size(); I != N; ++I)
363 DB << SourceRange(Locations[I]);
367 bool Sema::DiagnoseUnexpandedParameterPack(SourceLocation Loc,
369 UnexpandedParameterPackContext UPPC) {
370 // C++0x [temp.variadic]p5:
371 // An appearance of a name of a parameter pack that is not expanded is
373 if (!T->getType()->containsUnexpandedParameterPack())
376 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
377 CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseTypeLoc(
379 assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
380 return DiagnoseUnexpandedParameterPacks(Loc, UPPC, Unexpanded);
383 bool Sema::DiagnoseUnexpandedParameterPack(Expr *E,
384 UnexpandedParameterPackContext UPPC) {
385 // C++0x [temp.variadic]p5:
386 // An appearance of a name of a parameter pack that is not expanded is
388 if (!E->containsUnexpandedParameterPack())
391 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
392 CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseStmt(E);
393 assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
394 return DiagnoseUnexpandedParameterPacks(E->getBeginLoc(), UPPC, Unexpanded);
397 bool Sema::DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS,
398 UnexpandedParameterPackContext UPPC) {
399 // C++0x [temp.variadic]p5:
400 // An appearance of a name of a parameter pack that is not expanded is
402 if (!SS.getScopeRep() ||
403 !SS.getScopeRep()->containsUnexpandedParameterPack())
406 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
407 CollectUnexpandedParameterPacksVisitor(Unexpanded)
408 .TraverseNestedNameSpecifier(SS.getScopeRep());
409 assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
410 return DiagnoseUnexpandedParameterPacks(SS.getRange().getBegin(),
414 bool Sema::DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo,
415 UnexpandedParameterPackContext UPPC) {
416 // C++0x [temp.variadic]p5:
417 // An appearance of a name of a parameter pack that is not expanded is
419 switch (NameInfo.getName().getNameKind()) {
420 case DeclarationName::Identifier:
421 case DeclarationName::ObjCZeroArgSelector:
422 case DeclarationName::ObjCOneArgSelector:
423 case DeclarationName::ObjCMultiArgSelector:
424 case DeclarationName::CXXOperatorName:
425 case DeclarationName::CXXLiteralOperatorName:
426 case DeclarationName::CXXUsingDirective:
427 case DeclarationName::CXXDeductionGuideName:
430 case DeclarationName::CXXConstructorName:
431 case DeclarationName::CXXDestructorName:
432 case DeclarationName::CXXConversionFunctionName:
433 // FIXME: We shouldn't need this null check!
434 if (TypeSourceInfo *TSInfo = NameInfo.getNamedTypeInfo())
435 return DiagnoseUnexpandedParameterPack(NameInfo.getLoc(), TSInfo, UPPC);
437 if (!NameInfo.getName().getCXXNameType()->containsUnexpandedParameterPack())
443 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
444 CollectUnexpandedParameterPacksVisitor(Unexpanded)
445 .TraverseType(NameInfo.getName().getCXXNameType());
446 assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
447 return DiagnoseUnexpandedParameterPacks(NameInfo.getLoc(), UPPC, Unexpanded);
450 bool Sema::DiagnoseUnexpandedParameterPack(SourceLocation Loc,
451 TemplateName Template,
452 UnexpandedParameterPackContext UPPC) {
454 if (Template.isNull() || !Template.containsUnexpandedParameterPack())
457 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
458 CollectUnexpandedParameterPacksVisitor(Unexpanded)
459 .TraverseTemplateName(Template);
460 assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
461 return DiagnoseUnexpandedParameterPacks(Loc, UPPC, Unexpanded);
464 bool Sema::DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg,
465 UnexpandedParameterPackContext UPPC) {
466 if (Arg.getArgument().isNull() ||
467 !Arg.getArgument().containsUnexpandedParameterPack())
470 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
471 CollectUnexpandedParameterPacksVisitor(Unexpanded)
472 .TraverseTemplateArgumentLoc(Arg);
473 assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
474 return DiagnoseUnexpandedParameterPacks(Arg.getLocation(), UPPC, Unexpanded);
477 void Sema::collectUnexpandedParameterPacks(TemplateArgument Arg,
478 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
479 CollectUnexpandedParameterPacksVisitor(Unexpanded)
480 .TraverseTemplateArgument(Arg);
483 void Sema::collectUnexpandedParameterPacks(TemplateArgumentLoc Arg,
484 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
485 CollectUnexpandedParameterPacksVisitor(Unexpanded)
486 .TraverseTemplateArgumentLoc(Arg);
489 void Sema::collectUnexpandedParameterPacks(QualType T,
490 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
491 CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseType(T);
494 void Sema::collectUnexpandedParameterPacks(TypeLoc TL,
495 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
496 CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseTypeLoc(TL);
499 void Sema::collectUnexpandedParameterPacks(
500 NestedNameSpecifierLoc NNS,
501 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
502 CollectUnexpandedParameterPacksVisitor(Unexpanded)
503 .TraverseNestedNameSpecifierLoc(NNS);
506 void Sema::collectUnexpandedParameterPacks(
507 const DeclarationNameInfo &NameInfo,
508 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
509 CollectUnexpandedParameterPacksVisitor(Unexpanded)
510 .TraverseDeclarationNameInfo(NameInfo);
514 ParsedTemplateArgument
515 Sema::ActOnPackExpansion(const ParsedTemplateArgument &Arg,
516 SourceLocation EllipsisLoc) {
520 switch (Arg.getKind()) {
521 case ParsedTemplateArgument::Type: {
522 TypeResult Result = ActOnPackExpansion(Arg.getAsType(), EllipsisLoc);
523 if (Result.isInvalid())
524 return ParsedTemplateArgument();
526 return ParsedTemplateArgument(Arg.getKind(), Result.get().getAsOpaquePtr(),
530 case ParsedTemplateArgument::NonType: {
531 ExprResult Result = ActOnPackExpansion(Arg.getAsExpr(), EllipsisLoc);
532 if (Result.isInvalid())
533 return ParsedTemplateArgument();
535 return ParsedTemplateArgument(Arg.getKind(), Result.get(),
539 case ParsedTemplateArgument::Template:
540 if (!Arg.getAsTemplate().get().containsUnexpandedParameterPack()) {
541 SourceRange R(Arg.getLocation());
542 if (Arg.getScopeSpec().isValid())
543 R.setBegin(Arg.getScopeSpec().getBeginLoc());
544 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
546 return ParsedTemplateArgument();
549 return Arg.getTemplatePackExpansion(EllipsisLoc);
551 llvm_unreachable("Unhandled template argument kind?");
554 TypeResult Sema::ActOnPackExpansion(ParsedType Type,
555 SourceLocation EllipsisLoc) {
556 TypeSourceInfo *TSInfo;
557 GetTypeFromParser(Type, &TSInfo);
561 TypeSourceInfo *TSResult = CheckPackExpansion(TSInfo, EllipsisLoc, None);
565 return CreateParsedType(TSResult->getType(), TSResult);
569 Sema::CheckPackExpansion(TypeSourceInfo *Pattern, SourceLocation EllipsisLoc,
570 Optional<unsigned> NumExpansions) {
571 // Create the pack expansion type and source-location information.
572 QualType Result = CheckPackExpansion(Pattern->getType(),
573 Pattern->getTypeLoc().getSourceRange(),
574 EllipsisLoc, NumExpansions);
579 TLB.pushFullCopy(Pattern->getTypeLoc());
580 PackExpansionTypeLoc TL = TLB.push<PackExpansionTypeLoc>(Result);
581 TL.setEllipsisLoc(EllipsisLoc);
583 return TLB.getTypeSourceInfo(Context, Result);
586 QualType Sema::CheckPackExpansion(QualType Pattern, SourceRange PatternRange,
587 SourceLocation EllipsisLoc,
588 Optional<unsigned> NumExpansions) {
589 // C++11 [temp.variadic]p5:
590 // The pattern of a pack expansion shall name one or more
591 // parameter packs that are not expanded by a nested pack
594 // A pattern containing a deduced type can't occur "naturally" but arises in
595 // the desugaring of an init-capture pack.
596 if (!Pattern->containsUnexpandedParameterPack() &&
597 !Pattern->getContainedDeducedType()) {
598 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
603 return Context.getPackExpansionType(Pattern, NumExpansions);
606 ExprResult Sema::ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc) {
607 return CheckPackExpansion(Pattern, EllipsisLoc, None);
610 ExprResult Sema::CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
611 Optional<unsigned> NumExpansions) {
615 // C++0x [temp.variadic]p5:
616 // The pattern of a pack expansion shall name one or more
617 // parameter packs that are not expanded by a nested pack
619 if (!Pattern->containsUnexpandedParameterPack()) {
620 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
621 << Pattern->getSourceRange();
622 CorrectDelayedTyposInExpr(Pattern);
626 // Create the pack expansion expression and source-location information.
628 PackExpansionExpr(Context.DependentTy, Pattern, EllipsisLoc, NumExpansions);
631 bool Sema::CheckParameterPacksForExpansion(
632 SourceLocation EllipsisLoc, SourceRange PatternRange,
633 ArrayRef<UnexpandedParameterPack> Unexpanded,
634 const MultiLevelTemplateArgumentList &TemplateArgs, bool &ShouldExpand,
635 bool &RetainExpansion, Optional<unsigned> &NumExpansions) {
637 RetainExpansion = false;
638 std::pair<IdentifierInfo *, SourceLocation> FirstPack;
639 bool HaveFirstPack = false;
640 Optional<unsigned> NumPartialExpansions;
641 SourceLocation PartiallySubstitutedPackLoc;
643 for (ArrayRef<UnexpandedParameterPack>::iterator i = Unexpanded.begin(),
644 end = Unexpanded.end();
646 // Compute the depth and index for this parameter pack.
647 unsigned Depth = 0, Index = 0;
648 IdentifierInfo *Name;
649 bool IsVarDeclPack = false;
651 if (const TemplateTypeParmType *TTP
652 = i->first.dyn_cast<const TemplateTypeParmType *>()) {
653 Depth = TTP->getDepth();
654 Index = TTP->getIndex();
655 Name = TTP->getIdentifier();
657 NamedDecl *ND = i->first.get<NamedDecl *>();
658 if (isa<VarDecl>(ND))
659 IsVarDeclPack = true;
661 std::tie(Depth, Index) = getDepthAndIndex(ND);
663 Name = ND->getIdentifier();
666 // Determine the size of this argument pack.
667 unsigned NewPackSize;
669 // Figure out whether we're instantiating to an argument pack or not.
670 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
672 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Instantiation
673 = CurrentInstantiationScope->findInstantiationOf(
674 i->first.get<NamedDecl *>());
675 if (Instantiation->is<DeclArgumentPack *>()) {
676 // We could expand this function parameter pack.
677 NewPackSize = Instantiation->get<DeclArgumentPack *>()->size();
679 // We can't expand this function parameter pack, so we can't expand
680 // the pack expansion.
681 ShouldExpand = false;
685 // If we don't have a template argument at this depth/index, then we
686 // cannot expand the pack expansion. Make a note of this, but we still
687 // want to check any parameter packs we *do* have arguments for.
688 if (Depth >= TemplateArgs.getNumLevels() ||
689 !TemplateArgs.hasTemplateArgument(Depth, Index)) {
690 ShouldExpand = false;
694 // Determine the size of the argument pack.
695 NewPackSize = TemplateArgs(Depth, Index).pack_size();
698 // C++0x [temp.arg.explicit]p9:
699 // Template argument deduction can extend the sequence of template
700 // arguments corresponding to a template parameter pack, even when the
701 // sequence contains explicitly specified template arguments.
702 if (!IsVarDeclPack && CurrentInstantiationScope) {
703 if (NamedDecl *PartialPack
704 = CurrentInstantiationScope->getPartiallySubstitutedPack()){
705 unsigned PartialDepth, PartialIndex;
706 std::tie(PartialDepth, PartialIndex) = getDepthAndIndex(PartialPack);
707 if (PartialDepth == Depth && PartialIndex == Index) {
708 RetainExpansion = true;
709 // We don't actually know the new pack size yet.
710 NumPartialExpansions = NewPackSize;
711 PartiallySubstitutedPackLoc = i->second;
717 if (!NumExpansions) {
718 // The is the first pack we've seen for which we have an argument.
720 NumExpansions = NewPackSize;
721 FirstPack.first = Name;
722 FirstPack.second = i->second;
723 HaveFirstPack = true;
727 if (NewPackSize != *NumExpansions) {
728 // C++0x [temp.variadic]p5:
729 // All of the parameter packs expanded by a pack expansion shall have
730 // the same number of arguments specified.
732 Diag(EllipsisLoc, diag::err_pack_expansion_length_conflict)
733 << FirstPack.first << Name << *NumExpansions << NewPackSize
734 << SourceRange(FirstPack.second) << SourceRange(i->second);
736 Diag(EllipsisLoc, diag::err_pack_expansion_length_conflict_multilevel)
737 << Name << *NumExpansions << NewPackSize
738 << SourceRange(i->second);
743 // If we're performing a partial expansion but we also have a full expansion,
744 // expand to the number of common arguments. For example, given:
746 // template<typename ...T> struct A {
747 // template<typename ...U> void f(pair<T, U>...);
750 // ... a call to 'A<int, int>().f<int>' should expand the pack once and
751 // retain an expansion.
752 if (NumPartialExpansions) {
753 if (NumExpansions && *NumExpansions < *NumPartialExpansions) {
754 NamedDecl *PartialPack =
755 CurrentInstantiationScope->getPartiallySubstitutedPack();
756 Diag(EllipsisLoc, diag::err_pack_expansion_length_conflict_partial)
757 << PartialPack << *NumPartialExpansions << *NumExpansions
758 << SourceRange(PartiallySubstitutedPackLoc);
762 NumExpansions = NumPartialExpansions;
768 Optional<unsigned> Sema::getNumArgumentsInExpansion(QualType T,
769 const MultiLevelTemplateArgumentList &TemplateArgs) {
770 QualType Pattern = cast<PackExpansionType>(T)->getPattern();
771 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
772 CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseType(Pattern);
774 Optional<unsigned> Result;
775 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
776 // Compute the depth and index for this parameter pack.
780 if (const TemplateTypeParmType *TTP
781 = Unexpanded[I].first.dyn_cast<const TemplateTypeParmType *>()) {
782 Depth = TTP->getDepth();
783 Index = TTP->getIndex();
785 NamedDecl *ND = Unexpanded[I].first.get<NamedDecl *>();
786 if (isa<VarDecl>(ND)) {
787 // Function parameter pack or init-capture pack.
788 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
790 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Instantiation
791 = CurrentInstantiationScope->findInstantiationOf(
792 Unexpanded[I].first.get<NamedDecl *>());
793 if (Instantiation->is<Decl*>())
794 // The pattern refers to an unexpanded pack. We're not ready to expand
798 unsigned Size = Instantiation->get<DeclArgumentPack *>()->size();
799 assert((!Result || *Result == Size) && "inconsistent pack sizes");
804 std::tie(Depth, Index) = getDepthAndIndex(ND);
806 if (Depth >= TemplateArgs.getNumLevels() ||
807 !TemplateArgs.hasTemplateArgument(Depth, Index))
808 // The pattern refers to an unknown template argument. We're not ready to
809 // expand this pack yet.
812 // Determine the size of the argument pack.
813 unsigned Size = TemplateArgs(Depth, Index).pack_size();
814 assert((!Result || *Result == Size) && "inconsistent pack sizes");
821 bool Sema::containsUnexpandedParameterPacks(Declarator &D) {
822 const DeclSpec &DS = D.getDeclSpec();
823 switch (DS.getTypeSpecType()) {
826 case TST_underlyingType:
828 QualType T = DS.getRepAsType().get();
829 if (!T.isNull() && T->containsUnexpandedParameterPack())
836 if (DS.getRepAsExpr() &&
837 DS.getRepAsExpr()->containsUnexpandedParameterPack())
841 case TST_unspecified:
868 case TST_decltype_auto:
869 #define GENERIC_IMAGE_TYPE(ImgType, Id) case TST_##ImgType##_t:
870 #include "clang/Basic/OpenCLImageTypes.def"
871 case TST_unknown_anytype:
876 for (unsigned I = 0, N = D.getNumTypeObjects(); I != N; ++I) {
877 const DeclaratorChunk &Chunk = D.getTypeObject(I);
878 switch (Chunk.Kind) {
879 case DeclaratorChunk::Pointer:
880 case DeclaratorChunk::Reference:
881 case DeclaratorChunk::Paren:
882 case DeclaratorChunk::Pipe:
883 case DeclaratorChunk::BlockPointer:
884 // These declarator chunks cannot contain any parameter packs.
887 case DeclaratorChunk::Array:
888 if (Chunk.Arr.NumElts &&
889 Chunk.Arr.NumElts->containsUnexpandedParameterPack())
892 case DeclaratorChunk::Function:
893 for (unsigned i = 0, e = Chunk.Fun.NumParams; i != e; ++i) {
894 ParmVarDecl *Param = cast<ParmVarDecl>(Chunk.Fun.Params[i].Param);
895 QualType ParamTy = Param->getType();
896 assert(!ParamTy.isNull() && "Couldn't parse type?");
897 if (ParamTy->containsUnexpandedParameterPack()) return true;
900 if (Chunk.Fun.getExceptionSpecType() == EST_Dynamic) {
901 for (unsigned i = 0; i != Chunk.Fun.getNumExceptions(); ++i) {
902 if (Chunk.Fun.Exceptions[i]
904 ->containsUnexpandedParameterPack())
907 } else if (isComputedNoexcept(Chunk.Fun.getExceptionSpecType()) &&
908 Chunk.Fun.NoexceptExpr->containsUnexpandedParameterPack())
911 if (Chunk.Fun.hasTrailingReturnType()) {
912 QualType T = Chunk.Fun.getTrailingReturnType().get();
913 if (!T.isNull() && T->containsUnexpandedParameterPack())
918 case DeclaratorChunk::MemberPointer:
919 if (Chunk.Mem.Scope().getScopeRep() &&
920 Chunk.Mem.Scope().getScopeRep()->containsUnexpandedParameterPack())
931 // Callback to only accept typo corrections that refer to parameter packs.
932 class ParameterPackValidatorCCC final : public CorrectionCandidateCallback {
934 bool ValidateCandidate(const TypoCorrection &candidate) override {
935 NamedDecl *ND = candidate.getCorrectionDecl();
936 return ND && ND->isParameterPack();
939 std::unique_ptr<CorrectionCandidateCallback> clone() override {
940 return llvm::make_unique<ParameterPackValidatorCCC>(*this);
946 /// Called when an expression computing the size of a parameter pack
950 /// template<typename ...Types> struct count {
951 /// static const unsigned value = sizeof...(Types);
956 /// \param OpLoc The location of the "sizeof" keyword.
957 /// \param Name The name of the parameter pack whose size will be determined.
958 /// \param NameLoc The source location of the name of the parameter pack.
959 /// \param RParenLoc The location of the closing parentheses.
960 ExprResult Sema::ActOnSizeofParameterPackExpr(Scope *S,
961 SourceLocation OpLoc,
962 IdentifierInfo &Name,
963 SourceLocation NameLoc,
964 SourceLocation RParenLoc) {
965 // C++0x [expr.sizeof]p5:
966 // The identifier in a sizeof... expression shall name a parameter pack.
967 LookupResult R(*this, &Name, NameLoc, LookupOrdinaryName);
970 NamedDecl *ParameterPack = nullptr;
971 switch (R.getResultKind()) {
972 case LookupResult::Found:
973 ParameterPack = R.getFoundDecl();
976 case LookupResult::NotFound:
977 case LookupResult::NotFoundInCurrentInstantiation: {
978 ParameterPackValidatorCCC CCC{};
979 if (TypoCorrection Corrected =
980 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, nullptr,
981 CCC, CTK_ErrorRecovery)) {
982 diagnoseTypo(Corrected,
983 PDiag(diag::err_sizeof_pack_no_pack_name_suggest) << &Name,
984 PDiag(diag::note_parameter_pack_here));
985 ParameterPack = Corrected.getCorrectionDecl();
989 case LookupResult::FoundOverloaded:
990 case LookupResult::FoundUnresolvedValue:
993 case LookupResult::Ambiguous:
994 DiagnoseAmbiguousLookup(R);
998 if (!ParameterPack || !ParameterPack->isParameterPack()) {
999 Diag(NameLoc, diag::err_sizeof_pack_no_pack_name)
1004 MarkAnyDeclReferenced(OpLoc, ParameterPack, true);
1006 return SizeOfPackExpr::Create(Context, OpLoc, ParameterPack, NameLoc,
1011 Sema::getTemplateArgumentPackExpansionPattern(
1012 TemplateArgumentLoc OrigLoc,
1013 SourceLocation &Ellipsis, Optional<unsigned> &NumExpansions) const {
1014 const TemplateArgument &Argument = OrigLoc.getArgument();
1015 assert(Argument.isPackExpansion());
1016 switch (Argument.getKind()) {
1017 case TemplateArgument::Type: {
1018 // FIXME: We shouldn't ever have to worry about missing
1019 // type-source info!
1020 TypeSourceInfo *ExpansionTSInfo = OrigLoc.getTypeSourceInfo();
1021 if (!ExpansionTSInfo)
1022 ExpansionTSInfo = Context.getTrivialTypeSourceInfo(Argument.getAsType(),
1024 PackExpansionTypeLoc Expansion =
1025 ExpansionTSInfo->getTypeLoc().castAs<PackExpansionTypeLoc>();
1026 Ellipsis = Expansion.getEllipsisLoc();
1028 TypeLoc Pattern = Expansion.getPatternLoc();
1029 NumExpansions = Expansion.getTypePtr()->getNumExpansions();
1031 // We need to copy the TypeLoc because TemplateArgumentLocs store a
1033 // FIXME: Find some way to avoid the copy?
1035 TLB.pushFullCopy(Pattern);
1036 TypeSourceInfo *PatternTSInfo =
1037 TLB.getTypeSourceInfo(Context, Pattern.getType());
1038 return TemplateArgumentLoc(TemplateArgument(Pattern.getType()),
1042 case TemplateArgument::Expression: {
1043 PackExpansionExpr *Expansion
1044 = cast<PackExpansionExpr>(Argument.getAsExpr());
1045 Expr *Pattern = Expansion->getPattern();
1046 Ellipsis = Expansion->getEllipsisLoc();
1047 NumExpansions = Expansion->getNumExpansions();
1048 return TemplateArgumentLoc(Pattern, Pattern);
1051 case TemplateArgument::TemplateExpansion:
1052 Ellipsis = OrigLoc.getTemplateEllipsisLoc();
1053 NumExpansions = Argument.getNumTemplateExpansions();
1054 return TemplateArgumentLoc(Argument.getPackExpansionPattern(),
1055 OrigLoc.getTemplateQualifierLoc(),
1056 OrigLoc.getTemplateNameLoc());
1058 case TemplateArgument::Declaration:
1059 case TemplateArgument::NullPtr:
1060 case TemplateArgument::Template:
1061 case TemplateArgument::Integral:
1062 case TemplateArgument::Pack:
1063 case TemplateArgument::Null:
1064 return TemplateArgumentLoc();
1067 llvm_unreachable("Invalid TemplateArgument Kind!");
1070 Optional<unsigned> Sema::getFullyPackExpandedSize(TemplateArgument Arg) {
1071 assert(Arg.containsUnexpandedParameterPack());
1073 // If this is a substituted pack, grab that pack. If not, we don't know
1075 // FIXME: We could find a size in more cases by looking for a substituted
1076 // pack anywhere within this argument, but that's not necessary in the common
1077 // case for 'sizeof...(A)' handling.
1078 TemplateArgument Pack;
1079 switch (Arg.getKind()) {
1080 case TemplateArgument::Type:
1081 if (auto *Subst = Arg.getAsType()->getAs<SubstTemplateTypeParmPackType>())
1082 Pack = Subst->getArgumentPack();
1087 case TemplateArgument::Expression:
1089 dyn_cast<SubstNonTypeTemplateParmPackExpr>(Arg.getAsExpr()))
1090 Pack = Subst->getArgumentPack();
1091 else if (auto *Subst = dyn_cast<FunctionParmPackExpr>(Arg.getAsExpr())) {
1092 for (VarDecl *PD : *Subst)
1093 if (PD->isParameterPack())
1095 return Subst->getNumExpansions();
1100 case TemplateArgument::Template:
1101 if (SubstTemplateTemplateParmPackStorage *Subst =
1102 Arg.getAsTemplate().getAsSubstTemplateTemplateParmPack())
1103 Pack = Subst->getArgumentPack();
1108 case TemplateArgument::Declaration:
1109 case TemplateArgument::NullPtr:
1110 case TemplateArgument::TemplateExpansion:
1111 case TemplateArgument::Integral:
1112 case TemplateArgument::Pack:
1113 case TemplateArgument::Null:
1117 // Check that no argument in the pack is itself a pack expansion.
1118 for (TemplateArgument Elem : Pack.pack_elements()) {
1119 // There's no point recursing in this case; we would have already
1120 // expanded this pack expansion into the enclosing pack if we could.
1121 if (Elem.isPackExpansion())
1124 return Pack.pack_size();
1127 static void CheckFoldOperand(Sema &S, Expr *E) {
1131 E = E->IgnoreImpCasts();
1132 auto *OCE = dyn_cast<CXXOperatorCallExpr>(E);
1133 if ((OCE && OCE->isInfixBinaryOp()) || isa<BinaryOperator>(E) ||
1134 isa<AbstractConditionalOperator>(E)) {
1135 S.Diag(E->getExprLoc(), diag::err_fold_expression_bad_operand)
1136 << E->getSourceRange()
1137 << FixItHint::CreateInsertion(E->getBeginLoc(), "(")
1138 << FixItHint::CreateInsertion(E->getEndLoc(), ")");
1142 ExprResult Sema::ActOnCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
1143 tok::TokenKind Operator,
1144 SourceLocation EllipsisLoc, Expr *RHS,
1145 SourceLocation RParenLoc) {
1146 // LHS and RHS must be cast-expressions. We allow an arbitrary expression
1147 // in the parser and reduce down to just cast-expressions here.
1148 CheckFoldOperand(*this, LHS);
1149 CheckFoldOperand(*this, RHS);
1151 auto DiscardOperands = [&] {
1152 CorrectDelayedTyposInExpr(LHS);
1153 CorrectDelayedTyposInExpr(RHS);
1156 // [expr.prim.fold]p3:
1157 // In a binary fold, op1 and op2 shall be the same fold-operator, and
1158 // either e1 shall contain an unexpanded parameter pack or e2 shall contain
1159 // an unexpanded parameter pack, but not both.
1161 LHS->containsUnexpandedParameterPack() ==
1162 RHS->containsUnexpandedParameterPack()) {
1164 return Diag(EllipsisLoc,
1165 LHS->containsUnexpandedParameterPack()
1166 ? diag::err_fold_expression_packs_both_sides
1167 : diag::err_pack_expansion_without_parameter_packs)
1168 << LHS->getSourceRange() << RHS->getSourceRange();
1171 // [expr.prim.fold]p2:
1172 // In a unary fold, the cast-expression shall contain an unexpanded
1175 Expr *Pack = LHS ? LHS : RHS;
1176 assert(Pack && "fold expression with neither LHS nor RHS");
1178 if (!Pack->containsUnexpandedParameterPack())
1179 return Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1180 << Pack->getSourceRange();
1183 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Operator);
1184 return BuildCXXFoldExpr(LParenLoc, LHS, Opc, EllipsisLoc, RHS, RParenLoc,
1188 ExprResult Sema::BuildCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
1189 BinaryOperatorKind Operator,
1190 SourceLocation EllipsisLoc, Expr *RHS,
1191 SourceLocation RParenLoc,
1192 Optional<unsigned> NumExpansions) {
1193 return new (Context) CXXFoldExpr(Context.DependentTy, LParenLoc, LHS,
1194 Operator, EllipsisLoc, RHS, RParenLoc,
1198 ExprResult Sema::BuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc,
1199 BinaryOperatorKind Operator) {
1200 // [temp.variadic]p9:
1201 // If N is zero for a unary fold-expression, the value of the expression is
1205 // if the operator is not listed [above], the instantiation is ill-formed.
1207 // Note that we need to use something like int() here, not merely 0, to
1208 // prevent the result from being a null pointer constant.
1209 QualType ScalarType;
1212 return ActOnCXXBoolLiteral(EllipsisLoc, tok::kw_false);
1214 return ActOnCXXBoolLiteral(EllipsisLoc, tok::kw_true);
1216 ScalarType = Context.VoidTy;
1220 return Diag(EllipsisLoc, diag::err_fold_expression_empty)
1221 << BinaryOperator::getOpcodeStr(Operator);
1224 return new (Context) CXXScalarValueInitExpr(
1225 ScalarType, Context.getTrivialTypeSourceInfo(ScalarType, EllipsisLoc),