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