Coverage Report

Created: 2021-09-21 08:58

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/Sema/SemaTemplateVariadic.cpp
Line
Count
Source (jump to first uncovered line)
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
37.0k
    void addUnexpanded(NamedDecl *ND, SourceLocation Loc = SourceLocation()) {
42
37.0k
      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
7.32k
        auto *FD = dyn_cast<FunctionDecl>(VD->getDeclContext());
47
7.32k
        auto *FTD = FD ? 
FD->getDescribedFunctionTemplate()7.27k
:
nullptr56
;
48
7.32k
        if (FTD && 
FTD->getTemplateParameters()->getDepth() >= DepthLimit7.00k
)
49
0
          return;
50
29.7k
      } else if (getDepthAndIndex(ND).first >= DepthLimit)
51
0
        return;
52
53
37.0k
      Unexpanded.push_back({ND, Loc});
54
37.0k
    }
55
    void addUnexpanded(const TemplateTypeParmType *T,
56
373k
                       SourceLocation Loc = SourceLocation()) {
57
373k
      if (T->getDepth() < DepthLimit)
58
373k
        Unexpanded.push_back({T, Loc});
59
373k
    }
60
61
  public:
62
    explicit CollectUnexpandedParameterPacksVisitor(
63
        SmallVectorImpl<UnexpandedParameterPack> &Unexpanded)
64
389k
        : Unexpanded(Unexpanded) {}
65
66
390k
    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
303k
    bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
74
303k
      if (TL.getTypePtr()->isParameterPack())
75
303k
        addUnexpanded(TL.getTypePtr(), TL.getNameLoc());
76
303k
      return true;
77
303k
    }
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
70.4k
    bool VisitTemplateTypeParmType(TemplateTypeParmType *T) {
85
70.4k
      if (T->isParameterPack())
86
70.4k
        addUnexpanded(T);
87
88
70.4k
      return true;
89
70.4k
    }
90
91
    /// Record occurrences of function and non-type template
92
    /// parameter packs in an expression.
93
37.0k
    bool VisitDeclRefExpr(DeclRefExpr *E) {
94
37.0k
      if (E->getDecl()->isParameterPack())
95
36.9k
        addUnexpanded(E->getDecl(), E->getLocation());
96
97
37.0k
      return true;
98
37.0k
    }
99
100
    /// Record occurrences of template template parameter packs.
101
48.7k
    bool TraverseTemplateName(TemplateName Template) {
102
48.7k
      if (auto *TTP = dyn_cast_or_null<TemplateTemplateParmDecl>(
103
48.7k
              Template.getAsTemplateDecl())) {
104
4.90k
        if (TTP->isParameterPack())
105
96
          addUnexpanded(TTP);
106
4.90k
      }
107
108
48.7k
      return inherited::TraverseTemplateName(Template);
109
48.7k
    }
110
111
    /// Suppress traversal into Objective-C container literal
112
    /// elements that are pack expansions.
113
1
    bool TraverseObjCDictionaryLiteral(ObjCDictionaryLiteral *E) {
114
1
      if (!E->containsUnexpandedParameterPack())
115
0
        return true;
116
117
2
      
for (unsigned I = 0, N = E->getNumElements(); 1
I != N;
++I1
) {
118
1
        ObjCDictionaryElement Element = E->getKeyValueElement(I);
119
1
        if (Element.isPackExpansion())
120
0
          continue;
121
122
1
        TraverseStmt(Element.Key);
123
1
        TraverseStmt(Element.Value);
124
1
      }
125
1
      return true;
126
1
    }
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
105k
    bool TraverseStmt(Stmt *S) {
134
105k
      Expr *E = dyn_cast_or_null<Expr>(S);
135
105k
      if ((E && 
E->containsUnexpandedParameterPack()104k
) ||
InLambda8.00k
)
136
97.8k
        return inherited::TraverseStmt(S);
137
138
7.31k
      return true;
139
105k
    }
140
141
    /// Suppress traversal into types that do not contain
142
    /// unexpanded parameter packs.
143
113k
    bool TraverseType(QualType T) {
144
113k
      if ((!T.isNull() && 
T->containsUnexpandedParameterPack()113k
) ||
InLambda6.03k
)
145
107k
        return inherited::TraverseType(T);
146
147
5.99k
      return true;
148
113k
    }
149
150
    /// Suppress traversal into types with location information
151
    /// that do not contain unexpanded parameter packs.
152
397k
    bool TraverseTypeLoc(TypeLoc TL) {
153
397k
      if ((!TL.getType().isNull() &&
154
397k
           TL.getType()->containsUnexpandedParameterPack()) ||
155
397k
          
InLambda6.86k
)
156
390k
        return inherited::TraverseTypeLoc(TL);
157
158
6.72k
      return true;
159
397k
    }
160
161
    /// Suppress traversal of parameter packs.
162
340
    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
340
      if (D && 
D->isParameterPack()339
)
167
56
        return true;
168
169
284
      return inherited::TraverseDecl(D);
170
340
    }
171
172
    /// Suppress traversal of pack-expanded attributes.
173
6
    bool TraverseAttr(Attr *A) {
174
6
      if (A->isPackExpansion())
175
4
        return true;
176
177
2
      return inherited::TraverseAttr(A);
178
6
    }
179
180
    /// Suppress traversal of pack expansion expressions and types.
181
    ///@{
182
0
    bool TraversePackExpansionType(PackExpansionType *T) { return true; }
183
0
    bool TraversePackExpansionTypeLoc(PackExpansionTypeLoc TL) { return true; }
184
12
    bool TraversePackExpansionExpr(PackExpansionExpr *E) { return true; }
185
2
    bool TraverseCXXFoldExpr(CXXFoldExpr *E) { return true; }
186
187
    ///@}
188
189
    /// Suppress traversal of using-declaration pack expansion.
190
3
    bool TraverseUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
191
3
      if (D->isPackExpansion())
192
2
        return true;
193
194
1
      return inherited::TraverseUnresolvedUsingValueDecl(D);
195
3
    }
196
197
    /// Suppress traversal of using-declaration pack expansion.
198
3
    bool TraverseUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {
199
3
      if (D->isPackExpansion())
200
2
        return true;
201
202
1
      return inherited::TraverseUnresolvedUsingTypenameDecl(D);
203
3
    }
204
205
    /// Suppress traversal of template argument pack expansions.
206
61.7k
    bool TraverseTemplateArgument(const TemplateArgument &Arg) {
207
61.7k
      if (Arg.isPackExpansion())
208
8
        return true;
209
210
61.7k
      return inherited::TraverseTemplateArgument(Arg);
211
61.7k
    }
