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 #ifndef SKSL_CONSTANT_FOLDER 9 #define SKSL_CONSTANT_FOLDER 10 11 #include <memory> 12 13 #include "include/private/SkSLDefines.h" 14 #include "src/sksl/SkSLOperators.h" 15 16 namespace SkSL { 17 18 class Context; 19 class Expression; 20 21 /** 22 * Performs constant folding on IR expressions. This simplifies expressions containing 23 * compile-time constants, such as replacing `Literal(2) + Literal(2)` with `Literal(4)`. 24 */ 25 class ConstantFolder { 26 public: 27 /** 28 * If value is an int literal or const int variable with a known value, returns true and stores 29 * the value in out. Otherwise returns false. 30 */ 31 static bool GetConstantInt(const Expression& value, SKSL_INT* out); 32 33 /** 34 * If value is a literal or const scalar variable with a known value, returns true and stores 35 * the value in out. Otherwise returns false. 36 */ 37 static bool GetConstantValue(const Expression& value, double* out); 38 39 /** 40 * If the expression is a const variable with a known compile-time-constant value, returns that 41 * value. If not, returns the original expression as-is. 42 */ 43 static const Expression* GetConstantValueForVariable(const Expression& value); 44 45 /** 46 * If the expression is a const variable with a known compile-time-constant value, returns a 47 * clone of that value. If not, returns the original expression as-is. 48 */ 49 static std::unique_ptr<Expression> MakeConstantValueForVariable( 50 std::unique_ptr<Expression> expr); 51 52 /** Simplifies the binary expression `left OP right`. Returns null if it can't be simplified. */ 53 static std::unique_ptr<Expression> Simplify(const Context& context, 54 int line, 55 const Expression& left, 56 Operator op, 57 const Expression& right, 58 const Type& resultType); 59 }; 60 61 } // namespace SkSL 62 63 #endif // SKSL_CONSTANT_FOLDER 64