]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm-project/clang/lib/Sema/SemaTemplateVariadic.cpp
Fix clang assertion when compiling the devel/onetbb port
[FreeBSD/FreeBSD.git] / contrib / llvm-project / clang / lib / Sema / SemaTemplateVariadic.cpp
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   DiagnosticBuilder 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::DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS,
412                                         UnexpandedParameterPackContext UPPC) {
413   // C++0x [temp.variadic]p5:
414   //   An appearance of a name of a parameter pack that is not expanded is
415   //   ill-formed.
416   if (!SS.getScopeRep() ||
417       !SS.getScopeRep()->containsUnexpandedParameterPack())
418     return false;
419
420   SmallVector<UnexpandedParameterPack, 2> Unexpanded;
421   CollectUnexpandedParameterPacksVisitor(Unexpanded)
422     .TraverseNestedNameSpecifier(SS.getScopeRep());
423   assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
424   return DiagnoseUnexpandedParameterPacks(SS.getRange().getBegin(),
425                                           UPPC, Unexpanded);
426 }
427
428 bool Sema::DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo,
429                                          UnexpandedParameterPackContext UPPC) {
430   // C++0x [temp.variadic]p5:
431   //   An appearance of a name of a parameter pack that is not expanded is
432   //   ill-formed.
433   switch (NameInfo.getName().getNameKind()) {
434   case DeclarationName::Identifier:
435   case DeclarationName::ObjCZeroArgSelector:
436   case DeclarationName::ObjCOneArgSelector:
437   case DeclarationName::ObjCMultiArgSelector:
438   case DeclarationName::CXXOperatorName:
439   case DeclarationName::CXXLiteralOperatorName:
440   case DeclarationName::CXXUsingDirective:
441   case DeclarationName::CXXDeductionGuideName:
442     return false;
443
444   case DeclarationName::CXXConstructorName:
445   case DeclarationName::CXXDestructorName:
446   case DeclarationName::CXXConversionFunctionName:
447     // FIXME: We shouldn't need this null check!
448     if (TypeSourceInfo *TSInfo = NameInfo.getNamedTypeInfo())
449       return DiagnoseUnexpandedParameterPack(NameInfo.getLoc(), TSInfo, UPPC);
450
451     if (!NameInfo.getName().getCXXNameType()->containsUnexpandedParameterPack())
452       return false;
453
454     break;
455   }
456
457   SmallVector<UnexpandedParameterPack, 2> Unexpanded;
458   CollectUnexpandedParameterPacksVisitor(Unexpanded)
459     .TraverseType(NameInfo.getName().getCXXNameType());
460   assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
461   return DiagnoseUnexpandedParameterPacks(NameInfo.getLoc(), UPPC, Unexpanded);
462 }
463
464 bool Sema::DiagnoseUnexpandedParameterPack(SourceLocation Loc,
465                                            TemplateName Template,
466                                        UnexpandedParameterPackContext UPPC) {
467
468   if (Template.isNull() || !Template.containsUnexpandedParameterPack())
469     return false;
470
471   SmallVector<UnexpandedParameterPack, 2> Unexpanded;
472   CollectUnexpandedParameterPacksVisitor(Unexpanded)
473     .TraverseTemplateName(Template);
474   assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
475   return DiagnoseUnexpandedParameterPacks(Loc, UPPC, Unexpanded);
476 }
477
478 bool Sema::DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg,
479                                          UnexpandedParameterPackContext UPPC) {
480   if (Arg.getArgument().isNull() ||
481       !Arg.getArgument().containsUnexpandedParameterPack())
482     return false;
483
484   SmallVector<UnexpandedParameterPack, 2> Unexpanded;
485   CollectUnexpandedParameterPacksVisitor(Unexpanded)
486     .TraverseTemplateArgumentLoc(Arg);
487   assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
488   return DiagnoseUnexpandedParameterPacks(Arg.getLocation(), UPPC, Unexpanded);
489 }
490
491 void Sema::collectUnexpandedParameterPacks(TemplateArgument Arg,
492                    SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
493   CollectUnexpandedParameterPacksVisitor(Unexpanded)
494     .TraverseTemplateArgument(Arg);
495 }
496
497 void Sema::collectUnexpandedParameterPacks(TemplateArgumentLoc Arg,
498                    SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
499   CollectUnexpandedParameterPacksVisitor(Unexpanded)
500     .TraverseTemplateArgumentLoc(Arg);
501 }
502
503 void Sema::collectUnexpandedParameterPacks(QualType T,
504                    SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
505   CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseType(T);
506 }
507
508 void Sema::collectUnexpandedParameterPacks(TypeLoc TL,
509                    SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
510   CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseTypeLoc(TL);
511 }
512
513 void Sema::collectUnexpandedParameterPacks(
514     NestedNameSpecifierLoc NNS,
515     SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
516   CollectUnexpandedParameterPacksVisitor(Unexpanded)
517       .TraverseNestedNameSpecifierLoc(NNS);
518 }
519
520 void Sema::collectUnexpandedParameterPacks(
521     const DeclarationNameInfo &NameInfo,
522     SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
523   CollectUnexpandedParameterPacksVisitor(Unexpanded)
524     .TraverseDeclarationNameInfo(NameInfo);
525 }
526
527
528 ParsedTemplateArgument
529 Sema::ActOnPackExpansion(const ParsedTemplateArgument &Arg,
530                          SourceLocation EllipsisLoc) {
531   if (Arg.isInvalid())
532     return Arg;
533
534   switch (Arg.getKind()) {
535   case ParsedTemplateArgument::Type: {
536     TypeResult Result = ActOnPackExpansion(Arg.getAsType(), EllipsisLoc);
537     if (Result.isInvalid())
538       return ParsedTemplateArgument();
539
540     return ParsedTemplateArgument(Arg.getKind(), Result.get().getAsOpaquePtr(),
541                                   Arg.getLocation());
542   }
543
544   case ParsedTemplateArgument::NonType: {
545     ExprResult Result = ActOnPackExpansion(Arg.getAsExpr(), EllipsisLoc);
546     if (Result.isInvalid())
547       return ParsedTemplateArgument();
548
549     return ParsedTemplateArgument(Arg.getKind(), Result.get(),
550                                   Arg.getLocation());
551   }
552
553   case ParsedTemplateArgument::Template:
554     if (!Arg.getAsTemplate().get().containsUnexpandedParameterPack()) {
555       SourceRange R(Arg.getLocation());
556       if (Arg.getScopeSpec().isValid())
557         R.setBegin(Arg.getScopeSpec().getBeginLoc());
558       Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
559         << R;
560       return ParsedTemplateArgument();
561     }
562
563     return Arg.getTemplatePackExpansion(EllipsisLoc);
564   }
565   llvm_unreachable("Unhandled template argument kind?");
566 }
567
568 TypeResult Sema::ActOnPackExpansion(ParsedType Type,
569                                     SourceLocation EllipsisLoc) {
570   TypeSourceInfo *TSInfo;
571   GetTypeFromParser(Type, &TSInfo);
572   if (!TSInfo)
573     return true;
574
575   TypeSourceInfo *TSResult = CheckPackExpansion(TSInfo, EllipsisLoc, None);
576   if (!TSResult)
577     return true;
578
579   return CreateParsedType(TSResult->getType(), TSResult);
580 }
581
582 TypeSourceInfo *
583 Sema::CheckPackExpansion(TypeSourceInfo *Pattern, SourceLocation EllipsisLoc,
584                          Optional<unsigned> NumExpansions) {
585   // Create the pack expansion type and source-location information.
586   QualType Result = CheckPackExpansion(Pattern->getType(),
587                                        Pattern->getTypeLoc().getSourceRange(),
588                                        EllipsisLoc, NumExpansions);
589   if (Result.isNull())
590     return nullptr;
591
592   TypeLocBuilder TLB;
593   TLB.pushFullCopy(Pattern->getTypeLoc());
594   PackExpansionTypeLoc TL = TLB.push<PackExpansionTypeLoc>(Result);
595   TL.setEllipsisLoc(EllipsisLoc);
596
597   return TLB.getTypeSourceInfo(Context, Result);
598 }
599
600 QualType Sema::CheckPackExpansion(QualType Pattern, SourceRange PatternRange,
601                                   SourceLocation EllipsisLoc,
602                                   Optional<unsigned> NumExpansions) {
603   // C++11 [temp.variadic]p5:
604   //   The pattern of a pack expansion shall name one or more
605   //   parameter packs that are not expanded by a nested pack
606   //   expansion.
607   //
608   // A pattern containing a deduced type can't occur "naturally" but arises in
609   // the desugaring of an init-capture pack.
610   if (!Pattern->containsUnexpandedParameterPack() &&
611       !Pattern->getContainedDeducedType()) {
612     Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
613       << PatternRange;
614     return QualType();
615   }
616
617   return Context.getPackExpansionType(Pattern, NumExpansions,
618                                       /*ExpectPackInType=*/false);
619 }
620
621 ExprResult Sema::ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc) {
622   return CheckPackExpansion(Pattern, EllipsisLoc, None);
623 }
624
625 ExprResult Sema::CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
626                                     Optional<unsigned> NumExpansions) {
627   if (!Pattern)
628     return ExprError();
629
630   // C++0x [temp.variadic]p5:
631   //   The pattern of a pack expansion shall name one or more
632   //   parameter packs that are not expanded by a nested pack
633   //   expansion.
634   if (!Pattern->containsUnexpandedParameterPack()) {
635     Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
636     << Pattern->getSourceRange();
637     CorrectDelayedTyposInExpr(Pattern);
638     return ExprError();
639   }
640
641   // Create the pack expansion expression and source-location information.
642   return new (Context)
643     PackExpansionExpr(Context.DependentTy, Pattern, EllipsisLoc, NumExpansions);
644 }
645
646 bool Sema::CheckParameterPacksForExpansion(
647     SourceLocation EllipsisLoc, SourceRange PatternRange,
648     ArrayRef<UnexpandedParameterPack> Unexpanded,
649     const MultiLevelTemplateArgumentList &TemplateArgs, bool &ShouldExpand,
650     bool &RetainExpansion, Optional<unsigned> &NumExpansions) {
651   ShouldExpand = true;
652   RetainExpansion = false;
653   std::pair<IdentifierInfo *, SourceLocation> FirstPack;
654   bool HaveFirstPack = false;
655   Optional<unsigned> NumPartialExpansions;
656   SourceLocation PartiallySubstitutedPackLoc;
657
658   for (ArrayRef<UnexpandedParameterPack>::iterator i = Unexpanded.begin(),
659                                                  end = Unexpanded.end();
660                                                   i != end; ++i) {
661     // Compute the depth and index for this parameter pack.
662     unsigned Depth = 0, Index = 0;
663     IdentifierInfo *Name;
664     bool IsVarDeclPack = false;
665
666     if (const TemplateTypeParmType *TTP
667         = i->first.dyn_cast<const TemplateTypeParmType *>()) {
668       Depth = TTP->getDepth();
669       Index = TTP->getIndex();
670       Name = TTP->getIdentifier();
671     } else {
672       NamedDecl *ND = i->first.get<NamedDecl *>();
673       if (isa<VarDecl>(ND))
674         IsVarDeclPack = true;
675       else
676         std::tie(Depth, Index) = getDepthAndIndex(ND);
677
678       Name = ND->getIdentifier();
679     }
680
681     // Determine the size of this argument pack.
682     unsigned NewPackSize;
683     if (IsVarDeclPack) {
684       // Figure out whether we're instantiating to an argument pack or not.
685       typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
686
687       llvm::PointerUnion<Decl *, DeclArgumentPack *> *Instantiation
688         = CurrentInstantiationScope->findInstantiationOf(
689                                         i->first.get<NamedDecl *>());
690       if (Instantiation->is<DeclArgumentPack *>()) {
691         // We could expand this function parameter pack.
692         NewPackSize = Instantiation->get<DeclArgumentPack *>()->size();
693       } else {
694         // We can't expand this function parameter pack, so we can't expand
695         // the pack expansion.
696         ShouldExpand = false;
697         continue;
698       }
699     } else {
700       // If we don't have a template argument at this depth/index, then we
701       // cannot expand the pack expansion. Make a note of this, but we still
702       // want to check any parameter packs we *do* have arguments for.
703       if (Depth >= TemplateArgs.getNumLevels() ||
704           !TemplateArgs.hasTemplateArgument(Depth, Index)) {
705         ShouldExpand = false;
706         continue;
707       }
708
709       // Determine the size of the argument pack.
710       NewPackSize = TemplateArgs(Depth, Index).pack_size();
711     }
712
713     // C++0x [temp.arg.explicit]p9:
714     //   Template argument deduction can extend the sequence of template
715     //   arguments corresponding to a template parameter pack, even when the
716     //   sequence contains explicitly specified template arguments.
717     if (!IsVarDeclPack && CurrentInstantiationScope) {
718       if (NamedDecl *PartialPack
719                     = CurrentInstantiationScope->getPartiallySubstitutedPack()){
720         unsigned PartialDepth, PartialIndex;
721         std::tie(PartialDepth, PartialIndex) = getDepthAndIndex(PartialPack);
722         if (PartialDepth == Depth && PartialIndex == Index) {
723           RetainExpansion = true;
724           // We don't actually know the new pack size yet.
725           NumPartialExpansions = NewPackSize;
726           PartiallySubstitutedPackLoc = i->second;
727           continue;
728         }
729       }
730     }
731
732     if (!NumExpansions) {
733       // The is the first pack we've seen for which we have an argument.
734       // Record it.
735       NumExpansions = NewPackSize;
736       FirstPack.first = Name;
737       FirstPack.second = i->second;
738       HaveFirstPack = true;
739       continue;
740     }
741
742     if (NewPackSize != *NumExpansions) {
743       // C++0x [temp.variadic]p5:
744       //   All of the parameter packs expanded by a pack expansion shall have
745       //   the same number of arguments specified.
746       if (HaveFirstPack)
747         Diag(EllipsisLoc, diag::err_pack_expansion_length_conflict)
748           << FirstPack.first << Name << *NumExpansions << NewPackSize
749           << SourceRange(FirstPack.second) << SourceRange(i->second);
750       else
751         Diag(EllipsisLoc, diag::err_pack_expansion_length_conflict_multilevel)
752           << Name << *NumExpansions << NewPackSize
753           << SourceRange(i->second);
754       return true;
755     }
756   }
757
758   // If we're performing a partial expansion but we also have a full expansion,
759   // expand to the number of common arguments. For example, given:
760   //
761   //   template<typename ...T> struct A {
762   //     template<typename ...U> void f(pair<T, U>...);
763   //   };
764   //
765   // ... a call to 'A<int, int>().f<int>' should expand the pack once and
766   // retain an expansion.
767   if (NumPartialExpansions) {
768     if (NumExpansions && *NumExpansions < *NumPartialExpansions) {
769       NamedDecl *PartialPack =
770           CurrentInstantiationScope->getPartiallySubstitutedPack();
771       Diag(EllipsisLoc, diag::err_pack_expansion_length_conflict_partial)
772         << PartialPack << *NumPartialExpansions << *NumExpansions
773         << SourceRange(PartiallySubstitutedPackLoc);
774       return true;
775     }
776
777     NumExpansions = NumPartialExpansions;
778   }
779
780   return false;
781 }
782
783 Optional<unsigned> Sema::getNumArgumentsInExpansion(QualType T,
784                           const MultiLevelTemplateArgumentList &TemplateArgs) {
785   QualType Pattern = cast<PackExpansionType>(T)->getPattern();
786   SmallVector<UnexpandedParameterPack, 2> Unexpanded;
787   CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseType(Pattern);
788
789   Optional<unsigned> Result;
790   for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
791     // Compute the depth and index for this parameter pack.
792     unsigned Depth;
793     unsigned Index;
794
795     if (const TemplateTypeParmType *TTP
796           = Unexpanded[I].first.dyn_cast<const TemplateTypeParmType *>()) {
797       Depth = TTP->getDepth();
798       Index = TTP->getIndex();
799     } else {
800       NamedDecl *ND = Unexpanded[I].first.get<NamedDecl *>();
801       if (isa<VarDecl>(ND)) {
802         // Function parameter pack or init-capture pack.
803         typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
804
805         llvm::PointerUnion<Decl *, DeclArgumentPack *> *Instantiation
806           = CurrentInstantiationScope->findInstantiationOf(
807                                         Unexpanded[I].first.get<NamedDecl *>());
808         if (Instantiation->is<Decl*>())
809           // The pattern refers to an unexpanded pack. We're not ready to expand
810           // this pack yet.
811           return None;
812
813         unsigned Size = Instantiation->get<DeclArgumentPack *>()->size();
814         assert((!Result || *Result == Size) && "inconsistent pack sizes");
815         Result = Size;
816         continue;
817       }
818
819       std::tie(Depth, Index) = getDepthAndIndex(ND);
820     }
821     if (Depth >= TemplateArgs.getNumLevels() ||
822         !TemplateArgs.hasTemplateArgument(Depth, Index))
823       // The pattern refers to an unknown template argument. We're not ready to
824       // expand this pack yet.
825       return None;
826
827     // Determine the size of the argument pack.
828     unsigned Size = TemplateArgs(Depth, Index).pack_size();
829     assert((!Result || *Result == Size) && "inconsistent pack sizes");
830     Result = Size;
831   }
832
833   return Result;
834 }
835
836 bool Sema::containsUnexpandedParameterPacks(Declarator &D) {
837   const DeclSpec &DS = D.getDeclSpec();
838   switch (DS.getTypeSpecType()) {
839   case TST_typename:
840   case TST_typeofType:
841   case TST_underlyingType:
842   case TST_atomic: {
843     QualType T = DS.getRepAsType().get();
844     if (!T.isNull() && T->containsUnexpandedParameterPack())
845       return true;
846     break;
847   }
848
849   case TST_typeofExpr:
850   case TST_decltype:
851   case TST_extint:
852     if (DS.getRepAsExpr() &&
853         DS.getRepAsExpr()->containsUnexpandedParameterPack())
854       return true;
855     break;
856
857   case TST_unspecified:
858   case TST_void:
859   case TST_char:
860   case TST_wchar:
861   case TST_char8:
862   case TST_char16:
863   case TST_char32:
864   case TST_int:
865   case TST_int128:
866   case TST_half:
867   case TST_float:
868   case TST_double:
869   case TST_Accum:
870   case TST_Fract:
871   case TST_Float16:
872   case TST_float128:
873   case TST_bool:
874   case TST_decimal32:
875   case TST_decimal64:
876   case TST_decimal128:
877   case TST_enum:
878   case TST_union:
879   case TST_struct:
880   case TST_interface:
881   case TST_class:
882   case TST_auto:
883   case TST_auto_type:
884   case TST_decltype_auto:
885   case TST_BFloat16:
886 #define GENERIC_IMAGE_TYPE(ImgType, Id) case TST_##ImgType##_t:
887 #include "clang/Basic/OpenCLImageTypes.def"
888   case TST_unknown_anytype:
889   case TST_error:
890     break;
891   }
892
893   for (unsigned I = 0, N = D.getNumTypeObjects(); I != N; ++I) {
894     const DeclaratorChunk &Chunk = D.getTypeObject(I);
895     switch (Chunk.Kind) {
896     case DeclaratorChunk::Pointer:
897     case DeclaratorChunk::Reference:
898     case DeclaratorChunk::Paren:
899     case DeclaratorChunk::Pipe:
900     case DeclaratorChunk::BlockPointer:
901       // These declarator chunks cannot contain any parameter packs.
902       break;
903
904     case DeclaratorChunk::Array:
905       if (Chunk.Arr.NumElts &&
906           Chunk.Arr.NumElts->containsUnexpandedParameterPack())
907         return true;
908       break;
909     case DeclaratorChunk::Function:
910       for (unsigned i = 0, e = Chunk.Fun.NumParams; i != e; ++i) {
911         ParmVarDecl *Param = cast<ParmVarDecl>(Chunk.Fun.Params[i].Param);
912         QualType ParamTy = Param->getType();
913         assert(!ParamTy.isNull() && "Couldn't parse type?");
914         if (ParamTy->containsUnexpandedParameterPack()) return true;
915       }
916
917       if (Chunk.Fun.getExceptionSpecType() == EST_Dynamic) {
918         for (unsigned i = 0; i != Chunk.Fun.getNumExceptions(); ++i) {
919           if (Chunk.Fun.Exceptions[i]
920                   .Ty.get()
921                   ->containsUnexpandedParameterPack())
922             return true;
923         }
924       } else if (isComputedNoexcept(Chunk.Fun.getExceptionSpecType()) &&
925                  Chunk.Fun.NoexceptExpr->containsUnexpandedParameterPack())
926         return true;
927
928       if (Chunk.Fun.hasTrailingReturnType()) {
929         QualType T = Chunk.Fun.getTrailingReturnType().get();
930         if (!T.isNull() && T->containsUnexpandedParameterPack())
931           return true;
932       }
933       break;
934
935     case DeclaratorChunk::MemberPointer:
936       if (Chunk.Mem.Scope().getScopeRep() &&
937           Chunk.Mem.Scope().getScopeRep()->containsUnexpandedParameterPack())
938         return true;
939       break;
940     }
941   }
942
943   if (Expr *TRC = D.getTrailingRequiresClause())
944     if (TRC->containsUnexpandedParameterPack())
945       return true;
946
947   return false;
948 }
949
950 namespace {
951
952 // Callback to only accept typo corrections that refer to parameter packs.
953 class ParameterPackValidatorCCC final : public CorrectionCandidateCallback {
954  public:
955   bool ValidateCandidate(const TypoCorrection &candidate) override {
956     NamedDecl *ND = candidate.getCorrectionDecl();
957     return ND && ND->isParameterPack();
958   }
959
960   std::unique_ptr<CorrectionCandidateCallback> clone() override {
961     return std::make_unique<ParameterPackValidatorCCC>(*this);
962   }
963 };
964
965 }
966
967 /// Called when an expression computing the size of a parameter pack
968 /// is parsed.
969 ///
970 /// \code
971 /// template<typename ...Types> struct count {
972 ///   static const unsigned value = sizeof...(Types);
973 /// };
974 /// \endcode
975 ///
976 //
977 /// \param OpLoc The location of the "sizeof" keyword.
978 /// \param Name The name of the parameter pack whose size will be determined.
979 /// \param NameLoc The source location of the name of the parameter pack.
980 /// \param RParenLoc The location of the closing parentheses.
981 ExprResult Sema::ActOnSizeofParameterPackExpr(Scope *S,
982                                               SourceLocation OpLoc,
983                                               IdentifierInfo &Name,
984                                               SourceLocation NameLoc,
985                                               SourceLocation RParenLoc) {
986   // C++0x [expr.sizeof]p5:
987   //   The identifier in a sizeof... expression shall name a parameter pack.
988   LookupResult R(*this, &Name, NameLoc, LookupOrdinaryName);
989   LookupName(R, S);
990
991   NamedDecl *ParameterPack = nullptr;
992   switch (R.getResultKind()) {
993   case LookupResult::Found:
994     ParameterPack = R.getFoundDecl();
995     break;
996
997   case LookupResult::NotFound:
998   case LookupResult::NotFoundInCurrentInstantiation: {
999     ParameterPackValidatorCCC CCC{};
1000     if (TypoCorrection Corrected =
1001             CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, nullptr,
1002                         CCC, CTK_ErrorRecovery)) {
1003       diagnoseTypo(Corrected,
1004                    PDiag(diag::err_sizeof_pack_no_pack_name_suggest) << &Name,
1005                    PDiag(diag::note_parameter_pack_here));
1006       ParameterPack = Corrected.getCorrectionDecl();
1007     }
1008     break;
1009   }
1010   case LookupResult::FoundOverloaded:
1011   case LookupResult::FoundUnresolvedValue:
1012     break;
1013
1014   case LookupResult::Ambiguous:
1015     DiagnoseAmbiguousLookup(R);
1016     return ExprError();
1017   }
1018
1019   if (!ParameterPack || !ParameterPack->isParameterPack()) {
1020     Diag(NameLoc, diag::err_sizeof_pack_no_pack_name)
1021       << &Name;
1022     return ExprError();
1023   }
1024
1025   MarkAnyDeclReferenced(OpLoc, ParameterPack, true);
1026
1027   return SizeOfPackExpr::Create(Context, OpLoc, ParameterPack, NameLoc,
1028                                 RParenLoc);
1029 }
1030
1031 TemplateArgumentLoc
1032 Sema::getTemplateArgumentPackExpansionPattern(
1033       TemplateArgumentLoc OrigLoc,
1034       SourceLocation &Ellipsis, Optional<unsigned> &NumExpansions) const {
1035   const TemplateArgument &Argument = OrigLoc.getArgument();
1036   assert(Argument.isPackExpansion());
1037   switch (Argument.getKind()) {
1038   case TemplateArgument::Type: {
1039     // FIXME: We shouldn't ever have to worry about missing
1040     // type-source info!
1041     TypeSourceInfo *ExpansionTSInfo = OrigLoc.getTypeSourceInfo();
1042     if (!ExpansionTSInfo)
1043       ExpansionTSInfo = Context.getTrivialTypeSourceInfo(Argument.getAsType(),
1044                                                          Ellipsis);
1045     PackExpansionTypeLoc Expansion =
1046         ExpansionTSInfo->getTypeLoc().castAs<PackExpansionTypeLoc>();
1047     Ellipsis = Expansion.getEllipsisLoc();
1048
1049     TypeLoc Pattern = Expansion.getPatternLoc();
1050     NumExpansions = Expansion.getTypePtr()->getNumExpansions();
1051
1052     // We need to copy the TypeLoc because TemplateArgumentLocs store a
1053     // TypeSourceInfo.
1054     // FIXME: Find some way to avoid the copy?
1055     TypeLocBuilder TLB;
1056     TLB.pushFullCopy(Pattern);
1057     TypeSourceInfo *PatternTSInfo =
1058         TLB.getTypeSourceInfo(Context, Pattern.getType());
1059     return TemplateArgumentLoc(TemplateArgument(Pattern.getType()),
1060                                PatternTSInfo);
1061   }
1062
1063   case TemplateArgument::Expression: {
1064     PackExpansionExpr *Expansion
1065       = cast<PackExpansionExpr>(Argument.getAsExpr());
1066     Expr *Pattern = Expansion->getPattern();
1067     Ellipsis = Expansion->getEllipsisLoc();
1068     NumExpansions = Expansion->getNumExpansions();
1069     return TemplateArgumentLoc(Pattern, Pattern);
1070   }
1071
1072   case TemplateArgument::TemplateExpansion:
1073     Ellipsis = OrigLoc.getTemplateEllipsisLoc();
1074     NumExpansions = Argument.getNumTemplateExpansions();
1075     return TemplateArgumentLoc(Argument.getPackExpansionPattern(),
1076                                OrigLoc.getTemplateQualifierLoc(),
1077                                OrigLoc.getTemplateNameLoc());
1078
1079   case TemplateArgument::Declaration:
1080   case TemplateArgument::NullPtr:
1081   case TemplateArgument::Template:
1082   case TemplateArgument::Integral:
1083   case TemplateArgument::Pack:
1084   case TemplateArgument::Null:
1085     return TemplateArgumentLoc();
1086   }
1087
1088   llvm_unreachable("Invalid TemplateArgument Kind!");
1089 }
1090
1091 Optional<unsigned> Sema::getFullyPackExpandedSize(TemplateArgument Arg) {
1092   assert(Arg.containsUnexpandedParameterPack());
1093
1094   // If this is a substituted pack, grab that pack. If not, we don't know
1095   // the size yet.
1096   // FIXME: We could find a size in more cases by looking for a substituted
1097   // pack anywhere within this argument, but that's not necessary in the common
1098   // case for 'sizeof...(A)' handling.
1099   TemplateArgument Pack;
1100   switch (Arg.getKind()) {
1101   case TemplateArgument::Type:
1102     if (auto *Subst = Arg.getAsType()->getAs<SubstTemplateTypeParmPackType>())
1103       Pack = Subst->getArgumentPack();
1104     else
1105       return None;
1106     break;
1107
1108   case TemplateArgument::Expression:
1109     if (auto *Subst =
1110             dyn_cast<SubstNonTypeTemplateParmPackExpr>(Arg.getAsExpr()))
1111       Pack = Subst->getArgumentPack();
1112     else if (auto *Subst = dyn_cast<FunctionParmPackExpr>(Arg.getAsExpr()))  {
1113       for (VarDecl *PD : *Subst)
1114         if (PD->isParameterPack())
1115           return None;
1116       return Subst->getNumExpansions();
1117     } else
1118       return None;
1119     break;
1120
1121   case TemplateArgument::Template:
1122     if (SubstTemplateTemplateParmPackStorage *Subst =
1123             Arg.getAsTemplate().getAsSubstTemplateTemplateParmPack())
1124       Pack = Subst->getArgumentPack();
1125     else
1126       return None;
1127     break;
1128
1129   case TemplateArgument::Declaration:
1130   case TemplateArgument::NullPtr:
1131   case TemplateArgument::TemplateExpansion:
1132   case TemplateArgument::Integral:
1133   case TemplateArgument::Pack:
1134   case TemplateArgument::Null:
1135     return None;
1136   }
1137
1138   // Check that no argument in the pack is itself a pack expansion.
1139   for (TemplateArgument Elem : Pack.pack_elements()) {
1140     // There's no point recursing in this case; we would have already
1141     // expanded this pack expansion into the enclosing pack if we could.
1142     if (Elem.isPackExpansion())
1143       return None;
1144   }
1145   return Pack.pack_size();
1146 }
1147
1148 static void CheckFoldOperand(Sema &S, Expr *E) {
1149   if (!E)
1150     return;
1151
1152   E = E->IgnoreImpCasts();
1153   auto *OCE = dyn_cast<CXXOperatorCallExpr>(E);
1154   if ((OCE && OCE->isInfixBinaryOp()) || isa<BinaryOperator>(E) ||
1155       isa<AbstractConditionalOperator>(E)) {
1156     S.Diag(E->getExprLoc(), diag::err_fold_expression_bad_operand)
1157         << E->getSourceRange()
1158         << FixItHint::CreateInsertion(E->getBeginLoc(), "(")
1159         << FixItHint::CreateInsertion(E->getEndLoc(), ")");
1160   }
1161 }
1162
1163 ExprResult Sema::ActOnCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
1164                                   tok::TokenKind Operator,
1165                                   SourceLocation EllipsisLoc, Expr *RHS,
1166                                   SourceLocation RParenLoc) {
1167   // LHS and RHS must be cast-expressions. We allow an arbitrary expression
1168   // in the parser and reduce down to just cast-expressions here.
1169   CheckFoldOperand(*this, LHS);
1170   CheckFoldOperand(*this, RHS);
1171
1172   auto DiscardOperands = [&] {
1173     CorrectDelayedTyposInExpr(LHS);
1174     CorrectDelayedTyposInExpr(RHS);
1175   };
1176
1177   // [expr.prim.fold]p3:
1178   //   In a binary fold, op1 and op2 shall be the same fold-operator, and
1179   //   either e1 shall contain an unexpanded parameter pack or e2 shall contain
1180   //   an unexpanded parameter pack, but not both.
1181   if (LHS && RHS &&
1182       LHS->containsUnexpandedParameterPack() ==
1183           RHS->containsUnexpandedParameterPack()) {
1184     DiscardOperands();
1185     return Diag(EllipsisLoc,
1186                 LHS->containsUnexpandedParameterPack()
1187                     ? diag::err_fold_expression_packs_both_sides
1188                     : diag::err_pack_expansion_without_parameter_packs)
1189         << LHS->getSourceRange() << RHS->getSourceRange();
1190   }
1191
1192   // [expr.prim.fold]p2:
1193   //   In a unary fold, the cast-expression shall contain an unexpanded
1194   //   parameter pack.
1195   if (!LHS || !RHS) {
1196     Expr *Pack = LHS ? LHS : RHS;
1197     assert(Pack && "fold expression with neither LHS nor RHS");
1198     DiscardOperands();
1199     if (!Pack->containsUnexpandedParameterPack())
1200       return Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1201              << Pack->getSourceRange();
1202   }
1203
1204   BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Operator);
1205   return BuildCXXFoldExpr(LParenLoc, LHS, Opc, EllipsisLoc, RHS, RParenLoc,
1206                           None);
1207 }
1208
1209 ExprResult Sema::BuildCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
1210                                   BinaryOperatorKind Operator,
1211                                   SourceLocation EllipsisLoc, Expr *RHS,
1212                                   SourceLocation RParenLoc,
1213                                   Optional<unsigned> NumExpansions) {
1214   return new (Context) CXXFoldExpr(Context.DependentTy, LParenLoc, LHS,
1215                                    Operator, EllipsisLoc, RHS, RParenLoc,
1216                                    NumExpansions);
1217 }
1218
1219 ExprResult Sema::BuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc,
1220                                        BinaryOperatorKind Operator) {
1221   // [temp.variadic]p9:
1222   //   If N is zero for a unary fold-expression, the value of the expression is
1223   //       &&  ->  true
1224   //       ||  ->  false
1225   //       ,   ->  void()
1226   //   if the operator is not listed [above], the instantiation is ill-formed.
1227   //
1228   // Note that we need to use something like int() here, not merely 0, to
1229   // prevent the result from being a null pointer constant.
1230   QualType ScalarType;
1231   switch (Operator) {
1232   case BO_LOr:
1233     return ActOnCXXBoolLiteral(EllipsisLoc, tok::kw_false);
1234   case BO_LAnd:
1235     return ActOnCXXBoolLiteral(EllipsisLoc, tok::kw_true);
1236   case BO_Comma:
1237     ScalarType = Context.VoidTy;
1238     break;
1239
1240   default:
1241     return Diag(EllipsisLoc, diag::err_fold_expression_empty)
1242         << BinaryOperator::getOpcodeStr(Operator);
1243   }
1244
1245   return new (Context) CXXScalarValueInitExpr(
1246       ScalarType, Context.getTrivialTypeSourceInfo(ScalarType, EllipsisLoc),
1247       EllipsisLoc);
1248 }