212
213
    /// Suppress traversal of template argument pack expansions.
214
330k
    bool TraverseTemplateArgumentLoc(const TemplateArgumentLoc &ArgLoc) {
215
330k
      if (ArgLoc.getArgument().isPackExpansion())
216
398
        return true;
217
218
329k
      return inherited::TraverseTemplateArgumentLoc(ArgLoc);
219
330k
    }
220
221
    /// Suppress traversal of base specifier pack expansions.
222
14
    bool TraverseCXXBaseSpecifier(const CXXBaseSpecifier &Base) {
223
14
      if (Base.isPackExpansion())
224
10
        return true;
225
226
4
      return inherited::TraverseCXXBaseSpecifier(Base);
227
14
    }
228
229
    /// Suppress traversal of mem-initializer pack expansions.
230
6
    bool TraverseConstructorInitializer(CXXCtorInitializer *Init) {
231
6
      if (Init->isPackExpansion())
232
4
        return true;
233
234
2
      return inherited::TraverseConstructorInitializer(Init);
235
6
    }
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
138
    bool TraverseLambdaExpr(LambdaExpr *Lambda) {
243
      // The ContainsUnexpandedParameterPack bit on a lambda is always correct,
244
      // even if it's contained within another lambda.
245
138
      if (!Lambda->containsUnexpandedParameterPack())
246
8
        return true;
247
248
130
      bool WasInLambda = InLambda;
249
130
      unsigned OldDepthLimit = DepthLimit;
250
251
130
      InLambda = true;
252
130
      if (auto *TPL = Lambda->getTemplateParameterList())
253
16
        DepthLimit = TPL->getDepth();
254
255
130
      inherited::TraverseLambdaExpr(Lambda);
256
257
130
      InLambda = WasInLambda;
258
130
      DepthLimit = OldDepthLimit;
259
130
      return true;
260
138
    }
261
262
    /// Suppress traversal within pack expansions in lambda captures.
263
    bool TraverseLambdaCapture(LambdaExpr *Lambda, const LambdaCapture *C,
264
60
                               Expr *Init) {
265
60
      if (C->isPackExpansion())
266
12
        return true;
267
268
48
      return inherited::TraverseLambdaCapture(Lambda, C, Init);
269
60
    }
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
82
bool Sema::isUnexpandedParameterPackPermitted() {
281
82
  for (auto *SI : FunctionScopes)
282
4
    if (isa<sema::LambdaScopeInfo>(SI))
283
2
      return true;
284
80
  return false;
285
82
}
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
409
                                 ArrayRef<UnexpandedParameterPack> Unexpanded) {
293
409
  if (Unexpanded.empty())
294
0
    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
409
  SmallVector<UnexpandedParameterPack, 4> LambdaParamPackReferences;
302
409
  if (auto *LSI = getEnclosingLambda()) {
303
218
    for (auto &Pack : Unexpanded) {
304
218
      auto DeclaresThisPack = [&](NamedDecl *LocalPack) {
305
98
        if (auto *TTPT = Pack.first.dyn_cast<const TemplateTypeParmType *>()) {
306
15
          auto *TTPD = dyn_cast<TemplateTypeParmDecl>(LocalPack);
307
15
          return TTPD && 
TTPD->getTypeForDecl() == TTPT12
;
308
15
        }
309
83
        return declaresSameEntity(Pack.first.get<NamedDecl *>(), LocalPack);
310
98
      };
311
218
      if (std::find_if(LSI->LocalPacks.begin(), LSI->LocalPacks.end(),
312
218
                       DeclaresThisPack) != LSI->LocalPacks.end())
313
83
        LambdaParamPackReferences.push_back(Pack);
314
218
    }
315
316
215
    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
132
      bool EnclosingStmtExpr = false;
329
136
      for (unsigned N = FunctionScopes.size(); N; 
--N4
) {
330
136
        sema::FunctionScopeInfo *Func = FunctionScopes[N-1];
331
136
        if (std::any_of(
332
136
                Func->CompoundScopes.begin(), Func->CompoundScopes.end(),
333
136
                [](sema::CompoundScopeInfo &CSI) 
{ return CSI.IsStmtExpr; }94
)) {
334
1
          EnclosingStmtExpr = true;
335
1
          break;
336
1
        }
337
        // Coumpound-statements outside the lambda are OK for now; we'll check
338
        // for those when we finish handling the lambda.
339
135
        if (Func == LSI)
340
131
          break;
341
135
      }
342
343
132
      if (!EnclosingStmtExpr) {
344
131
        LSI->ContainsUnexpandedParameterPack = true;
345
131
        return false;
346
131
      }
347
132
    } else {
348
83
      Unexpanded = LambdaParamPackReferences;
349
83
    }
350
215
  }
351
352
278
  SmallVector<SourceLocation, 4> Locations;
353
278
  SmallVector<IdentifierInfo *, 4> Names;
354
278
  llvm::SmallPtrSet<IdentifierInfo *, 4> NamesKnown;
355
356
571
  for (unsigned I = 0, N = Unexpanded.size(); I != N; 
++I293
) {
357
293
    IdentifierInfo *Name = nullptr;
358
293
    if (const TemplateTypeParmType *TTP
359
293
          = Unexpanded[I].first.dyn_cast<const TemplateTypeParmType *>())
360
167
      Name = TTP->getIdentifier();
361
126
    else
362
126
      Name = Unexpanded[I].first.get<NamedDecl *>()->getIdentifier();
363
364
293
    if (Name && NamesKnown.insert(Name).second)
365
285
      Names.push_back(Name);
366
367
293
    if (Unexpanded[I].second.isValid())
368
273
      Locations.push_back(Unexpanded[I].second);
369
293
  }
370
371
278
  auto DB = Diag(Loc, diag::err_unexpanded_parameter_pack)
372
278
            << (int)UPPC << (int)Names.size();
373
562
  for (size_t I = 0, E = std::min(Names.size(), (size_t)2); I != E; 
++I284
)
374
284
    DB << Names[I];
375
376
551
  for (unsigned I = 0, N = Locations.size(); I != N; 
++I273
)
377
273
    DB << SourceRange(Locations[I]);
378
278
  return true;
