Coverage Report

Created: 2021-01-19 06:58

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/Sema/SemaTemplateVariadic.cpp
Line
Count
Source (jump to first uncovered line)
1
//===------- SemaTemplateVariadic.cpp - C++ Variadic Templates ------------===/
2
//
3
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
// See https://llvm.org/LICENSE.txt for license information.
5
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
//===----------------------------------------------------------------------===/
7
//
8
//  This file implements semantic analysis for C++0x variadic templates.
9
//===----------------------------------------------------------------------===/
10
11
#include "clang/Sema/Sema.h"
12
#include "TypeLocBuilder.h"
13
#include "clang/AST/Expr.h"
14
#include "clang/AST/RecursiveASTVisitor.h"
15
#include "clang/AST/TypeLoc.h"
16
#include "clang/Sema/Lookup.h"
17
#include "clang/Sema/ParsedTemplate.h"
18
#include "clang/Sema/ScopeInfo.h"
19
#include "clang/Sema/SemaInternal.h"
20
#include "clang/Sema/Template.h"
21
22
using namespace clang;
23
24
//----------------------------------------------------------------------------
25
// Visitor that collects unexpanded parameter packs
26
//----------------------------------------------------------------------------
27
28
namespace {
29
  /// A class that collects unexpanded parameter packs.
30
  class CollectUnexpandedParameterPacksVisitor :
31
    public RecursiveASTVisitor<CollectUnexpandedParameterPacksVisitor>
32
  {
33
    typedef RecursiveASTVisitor<CollectUnexpandedParameterPacksVisitor>
34
      inherited;
35
36
    SmallVectorImpl<UnexpandedParameterPack> &Unexpanded;
37
38
    bool InLambda = false;
39
    unsigned DepthLimit = (unsigned)-1;
40
41
53.2k
    void addUnexpanded(NamedDecl *ND, SourceLocation Loc = SourceLocation()) {
42
53.2k
      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.02k
        auto *FTD = FD ? FD->getDescribedFunctionTemplate() : 
nullptr56
;
48
7.08k
        if (FTD && 
FTD->getTemplateParameters()->getDepth() >= DepthLimit6.75k
)
49
0
          return;
50
46.1k
      } else if (getDepthAndIndex(ND).first >= DepthLimit)
51
0
        return;
52
53
53.2k
      Unexpanded.push_back({ND, Loc});
54
53.2k
    }
55
    void addUnexpanded(const TemplateTypeParmType *T,
56
255k
                       SourceLocation Loc = SourceLocation()) {
57
255k
      if (T->getDepth() < DepthLimit)
58
255k
        Unexpanded.push_back({T, Loc});
59
255k
    }
60
61
  public:
62
    explicit CollectUnexpandedParameterPacksVisitor(
63
        SmallVectorImpl<UnexpandedParameterPack> &Unexpanded)
64
301k
        : Unexpanded(Unexpanded) {}
65
66
220k
    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
182k
    bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
74
182k
      if (TL.getTypePtr()->isParameterPack())
75
182k
        addUnexpanded(TL.getTypePtr(), TL.getNameLoc());
76
182k
      return true;
77
182k
    }
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
72.6k
    bool VisitTemplateTypeParmType(TemplateTypeParmType *T) {
85
72.6k
      if (T->isParameterPack())
86
72.6k
        addUnexpanded(T);
87
88
72.6k
      return true;
89
72.6k
    }
90
91
    /// Record occurrences of function and non-type template
92
    /// parameter packs in an expression.
93
53.1k
    bool VisitDeclRefExpr(DeclRefExpr *E) {
94
53.1k
      if (E->getDecl()->isParameterPack())
95
53.1k
        addUnexpanded(E->getDecl(), E->getLocation());
96
97
53.1k
      return true;
98
53.1k
    }
99
100
    /// Record occurrences of template template parameter packs.
101
9.34k
    bool TraverseTemplateName(TemplateName Template) {
102
9.34k
      if (auto *TTP = dyn_cast_or_null<TemplateTemplateParmDecl>(
103
2.68k
              Template.getAsTemplateDecl())) {
104
2.68k
        if (TTP->isParameterPack())
105
96
          addUnexpanded(TTP);
106
2.68k
      }
107
108
9.34k
      return inherited::TraverseTemplateName(Template);
109
9.34k
    }
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
141k
    bool TraverseStmt(Stmt *S) {
134
141k
      Expr *E = dyn_cast_or_null<Expr>(S);
135
141k
      if ((E && 
E->containsUnexpandedParameterPack()141k
) ||
InLambda18.5k
)
136
123k
        return inherited::TraverseStmt(S);
137
138
17.8k
      return true;
139
17.8k
    }
140
141
    /// Suppress traversal into types that do not contain
142
    /// unexpanded parameter packs.
143
109k
    bool TraverseType(QualType T) {
144
109k
      if ((!T.isNull() && 
T->containsUnexpandedParameterPack()109k
) ||
InLambda990
)
145
109k
        return inherited::TraverseType(T);
146
147
957
      return true;
148
957
    }
149
150
    /// Suppress traversal into types with location information
151
    /// that do not contain unexpanded parameter packs.
152
236k
    bool TraverseTypeLoc(TypeLoc TL) {
153
236k
      if ((!TL.getType().isNull() &&
154
236k
           TL.getType()->containsUnexpandedParameterPack()) ||
155
16.7k
          InLambda)
156
220k
        return inherited::TraverseTypeLoc(TL);
157
158
16.6k
      return true;
159
16.6k
    }
160
161
    /// Suppress traversal of parameter packs.
162
320
    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
320
      if (D && 
D->isParameterPack()319
)
167
56
        return true;
168
169
264
      return inherited::TraverseDecl(D);
170
264
    }
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
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
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
202
1
      return inherited::TraverseUnresolvedUsingTypenameDecl(D);
203
1
    }
204
205
    /// Suppress traversal of template argument pack expansions.
