Coverage Report

Created: 2022-07-16 07:03

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