379
409
}
380
381
bool Sema::DiagnoseUnexpandedParameterPack(SourceLocation Loc,
382
                                           TypeSourceInfo *T,
383
38.6M
                                         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
38.6M
  if (!T->getType()->containsUnexpandedParameterPack())
388
38.6M
    return false;
389
390
149
  SmallVector<UnexpandedParameterPack, 2> Unexpanded;
391
149
  CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseTypeLoc(
392
149
                                                              T->getTypeLoc());
393
149
  assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
394
0
  return DiagnoseUnexpandedParameterPacks(Loc, UPPC, Unexpanded);
395
38.6M
}
396
397
bool Sema::DiagnoseUnexpandedParameterPack(Expr *E,
398
20.8M
                                        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
20.8M
  if (!E->containsUnexpandedParameterPack())
403
20.8M
    return false;
404
405
240
  SmallVector<UnexpandedParameterPack, 2> Unexpanded;
406
240
  CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseStmt(E);
407
240
  assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
408
0
  return DiagnoseUnexpandedParameterPacks(E->getBeginLoc(), UPPC, Unexpanded);
409
20.8M
}
410
411
216
bool Sema::DiagnoseUnexpandedParameterPackInRequiresExpr(RequiresExpr *RE) {
412
216
  if (!RE->containsUnexpandedParameterPack())
413
203
    return false;
414
415
13
  SmallVector<UnexpandedParameterPack, 2> Unexpanded;
416
13
  CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseStmt(RE);
417
13
  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
0
  auto Parms = RE->getLocalParameters();
422
13
  llvm::SmallPtrSet<NamedDecl*, 8> ParmSet(Parms.begin(), Parms.end());
423
13
  SmallVector<UnexpandedParameterPack, 2> UnexpandedParms;
424
13
  for (auto Parm : Unexpanded)
425
19
    if (ParmSet.contains(Parm.first.dyn_cast<NamedDecl*>()))
426
1
      UnexpandedParms.push_back(Parm);
427
13
  if (UnexpandedParms.empty())
428
12
    return false;
429
430
1
  return DiagnoseUnexpandedParameterPacks(RE->getBeginLoc(), UPPC_Requirement,
431
1
                                          UnexpandedParms);
432
13
}
433
434
bool Sema::DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS,
435
375k
                                        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
375k
  if (!SS.getScopeRep() ||
440
375k
      
!SS.getScopeRep()->containsUnexpandedParameterPack()349k
)
441
375k
    return false;
442
443
8
  SmallVector<UnexpandedParameterPack, 2> Unexpanded;
444
8
  CollectUnexpandedParameterPacksVisitor(Unexpanded)
445
8
    .TraverseNestedNameSpecifier(SS.getScopeRep());
446
8
  assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
447
0
  return DiagnoseUnexpandedParameterPacks(SS.getRange().getBegin(),
448
8
                                          UPPC, Unexpanded);
449
375k
}
450
451
bool Sema::DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo,
452
36.9M
                                         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
36.9M
  switch (NameInfo.getName().getNameKind()) {
457
36.2M
  case DeclarationName::Identifier:
458
36.2M
  case DeclarationName::ObjCZeroArgSelector:
459
36.2M
  case DeclarationName::ObjCOneArgSelector:
460
36.2M
  case DeclarationName::ObjCMultiArgSelector:
461
36.5M
  case DeclarationName::CXXOperatorName:
462
36.5M
  case DeclarationName::CXXLiteralOperatorName:
463
36.5M
  case DeclarationName::CXXUsingDirective:
464
36.5M
  case DeclarationName::CXXDeductionGuideName:
465
36.5M
    return false;
466
467
275k
  case DeclarationName::CXXConstructorName:
468
317k
  case DeclarationName::CXXDestructorName:
469
330k
  case DeclarationName::CXXConversionFunctionName:
470
    // FIXME: We shouldn't need this null check!
471
330k
    if (TypeSourceInfo *TSInfo = NameInfo.getNamedTypeInfo())
472
55.0k
      return DiagnoseUnexpandedParameterPack(NameInfo.getLoc(), TSInfo, UPPC);
473
474
275k
    if (!NameInfo.getName().getCXXNameType()->containsUnexpandedParameterPack())
475
275k
      return false;
476
477
0
    break;
478
36.9M
  }
479
480
0
  SmallVector<UnexpandedParameterPack, 2> Unexpanded;
481
0
  CollectUnexpandedParameterPacksVisitor(Unexpanded)
482
0
    .TraverseType(NameInfo.getName().getCXXNameType());
483
0
  assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
484
0
  return DiagnoseUnexpandedParameterPacks(NameInfo.getLoc(), UPPC, Unexpanded);