206
56.0k
    bool TraverseTemplateArgument(const TemplateArgument &Arg) {
207
56.0k
      if (Arg.isPackExpansion())
208
8
        return true;
209
210
56.0k
      return inherited::TraverseTemplateArgument(Arg);
211
56.0k
    }
212
213
    /// Suppress traversal of template argument pack expansions.
214
187k
    bool TraverseTemplateArgumentLoc(const TemplateArgumentLoc &ArgLoc) {
215
187k
      if (ArgLoc.getArgument().isPackExpansion())
216
426
        return true;
217
218
186k
      return inherited::TraverseTemplateArgumentLoc(ArgLoc);
219
186k
    }
220
221
    /// Suppress traversal of base specifier pack expansions.
222
14
    bool TraverseCXXBaseSpecifier(const CXXBaseSpecifier &Base) {
223
14
      if (Base.isPackExpansion())
224
10
        return true;
225
226
4
      return inherited::TraverseCXXBaseSpecifier(Base);
227
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
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
129
    bool TraverseLambdaExpr(LambdaExpr *Lambda) {
243
      // The ContainsUnexpandedParameterPack bit on a lambda is always correct,
244
      // even if it's contained within another lambda.
245
129
      if (!Lambda->containsUnexpandedParameterPack())
246
8
        return true;
247
248
121
      bool WasInLambda = InLambda;
249
121
      unsigned OldDepthLimit = DepthLimit;
250
251
121
      InLambda = true;
252
121
      if (auto *TPL = Lambda->getTemplateParameterList())
253
10
        DepthLimit = TPL->getDepth();
254
255
121
      inherited::TraverseLambdaExpr(Lambda);
256
257
121
      InLambda = WasInLambda;
258
121
      DepthLimit = OldDepthLimit;
259
121
      return true;
260
121
    }
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
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
390
                                 ArrayRef<UnexpandedParameterPack> Unexpanded) {
293
390
  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
390
  SmallVector<UnexpandedParameterPack, 4> LambdaParamPackReferences;
302
390
  if (auto *LSI = getEnclosingLambda()) {
303
204
    for (auto &Pack : Unexpanded) {
304
94
      auto DeclaresThisPack = [&](NamedDecl *LocalPack) {
305
94
        if (auto *TTPT = Pack.first.dyn_cast<const TemplateTypeParmType *>()) {
306
11
          auto *TTPD = dyn_cast<TemplateTypeParmDecl>(LocalPack);
307
11
          return TTPD && 
TTPD->getTypeForDecl() == TTPT8
;
308
11
        }
309
83
        return declaresSameEntity(Pack.first.get<NamedDecl *>(), LocalPack);
310
83
      };
311
204
      if (std::find_if(LSI->LocalPacks.begin(), LSI->LocalPacks.end(),
312
204
                       DeclaresThisPack) != LSI->LocalPacks.end())
313
79
        LambdaParamPackReferences.push_back(Pack);
314
204
    }
315
316
201
    if (LambdaParamPackReferences.empty()) {
317
      // Construct in lambda only references packs declared outside the lambda.
318
      // That's OK for now, but the lambda itself is considered to contain an
319
      // unexpanded pack in this case, which will require expansion outside the
320
      // lambda.
321
322
      // We do not permit pack expansion that would duplicate a statement
323
      // expression, not even within a lambda.
324
      // FIXME: We could probably support this for statement expressions that
325
      // do not contain labels.
326
      // FIXME: This is insufficient to detect this problem; consider
327
      //   f( ({ bad: 0; }) + pack ... );
328
122
      bool EnclosingStmtExpr = false;
329
126
      for (unsigned N = FunctionScopes.size(); N; 
--N4
) {
330
126
        sema::FunctionScopeInfo *Func = FunctionScopes[N-1];
331
126
        if (std::any_of(
332
126
                Func->CompoundScopes.begin(), Func->CompoundScopes.end(),
333
90
                [](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
125
        if (Func == LSI)
340
121
          break;
341
125
      }
342
343
122
      if (!EnclosingStmtExpr) {
344
121
        LSI->ContainsUnexpandedParameterPack = true;
345
121
        return false;
346
121
      }
347
79
    } else {
348
79
      Unexpanded = LambdaParamPackReferences;
349
79
    }
350
201
  }
351
352
269
  SmallVector<SourceLocation, 4> Locations;
353
269
  SmallVector<IdentifierInfo *, 4> Names;
354
269
  llvm::SmallPtrSet<IdentifierInfo *, 4> NamesKnown;
355
356
550
  for (unsigned I = 0, N = Unexpanded.size(); I != N; 
++I281
) {
357
281
    IdentifierInfo *Name = nullptr;
358
281
    if (const TemplateTypeParmType *TTP
359
155
          = Unexpanded[I].first.dyn_cast<const TemplateTypeParmType *>())
360
155
      Name = TTP->getIdentifier();
361
126
    else
362
126
      Name = Unexpanded[I].first.get<NamedDecl *>()->getIdentifier();
363
364
281
    if (Name && NamesKnown.insert(Name).second)
365
276
      Names.push_back(Name);
366
367
281
    if (Unexpanded[I].second.isValid())
368
261
      Locations.push_back(Unexpanded[I].second);
369
281
  }
370
371
269
  auto DB = Diag(Loc, diag::err_unexpanded_parameter_pack)
372
269
            << (int)UPPC << (int)Names.size();
373
544
  for (size_t I = 0, E = std::min(Names.size(), (size_t)2); I != E; 
++I275
)
374
275
    DB << Names[I];
375
376
530
  for (unsigned I = 0, N = Locations.size(); I != N; 
++I261
)
377
261
    DB << SourceRange(Locations[I]);
378
269
  return true;
379
390
}
380
381
bool Sema::DiagnoseUnexpandedParameterPack(SourceLocation Loc,
382
                                           TypeSourceInfo *T,
383
20.8M
                                         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.8M
  if (!T->getType()->containsUnexpandedParameterPack())
388
20.8M
    return false;
389
390
147
  SmallVector<UnexpandedParameterPack, 2> Unexpanded;
391
147
  CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseTypeLoc(
392
147
                                                              T->getTypeLoc());
393
147
  assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
394
147
  return DiagnoseUnexpandedParameterPacks(Loc, UPPC, Unexpanded);
395
147
}
396
397
bool Sema::DiagnoseUnexpandedParameterPack(Expr *E,
398
20.9M
                                        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.9M
  if (!E->containsUnexpandedParameterPack())
403
20.9M
    return false;
404
405
232
  SmallVector<UnexpandedParameterPack, 2> Unexpanded;
406
232
  CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseStmt(E);
407
232
  assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
408
232
  return DiagnoseUnexpandedParameterPacks(E->getBeginLoc(), UPPC, Unexpanded);
409
232
}
410
411
205
bool Sema::DiagnoseUnexpandedParameterPackInRequiresExpr(RequiresExpr *RE) {
412
205
  if (!RE->containsUnexpandedParameterPack())
413
192
    return false;
414
415
13
  SmallVector<UnexpandedParameterPack, 2> Unexpanded;
416
13
  CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseStmt(RE);
417
13
  assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
418
419
  // We only care about unexpanded references to the RequiresExpr's own
420
  // parameter packs.
421
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
430
1
  return DiagnoseUnexpandedParameterPacks(RE->getBeginLoc(), UPPC_Requirement,
431
1
                                          UnexpandedParms);
432
1
}
433
434
bool Sema::DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS,
435
363k
                                        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
363k
  if (!SS.getScopeRep() ||
440
332k
      !SS.getScopeRep()->containsUnexpandedParameterPack())
441
363k
    return false;
442
443
8
  SmallVector<UnexpandedParameterPack, 2> Unexpanded;
444
8
  CollectUnexpandedParameterPacksVisitor(Unexpanded)
445
8
    .TraverseNestedNameSpecifier(SS.getScopeRep());
446
8
  assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
447
8
  return DiagnoseUnexpandedParameterPacks(SS.getRange().getBegin(),
448
8
                                          UPPC, Unexpanded);
449
8
}
450
451
bool Sema::DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo,
452
19.1M
                                         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
19.1M
  switch (NameInfo.getName().getNameKind()) {
457
18.5M
  case DeclarationName::Identifier:
458
18.5M
  case DeclarationName::ObjCZeroArgSelector:
459
18.5M
  case DeclarationName::ObjCOneArgSelector:
460
18.5M
  case DeclarationName::ObjCMultiArgSelector:
461
18.8M
  case DeclarationName::CXXOperatorName:
462
18.8M
  case DeclarationName::CXXLiteralOperatorName:
463
18.8M
  case DeclarationName::CXXUsingDirective:
464
18.8M
  case DeclarationName::CXXDeductionGuideName:
465
18.8M
    return false;
466
467
260k
  case DeclarationName::CXXConstructorName:
468
300k
  case DeclarationName::CXXDestructorName:
469
313k
  case DeclarationName::CXXConversionFunctionName:
470
    // FIXME: We shouldn't need this null check!
471
313k
    if (TypeSourceInfo *TSInfo = NameInfo.getNamedTypeInfo())
472
53.3k
      return DiagnoseUnexpandedParameterPack(NameInfo.getLoc(), TSInfo, UPPC);
473
474
260k
    if (!NameInfo.getName().getCXXNameType()->containsUnexpandedParameterPack())
475
260k
      return false;
476
477
0
    break;
478
0
  }
479
480
0
  SmallVector<UnexpandedParameterPack, 2> Unexpanded;
481
0
  CollectUnexpandedParameterPacksVisitor(Unexpanded)
482
0
    .TraverseType(NameInfo.getName().getCXXNameType());
483
0
  assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
484
0
  return DiagnoseUnexpandedParameterPacks(NameInfo.getLoc(), UPPC, Unexpanded);
485
0
}
486
487
bool Sema::DiagnoseUnexpandedParameterPack(SourceLocation Loc,
488
                                           TemplateName Template,
489
178
                                       UnexpandedParameterPackContext UPPC) {
490
491
178
  if (Template.isNull() || !Template.containsUnexpandedParameterPack())
492
177
    return false;
493
494
1
  SmallVector<UnexpandedParameterPack, 2> Unexpanded;
495
1
  CollectUnexpandedParameterPacksVisitor(Unexpanded)
496
1
    .TraverseTemplateName(Template);
497
1
  assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
498
1
  return DiagnoseUnexpandedParameterPacks(Loc, UPPC, Unexpanded);
499
1
}
500
501
bool Sema::DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg,
502
390k
                                         UnexpandedParameterPackContext UPPC) {
503
390k
  if (Arg.getArgument().isNull() ||
504
390k
      !Arg.getArgument().containsUnexpandedParameterPack())
505
390k
    return false;
506
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
55.4k
                   SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
516
55.4k
  CollectUnexpandedParameterPacksVisitor(Unexpanded)
517
55.4k
    .TraverseTemplateArgument(Arg);
518
55.4k
}
519
520
void Sema::collectUnexpandedParameterPacks(TemplateArgumentLoc Arg,
521
164k
                   SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
522
164k
  CollectUnexpandedParameterPacksVisitor(Unexpanded)
523
164k
    .TraverseTemplateArgumentLoc(Arg);
524
164k
}
525
526
void Sema::collectUnexpandedParameterPacks(QualType T,
527
700
                   SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
528
700
  CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseType(T);
529
700
}
530
531
void Sema::collectUnexpandedParameterPacks(TypeLoc TL,
532
50.2k
                   SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
533
50.2k
  CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseTypeLoc(TL);
534
50.2k
}
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
115k
                         SourceLocation EllipsisLoc) {
554
115k
  if (Arg.isInvalid())
555
1
    return Arg;
556
557
115k
  switch (Arg.getKind()) {
558
93.5k
  case ParsedTemplateArgument::Type: {
559
93.5k
    TypeResult Result = ActOnPackExpansion(Arg.getAsType(), EllipsisLoc);
560
93.5k
    if (Result.isInvalid())
561
2
      return ParsedTemplateArgument();
562
563
93.5k
    return ParsedTemplateArgument(Arg.getKind(), Result.get().getAsOpaquePtr(),
564
93.5k
                                  Arg.getLocation());
565
93.5k
  }
566
567
21.5k
  case ParsedTemplateArgument::NonType: {
568
21.5k
    ExprResult Result = ActOnPackExpansion(Arg.getAsExpr(), EllipsisLoc);
569
21.5k
    if (Result.isInvalid())
570
0
      return ParsedTemplateArgument();
571
572
21.5k
    return ParsedTemplateArgument(Arg.getKind(), Result.get(),
573
21.5k
                                  Arg.getLocation());
574
21.5k
  }
575
576
24
  case ParsedTemplateArgument::Template:
577
24
    if (!Arg.getAsTemplate().get().containsUnexpandedParameterPack()) {
578
0
      SourceRange R(Arg.getLocation());
579
0
      if (Arg.getScopeSpec().isValid())
580
0
        R.setBegin(Arg.getScopeSpec().getBeginLoc());
581
0
      Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
582
0
        << R;
583
0
      return ParsedTemplateArgument();
584
0
    }
585
586
24
    return Arg.getTemplatePackExpansion(EllipsisLoc);
587
0
  }
588
0
  llvm_unreachable("Unhandled template argument kind?");
589
0
}
590
591
TypeResult Sema::ActOnPackExpansion(ParsedType Type,
592
94.9k
                                    SourceLocation EllipsisLoc) {
593
94.9k
  TypeSourceInfo *TSInfo;
594
94.9k
  GetTypeFromParser(Type, &TSInfo);
595
94.9k
  if (!TSInfo)
596
0
    return true;
597
598
94.9k
  TypeSourceInfo *TSResult = CheckPackExpansion(TSInfo, EllipsisLoc, None);
599
94.9k
  if (!TSResult)
600
2
    return true;
601
602
94.9k
  return CreateParsedType(TSResult->getType(), TSResult);
603
94.9k
}
604
605
TypeSourceInfo *
606
Sema::CheckPackExpansion(TypeSourceInfo *Pattern, SourceLocation EllipsisLoc,
607
162k
                         Optional<unsigned> NumExpansions) {
608
  // Create the pack expansion type and source-location information.
609
162k
  QualType Result = CheckPackExpansion(Pattern->getType(),
610
162k
                                       Pattern->getTypeLoc().getSourceRange(),
611
162k
                                       EllipsisLoc, NumExpansions);
612
162k
  if (Result.isNull())
613
2
    return nullptr;
614
615
162k
  TypeLocBuilder TLB;
616
162k
  TLB.pushFullCopy(Pattern->getTypeLoc());
617
162k
  PackExpansionTypeLoc TL = TLB.push<PackExpansionTypeLoc>(Result);
618
162k
  TL.setEllipsisLoc(EllipsisLoc);
619
620
162k
  return TLB.getTypeSourceInfo(Context, Result);
621
162k
}
622
623
QualType Sema::CheckPackExpansion(QualType Pattern, SourceRange PatternRange,
624
                                  SourceLocation EllipsisLoc,
625
162k
                                  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
162k
  if (!Pattern->containsUnexpandedParameterPack() &&
634
52
      !Pattern->getContainedDeducedType()) {
635
2
    Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
636
2
      << PatternRange;
637
2
    return QualType();
638
2
  }
639
640
162k
  return Context.getPackExpansionType(Pattern, NumExpansions,
641
162k
                                      /*ExpectPackInType=*/false);
642
162k
}
643
644
64.5k
ExprResult Sema::ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc) {
645
64.5k
  return CheckPackExpansion(Pattern, EllipsisLoc, None);
646
64.5k
}
647
648
ExprResult Sema::CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
649
97.8k
                                    Optional<unsigned> NumExpansions) {
650
97.8k
  if (!Pattern)
651
0
    return ExprError();
652
653
  // C++0x [temp.variadic]p5:
654
  //   The pattern of a pack expansion shall name one or more
655
  //   parameter packs that are not expanded by a nested pack
656
  //   expansion.
657
97.8k
  if (!Pattern->containsUnexpandedParameterPack()) {
658
24
    Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
659
24
    << Pattern->getSourceRange();
660
24
    CorrectDelayedTyposInExpr(Pattern);
661
24
    return ExprError();
662
24
  }
663
664
  // Create the pack expansion expression and source-location information.
665
97.8k
  return new (Context)
666
97.8k
    PackExpansionExpr(Context.DependentTy, Pattern, EllipsisLoc, NumExpansions);
667
97.8k
}
668
669
bool Sema::CheckParameterPacksForExpansion(
670
    SourceLocation EllipsisLoc, SourceRange PatternRange,
671
    ArrayRef<UnexpandedParameterPack> Unexpanded,
672
    const MultiLevelTemplateArgumentList &TemplateArgs, bool &ShouldExpand,
673
264k
    bool &RetainExpansion, Optional<unsigned> &NumExpansions) {
674
264k
  ShouldExpand = true;
675
264k
  RetainExpansion = false;
676
264k
  std::pair<IdentifierInfo *, SourceLocation> FirstPack;
677
264k
  bool HaveFirstPack = false;
678
264k
  Optional<unsigned> NumPartialExpansions;
679
264k
  SourceLocation PartiallySubstitutedPackLoc;
680
681
264k
  for (ArrayRef<UnexpandedParameterPack>::iterator i = Unexpanded.begin(),
682
264k
                                                 end = Unexpanded.end();
683
537k
                                                  i != end; 
++i273k
) {
684
    // Compute the depth and index for this parameter pack.
685
273k
    unsigned Depth = 0, Index = 0;
686
273k
    IdentifierInfo *Name;
687
273k
    bool IsVarDeclPack = false;
688
689
273k
    if (const TemplateTypeParmType *TTP
690
163k
        = i->first.dyn_cast<const TemplateTypeParmType *>()) {
691
163k
      Depth = TTP->getDepth();
692
163k
      Index = TTP->getIndex();
693
163k
      Name = TTP->getIdentifier();
694
109k
    } else {
695
109k
      NamedDecl *ND = i->first.get<NamedDecl *>();
696
109k
      if (isa<VarDecl>(ND))
697
7.26k
        IsVarDeclPack = true;
698
102k
      else
699
102k
        std::tie(Depth, Index) = getDepthAndIndex(ND);
700
701
109k
      Name = ND->getIdentifier();
702
109k
    }
703
704
    // Determine the size of this argument pack.
705
273k
    unsigned NewPackSize;
706
273k
    if (IsVarDeclPack) {
707
      // Figure out whether we're instantiating to an argument pack or not.
708
7.26k
      typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
709
710
7.26k
      llvm::PointerUnion<Decl *, DeclArgumentPack *> *Instantiation
711
7.26k
        = CurrentInstantiationScope->findInstantiationOf(
712
7.26k
                                        i->first.get<NamedDecl *>());
713
7.26k
      if (Instantiation->is<DeclArgumentPack *>()) {
714
        // We could expand this function parameter pack.
715
6.75k
        NewPackSize = Instantiation->get<DeclArgumentPack *>()->size();
716
503
      } else {
717
        // We can't expand this function parameter pack, so we can't expand
718
        // the pack expansion.
719
503
        ShouldExpand = false;
720
503
        continue;
721
503
      }
722
265k
    } 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
265k
      if (Depth >= TemplateArgs.getNumLevels() ||
727
208k
          !TemplateArgs.hasTemplateArgument(Depth, Index)) {
728
80.3k
        ShouldExpand = false;
729
80.3k
        continue;
730
80.3k
      }
731
732
      // Determine the size of the argument pack.
733
185k
      NewPackSize = TemplateArgs(Depth, Index).pack_size();
734
185k
    }
735
736
    // C++0x [temp.arg.explicit]p9:
737
    //   Template argument deduction can extend the sequence of template
738
    //   arguments corresponding to a template parameter pack, even when the
739
    //   sequence contains explicitly specified template arguments.
740
192k
    if (!IsVarDeclPack && 
CurrentInstantiationScope185k
) {
741
185k
      if (NamedDecl *PartialPack
742
577
                    = CurrentInstantiationScope->getPartiallySubstitutedPack()){
743
577
        unsigned PartialDepth, PartialIndex;
744
577
        std::tie(PartialDepth, PartialIndex) = getDepthAndIndex(PartialPack);
745
577
        if (PartialDepth == Depth && PartialIndex == Index) {
746
577
          RetainExpansion = true;
747
          // We don't actually know the new pack size yet.
748
577
          NumPartialExpansions = NewPackSize;
749
577
          PartiallySubstitutedPackLoc = i->second;
750
577
          continue;
751
577
        }
752
191k
      }
753
185k
    }
754
755
191k
    if (!NumExpansions) {
756
      // The is the first pack we've seen for which we have an argument.
757
      // Record it.
758
184k
      NumExpansions = NewPackSize;
759
184k
      FirstPack.first = Name;
760
184k
      FirstPack.second = i->second;
761
184k
      HaveFirstPack = true;
762
184k
      continue;
763
184k
    }
764
765
7.53k
    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
7.53k
  }
