Coverage Report

Created: 2020-09-19 12:23

/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
55.4k
    void addUnexpanded(NamedDecl *ND, SourceLocation Loc = SourceLocation()) {
42
55.4k
      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
5.82k
        auto *FD = dyn_cast<FunctionDecl>(VD->getDeclContext());
47
5.79k
        auto *FTD = FD ? FD->getDescribedFunctionTemplate() : 
nullptr32
;
48
5.82k
        if (FTD && 
FTD->getTemplateParameters()->getDepth() >= DepthLimit5.56k
)
49
0
          return;
50
49.6k
      } else if (getDepthAndIndex(ND).first >= DepthLimit)
51
0
        return;
52
55.4k
53
55.4k
      Unexpanded.push_back({ND, Loc});
54
55.4k
    }
55
    void addUnexpanded(const TemplateTypeParmType *T,
56
267k
                       SourceLocation Loc = SourceLocation()) {
57
267k
      if (T->getDepth() < DepthLimit)
58
267k
        Unexpanded.push_back({T, Loc});
59
267k
    }
60
61
  public:
62
    explicit CollectUnexpandedParameterPacksVisitor(
63
        SmallVectorImpl<UnexpandedParameterPack> &Unexpanded)
64
313k
        : Unexpanded(Unexpanded) {}
65
66
236k
    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
192k
    bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
74
192k
      if (TL.getTypePtr()->isParameterPack())
75
192k
        addUnexpanded(TL.getTypePtr(), TL.getNameLoc());
76
192k
      return true;
77
192k
    }
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
74.4k
    bool VisitTemplateTypeParmType(TemplateTypeParmType *T) {
85
74.4k
      if (T->isParameterPack())
86
74.4k
        addUnexpanded(T);
87
74.4k
88
74.4k
      return true;
89
74.4k
    }
90
91
    /// Record occurrences of function and non-type template
92
    /// parameter packs in an expression.
93
55.4k
    bool VisitDeclRefExpr(DeclRefExpr *E) {
94
55.4k
      if (E->getDecl()->isParameterPack())
95
55.3k
        addUnexpanded(E->getDecl(), E->getLocation());
96
55.4k
97
55.4k
      return true;
98
55.4k
    }
99
100
    /// Record occurrences of template template parameter packs.
101
11.7k
    bool TraverseTemplateName(TemplateName Template) {
102
11.7k
      if (auto *TTP = dyn_cast_or_null<TemplateTemplateParmDecl>(
103
3.37k
              Template.getAsTemplateDecl())) {
104
3.37k
        if (TTP->isParameterPack())
105
92
          addUnexpanded(TTP);
106
3.37k
      }
107
11.7k
108
11.7k
      return inherited::TraverseTemplateName(Template);
109
11.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
1
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
1
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
153k
    bool TraverseStmt(Stmt *S) {
134
153k
      Expr *E = dyn_cast_or_null<Expr>(S);
135
153k
      if ((E && 
E->containsUnexpandedParameterPack()153k
) ||
InLambda20.0k
)
136
133k
        return inherited::TraverseStmt(S);
137
19.5k
138
19.5k
      return true;
139
19.5k
    }
140
141
    /// Suppress traversal into types that do not contain
142
    /// unexpanded parameter packs.
143
116k
    bool TraverseType(QualType T) {
144
116k
      if ((!T.isNull() && 
T->containsUnexpandedParameterPack()116k
) ||
InLambda991
)
145
115k
        return inherited::TraverseType(T);
146
958
147
958
      return true;
148
958
    }
149
150
    /// Suppress traversal into types with location information
151
    /// that do not contain unexpanded parameter packs.
152
254k
    bool TraverseTypeLoc(TypeLoc TL) {
153
254k
      if ((!TL.getType().isNull() &&
154
254k
           TL.getType()->containsUnexpandedParameterPack()) ||
155
18.3k
          InLambda)
156
236k
        return inherited::TraverseTypeLoc(TL);
157
18.2k
158
18.2k
      return true;
159
18.2k
    }
160
161
    /// Suppress traversal of parameter packs.
162
274
    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
274
      if (D && 
D->isParameterPack()273
)
167
36
        return true;
168
238
169
238
      return inherited::TraverseDecl(D);
170
238
    }
171
172
    /// Suppress traversal of pack-expanded attributes.
173
6
    bool TraverseAttr(Attr *A) {
174
6
      if (A->isPackExpansion())
175
4
        return true;
176
2
177
2
      return inherited::TraverseAttr(A);
178
2
    }
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
1
194
1
      return inherited::TraverseUnresolvedUsingValueDecl(D);
195
1
    }
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
1
202
1
      return inherited::TraverseUnresolvedUsingTypenameDecl(D);
203
1
    }
204
205
    /// Suppress traversal of template argument pack expansions.
206
57.5k
    bool TraverseTemplateArgument(const TemplateArgument &Arg) {
207
57.5k
      if (Arg.isPackExpansion())
208
8
        return true;
209
57.5k
210
57.5k
      return inherited::TraverseTemplateArgument(Arg);
211
57.5k
    }
212
213
    /// Suppress traversal of template argument pack expansions.
214
202k
    bool TraverseTemplateArgumentLoc(const TemplateArgumentLoc &ArgLoc) {
215
202k
      if (ArgLoc.getArgument().isPackExpansion())
216
543
        return true;
217
201k
218
201k
      return inherited::TraverseTemplateArgumentLoc(ArgLoc);
219
201k
    }
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
4
226
4
      return inherited::TraverseCXXBaseSpecifier(Base);
227
4
    }
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
2
234
2
      return inherited::TraverseConstructorInitializer(Init);
235
2
    }
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
109
    bool TraverseLambdaExpr(LambdaExpr *Lambda) {
243
      // The ContainsUnexpandedParameterPack bit on a lambda is always correct,
244
      // even if it's contained within another lambda.
245
109
      if (!Lambda->containsUnexpandedParameterPack())
246
8
        return true;
247
101
248
101
      bool WasInLambda = InLambda;
249
101
      unsigned OldDepthLimit = DepthLimit;
250
101
251
101
      InLambda = true;
252
101
      if (auto *TPL = Lambda->getTemplateParameterList())
253
4
        DepthLimit = TPL->getDepth();
254
101
255
101
      inherited::TraverseLambdaExpr(Lambda);
256
101
257
101
      InLambda = WasInLambda;
258
101
      DepthLimit = OldDepthLimit;
259
101
      return true;
260
101
    }