485
36.9M
}
486
487
bool Sema::DiagnoseUnexpandedParameterPack(SourceLocation Loc,
488
                                           TemplateName Template,
489
8.65k
                                       UnexpandedParameterPackContext UPPC) {
490
491
8.65k
  if (Template.isNull() || !Template.containsUnexpandedParameterPack())
492
8.64k
    return false;
493
494
1
  SmallVector<UnexpandedParameterPack, 2> Unexpanded;
495
1
  CollectUnexpandedParameterPacksVisitor(Unexpanded)
496
1
    .TraverseTemplateName(Template);
497
1
  assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
498
0
  return DiagnoseUnexpandedParameterPacks(Loc, UPPC, Unexpanded);
499
8.65k
}
500
501
bool Sema::DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg,
502
413k
                                         UnexpandedParameterPackContext UPPC) {
503
413k
  if (Arg.getArgument().isNull() ||
504
413k
      !Arg.getArgument().containsUnexpandedParameterPack())
505
413k
    return false;
506
507
9
  SmallVector<UnexpandedParameterPack, 2> Unexpanded;
508
9
  CollectUnexpandedParameterPacksVisitor(Unexpanded)
509
9
    .TraverseTemplateArgumentLoc(Arg);
510
9
  assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
511
0
  return DiagnoseUnexpandedParameterPacks(Arg.getLocation(), UPPC, Unexpanded);
512
413k
}
513
514
void Sema::collectUnexpandedParameterPacks(TemplateArgument Arg,
515
52.4k
                   SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
516
52.4k
  CollectUnexpandedParameterPacksVisitor(Unexpanded)
517
52.4k
    .TraverseTemplateArgument(Arg);
518
52.4k
}
519
520
void Sema::collectUnexpandedParameterPacks(TemplateArgumentLoc Arg,
521
252k
                   SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
522
252k
  CollectUnexpandedParameterPacksVisitor(Unexpanded)
523
252k
    .TraverseTemplateArgumentLoc(Arg);
524
252k
}
525
526
void Sema::collectUnexpandedParameterPacks(QualType T,
527
715
                   SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
528
715
  CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseType(T);
529
715
}
530
531
void Sema::collectUnexpandedParameterPacks(TypeLoc TL,
532
52.3k
                   SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
533
52.3k
  CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseTypeLoc(TL);
534
52.3k
}
535
536
void Sema::collectUnexpandedParameterPacks(
537
    NestedNameSpecifierLoc NNS,
538
62
    SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
539
62
  CollectUnexpandedParameterPacksVisitor(Unexpanded)
540
62
      .TraverseNestedNameSpecifierLoc(NNS);
541
62
}
542
543
void Sema::collectUnexpandedParameterPacks(
544
    const DeclarationNameInfo &NameInfo,
545
62
    SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
546
62
  CollectUnexpandedParameterPacksVisitor(Unexpanded)
547
62
    .TraverseDeclarationNameInfo(NameInfo);
548
62
}
549
550
551
ParsedTemplateArgument
552
Sema::ActOnPackExpansion(const ParsedTemplateArgument &Arg,
553
160k
                         SourceLocation EllipsisLoc) {
554
160k
  if (Arg.isInvalid())
555
9
    return Arg;
556
557
160k
  switch (Arg.getKind()) {
558
142k
  case ParsedTemplateArgument::Type: {
559
142k
    TypeResult Result = ActOnPackExpansion(Arg.getAsType(), EllipsisLoc);
560
142k
    if (Result.isInvalid())
561
2
      return ParsedTemplateArgument();
562
563
142k
    return ParsedTemplateArgument(Arg.getKind(), Result.get().getAsOpaquePtr(),
564
142k
                                  Arg.getLocation());
565
142k
  }
566
567
17.8k
  case ParsedTemplateArgument::NonType: {
568
17.8k
    ExprResult Result = ActOnPackExpansion(Arg.getAsExpr(), EllipsisLoc);
569
17.8k
    if (Result.isInvalid())
570
0
      return ParsedTemplateArgument();
571
572
17.8k
    return ParsedTemplateArgument(Arg.getKind(), Result.get(),
573
17.8k
                                  Arg.getLocation());
574
17.8k
  }
575
576
24
  case ParsedTemplateArgument::Template:
577
24
    if (!Arg.getAsTemplate().get().containsUnexpandedParameterPack()) {
578
0
      SourceRange R(Arg.getLocation());
579
0
      if (Arg.getScopeSpec().isValid())
580
0
        R.setBegin(Arg.getScopeSpec().getBeginLoc());
581
0
      Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
582
0
        << R;
583
0
      return ParsedTemplateArgument();
584
0
    }
585
586
24
    return Arg.getTemplatePackExpansion(EllipsisLoc);
587
160k
  }
588
0
  llvm_unreachable("Unhandled template argument kind?");
589
0
}
590
591
TypeResult Sema::ActOnPackExpansion(ParsedType Type,
592
143k
                                    SourceLocation EllipsisLoc) {
593
143k
  TypeSourceInfo *TSInfo;
594
143k
  GetTypeFromParser(Type, &TSInfo);
595
143k
  if (!TSInfo)
596
0
    return true;
597
598
143k
  TypeSourceInfo *TSResult = CheckPackExpansion(TSInfo, EllipsisLoc, None);
599
143k
  if (!TSResult)
600
2
    return true;
601
602
143k
  return CreateParsedType(TSResult->getType(), TSResult);
603
143k
}
604
605
TypeSourceInfo *
606
Sema::CheckPackExpansion(TypeSourceInfo *Pattern, SourceLocation EllipsisLoc,
607
291k
                         Optional<unsigned> NumExpansions) {
608
  // Create the pack expansion type and source-location information.
609
291k
  QualType Result = CheckPackExpansion(Pattern->getType(),
610
291k
                                       Pattern->getTypeLoc().getSourceRange(),
611
291k
                                       EllipsisLoc, NumExpansions);
612
291k
  if (Result.isNull())
613
2
    return nullptr;
614
615
291k
  TypeLocBuilder TLB;
616
291k
  TLB.pushFullCopy(Pattern->getTypeLoc());
617
291k
  PackExpansionTypeLoc TL = TLB.push<PackExpansionTypeLoc>(Result);
618
291k
  TL.setEllipsisLoc(EllipsisLoc);
619
620
291k
  return TLB.getTypeSourceInfo(Context, Result);
621
291k
}
622
623
QualType Sema::CheckPackExpansion(QualType Pattern, SourceRange PatternRange,
624
                                  SourceLocation EllipsisLoc,
625
291k
                                  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
291k
  if (!Pattern->containsUnexpandedParameterPack() &&
634
291k
      
!Pattern->getContainedDeducedType()52
) {
635
2
    Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
636
2
      << PatternRange;
637
2
    return QualType();
638
2
  }
639
640
291k
  return Context.getPackExpansionType(Pattern, NumExpansions,
641
291k
                                      /*ExpectPackInType=*/false);
642
291k
}
643
644
62.4k
ExprResult Sema::ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc) {
645
62.4k
  return CheckPackExpansion(Pattern, EllipsisLoc, None);
646
62.4k
}
647
648
ExprResult Sema::CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
649
82.5k
                                    Optional<unsigned> NumExpansions) {
650
82.5k
  if (!Pattern)
651
2
    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
82.5k
  if (!Pattern->containsUnexpandedParameterPack()) {
658
24
    Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
659
24
    << Pattern->getSourceRange();
660
24
    CorrectDelayedTyposInExpr(Pattern);
661
24
    return ExprError();
662
24
  }
663
664
  // Create the pack expansion expression and source-location information.
665
82.5k
  return new (Context)
666
82.5k
    PackExpansionExpr(Context.DependentTy, Pattern, EllipsisLoc, NumExpansions);
667
82.5k
}
668
669
bool Sema::CheckParameterPacksForExpansion(
670
    SourceLocation EllipsisLoc, SourceRange PatternRange,
671
    ArrayRef<UnexpandedParameterPack> Unexpanded,
672
    const MultiLevelTemplateArgumentList &TemplateArgs, bool &ShouldExpand,
673
319k
    bool &RetainExpansion, Optional<unsigned> &NumExpansions) {
674
319k
  ShouldExpand = true;
675
319k
  RetainExpansion = false;
676
319k
  std::pair<IdentifierInfo *, SourceLocation> FirstPack;
677
319k
  bool HaveFirstPack = false;
678
319k
  Optional<unsigned> NumPartialExpansions;
679
319k
  SourceLocation PartiallySubstitutedPackLoc;
680
681
319k
  for (ArrayRef<UnexpandedParameterPack>::iterator i = Unexpanded.begin(),
682
319k
                                                 end = Unexpanded.end();
683
654k
                                                  i != end; 
++i334k
) {
684
    // Compute the depth and index for this parameter pack.
685
334k
    unsigned Depth = 0, Index = 0;
686
334k
    IdentifierInfo *Name;
687
334k
    bool IsVarDeclPack = false;
688
689
334k
    if (const TemplateTypeParmType *TTP
690
334k
        = i->first.dyn_cast<const TemplateTypeParmType *>()) {
691
258k
      Depth = TTP->getDepth();
692
258k
      Index = TTP->getIndex();
693
258k
      Name = TTP->getIdentifier();
694
258k
    } else {
695
76.1k
      NamedDecl *ND = i->first.get<NamedDecl *>();
696
76.1k
      if (isa<VarDecl>(ND))
697
7.50k
        IsVarDeclPack = true;
698
68.6k
      else
699
68.6k
        std::tie(Depth, Index) = getDepthAndIndex(ND);
700
701
76.1k
      Name = ND->getIdentifier();
702
76.1k
    }
703
704
    // Determine the size of this argument pack.
705
334k
    unsigned NewPackSize;
706
334k
    if (IsVarDeclPack) {
707
      // Figure out whether we're instantiating to an argument pack or not.
708
7.50k
      typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
709
710
7.50k
      llvm::PointerUnion<Decl *, DeclArgumentPack *> *Instantiation
711
7.50k
        = CurrentInstantiationScope->findInstantiationOf(
712
7.50k
                                        i->first.get<NamedDecl *>());
713
7.50k
      if (Instantiation->is<DeclArgumentPack *>()) {
714
        // We could expand this function parameter pack.
715
7.00k
        NewPackSize = Instantiation->get<DeclArgumentPack *>()->size();
716
7.00k
      } else {
717
        // We can't expand this function parameter pack, so we can't expand
718
        // the pack expansion.
719
503
        ShouldExpand = false;
720
503
        continue;
721
503
      }
722
327k
    } 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
327k
      if (Depth >= TemplateArgs.getNumLevels() ||
727
327k
          
!TemplateArgs.hasTemplateArgument(Depth, Index)256k
) {
728
78.9k
        ShouldExpand = false;
729
78.9k
        continue;
730
78.9k
      }
731
732
      // Determine the size of the argument pack.
733
248k
      NewPackSize = TemplateArgs(Depth, Index).pack_size();
734
248k
    }
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
255k
    if (!IsVarDeclPack && 
CurrentInstantiationScope248k
) {
741
248k
      if (NamedDecl *PartialPack
742
248k
                    = CurrentInstantiationScope->getPartiallySubstitutedPack()){
743
10.7k
        unsigned PartialDepth, PartialIndex;
744
10.7k
        std::tie(PartialDepth, PartialIndex) = getDepthAndIndex(PartialPack);
745
10.7k
        if (PartialDepth == Depth && PartialIndex == Index) {
746
10.7k
          RetainExpansion = true;
747
          // We don't actually know the new pack size yet.
748
10.7k
          NumPartialExpansions = NewPackSize;
749
10.7k
          PartiallySubstitutedPackLoc = i->second;
750
10.7k
          continue;
751
10.7k
        }
752
10.7k
      }
753
248k
    }
754
755
244k
    if (!NumExpansions) {
756
      // The is the first pack we've seen for which we have an argument.
757
      // Record it.
758
231k
      NumExpansions = NewPackSize;
759
231k
      FirstPack.first = Name;
760
231k
      FirstPack.second = i->second;
761
231k
      HaveFirstPack = true;
762
231k
      continue;
763
231k
    }
764
765
13.5k
    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
473
      if (HaveFirstPack)
770
6
        Diag(EllipsisLoc, diag::err_pack_expansion_length_conflict)
771
6
          << FirstPack.first << Name << *NumExpansions << NewPackSize
772
6
          << SourceRange(FirstPack.second) << SourceRange(i->second);
773
467
      else
774
467
        Diag(EllipsisLoc, diag::err_pack_expansion_length_conflict_multilevel)
775
467
          << Name << *NumExpansions << NewPackSize
776
467
          << SourceRange(i->second);
777
473
      return true;
778
473
    }