780
781
  // If we're performing a partial expansion but we also have a full expansion,
782
  // expand to the number of common arguments. For example, given:
783
  //
784
  //   template<typename ...T> struct A {
785
  //     template<typename ...U> void f(pair<T, U>...);
786
  //   };
787
  //
788
  // ... a call to 'A<int, int>().f<int>' should expand the pack once and
789
  // retain an expansion.
790
264k
  if (NumPartialExpansions) {
791
577
    if (NumExpansions && 
*NumExpansions < *NumPartialExpansions7
) {
792
1
      NamedDecl *PartialPack =
793
1
          CurrentInstantiationScope->getPartiallySubstitutedPack();
794
1
      Diag(EllipsisLoc, diag::err_pack_expansion_length_conflict_partial)
795
1
        << PartialPack << *NumPartialExpansions << *NumExpansions
796
1
        << SourceRange(PartiallySubstitutedPackLoc);
797
1
      return true;
798
1
    }
799
800
576
    NumExpansions = NumPartialExpansions;
801
576
  }
802
803
264k
  return false;
804
264k
}
805
806
Optional<unsigned> Sema::getNumArgumentsInExpansion(QualType T,
807
29.6k
                          const MultiLevelTemplateArgumentList &TemplateArgs) {
808
29.6k
  QualType Pattern = cast<PackExpansionType>(T)->getPattern();
809
29.6k
  SmallVector<UnexpandedParameterPack, 2> Unexpanded;
810
29.6k
  CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseType(Pattern);
811
812
29.6k
  Optional<unsigned> Result;
813
45.4k
  for (unsigned I = 0, N = Unexpanded.size(); I != N; 
++I15.8k
) {
814
    // Compute the depth and index for this parameter pack.
815
29.6k
    unsigned Depth;
816
29.6k
    unsigned Index;
817
818
29.6k
    if (const TemplateTypeParmType *TTP
819
29.6k
          = Unexpanded[I].first.dyn_cast<const TemplateTypeParmType *>()) {
820
29.6k
      Depth = TTP->getDepth();
821
29.6k
      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
828
0
        llvm::PointerUnion<Decl *, DeclArgumentPack *> *Instantiation
829
0
          = CurrentInstantiationScope->findInstantiationOf(
830
0
                                        Unexpanded[I].first.get<NamedDecl *>());
831
0
        if (Instantiation->is<Decl*>())
832
          // The pattern refers to an unexpanded pack. We're not ready to expand
833
          // this pack yet.
834
0
          return None;
835
836
0
        unsigned Size = Instantiation->get<DeclArgumentPack *>()->size();
837
0
        assert((!Result || *Result == Size) && "inconsistent pack sizes");
838
0
        Result = Size;
839
0
        continue;
840
0
      }
841
842
62
      std::tie(Depth, Index) = getDepthAndIndex(ND);
843
62
    }
844
29.6k
    if (Depth >= TemplateArgs.getNumLevels() ||
845
15.8k
        !TemplateArgs.hasTemplateArgument(Depth, Index))
846
      // The pattern refers to an unknown template argument. We're not ready to
847
      // expand this pack yet.
848
13.8k
      return None;
849
850
    // Determine the size of the argument pack.
851
15.8k
    unsigned Size = TemplateArgs(Depth, Index).pack_size();
852
15.8k
    assert((!Result || *Result == Size) && "inconsistent pack sizes");
853
15.8k
    Result = Size;
854
15.8k
  }
