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