779
13.5k
  }
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
319k
  if (NumPartialExpansions) {
791
10.7k
    if (NumExpansions && 
*NumExpansions < *NumPartialExpansions7
) {
792
1
      NamedDecl *PartialPack =
793
1
          CurrentInstantiationScope->getPartiallySubstitutedPack();
794
1
      Diag(EllipsisLoc, diag::err_pack_expansion_length_conflict_partial)
795
1
        << PartialPack << *NumPartialExpansions << *NumExpansions
796
1
        << SourceRange(PartiallySubstitutedPackLoc);
797
1
      return true;
798
1
    }
799
800
10.7k
    NumExpansions = NumPartialExpansions;
801
10.7k
  }
802
803
319k
  return false;
804
319k
}
805
806
Optional<unsigned> Sema::getNumArgumentsInExpansion(QualType T,
807
30.5k
                          const MultiLevelTemplateArgumentList &TemplateArgs) {
808
30.5k
  QualType Pattern = cast<PackExpansionType>(T)->getPattern();
809
30.5k
  SmallVector<UnexpandedParameterPack, 2> Unexpanded;
810
30.5k
  CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseType(Pattern);
811
812
30.5k
  Optional<unsigned> Result;
813
46.9k
  for (unsigned I = 0, N = Unexpanded.size(); I != N; 
++I16.3k
) {
814
    // Compute the depth and index for this parameter pack.
815
30.6k
    unsigned Depth;
816
30.6k
    unsigned Index;
817
818
30.6k
    if (const TemplateTypeParmType *TTP
819
30.6k
          = Unexpanded[I].first.dyn_cast<const TemplateTypeParmType *>()) {
820
30.5k
      Depth = TTP->getDepth();
821
30.5k
      Index = TTP->getIndex();
822
30.5k
    } else {
823
62
      NamedDecl *ND = Unexpanded[I].first.get<NamedDecl *>();
824
62
      if (isa<VarDecl>(ND)) {
825
        // Function parameter pack or init-capture pack.
826
0
        typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
827
828
0
        llvm::PointerUnion<Decl *, DeclArgumentPack *> *Instantiation
829
0
          = CurrentInstantiationScope->findInstantiationOf(
830
0
                                        Unexpanded[I].first.get<NamedDecl *>());
831
0
        if (Instantiation->is<Decl*>())
832
          // The pattern refers to an unexpanded pack. We're not ready to expand
833
          // this pack yet.
834
0
          return None;
835
836
0
        unsigned Size = Instantiation->get<DeclArgumentPack *>()->size();
837
0
        assert((!Result || *Result == Size) && "inconsistent pack sizes");
838
0
        Result = Size;
839
0
        continue;
840
0
      }
841
842
62
      std::tie(Depth, Index) = getDepthAndIndex(ND);
843
62
    }
844
30.6k
    if (Depth >= TemplateArgs.getNumLevels() ||
845
30.6k
        
!TemplateArgs.hasTemplateArgument(Depth, Index)16.3k
)
846
      // The pattern refers to an unknown template argument. We're not ready to
847
      // expand this pack yet.
848
14.2k
      return None;
849
850
    // Determine the size of the argument pack.
851
16.3k
    unsigned Size = TemplateArgs(Depth, Index).pack_size();
852
16.3k
    assert((!Result || *Result == Size) && "inconsistent pack sizes");
853
0
    Result = Size;
854
16.3k
  }
855
856
16.3k
  return Result;
857
30.5k
}
858
859
44.1k
bool Sema::containsUnexpandedParameterPacks(Declarator &D) {
860
44.1k
  const DeclSpec &DS = D.getDeclSpec();
861
44.1k
  switch (DS.getTypeSpecType()) {
862
43.8k
  case TST_typename:
863
43.8k
  case TST_typeofType:
864
43.8k
  case TST_underlyingType:
865
43.8k
  case TST_atomic: {
866
43.8k
    QualType T = DS.getRepAsType().get();
867
43.8k
    if (!T.isNull() && T->containsUnexpandedParameterPack())
868
43.8k
      return true;
869
7
    break;
870
43.8k
  }
871
872
7
  case TST_typeofExpr:
873
48
  case TST_decltype:
874
48
  case TST_extint:
875
48
    if (DS.getRepAsExpr() &&
876
48
        DS.getRepAsExpr()->containsUnexpandedParameterPack())
877
48
      return true;
878
0
    break;
879
880
2
  case TST_unspecified:
881
2
  case TST_void:
882
26
  case TST_char:
883
26
  case TST_wchar:
884
26
  case TST_char8:
885
26
  case TST_char16:
886
26
  case TST_char32:
887
129
  case TST_int:
888
129
  case TST_int128:
889
129
  case TST_half:
890
155
  case TST_float:
891
158
  case TST_double:
892
158
  case TST_Accum:
893
158
  case TST_Fract:
894
158
  case TST_Float16:
895
158
  case TST_float128:
896
158
  case TST_ibm128:
897
158
  case TST_bool:
898
158
  case TST_decimal32:
899
158
  case TST_decimal64:
900
158
  case TST_decimal128:
901
158
  case TST_enum:
902
158
  case TST_union:
903
158
  case TST_struct:
904
158
  case TST_interface:
905
158
  case TST_class:
906
174
  case TST_auto:
907
174
  case TST_auto_type:
908
174
  case TST_decltype_auto:
909
174
  case TST_BFloat16:
910
2.08k
#define GENERIC_IMAGE_TYPE(ImgType, Id) case TST_##ImgType##_t:
911
2.08k
#include 
"clang/Basic/OpenCLImageTypes.def"174
912
2.08k
  case TST_unknown_anytype:
913
183
  case TST_error:
914
183
    break;
915
44.1k
  }
916
917
216
  
for (unsigned I = 0, N = D.getNumTypeObjects(); 190
I != N;
++I26
) {
918
26
    const DeclaratorChunk &Chunk = D.getTypeObject(I);
919
26
    switch (Chunk.Kind) {
920
0
    case DeclaratorChunk::Pointer:
921
0
    case DeclaratorChunk::Reference:
922
0
    case DeclaratorChunk::Paren:
923
0
    case DeclaratorChunk::Pipe:
924
0
    case DeclaratorChunk::BlockPointer:
925
      // These declarator chunks cannot contain any parameter packs.
926
0
      break;
927
928
20
    case DeclaratorChunk::Array:
929
20
      if (Chunk.Arr.NumElts &&
930
20
          
Chunk.Arr.NumElts->containsUnexpandedParameterPack()0
)
931
0
        return true;
932
20
      break;
933
20
    case DeclaratorChunk::Function:
934
10
      for (unsigned i = 0, e = Chunk.Fun.NumParams; i != e; 
++i4
) {
935
4
        ParmVarDecl *Param = cast<ParmVarDecl>(Chunk.Fun.Params[i].Param);
936
4
        QualType ParamTy = Param->getType();
937
4
        assert(!ParamTy.isNull() && "Couldn't parse type?");
938
4
        if (ParamTy->containsUnexpandedParameterPack()) 
return true0
;
939
4
      }
940
941
6
      if (Chunk.Fun.getExceptionSpecType() == EST_Dynamic) {
942
0
        for (unsigned i = 0; i != Chunk.Fun.getNumExceptions(); ++i) {
943
0
          if (Chunk.Fun.Exceptions[i]
944
0
                  .Ty.get()
945
0
                  ->containsUnexpandedParameterPack())
946
0
            return true;
947
0
        }
948
6
      } else if (isComputedNoexcept(Chunk.Fun.getExceptionSpecType()) &&
949
6
                 
Chunk.Fun.NoexceptExpr->containsUnexpandedParameterPack()0
)
950
0
        return true;
951
952
6
      if (Chunk.Fun.hasTrailingReturnType()) {
953
6
        QualType T = Chunk.Fun.getTrailingReturnType().get();
954
6
        if (!T.isNull() && 
T->containsUnexpandedParameterPack()0
)
955
0
          return true;
956
6
      }
957
6
      break;
958
959
6
    case DeclaratorChunk::MemberPointer:
960
0
      if (Chunk.Mem.Scope().getScopeRep() &&
961
0
          Chunk.Mem.Scope().getScopeRep()->containsUnexpandedParameterPack())
962
0
        return true;
963
0
      break;
964
26
    }
965
26
  }
966
967
190
  if (Expr *TRC = D.getTrailingRequiresClause())
968
0
    if (TRC->containsUnexpandedParameterPack())
969
0
      return true;
970
971
190
  return false;
972
190
}
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
7
  bool ValidateCandidate(const TypoCorrection &candidate) override {
980
7
    NamedDecl *ND = candidate.getCorrectionDecl();
981
7
    return ND && ND->isParameterPack();
982
7
  }