855
856
15.7k
  return Result;
857
29.6k
}
858
859
42.2k
bool Sema::containsUnexpandedParameterPacks(Declarator &D) {
860
42.2k
  const DeclSpec &DS = D.getDeclSpec();
861
42.2k
  switch (DS.getTypeSpecType()) {
862
42.0k
  case TST_typename:
863
42.0k
  case TST_typeofType:
864
42.0k
  case TST_underlyingType:
865
42.0k
  case TST_atomic: {
866
42.0k
    QualType T = DS.getRepAsType().get();
867
42.0k
    if (!T.isNull() && T->containsUnexpandedParameterPack())
868
42.0k
      return true;
869
7
    break;
870
7
  }
871
872
0
  case TST_typeofExpr:
873
48
  case TST_decltype:
874
48
  case TST_extint:
875
48
    if (DS.getRepAsExpr() &&
876
48
        DS.getRepAsExpr()->containsUnexpandedParameterPack())
877
48
      return true;
878
0
    break;
879
880
2
  case TST_unspecified:
881
2
  case TST_void:
882
26
  case TST_char:
883
26
  case TST_wchar:
884
26
  case TST_char8:
885
26
  case TST_char16:
886
26
  case TST_char32:
887
129
  case TST_int:
888
129
  case TST_int128:
889
129
  case TST_half:
890
151
  case TST_float:
891
154
  case TST_double:
892
154
  case TST_Accum:
893
154
  case TST_Fract:
894
154
  case TST_Float16:
895
154
  case TST_float128:
896
154
  case TST_bool:
897
154
  case TST_decimal32:
898
154
  case TST_decimal64:
899
154
  case TST_decimal128:
900
154
  case TST_enum:
901
154
  case TST_union:
902
154
  case TST_struct:
903
154
  case TST_interface:
904
154
  case TST_class:
905
169
  case TST_auto:
906
169
  case TST_auto_type:
907
169
  case TST_decltype_auto:
908
169
  case TST_BFloat16:
909
2.02k
#define GENERIC_IMAGE_TYPE(ImgType, Id) case TST_##ImgType##_t:
910
2.02k
#include 
"clang/Basic/OpenCLImageTypes.def"169
911
169
  case TST_unknown_anytype:
912
172
  case TST_error:
913
172
    break;
914
179
  }
915
916
205
  
for (unsigned I = 0, N = D.getNumTypeObjects(); 179
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
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
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
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
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
966
179
  if (Expr *TRC = D.getTrailingRequiresClause())
967
0
    if (TRC->containsUnexpandedParameterPack())
968
0
      return true;
969
970
179
  return false;
971
179
}
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
46.1k
                                              SourceLocation RParenLoc) {
1009
  // C++0x [expr.sizeof]p5:
1010
  //   The identifier in a sizeof... expression shall name a parameter pack.
1011
46.1k
  LookupResult R(*this, &Name, NameLoc, LookupOrdinaryName);
1012
46.1k
  LookupName(R, S);
1013
1014
46.1k
  NamedDecl *ParameterPack = nullptr;
1015
46.1k
  switch (R.getResultKind()) {
1016
46.1k
  case LookupResult::Found:
1017
46.1k
    ParameterPack = R.getFoundDecl();
1018
46.1k
    break;
1019
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
1037
0
  case LookupResult::Ambiguous:
1038
0
    DiagnoseAmbiguousLookup(R);
1039
0
    return ExprError();
1040
46.1k
  }
1041
1042
46.1k
  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
1048
46.1k
  MarkAnyDeclReferenced(OpLoc, ParameterPack, true);
1049
1050
46.1k
  return SizeOfPackExpr::Create(Context, OpLoc, ParameterPack, NameLoc,
1051
46.1k
                                RParenLoc);
1052
46.1k
}
1053
1054
TemplateArgumentLoc
1055
Sema::getTemplateArgumentPackExpansionPattern(
1056
      TemplateArgumentLoc OrigLoc,
1057
213k
      SourceLocation &Ellipsis, Optional<unsigned> &NumExpansions) const {
1058
213k
  const TemplateArgument &Argument = OrigLoc.getArgument();
1059
213k
  assert(Argument.isPackExpansion());
1060
213k
  switch (Argument.getKind()) {
1061
168k
  case TemplateArgument::Type: {
1062
    // FIXME: We shouldn't ever have to worry about missing
1063
    // type-source info!
1064
168k
    TypeSourceInfo *ExpansionTSInfo = OrigLoc.getTypeSourceInfo();
1065
168k
    if (!ExpansionTSInfo)
1066
0
      ExpansionTSInfo = Context.getTrivialTypeSourceInfo(Argument.getAsType(),
1067
0
                                                         Ellipsis);
1068
168k
    PackExpansionTypeLoc Expansion =
1069
168k
        ExpansionTSInfo->getTypeLoc().castAs<PackExpansionTypeLoc>();
1070
168k
    Ellipsis = Expansion.getEllipsisLoc();
1071
1072
168k
    TypeLoc Pattern = Expansion.getPatternLoc();
1073
168k
    NumExpansions = Expansion.getTypePtr()->getNumExpansions();
1074
1075
    // We need to copy the TypeLoc because TemplateArgumentLocs store a
1076
    // TypeSourceInfo.
1077
    // FIXME: Find some way to avoid the copy?
1078
168k
    TypeLocBuilder TLB;
1079
168k
    TLB.pushFullCopy(Pattern);
1080
168k
    TypeSourceInfo *PatternTSInfo =
1081
168k
        TLB.getTypeSourceInfo(Context, Pattern.getType());
1082
168k
    return TemplateArgumentLoc(TemplateArgument(Pattern.getType()),
1083
168k
                               PatternTSInfo);
1084
0
  }
1085
1086
44.6k
  case TemplateArgument::Expression: {
1087
44.6k
    PackExpansionExpr *Expansion
1088
44.6k
      = cast<PackExpansionExpr>(Argument.getAsExpr());
1089
44.6k
    Expr *Pattern = Expansion->getPattern();
1090
44.6k
    Ellipsis = Expansion->getEllipsisLoc();
1091
44.6k
    NumExpansions = Expansion->getNumExpansions();
1092
44.6k
    return TemplateArgumentLoc(Pattern, Pattern);
1093
0
  }
1094
1095
35
  case TemplateArgument::TemplateExpansion:
1096
35
    Ellipsis = OrigLoc.getTemplateEllipsisLoc();
1097
35
    NumExpansions = Argument.getNumTemplateExpansions();
1098
35
    return TemplateArgumentLoc(Context, Argument.getPackExpansionPattern(),
1099
35
                               OrigLoc.getTemplateQualifierLoc(),
1100
35
                               OrigLoc.getTemplateNameLoc());
1101
1102
0
  case TemplateArgument::Declaration:
1103
0
  case TemplateArgument::NullPtr:
1104
0
  case TemplateArgument::Template:
1105
0
  case TemplateArgument::Integral:
1106
0
  case TemplateArgument::UncommonValue:
1107
0
  case TemplateArgument::Pack:
1108
0
  case TemplateArgument::Null:
1109
0
    return TemplateArgumentLoc();
1110
0
  }
1111
1112
0
  llvm_unreachable("Invalid TemplateArgument Kind!");
1113
0
}
1114
1115
49.0k
Optional<unsigned> Sema::getFullyPackExpandedSize(TemplateArgument Arg) {
1116
49.0k
  assert(Arg.containsUnexpandedParameterPack());
1117
1118
  // If this is a substituted pack, grab that pack. If not, we don't know
1119
  // the size yet.
1120
  // FIXME: We could find a size in more cases by looking for a substituted
1121
  // pack anywhere within this argument, but that's not necessary in the common
1122
  // case for 'sizeof...(A)' handling.
1123
49.0k
  TemplateArgument Pack;
1124
49.0k
  switch (Arg.getKind()) {
1125
48.8k
  case TemplateArgument::Type:
1126
48.8k
    if (auto *Subst = Arg.getAsType()->getAs<SubstTemplateTypeParmPackType>())
1127
48.8k
      Pack = Subst->getArgumentPack();
1128
36
    else
1129
36
      return None;
1130
48.8k
    break;
1131
1132
174
  case TemplateArgument::Expression:
1133
174
    if (auto *Subst =
1134
27
            dyn_cast<SubstNonTypeTemplateParmPackExpr>(Arg.getAsExpr()))
1135
27
      Pack = Subst->getArgumentPack();
1136
147
    else if (auto *Subst = dyn_cast<FunctionParmPackExpr>(Arg.getAsExpr()))  {
1137
147
      for (VarDecl *PD : *Subst)
1138
871
        if (PD->isParameterPack())
1139
1
          return None;
1140
146
      return Subst->getNumExpansions();
1141
0
    } else
1142
0
      return None;
1143
27
    break;
1144
1145
4
  case TemplateArgument::Template:
1146
4
    if (SubstTemplateTemplateParmPackStorage *Subst =
1147
4
            Arg.getAsTemplate().getAsSubstTemplateTemplateParmPack())
1148
4
      Pack = Subst->getArgumentPack();
1149
0
    else
1150
0
      return None;
1151
4
    break;
1152
1153
0
  case TemplateArgument::Declaration:
1154
0
  case TemplateArgument::NullPtr:
1155
0
  case TemplateArgument::TemplateExpansion:
1156
0
  case TemplateArgument::Integral:
1157
0
  case TemplateArgument::UncommonValue:
1158
0
  case TemplateArgument::Pack:
1159
0
  case TemplateArgument::Null:
1160
0
    return None;
1161
48.8k
  }
1162
1163
  // Check that no argument in the pack is itself a pack expansion.
1164
108k
  
for (TemplateArgument Elem : Pack.pack_elements())48.8k
{
1165
    // There's no point recursing in this case; we would have already
1166
    // expanded this pack expansion into the enclosing pack if we could.
1167
108k
    if (Elem.isPackExpansion())
1168
42
      return None;
1169
108k
  }
1170
48.8k
  return Pack.pack_size();
1171
48.8k
}
1172
1173
376
static void CheckFoldOperand(Sema &S, Expr *E) {
1174
376
  if (!E)
1175
140
    return;
1176
1177
236
  E = E->IgnoreImpCasts();
1178
236
  auto *OCE = dyn_cast<CXXOperatorCallExpr>(E);
1179
236
  if ((OCE && 
OCE->isInfixBinaryOp()5
) ||
isa<BinaryOperator>(E)233
||
1180
230
      isa<AbstractConditionalOperator>(E)) {
1181
6
    S.Diag(E->getExprLoc(), diag::err_fold_expression_bad_operand)
1182
6
        << E->getSourceRange()
1183
6
        << FixItHint::CreateInsertion(E->getBeginLoc(), "(")
1184
6
        << FixItHint::CreateInsertion(E->getEndLoc(), ")");
1185
6
  }
1186
236
}
1187
1188
ExprResult Sema::ActOnCXXFoldExpr(Scope *S, SourceLocation LParenLoc, Expr *LHS,
1189
                                  tok::TokenKind Operator,
1190
                                  SourceLocation EllipsisLoc, Expr *RHS,
1191
188
                                  SourceLocation RParenLoc) {
1192
  // LHS and RHS must be cast-expressions. We allow an arbitrary expression
1193
  // in the parser and reduce down to just cast-expressions here.
1194
188
  CheckFoldOperand(*this, LHS);
1195
188
  CheckFoldOperand(*this, RHS);
1196
1197
143
  auto DiscardOperands = [&] {
1198
143
    CorrectDelayedTyposInExpr(LHS);
1199
143
    CorrectDelayedTyposInExpr(RHS);
1200
143
  };
1201
1202
  // [expr.prim.fold]p3:
1203
  //   In a binary fold, op1 and op2 shall be the same fold-operator, and
1204
  //   either e1 shall contain an unexpanded parameter pack or e2 shall contain
1205
  //   an unexpanded parameter pack, but not both.
1206
188
  if (LHS && 
RHS176
&&
1207
48
      LHS->containsUnexpandedParameterPack() ==
1208
3
          RHS->containsUnexpandedParameterPack()) {
1209
3
    DiscardOperands();
1210
3
    return Diag(EllipsisLoc,
1211
3
                LHS->containsUnexpandedParameterPack()
1212
1
                    ? diag::err_fold_expression_packs_both_sides
1213
2
                    : diag::err_pack_expansion_without_parameter_packs)
1214
3
        << LHS->getSourceRange() << RHS->getSourceRange();
1215
3
  }
1216
1217
  // [expr.prim.fold]p2:
1218
  //   In a unary fold, the cast-expression shall contain an unexpanded
1219
  //   parameter pack.
1220
185
  if (!LHS || 
!RHS173
) {
1221
128
    Expr *Pack = LHS ? LHS : 
RHS12
;
1222
140
    assert(Pack && "fold expression with neither LHS nor RHS");
1223
140
    DiscardOperands();
1224
140
    if (!Pack->containsUnexpandedParameterPack())
1225
29
      return Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1226
29
             << Pack->getSourceRange();
1227
156
  }
1228
1229
156
  BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Operator);