261
262
    /// Suppress traversal within pack expansions in lambda captures.
263
    bool TraverseLambdaCapture(LambdaExpr *Lambda, const LambdaCapture *C,
264
56
                               Expr *Init) {
265
56
      if (C->isPackExpansion())
266
8
        return true;
267
48
268
48
      return inherited::TraverseLambdaCapture(Lambda, C, Init);
269
48
    }
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
78
bool Sema::isUnexpandedParameterPackPermitted() {
281
78
  for (auto *SI : FunctionScopes)
282
4
    if (isa<sema::LambdaScopeInfo>(SI))
283
2
      return true;
284
76
  return false;
285
78
}
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
324
                                 ArrayRef<UnexpandedParameterPack> Unexpanded) {
293
324
  if (Unexpanded.empty())
294
0
    return false;
295
324
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
324
  SmallVector<UnexpandedParameterPack, 4> LambdaParamPackReferences;
302
324
  if (auto *LSI = getEnclosingLambda()) {
303
144
    for (auto &Pack : Unexpanded) {
304
54
      auto DeclaresThisPack = [&](NamedDecl *LocalPack) {
305
54
        if (auto *TTPT = Pack.first.dyn_cast<const TemplateTypeParmType *>()) {
306
7
          auto *TTPD = dyn_cast<TemplateTypeParmDecl>(LocalPack);
307
7
          return TTPD && 
TTPD->getTypeForDecl() == TTPT4
;
308
7
        }
309
47
        return declaresSameEntity(Pack.first.get<NamedDecl *>(), LocalPack);
310
47
      };
311
144
      if (std::find_if(LSI->LocalPacks.begin(), LSI->LocalPacks.end(),
312
144
                       DeclaresThisPack) != LSI->LocalPacks.end())
313
43
        LambdaParamPackReferences.push_back(Pack);
314
144
    }
315
141
316
141
    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
98
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
98
      bool EnclosingStmtExpr = false;
329
102
      for (unsigned N = FunctionScopes.size(); N; 
--N4
) {
330
102
        sema::FunctionScopeInfo *Func = FunctionScopes[N-1];
331
102
        if (std::any_of(
332
102
                Func->CompoundScopes.begin(), Func->CompoundScopes.end(),
333
74
                [](sema::CompoundScopeInfo &CSI) { return CSI.IsStmtExpr; })) {
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
101
        if (Func == LSI)
340
97
          break;
341
101
      }
342
98
343
98
      if (!EnclosingStmtExpr) {
344
97
        LSI->ContainsUnexpandedParameterPack = true;
345
97
        return false;
346
97
      }
347
43
    } else {
348
43
      Unexpanded = LambdaParamPackReferences;
349
43
    }
350
141
  }
351
324
352
227
  SmallVector<SourceLocation, 4> Locations;
353
227
  SmallVector<IdentifierInfo *, 4> Names;
354
227
  llvm::SmallPtrSet<IdentifierInfo *, 4> NamesKnown;
355
227
356
466
  for (unsigned I = 0, N = Unexpanded.size(); I != N; 
++I239
) {
357
239
    IdentifierInfo *Name = nullptr;
358
239
    if (const TemplateTypeParmType *TTP
359
145
          = Unexpanded[I].first.dyn_cast<const TemplateTypeParmType *>())
360
145
      Name = TTP->getIdentifier();
361
94
    else
362
94
      Name = Unexpanded[I].first.get<NamedDecl *>()->getIdentifier();
363
239
364
239
    if (Name && NamesKnown.insert(Name).second)
365
234
      Names.push_back(Name);
366
239
367
239
    if (Unexpanded[I].second.isValid())
368
223
      Locations.push_back(Unexpanded[I].second);
369
239
  }
370
227
371
227
  DiagnosticBuilder DB = Diag(Loc, diag::err_unexpanded_parameter_pack)
372
227
                         << (int)UPPC << (int)Names.size();
373
460
  for (size_t I = 0, E = std::min(Names.size(), (size_t)2); I != E; 
++I233
)
374
233
    DB << Names[I];
375
227
376
450
  for (unsigned I = 0, N = Locations.size(); I != N; 
++I223
)
377
223
    DB << SourceRange(Locations[I]);
378
227
  return true;
379
324
}
380
381
bool Sema::DiagnoseUnexpandedParameterPack(SourceLocation Loc,
382
                                           TypeSourceInfo *T,
383
20.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
20.6M
  if (!T->getType()->containsUnexpandedParameterPack())
388
20.6M
    return false;
389
122
390
122
  SmallVector<UnexpandedParameterPack, 2> Unexpanded;
391
122
  CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseTypeLoc(
392
122
                                                              T->getTypeLoc());
393
122
  assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
394
122
  return DiagnoseUnexpandedParameterPacks(Loc, UPPC, Unexpanded);
395
122
}
396
397
bool Sema::DiagnoseUnexpandedParameterPack(Expr *E,
398
20.6M
                                        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.6M
  if (!E->containsUnexpandedParameterPack())
403
20.6M
    return false;
404
190
405
190
  SmallVector<UnexpandedParameterPack, 2> Unexpanded;
406
190
  CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseStmt(E);
407
190
  assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
408
190
  return DiagnoseUnexpandedParameterPacks(E->getBeginLoc(), UPPC, Unexpanded);
409
190
}
410
411
205
bool Sema::DiagnoseUnexpandedParameterPackInRequiresExpr(RequiresExpr *RE) {
412
205
  if (!RE->containsUnexpandedParameterPack())
413
192
    return false;
414
13
415
13
  SmallVector<UnexpandedParameterPack, 2> Unexpanded;
416
13
  CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseStmt(RE);
417
13
  assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
418
13
419
  // We only care about unexpanded references to the RequiresExpr's own
420
  // parameter packs.
421
13
  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
1
430
1
  return DiagnoseUnexpandedParameterPacks(RE->getBeginLoc(), UPPC_Requirement,
431
1
                                          UnexpandedParms);
432
1
}
433
434
bool Sema::DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS,
435
356k
                                        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