983
984
3
  std::unique_ptr<CorrectionCandidateCallback> clone() override {
985
3
    return std::make_unique<ParameterPackValidatorCCC>(*this);
986
3
  }
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
46.3k
                                              SourceLocation RParenLoc) {
1010
  // C++0x [expr.sizeof]p5:
1011
  //   The identifier in a sizeof... expression shall name a parameter pack.
1012
46.3k
  LookupResult R(*this, &Name, NameLoc, LookupOrdinaryName);
1013
46.3k
  LookupName(R, S);
1014
1015
46.3k
  NamedDecl *ParameterPack = nullptr;
1016
46.3k
  switch (R.getResultKind()) {
1017
46.3k
  case LookupResult::Found:
1018
46.3k
    ParameterPack = R.getFoundDecl();
1019
46.3k
    break;
1020
1021
3
  case LookupResult::NotFound:
1022
3
  case LookupResult::NotFoundInCurrentInstantiation: {
1023
3
    ParameterPackValidatorCCC CCC{};
1024
3
    if (TypoCorrection Corrected =
1025
3
            CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, nullptr,
1026
3
                        CCC, CTK_ErrorRecovery)) {
1027
3
      diagnoseTypo(Corrected,
1028
3
                   PDiag(diag::err_sizeof_pack_no_pack_name_suggest) << &Name,
1029
3
                   PDiag(diag::note_parameter_pack_here));
1030
3
      ParameterPack = Corrected.getCorrectionDecl();
1031
3
    }
1032
3
    break;
1033
3
  }
1034
0
  case LookupResult::FoundOverloaded:
1035
0
  case LookupResult::FoundUnresolvedValue:
1036
0
    break;
1037
1038
0
  case LookupResult::Ambiguous:
1039
0
    DiagnoseAmbiguousLookup(R);
1040
0
    return ExprError();
1041
46.3k
  }