1230
1231
  // Perform first-phase name lookup now.
1232
156
  UnresolvedLookupExpr *ULE = nullptr;
1233
156
  {
1234
156
    UnresolvedSet<16> Functions;
1235
156
    LookupBinOp(S, EllipsisLoc, Opc, Functions);
1236
156
    if (!Functions.empty()) {
1237
9
      DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(
1238
9
          BinaryOperator::getOverloadedOperator(Opc));
1239
9
      ExprResult Callee = CreateUnresolvedLookupExpr(
1240
9
          /*NamingClass*/ nullptr, NestedNameSpecifierLoc(),
1241
9
          DeclarationNameInfo(OpName, EllipsisLoc), Functions);
1242
9
      if (Callee.isInvalid())
1243
0
        return ExprError();
1244
9
      ULE = cast<UnresolvedLookupExpr>(Callee.get());
1245
9
    }
1246
156
  }
1247
1248
156
  return BuildCXXFoldExpr(ULE, LParenLoc, LHS, Opc, EllipsisLoc, RHS, RParenLoc,
1249
156
                          None);
1250
156
}
1251
1252
ExprResult Sema::BuildCXXFoldExpr(UnresolvedLookupExpr *Callee,
1253
                                  SourceLocation LParenLoc, Expr *LHS,
1254
                                  BinaryOperatorKind Operator,
1255
                                  SourceLocation EllipsisLoc, Expr *RHS,
1256
                                  SourceLocation RParenLoc,
1257
229
                                  Optional<unsigned> NumExpansions) {
1258
229
  return new (Context)
1259
229
      CXXFoldExpr(Context.DependentTy, Callee, LParenLoc, LHS, Operator,
1260
229
                  EllipsisLoc, RHS, RParenLoc, NumExpansions);
1261
229
}
1262
1263
ExprResult Sema::BuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc,
1264
33
                                       BinaryOperatorKind Operator) {
1265
  // [temp.variadic]p9:
1266
  //   If N is zero for a unary fold-expression, the value of the expression is
1267
  //       &&  ->  true
1268
  //       ||  ->  false
1269
  //       ,   ->  void()
1270
  //   if the operator is not listed [above], the instantiation is ill-formed.
1271
  //
1272
  // Note that we need to use something like int() here, not merely 0, to
1273
  // prevent the result from being a null pointer constant.
1274
33
  QualType ScalarType;
1275
33
  switch (Operator) {
1276
4
  case BO_LOr:
1277
4
    return ActOnCXXBoolLiteral(EllipsisLoc, tok::kw_false);
1278
6
  case BO_LAnd:
1279
6
    return ActOnCXXBoolLiteral(EllipsisLoc, tok::kw_true);
1280
7
  case BO_Comma:
1281
7
    ScalarType = Context.VoidTy;
1282
7
    break;
1283
1284
16
  default:
1285
16
    return Diag(EllipsisLoc, diag::err_fold_expression_empty)
1286
16
        << BinaryOperator::getOpcodeStr(Operator);
1287
7
  }
1288
1289
7
  return new (Context) CXXScalarValueInitExpr(
1290
7
      ScalarType, Context.getTrivialTypeSourceInfo(ScalarType, EllipsisLoc),
1291
7
      EllipsisLoc);
1292
7
}