xref: /aosp_15_r20/external/skia/src/sksl/SkSLAnalysis.cpp (revision c8dee2aa9b3f27cf6c858bd81872bdeb2c07ed17)
1 /*
2  * Copyright 2020 Google LLC.
3  *
4  * Use of this source code is governed by a BSD-style license that can be
5  * found in the LICENSE file.
6  */
7 
8 #include "src/sksl/SkSLAnalysis.h"
9 
10 #include "include/core/SkSpan.h"
11 #include "include/core/SkTypes.h"
12 #include "include/private/SkSLSampleUsage.h"
13 #include "include/private/base/SkTArray.h"
14 #include "src/base/SkEnumBitMask.h"
15 #include "src/core/SkTHash.h"
16 #include "src/sksl/SkSLBuiltinTypes.h"
17 #include "src/sksl/SkSLCompiler.h"
18 #include "src/sksl/SkSLConstantFolder.h"
19 #include "src/sksl/SkSLContext.h"
20 #include "src/sksl/SkSLDefines.h"
21 #include "src/sksl/SkSLErrorReporter.h"
22 #include "src/sksl/SkSLIntrinsicList.h"
23 #include "src/sksl/SkSLOperator.h"
24 #include "src/sksl/analysis/SkSLNoOpErrorReporter.h"
25 #include "src/sksl/analysis/SkSLProgramUsage.h"
26 #include "src/sksl/analysis/SkSLProgramVisitor.h"
27 #include "src/sksl/ir/SkSLBinaryExpression.h"
28 #include "src/sksl/ir/SkSLBlock.h"
29 #include "src/sksl/ir/SkSLChildCall.h"
30 #include "src/sksl/ir/SkSLConstructor.h"
31 #include "src/sksl/ir/SkSLDoStatement.h"
32 #include "src/sksl/ir/SkSLExpression.h"
33 #include "src/sksl/ir/SkSLExpressionStatement.h"
34 #include "src/sksl/ir/SkSLFieldAccess.h"
35 #include "src/sksl/ir/SkSLForStatement.h"
36 #include "src/sksl/ir/SkSLFunctionCall.h"
37 #include "src/sksl/ir/SkSLFunctionDeclaration.h"
38 #include "src/sksl/ir/SkSLFunctionDefinition.h"
39 #include "src/sksl/ir/SkSLIRNode.h"
40 #include "src/sksl/ir/SkSLIfStatement.h"
41 #include "src/sksl/ir/SkSLIndexExpression.h"
42 #include "src/sksl/ir/SkSLLayout.h"
43 #include "src/sksl/ir/SkSLModifierFlags.h"
44 #include "src/sksl/ir/SkSLPostfixExpression.h"
45 #include "src/sksl/ir/SkSLPrefixExpression.h"
46 #include "src/sksl/ir/SkSLProgram.h"
47 #include "src/sksl/ir/SkSLProgramElement.h"
48 #include "src/sksl/ir/SkSLReturnStatement.h"
49 #include "src/sksl/ir/SkSLStatement.h"
50 #include "src/sksl/ir/SkSLSwitchCase.h"
51 #include "src/sksl/ir/SkSLSwitchStatement.h"
52 #include "src/sksl/ir/SkSLSwizzle.h"
53 #include "src/sksl/ir/SkSLSymbol.h"
54 #include "src/sksl/ir/SkSLTernaryExpression.h"
55 #include "src/sksl/ir/SkSLType.h"
56 #include "src/sksl/ir/SkSLVarDeclarations.h"
57 #include "src/sksl/ir/SkSLVariable.h"
58 #include "src/sksl/ir/SkSLVariableReference.h"
59 #include "src/sksl/transform/SkSLProgramWriter.h"
60 
61 #include <optional>
62 #include <string>
63 #include <string_view>
64 
65 namespace SkSL {
66 
67 namespace {
68 
69 // Visitor that determines the merged SampleUsage for a given child in the program.
70 class MergeSampleUsageVisitor : public ProgramVisitor {
71 public:
MergeSampleUsageVisitor(const Context & context,const Variable & child,bool writesToSampleCoords)72     MergeSampleUsageVisitor(const Context& context,
73                             const Variable& child,
74                             bool writesToSampleCoords)
75             : fContext(context), fChild(child), fWritesToSampleCoords(writesToSampleCoords) {}
76 
visit(const Program & program)77     SampleUsage visit(const Program& program) {
78         fUsage = SampleUsage(); // reset to none
79         INHERITED::visit(program);
80         return fUsage;
81     }
82 
elidedSampleCoordCount() const83     int elidedSampleCoordCount() const { return fElidedSampleCoordCount; }
84 
85 protected:
86     const Context& fContext;
87     const Variable& fChild;
88     const Variable* fMainCoordsParam = nullptr;
89     const bool fWritesToSampleCoords;
90     SampleUsage fUsage;
91     int fElidedSampleCoordCount = 0;
92 
visitProgramElement(const ProgramElement & pe)93     bool visitProgramElement(const ProgramElement& pe) override {
94         fMainCoordsParam = pe.is<FunctionDefinition>()
95                                ? pe.as<FunctionDefinition>().declaration().getMainCoordsParameter()
96                                : nullptr;
97         return INHERITED::visitProgramElement(pe);
98     }
99 
visitExpression(const Expression & e)100     bool visitExpression(const Expression& e) override {
101         switch (e.kind()) {
102             case ExpressionKind::kChildCall: {
103                 const ChildCall& cc = e.as<ChildCall>();
104                 if (&cc.child() == &fChild) {
105                     // Determine the type of call at this site, and merge it with the accumulated
106                     // state
107                     const ExpressionArray& arguments = cc.arguments();
108                     SkASSERT(!arguments.empty());
109 
110                     const Expression* maybeCoords = arguments[0].get();
111                     if (maybeCoords->type().matches(*fContext.fTypes.fFloat2)) {
112                         // If the coords are a direct reference to the program's sample-coords, and
113                         // those coords are never modified, we can conservatively turn this into
114                         // PassThrough sampling. In all other cases, we consider it Explicit.
115                         if (!fWritesToSampleCoords && maybeCoords->is<VariableReference>() &&
116                             maybeCoords->as<VariableReference>().variable() == fMainCoordsParam) {
117                             fUsage.merge(SampleUsage::PassThrough());
118                             ++fElidedSampleCoordCount;
119                         } else {
120                             fUsage.merge(SampleUsage::Explicit());
121                         }
122                     } else {
123                         // child(inputColor) or child(srcColor, dstColor) -> PassThrough
124                         fUsage.merge(SampleUsage::PassThrough());
125                     }
126                 }
127                 break;
128             }
129             case ExpressionKind::kFunctionCall: {
130                 // If this child effect is ever passed via a function call...
131                 const FunctionCall& call = e.as<FunctionCall>();
132                 for (const std::unique_ptr<Expression>& arg : call.arguments()) {
133                     if (arg->is<VariableReference>() &&
134                         arg->as<VariableReference>().variable() == &fChild) {
135                         // ... we must treat it as explicitly sampled, since the program's
136                         // sample-coords only exist as a parameter to `main`.
137                         fUsage.merge(SampleUsage::Explicit());
138                         break;
139                     }
140                 }
141                 break;
142             }
143             default:
144                 break;
145         }
146         return INHERITED::visitExpression(e);
147     }
148 
149     using INHERITED = ProgramVisitor;
150 };
151 
152 // Visitor that searches for child calls from a function other than main()
153 class SampleOutsideMainVisitor : public ProgramVisitor {
154 public:
SampleOutsideMainVisitor()155     SampleOutsideMainVisitor() {}
156 
visitExpression(const Expression & e)157     bool visitExpression(const Expression& e) override {
158         if (e.is<ChildCall>()) {
159             return true;
160         }
161         return INHERITED::visitExpression(e);
162     }
163 
visitProgramElement(const ProgramElement & p)164     bool visitProgramElement(const ProgramElement& p) override {
165         return p.is<FunctionDefinition>() &&
166                !p.as<FunctionDefinition>().declaration().isMain() &&
167                INHERITED::visitProgramElement(p);
168     }
169 
170     using INHERITED = ProgramVisitor;
171 };
172 
173 class ReturnsNonOpaqueColorVisitor : public ProgramVisitor {
174 public:
ReturnsNonOpaqueColorVisitor()175     ReturnsNonOpaqueColorVisitor() {}
176 
visitStatement(const Statement & s)177     bool visitStatement(const Statement& s) override {
178         if (s.is<ReturnStatement>()) {
179             const Expression* e = s.as<ReturnStatement>().expression().get();
180             bool knownOpaque = e && e->type().slotCount() == 4 &&
181                                ConstantFolder::GetConstantValueForVariable(*e)
182                                                ->getConstantValue(/*n=*/3)
183                                                .value_or(0) == 1;
184             return !knownOpaque;
185         }
186         return INHERITED::visitStatement(s);
187     }
188 
visitExpression(const Expression & e)189     bool visitExpression(const Expression& e) override {
190         // No need to recurse into expressions, these can never contain return statements
191         return false;
192     }
193 
194     using INHERITED = ProgramVisitor;
195     using INHERITED::visitProgramElement;
196 };
197 
198 // Visitor that counts the number of nodes visited
199 class NodeCountVisitor : public ProgramVisitor {
200 public:
NodeCountVisitor(int limit)201     NodeCountVisitor(int limit) : fLimit(limit) {}
202 
visit(const Statement & s)203     int visit(const Statement& s) {
204         this->visitStatement(s);
205         return fCount;
206     }
207 
visitExpression(const Expression & e)208     bool visitExpression(const Expression& e) override {
209         ++fCount;
210         return (fCount >= fLimit) || INHERITED::visitExpression(e);
211     }
212 
visitProgramElement(const ProgramElement & p)213     bool visitProgramElement(const ProgramElement& p) override {
214         ++fCount;
215         return (fCount >= fLimit) || INHERITED::visitProgramElement(p);
216     }
217 
visitStatement(const Statement & s)218     bool visitStatement(const Statement& s) override {
219         ++fCount;
220         return (fCount >= fLimit) || INHERITED::visitStatement(s);
221     }
222 
223 private:
224     int fCount = 0;
225     int fLimit;
226 
227     using INHERITED = ProgramVisitor;
228 };
229 
230 class VariableWriteVisitor : public ProgramVisitor {
231 public:
VariableWriteVisitor(const Variable * var)232     VariableWriteVisitor(const Variable* var)
233         : fVar(var) {}
234 
visit(const Statement & s)235     bool visit(const Statement& s) {
236         return this->visitStatement(s);
237     }
238 
visitExpression(const Expression & e)239     bool visitExpression(const Expression& e) override {
240         if (e.is<VariableReference>()) {
241             const VariableReference& ref = e.as<VariableReference>();
242             if (ref.variable() == fVar &&
243                 (ref.refKind() == VariableReference::RefKind::kWrite ||
244                  ref.refKind() == VariableReference::RefKind::kReadWrite ||
245                  ref.refKind() == VariableReference::RefKind::kPointer)) {
246                 return true;
247             }
248         }
249         return INHERITED::visitExpression(e);
250     }
251 
252 private:
253     const Variable* fVar;
254 
255     using INHERITED = ProgramVisitor;
256 };
257 
258 // This isn't actually using ProgramVisitor, because it only considers a subset of the fields for
259 // any given expression kind. For instance, when indexing an array (e.g. `x[1]`), we only want to
260 // know if the base (`x`) is assignable; the index expression (`1`) doesn't need to be.
261 class IsAssignableVisitor {
262 public:
IsAssignableVisitor(ErrorReporter * errors)263     IsAssignableVisitor(ErrorReporter* errors) : fErrors(errors) {}
264 
visit(Expression & expr,Analysis::AssignmentInfo * info)265     bool visit(Expression& expr, Analysis::AssignmentInfo* info) {
266         int oldErrorCount = fErrors->errorCount();
267         this->visitExpression(expr);
268         if (info) {
269             info->fAssignedVar = fAssignedVar;
270         }
271         return fErrors->errorCount() == oldErrorCount;
272     }
273 
visitExpression(Expression & expr,const FieldAccess * fieldAccess=nullptr)274     void visitExpression(Expression& expr, const FieldAccess* fieldAccess = nullptr) {
275         switch (expr.kind()) {
276             case Expression::Kind::kVariableReference: {
277                 VariableReference& varRef = expr.as<VariableReference>();
278                 const Variable* var = varRef.variable();
279                 auto fieldName = [&] {
280                     return fieldAccess ? fieldAccess->description(OperatorPrecedence::kExpression)
281                                        : std::string(var->name());
282                 };
283                 if (var->modifierFlags().isConst() || var->modifierFlags().isUniform()) {
284                     fErrors->error(expr.fPosition,
285                                    "cannot modify immutable variable '" + fieldName() + "'");
286                 } else if (var->storage() == Variable::Storage::kGlobal &&
287                            (var->modifierFlags() & ModifierFlag::kIn)) {
288                     fErrors->error(expr.fPosition,
289                                    "cannot modify pipeline input variable '" + fieldName() + "'");
290                 } else {
291                     SkASSERT(fAssignedVar == nullptr);
292                     fAssignedVar = &varRef;
293                 }
294                 break;
295             }
296             case Expression::Kind::kFieldAccess: {
297                 const FieldAccess& f = expr.as<FieldAccess>();
298                 this->visitExpression(*f.base(), &f);
299                 break;
300             }
301             case Expression::Kind::kSwizzle: {
302                 const Swizzle& swizzle = expr.as<Swizzle>();
303                 this->checkSwizzleWrite(swizzle);
304                 this->visitExpression(*swizzle.base(), fieldAccess);
305                 break;
306             }
307             case Expression::Kind::kIndex:
308                 this->visitExpression(*expr.as<IndexExpression>().base(), fieldAccess);
309                 break;
310 
311             case Expression::Kind::kPoison:
312                 break;
313 
314             default:
315                 fErrors->error(expr.fPosition, "cannot assign to this expression");
316                 break;
317         }
318     }
319 
320 private:
checkSwizzleWrite(const Swizzle & swizzle)321     void checkSwizzleWrite(const Swizzle& swizzle) {
322         int bits = 0;
323         for (int8_t idx : swizzle.components()) {
324             SkASSERT(idx >= SwizzleComponent::X && idx <= SwizzleComponent::W);
325             int bit = 1 << idx;
326             if (bits & bit) {
327                 fErrors->error(swizzle.fPosition,
328                                "cannot write to the same swizzle field more than once");
329                 break;
330             }
331             bits |= bit;
332         }
333     }
334 
335     ErrorReporter* fErrors;
336     VariableReference* fAssignedVar = nullptr;
337 
338     using INHERITED = ProgramVisitor;
339 };
340 
341 }  // namespace
342 
343 ////////////////////////////////////////////////////////////////////////////////
344 // Analysis
345 
GetSampleUsage(const Program & program,const Variable & child,bool writesToSampleCoords,int * elidedSampleCoordCount)346 SampleUsage Analysis::GetSampleUsage(const Program& program,
347                                      const Variable& child,
348                                      bool writesToSampleCoords,
349                                      int* elidedSampleCoordCount) {
350     MergeSampleUsageVisitor visitor(*program.fContext, child, writesToSampleCoords);
351     SampleUsage result = visitor.visit(program);
352     if (elidedSampleCoordCount) {
353         *elidedSampleCoordCount += visitor.elidedSampleCoordCount();
354     }
355     return result;
356 }
357 
ReferencesBuiltin(const Program & program,int builtin)358 bool Analysis::ReferencesBuiltin(const Program& program, int builtin) {
359     SkASSERT(program.fUsage);
360     for (const auto& [variable, counts] : program.fUsage->fVariableCounts) {
361         if (counts.fRead > 0 && variable->layout().fBuiltin == builtin) {
362             return true;
363         }
364     }
365     return false;
366 }
367 
ReferencesSampleCoords(const Program & program)368 bool Analysis::ReferencesSampleCoords(const Program& program) {
369     // Look for main().
370     for (const std::unique_ptr<ProgramElement>& pe : program.fOwnedElements) {
371         if (pe->is<FunctionDefinition>()) {
372             const FunctionDeclaration& func = pe->as<FunctionDefinition>().declaration();
373             if (func.isMain()) {
374                 // See if main() has a coords parameter that is read from anywhere.
375                 if (const Variable* coords = func.getMainCoordsParameter()) {
376                     ProgramUsage::VariableCounts counts = program.fUsage->get(*coords);
377                     return counts.fRead > 0;
378                 }
379             }
380         }
381     }
382     // The program is missing a main().
383     return false;
384 }
385 
ReferencesFragCoords(const Program & program)386 bool Analysis::ReferencesFragCoords(const Program& program) {
387     return Analysis::ReferencesBuiltin(program, SK_FRAGCOORD_BUILTIN);
388 }
389 
CallsSampleOutsideMain(const Program & program)390 bool Analysis::CallsSampleOutsideMain(const Program& program) {
391     SampleOutsideMainVisitor visitor;
392     return visitor.visit(program);
393 }
394 
CallsColorTransformIntrinsics(const Program & program)395 bool Analysis::CallsColorTransformIntrinsics(const Program& program) {
396     for (auto [symbol, count] : program.usage()->fCallCounts) {
397         const FunctionDeclaration& fn = symbol->as<FunctionDeclaration>();
398         if (count != 0 && (fn.intrinsicKind() == k_toLinearSrgb_IntrinsicKind ||
399                            fn.intrinsicKind() == k_fromLinearSrgb_IntrinsicKind)) {
400             return true;
401         }
402     }
403     return false;
404 }
405 
ReturnsOpaqueColor(const FunctionDefinition & function)406 bool Analysis::ReturnsOpaqueColor(const FunctionDefinition& function) {
407     ReturnsNonOpaqueColorVisitor visitor;
408     return !visitor.visitProgramElement(function);
409 }
410 
ContainsRTAdjust(const Expression & expr)411 bool Analysis::ContainsRTAdjust(const Expression& expr) {
412     class ContainsRTAdjustVisitor : public ProgramVisitor {
413     public:
414         bool visitExpression(const Expression& expr) override {
415             if (expr.is<VariableReference>() &&
416                 expr.as<VariableReference>().variable()->name() == Compiler::RTADJUST_NAME) {
417                 return true;
418             }
419             return INHERITED::visitExpression(expr);
420         }
421 
422         using INHERITED = ProgramVisitor;
423     };
424 
425     ContainsRTAdjustVisitor visitor;
426     return visitor.visitExpression(expr);
427 }
428 
ContainsVariable(const Expression & expr,const Variable & var)429 bool Analysis::ContainsVariable(const Expression& expr, const Variable& var) {
430     class ContainsVariableVisitor : public ProgramVisitor {
431     public:
432         ContainsVariableVisitor(const Variable* v) : fVariable(v) {}
433 
434         bool visitExpression(const Expression& expr) override {
435             if (expr.is<VariableReference>() &&
436                 expr.as<VariableReference>().variable() == fVariable) {
437                 return true;
438             }
439             return INHERITED::visitExpression(expr);
440         }
441 
442         using INHERITED = ProgramVisitor;
443         const Variable* fVariable;
444     };
445 
446     ContainsVariableVisitor visitor{&var};
447     return visitor.visitExpression(expr);
448 }
449 
IsCompileTimeConstant(const Expression & expr)450 bool Analysis::IsCompileTimeConstant(const Expression& expr) {
451     class IsCompileTimeConstantVisitor : public ProgramVisitor {
452     public:
453         bool visitExpression(const Expression& expr) override {
454             switch (expr.kind()) {
455                 case Expression::Kind::kLiteral:
456                     // Literals are compile-time constants.
457                     return false;
458 
459                 case Expression::Kind::kConstructorArray:
460                 case Expression::Kind::kConstructorCompound:
461                 case Expression::Kind::kConstructorDiagonalMatrix:
462                 case Expression::Kind::kConstructorMatrixResize:
463                 case Expression::Kind::kConstructorSplat:
464                 case Expression::Kind::kConstructorStruct:
465                     // Constructors might be compile-time constants, if they are composed entirely
466                     // of literals and constructors. (Casting constructors are intentionally omitted
467                     // here. If the value inside was a compile-time constant, we would have not have
468                     // generated a cast at all.)
469                     return INHERITED::visitExpression(expr);
470 
471                 default:
472                     // This expression isn't a compile-time constant.
473                     fIsConstant = false;
474                     return true;
475             }
476         }
477 
478         bool fIsConstant = true;
479         using INHERITED = ProgramVisitor;
480     };
481 
482     IsCompileTimeConstantVisitor visitor;
483     visitor.visitExpression(expr);
484     return visitor.fIsConstant;
485 }
486 
DetectVarDeclarationWithoutScope(const Statement & stmt,ErrorReporter * errors)487 bool Analysis::DetectVarDeclarationWithoutScope(const Statement& stmt, ErrorReporter* errors) {
488     // A variable declaration can create either a lone VarDeclaration or an unscoped Block
489     // containing multiple VarDeclaration statements. We need to detect either case.
490     const Variable* var;
491     if (stmt.is<VarDeclaration>()) {
492         // The single-variable case. No blocks at all.
493         var = stmt.as<VarDeclaration>().var();
494     } else if (stmt.is<Block>()) {
495         // The multiple-variable case: an unscoped, non-empty block...
496         const Block& block = stmt.as<Block>();
497         if (block.isScope() || block.children().empty()) {
498             return false;
499         }
500         // ... holding a variable declaration.
501         const Statement& innerStmt = *block.children().front();
502         if (!innerStmt.is<VarDeclaration>()) {
503             return false;
504         }
505         var = innerStmt.as<VarDeclaration>().var();
506     } else {
507         // This statement wasn't a variable declaration. No problem.
508         return false;
509     }
510 
511     // Report an error.
512     SkASSERT(var);
513     if (errors) {
514         errors->error(var->fPosition,
515                       "variable '" + std::string(var->name()) + "' must be created in a scope");
516     }
517     return true;
518 }
519 
NodeCountUpToLimit(const FunctionDefinition & function,int limit)520 int Analysis::NodeCountUpToLimit(const FunctionDefinition& function, int limit) {
521     return NodeCountVisitor{limit}.visit(*function.body());
522 }
523 
StatementWritesToVariable(const Statement & stmt,const Variable & var)524 bool Analysis::StatementWritesToVariable(const Statement& stmt, const Variable& var) {
525     return VariableWriteVisitor(&var).visit(stmt);
526 }
527 
IsAssignable(Expression & expr,AssignmentInfo * info,ErrorReporter * errors)528 bool Analysis::IsAssignable(Expression& expr, AssignmentInfo* info, ErrorReporter* errors) {
529     NoOpErrorReporter unusedErrors;
530     return IsAssignableVisitor{errors ? errors : &unusedErrors}.visit(expr, info);
531 }
532 
UpdateVariableRefKind(Expression * expr,VariableReference::RefKind kind,ErrorReporter * errors)533 bool Analysis::UpdateVariableRefKind(Expression* expr,
534                                      VariableReference::RefKind kind,
535                                      ErrorReporter* errors) {
536     Analysis::AssignmentInfo info;
537     if (!Analysis::IsAssignable(*expr, &info, errors)) {
538         return false;
539     }
540     if (!info.fAssignedVar) {
541         if (errors) {
542             errors->error(expr->fPosition, "can't assign to expression '" + expr->description() +
543                     "'");
544         }
545         return false;
546     }
547     info.fAssignedVar->setRefKind(kind);
548     return true;
549 }
550 
551 ////////////////////////////////////////////////////////////////////////////////
552 // ProgramVisitor
553 
visit(const Program & program)554 bool ProgramVisitor::visit(const Program& program) {
555     for (const ProgramElement* pe : program.elements()) {
556         if (this->visitProgramElement(*pe)) {
557             return true;
558         }
559     }
560     return false;
561 }
562 
visitExpression(typename T::Expression & e)563 template <typename T> bool TProgramVisitor<T>::visitExpression(typename T::Expression& e) {
564     switch (e.kind()) {
565         case Expression::Kind::kEmpty:
566         case Expression::Kind::kFunctionReference:
567         case Expression::Kind::kLiteral:
568         case Expression::Kind::kMethodReference:
569         case Expression::Kind::kPoison:
570         case Expression::Kind::kSetting:
571         case Expression::Kind::kTypeReference:
572         case Expression::Kind::kVariableReference:
573             // Leaf expressions return false
574             return false;
575 
576         case Expression::Kind::kBinary: {
577             auto& b = e.template as<BinaryExpression>();
578             return (b.left() && this->visitExpressionPtr(b.left())) ||
579                    (b.right() && this->visitExpressionPtr(b.right()));
580         }
581         case Expression::Kind::kChildCall: {
582             // We don't visit the child variable itself, just the arguments
583             auto& c = e.template as<ChildCall>();
584             for (auto& arg : c.arguments()) {
585                 if (arg && this->visitExpressionPtr(arg)) { return true; }
586             }
587             return false;
588         }
589         case Expression::Kind::kConstructorArray:
590         case Expression::Kind::kConstructorArrayCast:
591         case Expression::Kind::kConstructorCompound:
592         case Expression::Kind::kConstructorCompoundCast:
593         case Expression::Kind::kConstructorDiagonalMatrix:
594         case Expression::Kind::kConstructorMatrixResize:
595         case Expression::Kind::kConstructorScalarCast:
596         case Expression::Kind::kConstructorSplat:
597         case Expression::Kind::kConstructorStruct: {
598             auto& c = e.asAnyConstructor();
599             for (auto& arg : c.argumentSpan()) {
600                 if (this->visitExpressionPtr(arg)) { return true; }
601             }
602             return false;
603         }
604         case Expression::Kind::kFieldAccess:
605             return this->visitExpressionPtr(e.template as<FieldAccess>().base());
606 
607         case Expression::Kind::kFunctionCall: {
608             auto& c = e.template as<FunctionCall>();
609             for (auto& arg : c.arguments()) {
610                 if (arg && this->visitExpressionPtr(arg)) { return true; }
611             }
612             return false;
613         }
614         case Expression::Kind::kIndex: {
615             auto& i = e.template as<IndexExpression>();
616             return this->visitExpressionPtr(i.base()) || this->visitExpressionPtr(i.index());
617         }
618         case Expression::Kind::kPostfix:
619             return this->visitExpressionPtr(e.template as<PostfixExpression>().operand());
620 
621         case Expression::Kind::kPrefix:
622             return this->visitExpressionPtr(e.template as<PrefixExpression>().operand());
623 
624         case Expression::Kind::kSwizzle: {
625             auto& s = e.template as<Swizzle>();
626             return s.base() && this->visitExpressionPtr(s.base());
627         }
628 
629         case Expression::Kind::kTernary: {
630             auto& t = e.template as<TernaryExpression>();
631             return this->visitExpressionPtr(t.test()) ||
632                    (t.ifTrue() && this->visitExpressionPtr(t.ifTrue())) ||
633                    (t.ifFalse() && this->visitExpressionPtr(t.ifFalse()));
634         }
635         default:
636             SkUNREACHABLE;
637     }
638 }
639 
visitStatement(typename T::Statement & s)640 template <typename T> bool TProgramVisitor<T>::visitStatement(typename T::Statement& s) {
641     switch (s.kind()) {
642         case Statement::Kind::kBreak:
643         case Statement::Kind::kContinue:
644         case Statement::Kind::kDiscard:
645         case Statement::Kind::kNop:
646             // Leaf statements just return false
647             return false;
648 
649         case Statement::Kind::kBlock:
650             for (auto& stmt : s.template as<Block>().children()) {
651                 if (stmt && this->visitStatementPtr(stmt)) {
652                     return true;
653                 }
654             }
655             return false;
656 
657         case Statement::Kind::kSwitchCase: {
658             auto& sc = s.template as<SwitchCase>();
659             return this->visitStatementPtr(sc.statement());
660         }
661         case Statement::Kind::kDo: {
662             auto& d = s.template as<DoStatement>();
663             return this->visitExpressionPtr(d.test()) || this->visitStatementPtr(d.statement());
664         }
665         case Statement::Kind::kExpression:
666             return this->visitExpressionPtr(s.template as<ExpressionStatement>().expression());
667 
668         case Statement::Kind::kFor: {
669             auto& f = s.template as<ForStatement>();
670             return (f.initializer() && this->visitStatementPtr(f.initializer())) ||
671                    (f.test() && this->visitExpressionPtr(f.test())) ||
672                    (f.next() && this->visitExpressionPtr(f.next())) ||
673                    this->visitStatementPtr(f.statement());
674         }
675         case Statement::Kind::kIf: {
676             auto& i = s.template as<IfStatement>();
677             return (i.test() && this->visitExpressionPtr(i.test())) ||
678                    (i.ifTrue() && this->visitStatementPtr(i.ifTrue())) ||
679                    (i.ifFalse() && this->visitStatementPtr(i.ifFalse()));
680         }
681         case Statement::Kind::kReturn: {
682             auto& r = s.template as<ReturnStatement>();
683             return r.expression() && this->visitExpressionPtr(r.expression());
684         }
685         case Statement::Kind::kSwitch: {
686             auto& sw = s.template as<SwitchStatement>();
687             return this->visitExpressionPtr(sw.value()) || this->visitStatementPtr(sw.caseBlock());
688         }
689         case Statement::Kind::kVarDeclaration: {
690             auto& v = s.template as<VarDeclaration>();
691             return v.value() && this->visitExpressionPtr(v.value());
692         }
693         default:
694             SkUNREACHABLE;
695     }
696 }
697 
visitProgramElement(typename T::ProgramElement & pe)698 template <typename T> bool TProgramVisitor<T>::visitProgramElement(typename T::ProgramElement& pe) {
699     switch (pe.kind()) {
700         case ProgramElement::Kind::kExtension:
701         case ProgramElement::Kind::kFunctionPrototype:
702         case ProgramElement::Kind::kInterfaceBlock:
703         case ProgramElement::Kind::kModifiers:
704         case ProgramElement::Kind::kStructDefinition:
705             // Leaf program elements just return false by default
706             return false;
707 
708         case ProgramElement::Kind::kFunction:
709             return this->visitStatementPtr(pe.template as<FunctionDefinition>().body());
710 
711         case ProgramElement::Kind::kGlobalVar:
712             return this->visitStatementPtr(pe.template as<GlobalVarDeclaration>().declaration());
713 
714         default:
715             SkUNREACHABLE;
716     }
717 }
718 
719 template class TProgramVisitor<ProgramVisitorTypes>;
720 template class TProgramVisitor<ProgramWriterTypes>;
721 
722 }  // namespace SkSL
723