Bug Summary

File:tools/clang/lib/Sema/SemaTemplateVariadic.cpp
Warning:line 669, column 11
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

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