356k
  if (!SS.getScopeRep() ||
440
326k
      !SS.getScopeRep()->containsUnexpandedParameterPack())
441
356k
    return false;
442
8
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
8
  return DiagnoseUnexpandedParameterPacks(SS.getRange().getBegin(),
448
8
                                          UPPC, Unexpanded);
449
8
}
450
451
bool Sema::DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo,
452
18.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
18.9M
  switch (NameInfo.getName().getNameKind()) {
457
18.6M
  case DeclarationName::Identifier:
458
18.6M
  case DeclarationName::ObjCZeroArgSelector:
459
18.6M
  case DeclarationName::ObjCOneArgSelector:
460
18.6M
  case DeclarationName::ObjCMultiArgSelector:
461
18.6M
  case DeclarationName::CXXOperatorName:
462
18.6M
  case DeclarationName::CXXLiteralOperatorName:
463
18.6M
  case DeclarationName::CXXUsingDirective:
464
18.6M
  case DeclarationName::CXXDeductionGuideName:
465
18.6M
    return false;
466
18.6M
467
302k
  case DeclarationName::CXXConstructorName:
468
302k
  case DeclarationName::CXXDestructorName:
469
302k
  case DeclarationName::CXXConversionFunctionName:
470
    // FIXME: We shouldn't need this null check!
471
302k
    if (TypeSourceInfo *TSInfo = NameInfo.getNamedTypeInfo())
472
51.2k
      return DiagnoseUnexpandedParameterPack(NameInfo.getLoc(), TSInfo, UPPC);
473
251k
474
251k
    if (!NameInfo.getName().getCXXNameType()->containsUnexpandedParameterPack())
475
251k
      return false;
476
0
477
0
    break;
478
0
  }
