Coverage Report

Created: 2020-02-25 14:32

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