1042
1043
46.3k
  if (!ParameterPack || !ParameterPack->isParameterPack()) {
1044
1
    Diag(NameLoc, diag::err_sizeof_pack_no_pack_name)
1045
1
      << &Name;
1046
1
    return ExprError();
1047
1
  }
1048
1049
46.3k
  MarkAnyDeclReferenced(OpLoc, ParameterPack, true);
1050
1051
46.3k
  return SizeOfPackExpr::Create(Context, OpLoc, ParameterPack, NameLoc,
1052
46.3k
                                RParenLoc);
1053
46.3k
}
1054
1055
TemplateArgumentLoc
1056
Sema::getTemplateArgumentPackExpansionPattern(
1057
      TemplateArgumentLoc OrigLoc,
1058
289k
      SourceLocation &Ellipsis, Optional<unsigned> &NumExpansions) const {
1059
289k
  const TemplateArgument &Argument = OrigLoc.getArgument();
1060
289k
  assert(Argument.isPackExpansion());
1061
0
  switch (Argument.getKind()) {
1062
264k
  case TemplateArgument::Type: {
1063
    // FIXME: We shouldn't ever have to worry about missing
1064
    // type-source info!
1065
264k
    TypeSourceInfo *ExpansionTSInfo = OrigLoc.getTypeSourceInfo();
1066
264k
    if (!ExpansionTSInfo)
1067
0
      ExpansionTSInfo = Context.getTrivialTypeSourceInfo(Argument.getAsType(),
1068
0
                                                         Ellipsis);
1069
264k
    PackExpansionTypeLoc Expansion =
1070
264k
        ExpansionTSInfo->getTypeLoc().castAs<PackExpansionTypeLoc>();
1071
264k
    Ellipsis = Expansion.getEllipsisLoc();
1072
1073
264k
    TypeLoc Pattern = Expansion.getPatternLoc();
1074
264k
    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
264k
    TypeLocBuilder TLB;
1080
264k
    TLB.pushFullCopy(Pattern);
1081
264k
    TypeSourceInfo *PatternTSInfo =
1082
264k
        TLB.getTypeSourceInfo(Context, Pattern.getType());
1083
264k
    return TemplateArgumentLoc(TemplateArgument(Pattern.getType()),
1084
264k
                               PatternTSInfo);
1085
0
  }
1086
1087
25.3k
  case TemplateArgument::Expression: {
1088
25.3k
    PackExpansionExpr *Expansion
1089
25.3k
      = cast<PackExpansionExpr>(Argument.getAsExpr());
1090
25.3k
    Expr *Pattern = Expansion->getPattern();
1091
25.3k
    Ellipsis = Expansion->getEllipsisLoc();
1092
25.3k
    NumExpansions = Expansion->getNumExpansions();
1093
25.3k
    return TemplateArgumentLoc(Pattern, Pattern);
1094
0
  }
1095
1096
35
  case TemplateArgument::TemplateExpansion:
1097
35
    Ellipsis = OrigLoc.getTemplateEllipsisLoc();
1098
35
    NumExpansions = Argument.getNumTemplateExpansions();
1099
35
    return TemplateArgumentLoc(Context, Argument.getPackExpansionPattern(),
1100
35
                               OrigLoc.getTemplateQualifierLoc(),
1101
35
                               OrigLoc.getTemplateNameLoc());
1102
1103
0
  case TemplateArgument::Declaration:
1104
0
  case TemplateArgument::NullPtr:
1105
0
  case TemplateArgument::Template:
1106
0
  case TemplateArgument::Integral:
1107
0
  case TemplateArgument::Pack:
1108
0
  case TemplateArgument::Null:
1109
0
    return TemplateArgumentLoc();
1110
289k
  }
1111
1112
0
  llvm_unreachable("Invalid TemplateArgument Kind!");
1113
0
}
1114
1115
37.1k
Optional<unsigned> Sema::getFullyPackExpandedSize(TemplateArgument Arg) {
1116
37.1k
  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
0
  TemplateArgument Pack;
1124
37.1k
  switch (Arg.getKind()) {
1125
36.9k
  case TemplateArgument::Type:
1126
36.9k
    if (auto *Subst = Arg.getAsType()->getAs<SubstTemplateTypeParmPackType>())
1127
36.8k
      Pack = Subst->getArgumentPack();
1128
72
    else
1129
72
      return None;
1130
36.8k
    break;
1131
1132
36.8k
  case TemplateArgument::Expression:
1133
186
    if (auto *Subst =
1134
186
            dyn_cast<SubstNonTypeTemplateParmPackExpr>(Arg.getAsExpr()))
1135
39
      Pack = Subst->getArgumentPack();
1136
147
    else if (auto *Subst = dyn_cast<FunctionParmPackExpr>(Arg.getAsExpr()))  {
1137
147
      for (VarDecl *PD : *Subst)
1138
871
        if (PD->isParameterPack())
1139
1
          return None;
1140
146
      return Subst->getNumExpansions();
1141
147
    } else
1142
0
      return None;
1143
39
    break;
1144
1145
39
  case TemplateArgument::Template:
1146
4
    if (SubstTemplateTemplateParmPackStorage *Subst =
1147
4
            Arg.getAsTemplate().getAsSubstTemplateTemplateParmPack())
1148
4
      Pack = Subst->getArgumentPack();
1149
0
    else
1150
0
      return None;
1151
4
    break;
1152
1153
4
  case TemplateArgument::Declaration:
1154
0
  case TemplateArgument::NullPtr:
1155
0
  case TemplateArgument::TemplateExpansion:
1156
0
  case TemplateArgument::Integral:
1157
0
  case TemplateArgument::Pack:
1158
0
  case TemplateArgument::Null:
1159
0
    return None;
1160
37.1k
  }
1161
1162
  // Check that no argument in the pack is itself a pack expansion.
1163
78.6k
  
for (TemplateArgument Elem : Pack.pack_elements())36.9k
{
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
78.6k
    if (Elem.isPackExpansion())
1167
15.2k
      return None;
1168
78.6k
  }
1169
21.6k
  return Pack.pack_size();
1170
36.9k
}
1171
1172
434
static void CheckFoldOperand(Sema &S, Expr *E) {
1173
434
  if (!E)
1174
161
    return;
1175
1176
273
  E = E->IgnoreImpCasts();
1177
273
  auto *OCE = dyn_cast<CXXOperatorCallExpr>(E);
1178
273
  if ((OCE && 
OCE->isInfixBinaryOp()8
) ||
isa<BinaryOperator>(E)270
||
1179
273
      
isa<AbstractConditionalOperator>(E)267
) {
1180
6
    S.Diag(E->getExprLoc(), diag::err_fold_expression_bad_operand)
1181
6
        << E->getSourceRange()
1182
6
        << FixItHint::CreateInsertion(E->getBeginLoc(), "(")
1183
6
        << FixItHint::CreateInsertion(E->getEndLoc(), ")");
1184
6
  }
1185
273
}
1186
1187
ExprResult Sema::ActOnCXXFoldExpr(Scope *S, SourceLocation LParenLoc, Expr *LHS,
1188
                                  tok::TokenKind Operator,
1189
                                  SourceLocation EllipsisLoc, Expr *RHS,
1190
217
                                  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
217
  CheckFoldOperand(*this, LHS);
1194
217
  CheckFoldOperand(*this, RHS);
1195
1196
217
  auto DiscardOperands = [&] {
1197
164
    CorrectDelayedTyposInExpr(LHS);
1198
164
    CorrectDelayedTyposInExpr(RHS);
1199
164
  };
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
217
  if (LHS && 
RHS194
&&
1206
217
      LHS->containsUnexpandedParameterPack() ==
1207
56
          RHS->containsUnexpandedParameterPack()) {
1208
3
    DiscardOperands();
1209
3
    return Diag(EllipsisLoc,
1210
3
                LHS->containsUnexpandedParameterPack()
1211
3
                    ? 
diag::err_fold_expression_packs_both_sides1
1212
3
                    : 
diag::err_pack_expansion_without_parameter_packs2
)
1213
3
        << LHS->getSourceRange() << RHS->getSourceRange();
1214
3
  }
1215
1216
  // [expr.prim.fold]p2:
1217
  //   In a unary fold, the cast-expression shall contain an unexpanded
1218
  //   parameter pack.
1219
214
  if (!LHS || 
!RHS191
) {
1220
161
    Expr *Pack = LHS ? 
LHS138
:
RHS23
;
1221
161
    assert(Pack && "fold expression with neither LHS nor RHS");
1222
0
    DiscardOperands();
1223
161
    if (!Pack->containsUnexpandedParameterPack())
1224
32
      return Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1225
32
             << Pack->getSourceRange();
1226
161
  }
1227
1228
182
  BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Operator);