479
0
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
0
}
486
487
bool Sema::DiagnoseUnexpandedParameterPack(SourceLocation Loc,
488
                                           TemplateName Template,
489
172
                                       UnexpandedParameterPackContext UPPC) {
490
172
491
172
  if (Template.isNull() || !Template.containsUnexpandedParameterPack())
492
171
    return false;
493
1
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
1
  return DiagnoseUnexpandedParameterPacks(Loc, UPPC, Unexpanded);
499
1
}
500
501
bool Sema::DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg,
502
371k
                                         UnexpandedParameterPackContext UPPC) {
503
371k
  if (Arg.getArgument().isNull() ||
504
371k
      !Arg.getArgument().containsUnexpandedParameterPack())
505
371k
    return false;
506
1
507
1
  SmallVector<UnexpandedParameterPack, 2> Unexpanded;
508
1
  CollectUnexpandedParameterPacksVisitor(Unexpanded)
509
1
    .TraverseTemplateArgumentLoc(Arg);
510
1
  assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
511
1
  return DiagnoseUnexpandedParameterPacks(Arg.getLocation(), UPPC, Unexpanded);
512
1
}
513
514
void Sema::collectUnexpandedParameterPacks(TemplateArgument Arg,
515
56.9k
                   SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
516
56.9k
  CollectUnexpandedParameterPacksVisitor(Unexpanded)
517
56.9k
    .TraverseTemplateArgument(Arg);
518
56.9k
}
519
520
void Sema::collectUnexpandedParameterPacks(TemplateArgumentLoc Arg,
521
174k
                   SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
522
174k
  CollectUnexpandedParameterPacksVisitor(Unexpanded)
523
174k
    .TraverseTemplateArgumentLoc(Arg);
524
174k
}
525
526
void Sema::collectUnexpandedParameterPacks(QualType T,
527
689
                   SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
528
689
  CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseType(T);
529
689
}
530
531
void Sema::collectUnexpandedParameterPacks(TypeLoc TL,
532
50.9k
                   SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
533
50.9k
  CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseTypeLoc(TL);
534
50.9k
}
535
536
void Sema::collectUnexpandedParameterPacks(
537
    NestedNameSpecifierLoc NNS,
538
48
    SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
539
48
  CollectUnexpandedParameterPacksVisitor(Unexpanded)
540
48
      .TraverseNestedNameSpecifierLoc(NNS);
541
48
}
542
543
void Sema::collectUnexpandedParameterPacks(
544
    const DeclarationNameInfo &NameInfo,
545
48
    SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
546
48
  CollectUnexpandedParameterPacksVisitor(Unexpanded)
547
48
    .TraverseDeclarationNameInfo(NameInfo);
548
48
}
549
550
551
ParsedTemplateArgument
552
Sema::ActOnPackExpansion(const ParsedTemplateArgument &Arg,
553
111k
                         SourceLocation EllipsisLoc) {
554
111k
  if (Arg.isInvalid())
555
1
    return Arg;
556
111k
557
111k
  switch (Arg.getKind()) {
558
90.3k
  case ParsedTemplateArgument::Type: {
559
90.3k
    TypeResult Result = ActOnPackExpansion(Arg.getAsType(), EllipsisLoc);
560
90.3k
    if (Result.isInvalid())
561
2
      return ParsedTemplateArgument();
562
90.3k
563
90.3k
    return ParsedTemplateArgument(Arg.getKind(), Result.get().getAsOpaquePtr(),
564
90.3k
                                  Arg.getLocation());
565
90.3k
  }
566
90.3k
567
20.8k
  case ParsedTemplateArgument::NonType: {
568
20.8k
    ExprResult Result = ActOnPackExpansion(Arg.getAsExpr(), EllipsisLoc);
569
20.8k
    if (Result.isInvalid())
570
0
      return ParsedTemplateArgument();
571
20.8k
572
20.8k
    return ParsedTemplateArgument(Arg.getKind(), Result.get(),
573
20.8k
                                  Arg.getLocation());
574
20.8k
  }
575
20.8k
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
24
586
24
    return Arg.getTemplatePackExpansion(EllipsisLoc);
587
0
  }
588
0
  llvm_unreachable("Unhandled template argument kind?");
589
0
}
590
591
TypeResult Sema::ActOnPackExpansion(ParsedType Type,
592
91.7k
                                    SourceLocation EllipsisLoc) {
593
91.7k
  TypeSourceInfo *TSInfo;
594
91.7k
  GetTypeFromParser(Type, &TSInfo);
595
91.7k
  if (!TSInfo)
596
0
    return true;
597
91.7k
598
91.7k
  TypeSourceInfo *TSResult = CheckPackExpansion(TSInfo, EllipsisLoc, None);
599
91.7k
  if (!TSResult)
600
2
    return true;
601
91.7k
602
91.7k
  return CreateParsedType(TSResult->getType(), TSResult);
603
91.7k
}
604
605
TypeSourceInfo *
606
Sema::CheckPackExpansion(TypeSourceInfo *Pattern, SourceLocation EllipsisLoc,
607
158k
                         Optional<unsigned> NumExpansions) {
608
  // Create the pack expansion type and source-location information.
609
158k
  QualType Result = CheckPackExpansion(Pattern->getType(),
610
158k
                                       Pattern->getTypeLoc().getSourceRange(),
611
158k
                                       EllipsisLoc, NumExpansions);
612
158k
  if (Result.isNull())
613
2
    return nullptr;
614
158k
615
158k
  TypeLocBuilder TLB;
616
158k
  TLB.pushFullCopy(Pattern->getTypeLoc());
617
158k
  PackExpansionTypeLoc TL = TLB.push<PackExpansionTypeLoc>(Result);
618
158k
  TL.setEllipsisLoc(EllipsisLoc);
619
158k
620
158k
  return TLB.getTypeSourceInfo(Context, Result);
621
158k
}
622
623
QualType Sema::CheckPackExpansion(QualType Pattern, SourceRange PatternRange,
624
                                  SourceLocation EllipsisLoc,
625
158k
                                  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
158k
  if (!Pattern->containsUnexpandedParameterPack() &&
634
48
      !Pattern->getContainedDeducedType()) {
635
2
    Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
636
2
      << PatternRange;
637
2
    return QualType();
638
2
  }
639
158k
640
158k
  return Context.getPackExpansionType(Pattern, NumExpansions,
641
158k
                                      /*ExpectPackInType=*/false);
642
158k
}
643
644
61.4k
ExprResult Sema::ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc) {
645
61.4k
  return CheckPackExpansion(Pattern, EllipsisLoc, None);
646
61.4k
}
647
648
ExprResult Sema::CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
649
95.0k
                                    Optional<unsigned> NumExpansions) {
650
95.0k
  if (!Pattern)
651
0
    return ExprError();
652
95.0k
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
95.0k
  if (!Pattern->containsUnexpandedParameterPack()) {
658
16
    Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
659
16
    << Pattern->getSourceRange();
660
16
    CorrectDelayedTyposInExpr(Pattern);
661
16
    return ExprError();
662
16
  }
663
95.0k
664
  // Create the pack expansion expression and source-location information.
665
95.0k
  return new (Context)
666
95.0k
    PackExpansionExpr(Context.DependentTy, Pattern, EllipsisLoc, NumExpansions);
667
95.0k
}
668
669
bool Sema::CheckParameterPacksForExpansion(
670
    SourceLocation EllipsisLoc, SourceRange PatternRange,
671
    ArrayRef<UnexpandedParameterPack> Unexpanded,
672
    const MultiLevelTemplateArgumentList &TemplateArgs, bool &ShouldExpand,
673
284k
    bool &RetainExpansion, Optional<unsigned> &NumExpansions) {
674
284k
  ShouldExpand = true;
675
284k
  RetainExpansion = false;
676
284k
  std::pair<IdentifierInfo *, SourceLocation> FirstPack;
677
284k
  bool HaveFirstPack = false;
678
284k
  Optional<unsigned> NumPartialExpansions;
679
284k
  SourceLocation PartiallySubstitutedPackLoc;
680
284k
681
284k
  for (ArrayRef<UnexpandedParameterPack>::iterator i = Unexpanded.begin(),
682
284k
                                                 end = Unexpanded.end();
683
580k
                                                  i != end; 
++i295k
) {
684
    // Compute the depth and index for this parameter pack.
685
295k
    unsigned Depth = 0, Index = 0;
686
295k
    IdentifierInfo *Name;
687
295k
    bool IsVarDeclPack = false;
688
295k
689
295k
    if (const TemplateTypeParmType *TTP
690
174k
        = i->first.dyn_cast<const TemplateTypeParmType *>()) {
691
174k
      Depth = TTP->getDepth();
692
174k
      Index = TTP->getIndex();
693
174k
      Name = TTP->getIdentifier();
694
121k
    } else {
695
121k
      NamedDecl *ND = i->first.get<NamedDecl *>();
696
121k
      if (isa<VarDecl>(ND))
697
5.89k
        IsVarDeclPack = true;
698
115k
      else
699
115k
        std::tie(Depth, Index) = getDepthAndIndex(ND);
700
121k
701
121k
      Name = ND->getIdentifier();
702
121k
    }
703
295k
704
    // Determine the size of this argument pack.
705
295k
    unsigned NewPackSize;
706
295k
    if (IsVarDeclPack) {
707
      // Figure out whether we're instantiating to an argument pack or not.
708
5.89k
      typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
709
5.89k
710
5.89k
      llvm::PointerUnion<Decl *, DeclArgumentPack *> *Instantiation
711
5.89k
        = CurrentInstantiationScope->findInstantiationOf(
712
5.89k
                                        i->first.get<NamedDecl *>());
713
5.89k
      if (Instantiation->is<DeclArgumentPack *>()) {
714
        // We could expand this function parameter pack.
715
5.63k
        NewPackSize = Instantiation->get<DeclArgumentPack *>()->size();
716
257
      } else {
717
        // We can't expand this function parameter pack, so we can't expand
718
        // the pack expansion.
719
257
        ShouldExpand = false;
720
257
        continue;
721
257
      }
722
289k
    } 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
289k
      if (Depth >= TemplateArgs.getNumLevels() ||
727
233k
          !TemplateArgs.hasTemplateArgument(Depth, Index)) {
728
81.6k
        ShouldExpand = false;
729
81.6k
        continue;
730
81.6k
      }
731
207k
732
      // Determine the size of the argument pack.
733
207k
      NewPackSize = TemplateArgs(Depth, Index).pack_size();
734
207k
    }
735
295k
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
213k
    if (!IsVarDeclPack && 
CurrentInstantiationScope207k
) {
741
207k
      if (NamedDecl *PartialPack
742
522
                    = CurrentInstantiationScope->getPartiallySubstitutedPack()){
743
522
        unsigned PartialDepth, PartialIndex;
744
522
        std::tie(PartialDepth, PartialIndex) = getDepthAndIndex(PartialPack);
745
522
        if (PartialDepth == Depth && PartialIndex == Index) {
746
522
          RetainExpansion = true;
747
          // We don't actually know the new pack size yet.
748
522
          NumPartialExpansions = NewPackSize;
749
522
          PartiallySubstitutedPackLoc = i->second;
750
522
          continue;
751
522
        }
752
212k
      }
753
207k
    }
754
212k
755
212k
    if (!NumExpansions) {
756
      // The is the first pack we've seen for which we have an argument.
757
      // Record it.
758
203k
      NumExpansions = NewPackSize;
759
203k
      FirstPack.first = Name;
760
203k
      FirstPack.second = i->second;
761
203k
      HaveFirstPack = true;
762
203k
      continue;
763
203k
    }
764
9.11k
765
9.11k
    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
17
      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
11
      else
774
11
        Diag(EllipsisLoc, diag::err_pack_expansion_length_conflict_multilevel)
775
11
          << Name << *NumExpansions << NewPackSize
776
11
          << SourceRange(i->second);
777
17
      return true;
778
17
    }
