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 "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"
21 
22 using namespace clang;
23 
24 //----------------------------------------------------------------------------
25 // Visitor that collects unexpanded parameter packs
26 //----------------------------------------------------------------------------
27 
28 namespace {
29   /// A class that collects unexpanded parameter packs.
30   class CollectUnexpandedParameterPacksVisitor :
31     public RecursiveASTVisitor<CollectUnexpandedParameterPacksVisitor>
32   {
33     typedef RecursiveASTVisitor<CollectUnexpandedParameterPacksVisitor>
34       inherited;
35 
36     SmallVectorImpl<UnexpandedParameterPack> &Unexpanded;
37 
38     bool InLambda = false;
39     unsigned DepthLimit = (unsigned)-1;
40 
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)
49           return;
50       } else if (getDepthAndIndex(ND).first >= DepthLimit)
51         return;
52 
53       Unexpanded.push_back({ND, Loc});
54     }
55     void addUnexpanded(const TemplateTypeParmType *T,
56                        SourceLocation Loc = SourceLocation()) {
57       if (T->getDepth() < DepthLimit)
58         Unexpanded.push_back({T, Loc});
59     }
60 
61   public:
62     explicit CollectUnexpandedParameterPacksVisitor(
63         SmallVectorImpl<UnexpandedParameterPack> &Unexpanded)
64         : Unexpanded(Unexpanded) {}
65 
66     bool shouldWalkTypesOfTypeLocs() const { return false; }
67 
68     //------------------------------------------------------------------------
69     // Recording occurrences of (unexpanded) parameter packs.
70     //------------------------------------------------------------------------
71 
72     /// Record occurrences of template type parameter packs.
73     bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
74       if (TL.getTypePtr()->isParameterPack())
75         addUnexpanded(TL.getTypePtr(), TL.getNameLoc());
76       return true;
77     }
78 
79     /// Record occurrences of template type parameter packs
80     /// when we don't have proper source-location information for
81     /// them.
82     ///
83     /// Ideally, this routine would never be used.
84     bool VisitTemplateTypeParmType(TemplateTypeParmType *T) {
85       if (T->isParameterPack())
86         addUnexpanded(T);
87 
88       return true;
89     }
90 
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());
96 
97       return true;
98     }
99 
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())
105           addUnexpanded(TTP);
106       }
107 
108       return inherited::TraverseTemplateName(Template);
109     }
110 
111     /// Suppress traversal into Objective-C container literal
112     /// elements that are pack expansions.
113     bool TraverseObjCDictionaryLiteral(ObjCDictionaryLiteral *E) {
114       if (!E->containsUnexpandedParameterPack())
115         return true;
116 
117       for (unsigned I = 0, N = E->getNumElements(); I != N; ++I) {
118         ObjCDictionaryElement Element = E->getKeyValueElement(I);
119         if (Element.isPackExpansion())
120           continue;
121 
122         TraverseStmt(Element.Key);
123         TraverseStmt(Element.Value);
124       }
125       return true;
126     }
127     //------------------------------------------------------------------------
128     // Pruning the search for unexpanded parameter packs.
129     //------------------------------------------------------------------------
130 
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);
137 
138       return true;
139     }
140 
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);
146 
147       return true;
148     }
149 
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()) ||
155           InLambda)
156         return inherited::TraverseTypeLoc(TL);
157 
158       return true;
159     }
160 
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())
167         return true;
168 
169       return inherited::TraverseDecl(D);
170     }
171 
172     /// Suppress traversal of pack-expanded attributes.
173     bool TraverseAttr(Attr *A) {
174       if (A->isPackExpansion())
175         return true;
176 
177       return inherited::TraverseAttr(A);
178     }
179 
180     /// Suppress traversal of pack expansion expressions and types.
181     ///@{
182     bool TraversePackExpansionType(PackExpansionType *T) { return true; }
183     bool TraversePackExpansionTypeLoc(PackExpansionTypeLoc TL) { return true; }
184     bool TraversePackExpansionExpr(PackExpansionExpr *E) { return true; }
185     bool TraverseCXXFoldExpr(CXXFoldExpr *E) { return true; }
186 
187     ///@}
188 
189     /// Suppress traversal of using-declaration pack expansion.
190     bool TraverseUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
191       if (D->isPackExpansion())
192         return true;
193 
194       return inherited::TraverseUnresolvedUsingValueDecl(D);
195     }
196 
197     /// Suppress traversal of using-declaration pack expansion.
198     bool TraverseUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {
199       if (D->isPackExpansion())
200         return true;
201 
202       return inherited::TraverseUnresolvedUsingTypenameDecl(D);
203     }
204 
205     /// Suppress traversal of template argument pack expansions.
206     bool TraverseTemplateArgument(const TemplateArgument &Arg) {
207       if (Arg.isPackExpansion())
208         return true;
209 
210       return inherited::TraverseTemplateArgument(Arg);
211     }
212 
213     /// Suppress traversal of template argument pack expansions.
214     bool TraverseTemplateArgumentLoc(const TemplateArgumentLoc &ArgLoc) {
215       if (ArgLoc.getArgument().isPackExpansion())
216         return true;
217 
218       return inherited::TraverseTemplateArgumentLoc(ArgLoc);
219     }
220 
221     /// Suppress traversal of base specifier pack expansions.
222     bool TraverseCXXBaseSpecifier(const CXXBaseSpecifier &Base) {
223       if (Base.isPackExpansion())
224         return true;
225 
226       return inherited::TraverseCXXBaseSpecifier(Base);
227     }
228 
229     /// Suppress traversal of mem-initializer pack expansions.
230     bool TraverseConstructorInitializer(CXXCtorInitializer *Init) {
231       if (Init->isPackExpansion())
232         return true;
233 
234       return inherited::TraverseConstructorInitializer(Init);
235     }
236 
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())
246         return true;
247 
248       bool WasInLambda = InLambda;
249       unsigned OldDepthLimit = DepthLimit;
250 
251       InLambda = true;
252       if (auto *TPL = Lambda->getTemplateParameterList())
253         DepthLimit = TPL->getDepth();
254 
255       inherited::TraverseLambdaExpr(Lambda);
256 
257       InLambda = WasInLambda;
258       DepthLimit = OldDepthLimit;
259       return true;
260     }
261 
262     /// Suppress traversal within pack expansions in lambda captures.
263     bool TraverseLambdaCapture(LambdaExpr *Lambda, const LambdaCapture *C,
264                                Expr *Init) {
265       if (C->isPackExpansion())
266         return true;
267 
268       return inherited::TraverseLambdaCapture(Lambda, C, Init);
269     }
270   };
271 }
272 
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.
277 ///
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))
283       return true;
284   return false;
285 }
286 
287 /// Diagnose all of the unexpanded parameter packs in the given
288 /// vector.
289 bool
290 Sema::DiagnoseUnexpandedParameterPacks(SourceLocation Loc,
291                                        UnexpandedParameterPackContext UPPC,
292                                  ArrayRef<UnexpandedParameterPack> Unexpanded) {
293   if (Unexpanded.empty())
294     return false;
295 
296   // If we are within a lambda expression and referencing a pack that is not
297   // declared within 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
300   // later.
301   SmallVector<UnexpandedParameterPack, 4> LambdaParamPackReferences;
302   if (auto *LSI = getEnclosingLambda()) {
303     for (auto &Pack : Unexpanded) {
304       auto DeclaresThisPack = [&](NamedDecl *LocalPack) {
305         if (auto *TTPT = Pack.first.dyn_cast<const TemplateTypeParmType *>()) {
306           auto *TTPD = dyn_cast<TemplateTypeParmDecl>(LocalPack);
307           return TTPD && TTPD->getTypeForDecl() == TTPT;
308         }
309         return declaresSameEntity(Pack.first.get<NamedDecl *>(), LocalPack);
310       };
311       if (std::find_if(LSI->LocalPacks.begin(), LSI->LocalPacks.end(),
312                        DeclaresThisPack) != LSI->LocalPacks.end())
313         LambdaParamPackReferences.push_back(Pack);
314     }
315 
316     if (LambdaParamPackReferences.empty()) {
317       // Construct in lambda only references packs declared outside the lambda.
318       // That's OK for now, but the lambda itself is considered to contain an
319       // unexpanded pack in this case, which will require expansion outside the
320       // lambda.
321 
322       // We do not permit pack expansion that would duplicate a statement
323       // expression, not even within a lambda.
324       // FIXME: We could probably support this for statement expressions that
325       // do not contain labels.
326       // FIXME: This is insufficient to detect this problem; consider
327       //   f( ({ bad: 0; }) + pack ... );
328       bool EnclosingStmtExpr = false;
329       for (unsigned N = FunctionScopes.size(); N; --N) {
330         sema::FunctionScopeInfo *Func = FunctionScopes[N-1];
331         if (std::any_of(
332                 Func->CompoundScopes.begin(), Func->CompoundScopes.end(),
333                 [](sema::CompoundScopeInfo &CSI) { return CSI.IsStmtExpr; })) {
334           EnclosingStmtExpr = true;
335           break;
336         }
337         // Coumpound-statements outside the lambda are OK for now; we'll check
338         // for those when we finish handling the lambda.
339         if (Func == LSI)
340           break;
341       }
342 
343       if (!EnclosingStmtExpr) {
344         LSI->ContainsUnexpandedParameterPack = true;
345         return false;
346       }
347     } else {
348       Unexpanded = LambdaParamPackReferences;
349     }
350   }
351 
352   SmallVector<SourceLocation, 4> Locations;
353   SmallVector<IdentifierInfo *, 4> Names;
354   llvm::SmallPtrSet<IdentifierInfo *, 4> NamesKnown;
355 
356   for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
357     IdentifierInfo *Name = nullptr;
358     if (const TemplateTypeParmType *TTP
359           = Unexpanded[I].first.dyn_cast<const TemplateTypeParmType *>())
360       Name = TTP->getIdentifier();
361     else
362       Name = Unexpanded[I].first.get<NamedDecl *>()->getIdentifier();
363 
364     if (Name && NamesKnown.insert(Name).second)
365       Names.push_back(Name);
366 
367     if (Unexpanded[I].second.isValid())
368       Locations.push_back(Unexpanded[I].second);
369   }
370 
371   auto DB = Diag(Loc, diag::err_unexpanded_parameter_pack)
372             << (int)UPPC << (int)Names.size();
373   for (size_t I = 0, E = std::min(Names.size(), (size_t)2); I != E; ++I)
374     DB << Names[I];
375 
376   for (unsigned I = 0, N = Locations.size(); I != N; ++I)
377     DB << SourceRange(Locations[I]);
378   return true;
379 }
380 
381 bool Sema::DiagnoseUnexpandedParameterPack(SourceLocation Loc,
382                                            TypeSourceInfo *T,
383                                          UnexpandedParameterPackContext UPPC) {
384   // C++0x [temp.variadic]p5:
385   //   An appearance of a name of a parameter pack that is not expanded is
386   //   ill-formed.
387   if (!T->getType()->containsUnexpandedParameterPack())
388     return false;
389 
390   SmallVector<UnexpandedParameterPack, 2> Unexpanded;
391   CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseTypeLoc(
392                                                               T->getTypeLoc());
393   assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
394   return DiagnoseUnexpandedParameterPacks(Loc, UPPC, Unexpanded);
395 }
396 
397 bool Sema::DiagnoseUnexpandedParameterPack(Expr *E,
398                                         UnexpandedParameterPackContext UPPC) {
399   // C++0x [temp.variadic]p5:
400   //   An appearance of a name of a parameter pack that is not expanded is
401   //   ill-formed.
402   if (!E->containsUnexpandedParameterPack())
403     return false;
404 
405   SmallVector<UnexpandedParameterPack, 2> Unexpanded;
406   CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseStmt(E);
407   assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
408   return DiagnoseUnexpandedParameterPacks(E->getBeginLoc(), UPPC, Unexpanded);
409 }
410 
411 bool Sema::DiagnoseUnexpandedParameterPackInRequiresExpr(RequiresExpr *RE) {
412   if (!RE->containsUnexpandedParameterPack())
413     return false;
414 
415   SmallVector<UnexpandedParameterPack, 2> Unexpanded;
416   CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseStmt(RE);
417   assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
418 
419   // We only care about unexpanded references to the RequiresExpr's own
420   // parameter packs.
421   auto Parms = RE->getLocalParameters();
422   llvm::SmallPtrSet<NamedDecl*, 8> ParmSet(Parms.begin(), Parms.end());
423   SmallVector<UnexpandedParameterPack, 2> UnexpandedParms;
424   for (auto Parm : Unexpanded)
425     if (ParmSet.contains(Parm.first.dyn_cast<NamedDecl*>()))
426       UnexpandedParms.push_back(Parm);
427   if (UnexpandedParms.empty())
428     return false;
429 
430   return DiagnoseUnexpandedParameterPacks(RE->getBeginLoc(), UPPC_Requirement,
431                                           UnexpandedParms);
432 }
433 
434 bool Sema::DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS,
435                                         UnexpandedParameterPackContext UPPC) {
436   // C++0x [temp.variadic]p5:
437   //   An appearance of a name of a parameter pack that is not expanded is
438   //   ill-formed.
439   if (!SS.getScopeRep() ||
440       !SS.getScopeRep()->containsUnexpandedParameterPack())
441     return false;
442 
443   SmallVector<UnexpandedParameterPack, 2> Unexpanded;
444   CollectUnexpandedParameterPacksVisitor(Unexpanded)
445     .TraverseNestedNameSpecifier(SS.getScopeRep());
446   assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
447   return DiagnoseUnexpandedParameterPacks(SS.getRange().getBegin(),
448                                           UPPC, Unexpanded);
449 }
450 
451 bool Sema::DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo,
452                                          UnexpandedParameterPackContext UPPC) {
453   // C++0x [temp.variadic]p5:
454   //   An appearance of a name of a parameter pack that is not expanded is
455   //   ill-formed.
456   switch (NameInfo.getName().getNameKind()) {
457   case DeclarationName::Identifier:
458   case DeclarationName::ObjCZeroArgSelector:
459   case DeclarationName::ObjCOneArgSelector:
460   case DeclarationName::ObjCMultiArgSelector:
461   case DeclarationName::CXXOperatorName:
462   case DeclarationName::CXXLiteralOperatorName:
463   case DeclarationName::CXXUsingDirective:
464   case DeclarationName::CXXDeductionGuideName:
465     return false;
466 
467   case DeclarationName::CXXConstructorName:
468   case DeclarationName::CXXDestructorName:
469   case DeclarationName::CXXConversionFunctionName:
470     // FIXME: We shouldn't need this null check!
471     if (TypeSourceInfo *TSInfo = NameInfo.getNamedTypeInfo())
472       return DiagnoseUnexpandedParameterPack(NameInfo.getLoc(), TSInfo, UPPC);
473 
474     if (!NameInfo.getName().getCXXNameType()->containsUnexpandedParameterPack())
475       return false;
476 
477     break;
478   }
479 
480   SmallVector<UnexpandedParameterPack, 2> Unexpanded;
481   CollectUnexpandedParameterPacksVisitor(Unexpanded)
482     .TraverseType(NameInfo.getName().getCXXNameType());
483   assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
484   return DiagnoseUnexpandedParameterPacks(NameInfo.getLoc(), UPPC, Unexpanded);
485 }
486 
487 bool Sema::DiagnoseUnexpandedParameterPack(SourceLocation Loc,
488                                            TemplateName Template,
489                                        UnexpandedParameterPackContext UPPC) {
490 
491   if (Template.isNull() || !Template.containsUnexpandedParameterPack())
492     return false;
493 
494   SmallVector<UnexpandedParameterPack, 2> Unexpanded;
495   CollectUnexpandedParameterPacksVisitor(Unexpanded)
496     .TraverseTemplateName(Template);
497   assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
498   return DiagnoseUnexpandedParameterPacks(Loc, UPPC, Unexpanded);
499 }
500 
501 bool Sema::DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg,
502                                          UnexpandedParameterPackContext UPPC) {
503   if (Arg.getArgument().isNull() ||
504       !Arg.getArgument().containsUnexpandedParameterPack())
505     return false;
506 
507   SmallVector<UnexpandedParameterPack, 2> Unexpanded;
508   CollectUnexpandedParameterPacksVisitor(Unexpanded)
509     .TraverseTemplateArgumentLoc(Arg);
510   assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
511   return DiagnoseUnexpandedParameterPacks(Arg.getLocation(), UPPC, Unexpanded);
512 }
513 
514 void Sema::collectUnexpandedParameterPacks(TemplateArgument Arg,
515                    SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
516   CollectUnexpandedParameterPacksVisitor(Unexpanded)
517     .TraverseTemplateArgument(Arg);
518 }
519 
520 void Sema::collectUnexpandedParameterPacks(TemplateArgumentLoc Arg,
521                    SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
522   CollectUnexpandedParameterPacksVisitor(Unexpanded)
523     .TraverseTemplateArgumentLoc(Arg);
524 }
525 
526 void Sema::collectUnexpandedParameterPacks(QualType T,
527                    SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
528   CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseType(T);
529 }
530 
531 void Sema::collectUnexpandedParameterPacks(TypeLoc TL,
532                    SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
533   CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseTypeLoc(TL);
534 }
535 
536 void Sema::collectUnexpandedParameterPacks(
537     NestedNameSpecifierLoc NNS,
538     SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
539   CollectUnexpandedParameterPacksVisitor(Unexpanded)
540       .TraverseNestedNameSpecifierLoc(NNS);
541 }
542 
543 void Sema::collectUnexpandedParameterPacks(
544     const DeclarationNameInfo &NameInfo,
545     SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
546   CollectUnexpandedParameterPacksVisitor(Unexpanded)
547     .TraverseDeclarationNameInfo(NameInfo);
548 }
549 
550 
551 ParsedTemplateArgument
552 Sema::ActOnPackExpansion(const ParsedTemplateArgument &Arg,
553                          SourceLocation EllipsisLoc) {
554   if (Arg.isInvalid())
555     return Arg;
556 
557   switch (Arg.getKind()) {
558   case ParsedTemplateArgument::Type: {
559     TypeResult Result = ActOnPackExpansion(Arg.getAsType(), EllipsisLoc);
560     if (Result.isInvalid())
561       return ParsedTemplateArgument();
562 
563     return ParsedTemplateArgument(Arg.getKind(), Result.get().getAsOpaquePtr(),
564                                   Arg.getLocation());
565   }
566 
567   case ParsedTemplateArgument::NonType: {
568     ExprResult Result = ActOnPackExpansion(Arg.getAsExpr(), EllipsisLoc);
569     if (Result.isInvalid())
570       return ParsedTemplateArgument();
571 
572     return ParsedTemplateArgument(Arg.getKind(), Result.get(),
573                                   Arg.getLocation());
574   }
575 
576   case ParsedTemplateArgument::Template:
577     if (!Arg.getAsTemplate().get().containsUnexpandedParameterPack()) {
578       SourceRange R(Arg.getLocation());
579       if (Arg.getScopeSpec().isValid())
580         R.setBegin(Arg.getScopeSpec().getBeginLoc());
581       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
582         << R;
583       return ParsedTemplateArgument();
584     }
585 
586     return Arg.getTemplatePackExpansion(EllipsisLoc);
587   }
588   llvm_unreachable("Unhandled template argument kind?");
589 }
590 
591 TypeResult Sema::ActOnPackExpansion(ParsedType Type,
592                                     SourceLocation EllipsisLoc) {
593   TypeSourceInfo *TSInfo;
594   GetTypeFromParser(Type, &TSInfo);
595   if (!TSInfo)
596     return true;
597 
598   TypeSourceInfo *TSResult = CheckPackExpansion(TSInfo, EllipsisLoc, None);
599   if (!TSResult)
600     return true;
601 
602   return CreateParsedType(TSResult->getType(), TSResult);
603 }
604 
605 TypeSourceInfo *
606 Sema::CheckPackExpansion(TypeSourceInfo *Pattern, SourceLocation EllipsisLoc,
607                          Optional<unsigned> NumExpansions) {
608   // Create the pack expansion type and source-location information.
609   QualType Result = CheckPackExpansion(Pattern->getType(),
610                                        Pattern->getTypeLoc().getSourceRange(),
611                                        EllipsisLoc, NumExpansions);
612   if (Result.isNull())
613     return nullptr;
614 
615   TypeLocBuilder TLB;
616   TLB.pushFullCopy(Pattern->getTypeLoc());
617   PackExpansionTypeLoc TL = TLB.push<PackExpansionTypeLoc>(Result);
618   TL.setEllipsisLoc(EllipsisLoc);
619 
620   return TLB.getTypeSourceInfo(Context, Result);
621 }
622 
623 QualType Sema::CheckPackExpansion(QualType Pattern, SourceRange PatternRange,
624                                   SourceLocation EllipsisLoc,
625                                   Optional<unsigned> NumExpansions) {
626   // C++11 [temp.variadic]p5:
627   //   The pattern of a pack expansion shall name one or more
628   //   parameter packs that are not expanded by a nested pack
629   //   expansion.
630   //
631   // A pattern containing a deduced type can't occur "naturally" but arises in
632   // the desugaring of an init-capture pack.
633   if (!Pattern->containsUnexpandedParameterPack() &&
634       !Pattern->getContainedDeducedType()) {
635     Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
636       << PatternRange;
637     return QualType();
638   }
639 
640   return Context.getPackExpansionType(Pattern, NumExpansions,
641                                       /*ExpectPackInType=*/false);
642 }
643 
644 ExprResult Sema::ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc) {
645   return CheckPackExpansion(Pattern, EllipsisLoc, None);
646 }
647 
648 ExprResult Sema::CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
649                                     Optional<unsigned> NumExpansions) {
650   if (!Pattern)
651     return ExprError();
652 
653   // C++0x [temp.variadic]p5:
654   //   The pattern of a pack expansion shall name one or more
655   //   parameter packs that are not expanded by a nested pack
656   //   expansion.
657   if (!Pattern->containsUnexpandedParameterPack()) {
658     Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
659     << Pattern->getSourceRange();
660     CorrectDelayedTyposInExpr(Pattern);
661     return ExprError();
662   }
663 
664   // Create the pack expansion expression and source-location information.
665   return new (Context)
666     PackExpansionExpr(Context.DependentTy, Pattern, EllipsisLoc, NumExpansions);
667 }
668 
669 bool Sema::CheckParameterPacksForExpansion(
670     SourceLocation EllipsisLoc, SourceRange PatternRange,
671     ArrayRef<UnexpandedParameterPack> Unexpanded,
672     const MultiLevelTemplateArgumentList &TemplateArgs, bool &ShouldExpand,
673     bool &RetainExpansion, Optional<unsigned> &NumExpansions) {
674   ShouldExpand = true;
675   RetainExpansion = false;
676   std::pair<IdentifierInfo *, SourceLocation> FirstPack;
677   bool HaveFirstPack = false;
678   Optional<unsigned> NumPartialExpansions;
679   SourceLocation PartiallySubstitutedPackLoc;
680 
681   for (ArrayRef<UnexpandedParameterPack>::iterator i = Unexpanded.begin(),
682                                                  end = Unexpanded.end();
683                                                   i != end; ++i) {
684     // Compute the depth and index for this parameter pack.
685     unsigned Depth = 0, Index = 0;
686     IdentifierInfo *Name;
687     bool IsVarDeclPack = false;
688 
689     if (const TemplateTypeParmType *TTP
690         = i->first.dyn_cast<const TemplateTypeParmType *>()) {
691       Depth = TTP->getDepth();
692       Index = TTP->getIndex();
693       Name = TTP->getIdentifier();
694     } else {
695       NamedDecl *ND = i->first.get<NamedDecl *>();
696       if (isa<VarDecl>(ND))
697         IsVarDeclPack = true;
698       else
699         std::tie(Depth, Index) = getDepthAndIndex(ND);
700 
701       Name = ND->getIdentifier();
702     }
703 
704     // Determine the size of this argument pack.
705     unsigned NewPackSize;
706     if (IsVarDeclPack) {
707       // Figure out whether we're instantiating to an argument pack or not.
708       typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
709 
710       llvm::PointerUnion<Decl *, DeclArgumentPack *> *Instantiation
711         = CurrentInstantiationScope->findInstantiationOf(
712                                         i->first.get<NamedDecl *>());
713       if (Instantiation->is<DeclArgumentPack *>()) {
714         // We could expand this function parameter pack.
715         NewPackSize = Instantiation->get<DeclArgumentPack *>()->size();
716       } else {
717         // We can't expand this function parameter pack, so we can't expand
718         // the pack expansion.
719         ShouldExpand = false;
720         continue;
721       }
722     } else {
723       // If we don't have a template argument at this depth/index, then we
724       // cannot expand the pack expansion. Make a note of this, but we still
725       // want to check any parameter packs we *do* have arguments for.
726       if (Depth >= TemplateArgs.getNumLevels() ||
727           !TemplateArgs.hasTemplateArgument(Depth, Index)) {
728         ShouldExpand = false;
729         continue;
730       }
731 
732       // Determine the size of the argument pack.
733       NewPackSize = TemplateArgs(Depth, Index).pack_size();
734     }
735 
736     // C++0x [temp.arg.explicit]p9:
737     //   Template argument deduction can extend the sequence of template
738     //   arguments corresponding to a template parameter pack, even when the
739     //   sequence contains explicitly specified template arguments.
740     if (!IsVarDeclPack && CurrentInstantiationScope) {
741       if (NamedDecl *PartialPack
742                     = CurrentInstantiationScope->getPartiallySubstitutedPack()){
743         unsigned PartialDepth, PartialIndex;
744         std::tie(PartialDepth, PartialIndex) = getDepthAndIndex(PartialPack);
745         if (PartialDepth == Depth && PartialIndex == Index) {
746           RetainExpansion = true;
747           // We don't actually know the new pack size yet.
748           NumPartialExpansions = NewPackSize;
749           PartiallySubstitutedPackLoc = i->second;
750           continue;
751         }
752       }
753     }
754 
755     if (!NumExpansions) {
756       // The is the first pack we've seen for which we have an argument.
757       // Record it.
758       NumExpansions = NewPackSize;
759       FirstPack.first = Name;
760       FirstPack.second = i->second;
761       HaveFirstPack = true;
762       continue;
763     }
764 
765     if (NewPackSize != *NumExpansions) {
766       // C++0x [temp.variadic]p5:
767       //   All of the parameter packs expanded by a pack expansion shall have
768       //   the same number of arguments specified.
769       if (HaveFirstPack)
770         Diag(EllipsisLoc, diag::err_pack_expansion_length_conflict)
771           << FirstPack.first << Name << *NumExpansions << NewPackSize
772           << SourceRange(FirstPack.second) << SourceRange(i->second);
773       else
774         Diag(EllipsisLoc, diag::err_pack_expansion_length_conflict_multilevel)
775           << Name << *NumExpansions << NewPackSize
776           << SourceRange(i->second);
777       return true;
778     }
779   }
780 
781   // If we're performing a partial expansion but we also have a full expansion,
782   // expand to the number of common arguments. For example, given:
783   //
784   //   template<typename ...T> struct A {
785   //     template<typename ...U> void f(pair<T, U>...);
786   //   };
787   //
788   // ... a call to 'A<int, int>().f<int>' should expand the pack once and
789   // retain an expansion.
790   if (NumPartialExpansions) {
791     if (NumExpansions && *NumExpansions < *NumPartialExpansions) {
792       NamedDecl *PartialPack =
793           CurrentInstantiationScope->getPartiallySubstitutedPack();
794       Diag(EllipsisLoc, diag::err_pack_expansion_length_conflict_partial)
795         << PartialPack << *NumPartialExpansions << *NumExpansions
796         << SourceRange(PartiallySubstitutedPackLoc);
797       return true;
798     }
799 
800     NumExpansions = NumPartialExpansions;
801   }
802 
803   return false;
804 }
805 
806 Optional<unsigned> Sema::getNumArgumentsInExpansion(QualType T,
807                           const MultiLevelTemplateArgumentList &TemplateArgs) {
808   QualType Pattern = cast<PackExpansionType>(T)->getPattern();
809   SmallVector<UnexpandedParameterPack, 2> Unexpanded;
810   CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseType(Pattern);
811 
812   Optional<unsigned> Result;
813   for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
814     // Compute the depth and index for this parameter pack.
815     unsigned Depth;
816     unsigned Index;
817 
818     if (const TemplateTypeParmType *TTP
819           = Unexpanded[I].first.dyn_cast<const TemplateTypeParmType *>()) {
820       Depth = TTP->getDepth();
821       Index = TTP->getIndex();
822     } else {
823       NamedDecl *ND = Unexpanded[I].first.get<NamedDecl *>();
824       if (isa<VarDecl>(ND)) {
825         // Function parameter pack or init-capture pack.
826         typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
827 
828         llvm::PointerUnion<Decl *, DeclArgumentPack *> *Instantiation
829           = CurrentInstantiationScope->findInstantiationOf(
830                                         Unexpanded[I].first.get<NamedDecl *>());
831         if (Instantiation->is<Decl*>())
832           // The pattern refers to an unexpanded pack. We're not ready to expand
833           // this pack yet.
834           return None;
835 
836         unsigned Size = Instantiation->get<DeclArgumentPack *>()->size();
837         assert((!Result || *Result == Size) && "inconsistent pack sizes");
838         Result = Size;
839         continue;
840       }
841 
842       std::tie(Depth, Index) = getDepthAndIndex(ND);
843     }
844     if (Depth >= TemplateArgs.getNumLevels() ||
845         !TemplateArgs.hasTemplateArgument(Depth, Index))
846       // The pattern refers to an unknown template argument. We're not ready to
847       // expand this pack yet.
848       return None;
849 
850     // Determine the size of the argument pack.
851     unsigned Size = TemplateArgs(Depth, Index).pack_size();
852     assert((!Result || *Result == Size) && "inconsistent pack sizes");
853     Result = Size;
854   }
855 
856   return Result;
857 }
858 
859 bool Sema::containsUnexpandedParameterPacks(Declarator &D) {
860   const DeclSpec &DS = D.getDeclSpec();
861   switch (DS.getTypeSpecType()) {
862   case TST_typename:
863   case TST_typeofType:
864   case TST_underlyingType:
865   case TST_atomic: {
866     QualType T = DS.getRepAsType().get();
867     if (!T.isNull() && T->containsUnexpandedParameterPack())
868       return true;
869     break;
870   }
871 
872   case TST_typeofExpr:
873   case TST_decltype:
874   case TST_extint:
875     if (DS.getRepAsExpr() &&
876         DS.getRepAsExpr()->containsUnexpandedParameterPack())
877       return true;
878     break;
879 
880   case TST_unspecified:
881   case TST_void:
882   case TST_char:
883   case TST_wchar:
884   case TST_char8:
885   case TST_char16:
886   case TST_char32:
887   case TST_int:
888   case TST_int128:
889   case TST_half:
890   case TST_float:
891   case TST_double:
892   case TST_Accum:
893   case TST_Fract:
894   case TST_Float16:
895   case TST_float128:
896   case TST_ibm128:
897   case TST_bool:
898   case TST_decimal32:
899   case TST_decimal64:
900   case TST_decimal128:
901   case TST_enum:
902   case TST_union:
903   case TST_struct:
904   case TST_interface:
905   case TST_class:
906   case TST_auto:
907   case TST_auto_type:
908   case TST_decltype_auto:
909   case TST_BFloat16:
910 #define GENERIC_IMAGE_TYPE(ImgType, Id) case TST_##ImgType##_t:
911 #include "clang/Basic/OpenCLImageTypes.def"
912   case TST_unknown_anytype:
913   case TST_error:
914     break;
915   }
916 
917   for (unsigned I = 0, N = D.getNumTypeObjects(); I != N; ++I) {
918     const DeclaratorChunk &Chunk = D.getTypeObject(I);
919     switch (Chunk.Kind) {
920     case DeclaratorChunk::Pointer:
921     case DeclaratorChunk::Reference:
922     case DeclaratorChunk::Paren:
923     case DeclaratorChunk::Pipe:
924     case DeclaratorChunk::BlockPointer:
925       // These declarator chunks cannot contain any parameter packs.
926       break;
927 
928     case DeclaratorChunk::Array:
929       if (Chunk.Arr.NumElts &&
930           Chunk.Arr.NumElts->containsUnexpandedParameterPack())
931         return true;
932       break;
933     case DeclaratorChunk::Function:
934       for (unsigned i = 0, e = Chunk.Fun.NumParams; i != e; ++i) {
935         ParmVarDecl *Param = cast<ParmVarDecl>(Chunk.Fun.Params[i].Param);
936         QualType ParamTy = Param->getType();
937         assert(!ParamTy.isNull() && "Couldn't parse type?");
938         if (ParamTy->containsUnexpandedParameterPack()) return true;
939       }
940 
941       if (Chunk.Fun.getExceptionSpecType() == EST_Dynamic) {
942         for (unsigned i = 0; i != Chunk.Fun.getNumExceptions(); ++i) {
943           if (Chunk.Fun.Exceptions[i]
944                   .Ty.get()
945                   ->containsUnexpandedParameterPack())
946             return true;
947         }
948       } else if (isComputedNoexcept(Chunk.Fun.getExceptionSpecType()) &&
949                  Chunk.Fun.NoexceptExpr->containsUnexpandedParameterPack())
950         return true;
951 
952       if (Chunk.Fun.hasTrailingReturnType()) {
953         QualType T = Chunk.Fun.getTrailingReturnType().get();
954         if (!T.isNull() && T->containsUnexpandedParameterPack())
955           return true;
956       }
957       break;
958 
959     case DeclaratorChunk::MemberPointer:
960       if (Chunk.Mem.Scope().getScopeRep() &&
961           Chunk.Mem.Scope().getScopeRep()->containsUnexpandedParameterPack())
962         return true;
963       break;
964     }
965   }
966 
967   if (Expr *TRC = D.getTrailingRequiresClause())
968     if (TRC->containsUnexpandedParameterPack())
969       return true;
970 
971   return false;
972 }
973 
974 namespace {
975 
976 // Callback to only accept typo corrections that refer to parameter packs.
977 class ParameterPackValidatorCCC final : public CorrectionCandidateCallback {
978  public:
979   bool ValidateCandidate(const TypoCorrection &candidate) override {
980     NamedDecl *ND = candidate.getCorrectionDecl();
981     return ND && ND->isParameterPack();
982   }
983 
984   std::unique_ptr<CorrectionCandidateCallback> clone() override {
985     return std::make_unique<ParameterPackValidatorCCC>(*this);
986   }
987 };
988 
989 }
990 
991 /// Called when an expression computing the size of a parameter pack
992 /// is parsed.
993 ///
994 /// \code
995 /// template<typename ...Types> struct count {
996 ///   static const unsigned value = sizeof...(Types);
997 /// };
998 /// \endcode
999 ///
1000 //
1001 /// \param OpLoc The location of the "sizeof" keyword.
1002 /// \param Name The name of the parameter pack whose size will be determined.
1003 /// \param NameLoc The source location of the name of the parameter pack.
1004 /// \param RParenLoc The location of the closing parentheses.
1005 ExprResult Sema::ActOnSizeofParameterPackExpr(Scope *S,
1006                                               SourceLocation OpLoc,
1007                                               IdentifierInfo &Name,
1008                                               SourceLocation NameLoc,
1009                                               SourceLocation RParenLoc) {
1010   // C++0x [expr.sizeof]p5:
1011   //   The identifier in a sizeof... expression shall name a parameter pack.
1012   LookupResult R(*this, &Name, NameLoc, LookupOrdinaryName);
1013   LookupName(R, S);
1014 
1015   NamedDecl *ParameterPack = nullptr;
1016   switch (R.getResultKind()) {
1017   case LookupResult::Found:
1018     ParameterPack = R.getFoundDecl();
1019     break;
1020 
1021   case LookupResult::NotFound:
1022   case LookupResult::NotFoundInCurrentInstantiation: {
1023     ParameterPackValidatorCCC CCC{};
1024     if (TypoCorrection Corrected =
1025             CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, nullptr,
1026                         CCC, CTK_ErrorRecovery)) {
1027       diagnoseTypo(Corrected,
1028                    PDiag(diag::err_sizeof_pack_no_pack_name_suggest) << &Name,
1029                    PDiag(diag::note_parameter_pack_here));
1030       ParameterPack = Corrected.getCorrectionDecl();
1031     }
1032     break;
1033   }
1034   case LookupResult::FoundOverloaded:
1035   case LookupResult::FoundUnresolvedValue:
1036     break;
1037 
1038   case LookupResult::Ambiguous:
1039     DiagnoseAmbiguousLookup(R);
1040     return ExprError();
1041   }
1042 
1043   if (!ParameterPack || !ParameterPack->isParameterPack()) {
1044     Diag(NameLoc, diag::err_sizeof_pack_no_pack_name)
1045       << &Name;
1046     return ExprError();
1047   }
1048 
1049   MarkAnyDeclReferenced(OpLoc, ParameterPack, true);
1050 
1051   return SizeOfPackExpr::Create(Context, OpLoc, ParameterPack, NameLoc,
1052                                 RParenLoc);
1053 }
1054 
1055 TemplateArgumentLoc
1056 Sema::getTemplateArgumentPackExpansionPattern(
1057       TemplateArgumentLoc OrigLoc,
1058       SourceLocation &Ellipsis, Optional<unsigned> &NumExpansions) const {
1059   const TemplateArgument &Argument = OrigLoc.getArgument();
1060   assert(Argument.isPackExpansion());
1061   switch (Argument.getKind()) {
1062   case TemplateArgument::Type: {
1063     // FIXME: We shouldn't ever have to worry about missing
1064     // type-source info!
1065     TypeSourceInfo *ExpansionTSInfo = OrigLoc.getTypeSourceInfo();
1066     if (!ExpansionTSInfo)
1067       ExpansionTSInfo = Context.getTrivialTypeSourceInfo(Argument.getAsType(),
1068                                                          Ellipsis);
1069     PackExpansionTypeLoc Expansion =
1070         ExpansionTSInfo->getTypeLoc().castAs<PackExpansionTypeLoc>();
1071     Ellipsis = Expansion.getEllipsisLoc();
1072 
1073     TypeLoc Pattern = Expansion.getPatternLoc();
1074     NumExpansions = Expansion.getTypePtr()->getNumExpansions();
1075 
1076     // We need to copy the TypeLoc because TemplateArgumentLocs store a
1077     // TypeSourceInfo.
1078     // FIXME: Find some way to avoid the copy?
1079     TypeLocBuilder TLB;
1080     TLB.pushFullCopy(Pattern);
1081     TypeSourceInfo *PatternTSInfo =
1082         TLB.getTypeSourceInfo(Context, Pattern.getType());
1083     return TemplateArgumentLoc(TemplateArgument(Pattern.getType()),
1084                                PatternTSInfo);
1085   }
1086 
1087   case TemplateArgument::Expression: {
1088     PackExpansionExpr *Expansion
1089       = cast<PackExpansionExpr>(Argument.getAsExpr());
1090     Expr *Pattern = Expansion->getPattern();
1091     Ellipsis = Expansion->getEllipsisLoc();
1092     NumExpansions = Expansion->getNumExpansions();
1093     return TemplateArgumentLoc(Pattern, Pattern);
1094   }
1095 
1096   case TemplateArgument::TemplateExpansion:
1097     Ellipsis = OrigLoc.getTemplateEllipsisLoc();
1098     NumExpansions = Argument.getNumTemplateExpansions();
1099     return TemplateArgumentLoc(Context, Argument.getPackExpansionPattern(),
1100                                OrigLoc.getTemplateQualifierLoc(),
1101                                OrigLoc.getTemplateNameLoc());
1102 
1103   case TemplateArgument::Declaration:
1104   case TemplateArgument::NullPtr:
1105   case TemplateArgument::Template:
1106   case TemplateArgument::Integral:
1107   case TemplateArgument::Pack:
1108   case TemplateArgument::Null:
1109     return TemplateArgumentLoc();
1110   }
1111 
1112   llvm_unreachable("Invalid TemplateArgument Kind!");
1113 }
1114 
1115 Optional<unsigned> Sema::getFullyPackExpandedSize(TemplateArgument Arg) {
1116   assert(Arg.containsUnexpandedParameterPack());
1117 
1118   // If this is a substituted pack, grab that pack. If not, we don't know
1119   // the size yet.
1120   // FIXME: We could find a size in more cases by looking for a substituted
1121   // pack anywhere within this argument, but that's not necessary in the common
1122   // case for 'sizeof...(A)' handling.
1123   TemplateArgument Pack;
1124   switch (Arg.getKind()) {
1125   case TemplateArgument::Type:
1126     if (auto *Subst = Arg.getAsType()->getAs<SubstTemplateTypeParmPackType>())
1127       Pack = Subst->getArgumentPack();
1128     else
1129       return None;
1130     break;
1131 
1132   case TemplateArgument::Expression:
1133     if (auto *Subst =
1134             dyn_cast<SubstNonTypeTemplateParmPackExpr>(Arg.getAsExpr()))
1135       Pack = Subst->getArgumentPack();
1136     else if (auto *Subst = dyn_cast<FunctionParmPackExpr>(Arg.getAsExpr()))  {
1137       for (VarDecl *PD : *Subst)
1138         if (PD->isParameterPack())
1139           return None;
1140       return Subst->getNumExpansions();
1141     } else
1142       return None;
1143     break;
1144 
1145   case TemplateArgument::Template:
1146     if (SubstTemplateTemplateParmPackStorage *Subst =
1147             Arg.getAsTemplate().getAsSubstTemplateTemplateParmPack())
1148       Pack = Subst->getArgumentPack();
1149     else
1150       return None;
1151     break;
1152 
1153   case TemplateArgument::Declaration:
1154   case TemplateArgument::NullPtr:
1155   case TemplateArgument::TemplateExpansion:
1156   case TemplateArgument::Integral:
1157   case TemplateArgument::Pack:
1158   case TemplateArgument::Null:
1159     return None;
1160   }
1161 
1162   // Check that no argument in the pack is itself a pack expansion.
1163   for (TemplateArgument Elem : Pack.pack_elements()) {
1164     // There's no point recursing in this case; we would have already
1165     // expanded this pack expansion into the enclosing pack if we could.
1166     if (Elem.isPackExpansion())
1167       return None;
1168   }
1169   return Pack.pack_size();
1170 }
1171 
1172 static void CheckFoldOperand(Sema &S, Expr *E) {
1173   if (!E)
1174     return;
1175 
1176   E = E->IgnoreImpCasts();
1177   auto *OCE = dyn_cast<CXXOperatorCallExpr>(E);
1178   if ((OCE && OCE->isInfixBinaryOp()) || isa<BinaryOperator>(E) ||
1179       isa<AbstractConditionalOperator>(E)) {
1180     S.Diag(E->getExprLoc(), diag::err_fold_expression_bad_operand)
1181         << E->getSourceRange()
1182         << FixItHint::CreateInsertion(E->getBeginLoc(), "(")
1183         << FixItHint::CreateInsertion(E->getEndLoc(), ")");
1184   }
1185 }
1186 
1187 ExprResult Sema::ActOnCXXFoldExpr(Scope *S, SourceLocation LParenLoc, Expr *LHS,
1188                                   tok::TokenKind Operator,
1189                                   SourceLocation EllipsisLoc, Expr *RHS,
1190                                   SourceLocation RParenLoc) {
1191   // LHS and RHS must be cast-expressions. We allow an arbitrary expression
1192   // in the parser and reduce down to just cast-expressions here.
1193   CheckFoldOperand(*this, LHS);
1194   CheckFoldOperand(*this, RHS);
1195 
1196   auto DiscardOperands = [&] {
1197     CorrectDelayedTyposInExpr(LHS);
1198     CorrectDelayedTyposInExpr(RHS);
1199   };
1200 
1201   // [expr.prim.fold]p3:
1202   //   In a binary fold, op1 and op2 shall be the same fold-operator, and
1203   //   either e1 shall contain an unexpanded parameter pack or e2 shall contain
1204   //   an unexpanded parameter pack, but not both.
1205   if (LHS && RHS &&
1206       LHS->containsUnexpandedParameterPack() ==
1207           RHS->containsUnexpandedParameterPack()) {
1208     DiscardOperands();
1209     return Diag(EllipsisLoc,
1210                 LHS->containsUnexpandedParameterPack()
1211                     ? diag::err_fold_expression_packs_both_sides
1212                     : diag::err_pack_expansion_without_parameter_packs)
1213         << LHS->getSourceRange() << RHS->getSourceRange();
1214   }
1215 
1216   // [expr.prim.fold]p2:
1217   //   In a unary fold, the cast-expression shall contain an unexpanded
1218   //   parameter pack.
1219   if (!LHS || !RHS) {
1220     Expr *Pack = LHS ? LHS : RHS;
1221     assert(Pack && "fold expression with neither LHS nor RHS");
1222     DiscardOperands();
1223     if (!Pack->containsUnexpandedParameterPack())
1224       return Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1225              << Pack->getSourceRange();
1226   }
1227 
1228   BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Operator);
1229 
1230   // Perform first-phase name lookup now.
1231   UnresolvedLookupExpr *ULE = nullptr;
1232   {
1233     UnresolvedSet<16> Functions;
1234     LookupBinOp(S, EllipsisLoc, Opc, Functions);
1235     if (!Functions.empty()) {
1236       DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(
1237           BinaryOperator::getOverloadedOperator(Opc));
1238       ExprResult Callee = CreateUnresolvedLookupExpr(
1239           /*NamingClass*/ nullptr, NestedNameSpecifierLoc(),
1240           DeclarationNameInfo(OpName, EllipsisLoc), Functions);
1241       if (Callee.isInvalid())
1242         return ExprError();
1243       ULE = cast<UnresolvedLookupExpr>(Callee.get());
1244     }
1245   }
1246 
1247   return BuildCXXFoldExpr(ULE, LParenLoc, LHS, Opc, EllipsisLoc, RHS, RParenLoc,
1248                           None);
1249 }
1250 
1251 ExprResult Sema::BuildCXXFoldExpr(UnresolvedLookupExpr *Callee,
1252                                   SourceLocation LParenLoc, Expr *LHS,
1253                                   BinaryOperatorKind Operator,
1254                                   SourceLocation EllipsisLoc, Expr *RHS,
1255                                   SourceLocation RParenLoc,
1256                                   Optional<unsigned> NumExpansions) {
1257   return new (Context)
1258       CXXFoldExpr(Context.DependentTy, Callee, LParenLoc, LHS, Operator,
1259                   EllipsisLoc, RHS, RParenLoc, NumExpansions);
1260 }
1261 
1262 ExprResult Sema::BuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc,
1263                                        BinaryOperatorKind Operator) {
1264   // [temp.variadic]p9:
1265   //   If N is zero for a unary fold-expression, the value of the expression is
1266   //       &&  ->  true
1267   //       ||  ->  false
1268   //       ,   ->  void()
1269   //   if the operator is not listed [above], the instantiation is ill-formed.
1270   //
1271   // Note that we need to use something like int() here, not merely 0, to
1272   // prevent the result from being a null pointer constant.
1273   QualType ScalarType;
1274   switch (Operator) {
1275   case BO_LOr:
1276     return ActOnCXXBoolLiteral(EllipsisLoc, tok::kw_false);
1277   case BO_LAnd:
1278     return ActOnCXXBoolLiteral(EllipsisLoc, tok::kw_true);
1279   case BO_Comma:
1280     ScalarType = Context.VoidTy;
1281     break;
1282 
1283   default:
1284     return Diag(EllipsisLoc, diag::err_fold_expression_empty)
1285         << BinaryOperator::getOpcodeStr(Operator);
1286   }
1287 
1288   return new (Context) CXXScalarValueInitExpr(
1289       ScalarType, Context.getTrivialTypeSourceInfo(ScalarType, EllipsisLoc),
1290       EllipsisLoc);
1291 }
1292