1229
1230
  // Perform first-phase name lookup now.
1231
182
  UnresolvedLookupExpr *ULE = nullptr;
1232
182
  {
1233
182
    UnresolvedSet<16> Functions;
1234
182
    LookupBinOp(S, EllipsisLoc, Opc, Functions);
1235
182
    if (!Functions.empty()) {
1236
9
      DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(
1237
9
          BinaryOperator::getOverloadedOperator(Opc));
1238
9
      ExprResult Callee = CreateUnresolvedLookupExpr(
1239
9
          /*NamingClass*/ nullptr, NestedNameSpecifierLoc(),
1240
9
          DeclarationNameInfo(OpName, EllipsisLoc), Functions);
1241
9
      if (Callee.isInvalid())
1242
0
        return ExprError();
1243
9
      ULE = cast<UnresolvedLookupExpr>(Callee.get());
1244
9
    }
1245
182
  }
1246
1247
182
  return BuildCXXFoldExpr(ULE, LParenLoc, LHS, Opc, EllipsisLoc, RHS, RParenLoc,
1248
182
                          None);
1249
182
}
1250
1251
ExprResult Sema::BuildCXXFoldExpr(UnresolvedLookupExpr *Callee,
1252
                                  SourceLocation LParenLoc, Expr *LHS,
1253
                                  BinaryOperatorKind Operator,
1254
                                  SourceLocation EllipsisLoc, Expr *RHS,
1255
                                  SourceLocation RParenLoc,
1256
258
                                  Optional<unsigned> NumExpansions) {
1257
258
  return new (Context)
1258
258
      CXXFoldExpr(Context.DependentTy, Callee, LParenLoc, LHS, Operator,
1259
258
                  EllipsisLoc, RHS, RParenLoc, NumExpansions);
1260
258
}
1261
1262
ExprResult Sema::BuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc,
1263
33
                                       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
33
  QualType ScalarType;
1274
33
  switch (Operator) {
1275
4
  case BO_LOr:
1276
4
    return ActOnCXXBoolLiteral(EllipsisLoc, tok::kw_false);
1277
6
  case BO_LAnd:
1278
6
    return ActOnCXXBoolLiteral(EllipsisLoc, tok::kw_true);
1279
7
  case BO_Comma:
1280
7
    ScalarType = Context.VoidTy;
1281
7
    break;
1282
1283
16
  default:
1284
16
    return Diag(EllipsisLoc, diag::err_fold_expression_empty)
1285
16
        << BinaryOperator::getOpcodeStr(Operator);
1286
33
  }
1287
1288
7
  return new (Context) CXXScalarValueInitExpr(
1289
7
      ScalarType, Context.getTrivialTypeSourceInfo(ScalarType, EllipsisLoc),
1290
7
      EllipsisLoc);
1291
33
}