779
9.11k
  }
780
284k
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
284k
  if (NumPartialExpansions) {
791
522
    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
521
800
521
    NumExpansions = NumPartialExpansions;
801
521
  }
802
284k
803
284k
  return false;
804
284k
}
805
806
Optional<unsigned> Sema::getNumArgumentsInExpansion(QualType T,
807
29.9k
                          const MultiLevelTemplateArgumentList &TemplateArgs) {
808
29.9k
  QualType Pattern = cast<PackExpansionType>(T)->getPattern();
809
29.9k
  SmallVector<UnexpandedParameterPack, 2> Unexpanded;
810
29.9k
  CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseType(Pattern);
811
29.9k
812
29.9k
  Optional<unsigned> Result;
813
44.5k
  for (unsigned I = 0, N = Unexpanded.size(); I != N; 
++I14.6k
) {
814
    // Compute the depth and index for this parameter pack.
815
29.9k
    unsigned Depth;
816
29.9k
    unsigned Index;
817
29.9k
818
29.9k
    if (const TemplateTypeParmType *TTP
819
29.9k
          = Unexpanded[I].first.dyn_cast<const TemplateTypeParmType *>()) {
820
29.9k
      Depth = TTP->getDepth();
821
29.9k
      Index = TTP->getIndex();
822
62
    } 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
0
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
0
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
62
842
62
      std::tie(Depth, Index) = getDepthAndIndex(ND);
843
62
    }
844
29.9k
    if (Depth >= TemplateArgs.getNumLevels() ||
845
14.6k
        !TemplateArgs.hasTemplateArgument(Depth, Index))
846
      // The pattern refers to an unknown template argument. We're not ready to
847
      // expand this pack yet.
848
15.3k
      return None;
849
14.6k
850
    // Determine the size of the argument pack.
851
14.6k
    unsigned Size = TemplateArgs(Depth, Index).pack_size();
852
14.6k
    assert((!Result || *Result == Size) && "inconsistent pack sizes");
853
14.6k
    Result = Size;
854
14.6k
  }
855
29.9k
856
14.5k
  return Result;
857
29.9k
}
858
859
40.8k
bool Sema::containsUnexpandedParameterPacks(Declarator &D) {
860
40.8k
  const DeclSpec &DS = D.getDeclSpec();
861
40.8k
  switch (DS.getTypeSpecType()) {
862
40.6k
  case TST_typename:
863
40.6k
  case TST_typeofType:
864
40.6k
  case TST_underlyingType:
865
40.6k
  case TST_atomic: {
866
40.6k
    QualType T = DS.getRepAsType().get();
867
40.6k
    if (!T.isNull() && T->containsUnexpandedParameterPack())
868
40.6k
      return true;
869
7
    break;
870
7
  }
871
7
872
24
  case TST_typeofExpr:
873
24
  case TST_decltype:
874
24
  case TST_extint:
875
24
    if (DS.getRepAsExpr() &&
876
24
        DS.getRepAsExpr()->containsUnexpandedParameterPack())
877
24
      return true;
878
0
    break;
879
0
880
168
  case TST_unspecified:
881
168
  case TST_void:
882
168
  case TST_char:
883
168
  case TST_wchar:
884
168
  case TST_char8:
885
168
  case TST_char16:
886
168
  case TST_char32:
887
168
  case TST_int:
888
168
  case TST_int128:
889
168
  case TST_half:
890
168
  case TST_float:
891
168
  case TST_double:
892
168
  case TST_Accum:
893
168
  case TST_Fract:
894
168
  case TST_Float16:
895
168
  case TST_float128:
896
168
  case TST_bool:
897
168
  case TST_decimal32:
898
168
  case TST_decimal64:
899
168
  case TST_decimal128:
900
168
  case TST_enum:
901
168
  case TST_union:
902
168
  case TST_struct:
903
168
  case TST_interface:
904
168
  case TST_class:
905
168
  case TST_auto:
906
168
  case TST_auto_type:
907
168
  case TST_decltype_auto:
908
168
  case TST_BFloat16:
909
2.01k
#define GENERIC_IMAGE_TYPE(ImgType, Id) case TST_##ImgType##_t:
910
2.01k
#include 
"clang/Basic/OpenCLImageTypes.def"168
911
168
  case TST_unknown_anytype:
912
168
  case TST_error:
913
168
    break;
914
175
  }
915
175
916
201
  
for (unsigned I = 0, N = D.getNumTypeObjects(); 175
I != N;
++I26
) {
917
26
    const DeclaratorChunk &Chunk = D.getTypeObject(I);
918
26
    switch (Chunk.Kind) {
919
0
    case DeclaratorChunk::Pointer:
920
0
    case DeclaratorChunk::Reference:
921
0
    case DeclaratorChunk::Paren:
922
0
    case DeclaratorChunk::Pipe:
923
0
    case DeclaratorChunk::BlockPointer:
924
      // These declarator chunks cannot contain any parameter packs.
925
0
      break;
926
0
927
20
    case DeclaratorChunk::Array:
928
20
      if (Chunk.Arr.NumElts &&
929
0
          Chunk.Arr.NumElts->containsUnexpandedParameterPack())
930
0
        return true;
931
20
      break;
932
6
    case DeclaratorChunk::Function:
933
10
      for (unsigned i = 0, e = Chunk.Fun.NumParams; i != e; 
++i4
) {
934
4
        ParmVarDecl *Param = cast<ParmVarDecl>(Chunk.Fun.Params[i].Param);
935
4
        QualType ParamTy = Param->getType();
936
4
        assert(!ParamTy.isNull() && "Couldn't parse type?");
937
4
        if (ParamTy->containsUnexpandedParameterPack()) 
return true0
;
938
4
      }
939
6
940
6
      if (Chunk.Fun.getExceptionSpecType() == EST_Dynamic) {
941
0
        for (unsigned i = 0; i != Chunk.Fun.getNumExceptions(); ++i) {
942
0
          if (Chunk.Fun.Exceptions[i]
943
0
                  .Ty.get()
944
0
                  ->containsUnexpandedParameterPack())
945
0
            return true;
946
0
        }
947
6
      } else if (isComputedNoexcept(Chunk.Fun.getExceptionSpecType()) &&
948
0
                 Chunk.Fun.NoexceptExpr->containsUnexpandedParameterPack())
949
0
        return true;
950
6
951
6
      if (Chunk.Fun.hasTrailingReturnType()) {
952
6
        QualType T = Chunk.Fun.getTrailingReturnType().get();
953
6
        if (!T.isNull() && 
T->containsUnexpandedParameterPack()0
)
954
0
          return true;
955
6
      }
956
6
      break;
957
6
958
0
    case DeclaratorChunk::MemberPointer:
959
0
      if (Chunk.Mem.Scope().getScopeRep() &&
960
0
          Chunk.Mem.Scope().getScopeRep()->containsUnexpandedParameterPack())
961
0
        return true;
962
0
      break;
963
26
    }
964
26
  }
965
175
966
175
  if (Expr *TRC = D.getTrailingRequiresClause())
967
0
    if (TRC->containsUnexpandedParameterPack())
968
0
      return true;
969
175
970
175
  return false;
971
175
}
972
973
namespace {
974
975
// Callback to only accept typo corrections that refer to parameter packs.
976
class ParameterPackValidatorCCC final : public CorrectionCandidateCallback {
977
 public:
978
7
  bool ValidateCandidate(const TypoCorrection &candidate) override {
979
7
    NamedDecl *ND = candidate.getCorrectionDecl();
980
7
    return ND && ND->isParameterPack();
981
7
  }
982
983
3
  std::unique_ptr<CorrectionCandidateCallback> clone() override {
984
3
    return std::make_unique<ParameterPackValidatorCCC>(*this);
985
3
  }
986
};
987
988
}
989
990
/// Called when an expression computing the size of a parameter pack
991
/// is parsed.
992
///
993
/// \code
994
/// template<typename ...Types> struct count {
995
///   static const unsigned value = sizeof...(Types);
996
/// };
997
/// \endcode
998
///
999
//
1000
/// \param OpLoc The location of the "sizeof" keyword.
1001
/// \param Name The name of the parameter pack whose size will be determined.
1002
/// \param NameLoc The source location of the name of the parameter pack.
1003
/// \param RParenLoc The location of the closing parentheses.
1004
ExprResult Sema::ActOnSizeofParameterPackExpr(Scope *S,
1005
                                              SourceLocation OpLoc,
1006
                                              IdentifierInfo &Name,
1007
                                              SourceLocation NameLoc,
1008
44.5k
                                              SourceLocation RParenLoc) {
1009
  // C++0x [expr.sizeof]p5:
1010
  //   The identifier in a sizeof... expression shall name a parameter pack.
1011
44.5k
  LookupResult R(*this, &Name, NameLoc, LookupOrdinaryName);
1012
44.5k
  LookupName(R, S);
1013
44.5k
1014
44.5k
  NamedDecl *ParameterPack = nullptr;
1015
44.5k
  switch (R.getResultKind()) {
1016
44.5k
  case LookupResult::Found:
1017
44.5k
    ParameterPack = R.getFoundDecl();
1018
44.5k
    break;
1019
0
1020
3
  case LookupResult::NotFound:
1021
3
  case LookupResult::NotFoundInCurrentInstantiation: {
1022
3
    ParameterPackValidatorCCC CCC{};
1023
3
    if (TypoCorrection Corrected =
1024
3
            CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, nullptr,
1025
3
                        CCC, CTK_ErrorRecovery)) {
1026
3
      diagnoseTypo(Corrected,
1027
3
                   PDiag(diag::err_sizeof_pack_no_pack_name_suggest) << &Name,
1028
3
                   PDiag(diag::note_parameter_pack_here));
1029
3
      ParameterPack = Corrected.getCorrectionDecl();
1030
3
    }
1031
3
    break;
1032
3
  }
1033
0
  case LookupResult::FoundOverloaded:
1034
0
  case LookupResult::FoundUnresolvedValue:
1035
0
    break;
1036
0
1037
0
  case LookupResult::Ambiguous:
1038
0
    DiagnoseAmbiguousLookup(R);
1039
0
    return ExprError();
1040
44.5k
  }
1041
44.5k
1042
44.5k
  if (!ParameterPack || !ParameterPack->isParameterPack()) {
1043
1
    Diag(NameLoc, diag::err_sizeof_pack_no_pack_name)
1044
1
      << &Name;
1045
1
    return ExprError();
1046
1
  }
1047
44.5k
1048
44.5k
  MarkAnyDeclReferenced(OpLoc, ParameterPack, true);
1049
44.5k
1050
44.5k
  return SizeOfPackExpr::Create(Context, OpLoc, ParameterPack, NameLoc,
1051
44.5k
                                RParenLoc);
1052
44.5k
}
1053
1054
TemplateArgumentLoc
1055
Sema::getTemplateArgumentPackExpansionPattern(
1056
      TemplateArgumentLoc OrigLoc,
1057
233k
      SourceLocation &Ellipsis, Optional<unsigned> &NumExpansions) const {
1058
233k
  const TemplateArgument &Argument = OrigLoc.getArgument();
1059
233k
  assert(Argument.isPackExpansion());
1060
233k
  switch (Argument.getKind()) {
1061
185k
  case TemplateArgument::Type: {
1062
    // FIXME: We shouldn't ever have to worry about missing
1063
    // type-source info!
1064
185k
    TypeSourceInfo *ExpansionTSInfo = OrigLoc.getTypeSourceInfo();
1065
185k
    if (!ExpansionTSInfo)
1066
0
      ExpansionTSInfo = Context.getTrivialTypeSourceInfo(Argument.getAsType(),
1067
0
                                                         Ellipsis);
1068
185k
    PackExpansionTypeLoc Expansion =
1069
185k
        ExpansionTSInfo->getTypeLoc().castAs<PackExpansionTypeLoc>();
1070
185k
    Ellipsis = Expansion.getEllipsisLoc();
1071
185k
1072
185k
    TypeLoc Pattern = Expansion.getPatternLoc();
1073
185k
    NumExpansions = Expansion.getTypePtr()->getNumExpansions();
1074
185k
1075
    // We need to copy the TypeLoc because TemplateArgumentLocs store a
1076
    // TypeSourceInfo.
1077
    // FIXME: Find some way to avoid the copy?
1078
185k
    TypeLocBuilder TLB;
1079
185k
    TLB.pushFullCopy(Pattern);
1080
185k
    TypeSourceInfo *PatternTSInfo =
1081
185k
        TLB.getTypeSourceInfo(Context, Pattern.getType());
1082
185k
    return TemplateArgumentLoc(TemplateArgument(Pattern.getType()),
1083
185k
                               PatternTSInfo);
1084
0
  }
1085
0
1086
47.9k
  case TemplateArgument::Expression: {
1087
47.9k
    PackExpansionExpr *Expansion
1088
47.9k
      = cast<PackExpansionExpr>(Argument.getAsExpr());
1089
47.9k
    Expr *Pattern = Expansion->getPattern();
1090
47.9k
    Ellipsis = Expansion->getEllipsisLoc();
1091
47.9k
    NumExpansions = Expansion->getNumExpansions();
1092
47.9k
    return TemplateArgumentLoc(Pattern, Pattern);
1093
0
  }
1094
0
1095
35
  case TemplateArgument::TemplateExpansion:
1096
35
    Ellipsis = OrigLoc.getTemplateEllipsisLoc();
1097
35
    NumExpansions = Argument.getNumTemplateExpansions();
1098
35
    return TemplateArgumentLoc(Argument.getPackExpansionPattern(),
1099
35
                               OrigLoc.getTemplateQualifierLoc(),
1100
35
                               OrigLoc.getTemplateNameLoc());
1101
0
1102
0
  case TemplateArgument::Declaration:
1103
0
  case TemplateArgument::NullPtr:
1104
0
  case TemplateArgument::Template:
1105
0
  case TemplateArgument::Integral:
1106
0
  case TemplateArgument::Pack:
1107
0
  case TemplateArgument::Null:
1108
0
    return TemplateArgumentLoc();
1109
0
  }
1110
0
1111
0
  llvm_unreachable("Invalid TemplateArgument Kind!");
1112
0
}
1113
1114
58.8k
Optional<unsigned> Sema::getFullyPackExpandedSize(TemplateArgument Arg) {
1115
58.8k
  assert(Arg.containsUnexpandedParameterPack());
1116
58.8k
1117
  // If this is a substituted pack, grab that pack. If not, we don't know
1118
  // the size yet.
1119
  // FIXME: We could find a size in more cases by looking for a substituted
1120
  // pack anywhere within this argument, but that's not necessary in the common
1121
  // case for 'sizeof...(A)' handling.
1122
58.8k
  TemplateArgument Pack;
1123
58.8k
  switch (Arg.getKind()) {
1124
58.7k
  case TemplateArgument::Type:
1125
58.7k
    if (auto *Subst = Arg.getAsType()->getAs<SubstTemplateTypeParmPackType>())
1126
58.7k
      Pack = Subst->getArgumentPack();
1127
36
    else
1128
36
      return None;
1129
58.7k
    break;
1130
58.7k
1131
110
  case TemplateArgument::Expression:
1132
110
    if (auto *Subst =
1133
27
            dyn_cast<SubstNonTypeTemplateParmPackExpr>(Arg.getAsExpr()))
1134
27
      Pack = Subst->getArgumentPack();
1135
83
    else if (auto *Subst = dyn_cast<FunctionParmPackExpr>(Arg.getAsExpr()))  {
1136
83
      for (VarDecl *PD : *Subst)
1137
455
        if (PD->isParameterPack())
1138
1
          return None;
1139
82
      return Subst->getNumExpansions();
1140
0
    } else
1141
0
      return None;
1142
27
    break;
1143
27
1144
4
  case TemplateArgument::Template:
1145
4
    if (SubstTemplateTemplateParmPackStorage *Subst =
1146
4
            Arg.getAsTemplate().getAsSubstTemplateTemplateParmPack())
1147
4
      Pack = Subst->getArgumentPack();
1148
0
    else
1149
0
      return None;
1150
4
    break;
1151
4
1152
0
  case TemplateArgument::Declaration:
1153
0
  case TemplateArgument::NullPtr:
1154
0
  case TemplateArgument::TemplateExpansion:
1155
0
  case TemplateArgument::Integral:
1156
0
  case TemplateArgument::Pack:
1157
0
  case TemplateArgument::Null:
1158
0
    return None;
1159
58.7k
  }
1160
58.7k
1161
  // Check that no argument in the pack is itself a pack expansion.
1162
123k
  
for (TemplateArgument Elem : Pack.pack_elements())58.7k
{
1163
    // There's no point recursing in this case; we would have already
1164
    // expanded this pack expansion into the enclosing pack if we could.
1165
123k
    if (Elem.isPackExpansion())
1166
42
      return None;
1167
123k
  }
1168
58.7k
  return Pack.pack_size();
1169
58.7k
}
1170
1171
336
static void CheckFoldOperand(Sema &S, Expr *E) {
1172
336
  if (!E)
1173
120
    return;
1174
216
1175
216
  E = E->IgnoreImpCasts();
1176
216
  auto *OCE = dyn_cast<CXXOperatorCallExpr>(E);
1177
216
  if ((OCE && 
OCE->isInfixBinaryOp()5
) ||
isa<BinaryOperator>(E)213
||
1178
210
      isa<AbstractConditionalOperator>(E)) {
1179
6
    S.Diag(E->getExprLoc(), diag::err_fold_expression_bad_operand)
1180
6
        << E->getSourceRange()
1181
6
        << FixItHint::CreateInsertion(E->getBeginLoc(), "(")
1182
6
        << FixItHint::CreateInsertion(E->getEndLoc(), ")");
1183
6
  }
1184
216
}
1185
1186
ExprResult Sema::ActOnCXXFoldExpr(Scope *S, SourceLocation LParenLoc, Expr *LHS,
1187
                                  tok::TokenKind Operator,
1188
                                  SourceLocation EllipsisLoc, Expr *RHS,
1189
168
                                  SourceLocation RParenLoc) {
1190
  // LHS and RHS must be cast-expressions. We allow an arbitrary expression
1191
  // in the parser and reduce down to just cast-expressions here.
1192
168
  CheckFoldOperand(*this, LHS);
1193
168
  CheckFoldOperand(*this, RHS);
1194
168
1195
123
  auto DiscardOperands = [&] {
1196
123
    CorrectDelayedTyposInExpr(LHS);
1197
123
    CorrectDelayedTyposInExpr(RHS);
1198
123
  };
1199
168
1200
  // [expr.prim.fold]p3:
1201
  //   In a binary fold, op1 and op2 shall be the same fold-operator, and
1202
  //   either e1 shall contain an unexpanded parameter pack or e2 shall contain
1203
  //   an unexpanded parameter pack, but not both.
1204
168
  if (LHS && 
RHS156
&&
1205
48
      LHS->containsUnexpandedParameterPack() ==
1206
3
          RHS->containsUnexpandedParameterPack()) {
1207
3
    DiscardOperands();
1208
3
    return Diag(EllipsisLoc,
1209
3
                LHS->containsUnexpandedParameterPack()
1210
1
                    ? diag::err_fold_expression_packs_both_sides
1211
2
                    : diag::err_pack_expansion_without_parameter_packs)
1212
3
        << LHS->getSourceRange() << RHS->getSourceRange();
1213
3
  }
1214
165
1215
  // [expr.prim.fold]p2:
1216
  //   In a unary fold, the cast-expression shall contain an unexpanded
1217
  //   parameter pack.
1218
165
  if (!LHS || 
!RHS153
) {
1219
108
    Expr *Pack = LHS ? LHS : 
RHS12
;
1220
120
    assert(Pack && "fold expression with neither LHS nor RHS");
1221
120
    DiscardOperands();
1222
120
    if (!Pack->containsUnexpandedParameterPack())
1223
17
      return Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1224
17
             << Pack->getSourceRange();
1225
148
  }
1226
148
1227
148
  BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Operator);
1228
148
1229
  // Perform first-phase name lookup now.
1230
148
  UnresolvedLookupExpr *ULE = nullptr;
1231
148
  {
1232
148
    UnresolvedSet<16> Functions;
1233
148
    LookupBinOp(S, EllipsisLoc, Opc, Functions);
1234
148
    if (!Functions.empty()) {
1235
9
      DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(
1236
9
          BinaryOperator::getOverloadedOperator(Opc));
1237
9
      ExprResult Callee = CreateUnresolvedLookupExpr(
1238
9
          /*NamingClass*/ nullptr, NestedNameSpecifierLoc(),
1239
9
          DeclarationNameInfo(OpName, EllipsisLoc), Functions);
1240
9
      if (Callee.isInvalid())
1241
0
        return ExprError();
1242
9
      ULE = cast<UnresolvedLookupExpr>(Callee.get());
1243
9
    }
1244
148
  }
1245
148
1246
148
  return BuildCXXFoldExpr(ULE, LParenLoc, LHS, Opc, EllipsisLoc, RHS, RParenLoc,
1247
148
                          None);
1248
148
}
1249
1250
ExprResult Sema::BuildCXXFoldExpr(UnresolvedLookupExpr *Callee,
1251
                                  SourceLocation LParenLoc, Expr *LHS,
1252
                                  BinaryOperatorKind Operator,
1253
                                  SourceLocation EllipsisLoc, Expr *RHS,
1254
                                  SourceLocation RParenLoc,
1255
219
                                  Optional<unsigned> NumExpansions) {
1256
219
  return new (Context)
1257
219
      CXXFoldExpr(Context.DependentTy, Callee, LParenLoc, LHS, Operator,
1258
219
                  EllipsisLoc, RHS, RParenLoc, NumExpansions);
1259
219
}
1260
1261
ExprResult Sema::BuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc,
1262
28
                                       BinaryOperatorKind Operator) {
1263
  // [temp.variadic]p9:
1264
  //   If N is zero for a unary fold-expression, the value of the expression is
1265
  //       &&  ->  true
1266
  //       ||  ->  false
1267
  //       ,   ->  void()
1268
  //   if the operator is not listed [above], the instantiation is ill-formed.
1269
  //
1270
  // Note that we need to use something like int() here, not merely 0, to
1271
  // prevent the result from being a null pointer constant.
1272
28
  QualType ScalarType;
1273
28
  switch (Operator) {
1274
4
  case BO_LOr:
1275
4
    return ActOnCXXBoolLiteral(EllipsisLoc, tok::kw_false);
1276
3
  case BO_LAnd:
1277
3
    return ActOnCXXBoolLiteral(EllipsisLoc, tok::kw_true);
1278
5
  case BO_Comma:
1279
5
    ScalarType = Context.VoidTy;
1280
5
    break;
1281
0
1282
16
  default:
1283
16
    return Diag(EllipsisLoc, diag::err_fold_expression_empty)
1284
16
        << BinaryOperator::getOpcodeStr(Operator);
1285
5
  }
1286
5
1287
5
  return new (Context) CXXScalarValueInitExpr(
1288
5
      ScalarType, Context.getTrivialTypeSourceInfo(ScalarType, EllipsisLoc),
1289
5
      EllipsisLoc);
1290
5
}