blob: 94aa5d0a30efa987230b90f3abab5094d7888756 [file] [log] [blame]
John Stilesdc8ec312021-01-11 11:05:21 -05001/*
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/SkSLConstantFolder.h"
9
10#include <limits>
11
12#include "src/sksl/SkSLContext.h"
13#include "src/sksl/SkSLErrorReporter.h"
14#include "src/sksl/ir/SkSLBinaryExpression.h"
15#include "src/sksl/ir/SkSLBoolLiteral.h"
16#include "src/sksl/ir/SkSLConstructor.h"
17#include "src/sksl/ir/SkSLExpression.h"
18#include "src/sksl/ir/SkSLFloatLiteral.h"
19#include "src/sksl/ir/SkSLIntLiteral.h"
20#include "src/sksl/ir/SkSLType.h"
21#include "src/sksl/ir/SkSLVariable.h"
22#include "src/sksl/ir/SkSLVariableReference.h"
23
24namespace SkSL {
25
26static std::unique_ptr<Expression> short_circuit_boolean(const Expression& left,
27 Token::Kind op,
28 const Expression& right) {
29 SkASSERT(left.is<BoolLiteral>());
30 bool leftVal = left.as<BoolLiteral>().value();
31
32 if (op == Token::Kind::TK_LOGICALAND) {
33 // (true && expr) -> (expr) and (false && expr) -> (false)
34 return leftVal ? right.clone()
35 : std::make_unique<BoolLiteral>(left.fOffset, /*value=*/false, &left.type());
36 }
37 if (op == Token::Kind::TK_LOGICALOR) {
38 // (true || expr) -> (true) and (false || expr) -> (expr)
39 return leftVal ? std::make_unique<BoolLiteral>(left.fOffset, /*value=*/true, &left.type())
40 : right.clone();
41 }
42 if (op == Token::Kind::TK_LOGICALXOR && !leftVal) {
43 // (false ^^ expr) -> (expr)
44 return right.clone();
45 }
46
47 return nullptr;
48}
49
50template <typename T>
51static std::unique_ptr<Expression> simplify_vector(const Context& context,
52 ErrorReporter& errors,
53 const Expression& left,
54 Token::Kind op,
55 const Expression& right) {
56 SkASSERT(left.type() == right.type());
57 const Type& type = left.type();
58
59 // Handle boolean operations: == !=
60 if (op == Token::Kind::TK_EQEQ || op == Token::Kind::TK_NEQ) {
61 bool equality = (op == Token::Kind::TK_EQEQ);
62
63 switch (left.compareConstant(right)) {
64 case Expression::ComparisonResult::kNotEqual:
65 equality = !equality;
66 [[fallthrough]];
67
68 case Expression::ComparisonResult::kEqual:
69 return std::make_unique<BoolLiteral>(context, left.fOffset, equality);
70
71 case Expression::ComparisonResult::kUnknown:
72 return nullptr;
73 }
74 }
75
76 // Handle floating-point arithmetic: + - * /
77 const auto vectorComponentwiseFold = [&](auto foldFn) -> std::unique_ptr<Constructor> {
78 const Type& componentType = type.componentType();
79 ExpressionArray args;
80 args.reserve_back(type.columns());
81 for (int i = 0; i < type.columns(); i++) {
82 T value = foldFn(left.getVecComponent<T>(i), right.getVecComponent<T>(i));
83 args.push_back(std::make_unique<Literal<T>>(left.fOffset, value, &componentType));
84 }
85 return std::make_unique<Constructor>(left.fOffset, &type, std::move(args));
86 };
87
88 const auto isVectorDivisionByZero = [&]() -> bool {
89 for (int i = 0; i < type.columns(); i++) {
90 if (right.getVecComponent<T>(i) == 0) {
91 return true;
92 }
93 }
94 return false;
95 };
96
97 switch (op) {
98 case Token::Kind::TK_PLUS: return vectorComponentwiseFold([](T a, T b) { return a + b; });
99 case Token::Kind::TK_MINUS: return vectorComponentwiseFold([](T a, T b) { return a - b; });
100 case Token::Kind::TK_STAR: return vectorComponentwiseFold([](T a, T b) { return a * b; });
101 case Token::Kind::TK_SLASH: {
102 if (isVectorDivisionByZero()) {
103 errors.error(right.fOffset, "division by zero");
104 return nullptr;
105 }
106 return vectorComponentwiseFold([](T a, T b) { return a / b; });
107 }
108 default:
109 return nullptr;
110 }
111}
112
113std::unique_ptr<Expression> ConstantFolder::Simplify(const Context& context,
114 ErrorReporter& errors,
115 const Expression& left,
116 Token::Kind op,
117 const Expression& right) {
118 // If the left side is a constant boolean literal, the right side does not need to be constant
119 // for short-circuit optimizations to allow the constant to be folded.
120 if (left.is<BoolLiteral>() && !right.isCompileTimeConstant()) {
121 return short_circuit_boolean(left, op, right);
122 }
123
124 if (right.is<BoolLiteral>() && !left.isCompileTimeConstant()) {
125 // There aren't side effects in SkSL within expressions, so (left OP right) is equivalent to
126 // (right OP left) for short-circuit optimizations
127 // TODO: (true || (a=b)) seems to disqualify the above statement. Test this.
128 return short_circuit_boolean(right, op, left);
129 }
130
131 // Other than the short-circuit cases above, constant folding requires both sides to be constant
132 if (!left.isCompileTimeConstant() || !right.isCompileTimeConstant()) {
133 return nullptr;
134 }
135
136 // Perform constant folding on pairs of Booleans.
137 if (left.is<BoolLiteral>() && right.is<BoolLiteral>()) {
138 bool leftVal = left.as<BoolLiteral>().value();
139 bool rightVal = right.as<BoolLiteral>().value();
140 bool result;
141 switch (op) {
142 case Token::Kind::TK_LOGICALAND: result = leftVal && rightVal; break;
143 case Token::Kind::TK_LOGICALOR: result = leftVal || rightVal; break;
144 case Token::Kind::TK_LOGICALXOR: result = leftVal ^ rightVal; break;
145 default: return nullptr;
146 }
147 return std::make_unique<BoolLiteral>(context, left.fOffset, result);
148 }
149
150 // Note that we expressly do not worry about precision and overflow here -- we use the maximum
151 // precision to calculate the results and hope the result makes sense.
152 // TODO: detect and handle integer overflow properly.
153 #define RESULT(t, op) std::make_unique<t ## Literal>(context, left.fOffset, \
154 leftVal op rightVal)
155 #define URESULT(t, op) std::make_unique<t ## Literal>(context, left.fOffset, \
156 (uint64_t) leftVal op \
157 (uint64_t) rightVal)
158 if (left.is<IntLiteral>() && right.is<IntLiteral>()) {
159 SKSL_INT leftVal = left.as<IntLiteral>().value();
160 SKSL_INT rightVal = right.as<IntLiteral>().value();
161 switch (op) {
162 case Token::Kind::TK_PLUS: return URESULT(Int, +);
163 case Token::Kind::TK_MINUS: return URESULT(Int, -);
164 case Token::Kind::TK_STAR: return URESULT(Int, *);
165 case Token::Kind::TK_SLASH:
166 if (leftVal == std::numeric_limits<SKSL_INT>::min() && rightVal == -1) {
167 errors.error(right.fOffset, "arithmetic overflow");
168 return nullptr;
169 }
170 if (!rightVal) {
171 errors.error(right.fOffset, "division by zero");
172 return nullptr;
173 }
174 return RESULT(Int, /);
175 case Token::Kind::TK_PERCENT:
176 if (leftVal == std::numeric_limits<SKSL_INT>::min() && rightVal == -1) {
177 errors.error(right.fOffset, "arithmetic overflow");
178 return nullptr;
179 }
180 if (!rightVal) {
181 errors.error(right.fOffset, "division by zero");
182 return nullptr;
183 }
184 return RESULT(Int, %);
185 case Token::Kind::TK_BITWISEAND: return RESULT(Int, &);
186 case Token::Kind::TK_BITWISEOR: return RESULT(Int, |);
187 case Token::Kind::TK_BITWISEXOR: return RESULT(Int, ^);
188 case Token::Kind::TK_EQEQ: return RESULT(Bool, ==);
189 case Token::Kind::TK_NEQ: return RESULT(Bool, !=);
190 case Token::Kind::TK_GT: return RESULT(Bool, >);
191 case Token::Kind::TK_GTEQ: return RESULT(Bool, >=);
192 case Token::Kind::TK_LT: return RESULT(Bool, <);
193 case Token::Kind::TK_LTEQ: return RESULT(Bool, <=);
194 case Token::Kind::TK_SHL:
195 if (rightVal >= 0 && rightVal <= 31) {
196 return RESULT(Int, <<);
197 }
198 errors.error(right.fOffset, "shift value out of range");
199 return nullptr;
200 case Token::Kind::TK_SHR:
201 if (rightVal >= 0 && rightVal <= 31) {
202 return RESULT(Int, >>);
203 }
204 errors.error(right.fOffset, "shift value out of range");
205 return nullptr;
206
207 default:
208 return nullptr;
209 }
210 }
211
212 // Perform constant folding on pairs of floating-point literals.
213 if (left.is<FloatLiteral>() && right.is<FloatLiteral>()) {
214 SKSL_FLOAT leftVal = left.as<FloatLiteral>().value();
215 SKSL_FLOAT rightVal = right.as<FloatLiteral>().value();
216 switch (op) {
217 case Token::Kind::TK_PLUS: return RESULT(Float, +);
218 case Token::Kind::TK_MINUS: return RESULT(Float, -);
219 case Token::Kind::TK_STAR: return RESULT(Float, *);
220 case Token::Kind::TK_SLASH:
221 if (rightVal) {
222 return RESULT(Float, /);
223 }
224 errors.error(right.fOffset, "division by zero");
225 return nullptr;
226 case Token::Kind::TK_EQEQ: return RESULT(Bool, ==);
227 case Token::Kind::TK_NEQ: return RESULT(Bool, !=);
228 case Token::Kind::TK_GT: return RESULT(Bool, >);
229 case Token::Kind::TK_GTEQ: return RESULT(Bool, >=);
230 case Token::Kind::TK_LT: return RESULT(Bool, <);
231 case Token::Kind::TK_LTEQ: return RESULT(Bool, <=);
232 default: return nullptr;
233 }
234 }
235
236 // Perform constant folding on pairs of vectors.
237 const Type& leftType = left.type();
238 const Type& rightType = right.type();
239 if (leftType.isVector() && leftType == rightType) {
240 if (leftType.componentType().isFloat()) {
241 return simplify_vector<SKSL_FLOAT>(context, errors, left, op, right);
242 }
243 if (leftType.componentType().isInteger()) {
244 return simplify_vector<SKSL_INT>(context, errors, left, op, right);
245 }
246 return nullptr;
247 }
248
249 // Perform constant folding on pairs of matrices.
250 if (leftType.isMatrix() && rightType.isMatrix()) {
251 bool equality;
252 switch (op) {
253 case Token::Kind::TK_EQEQ:
254 equality = true;
255 break;
256 case Token::Kind::TK_NEQ:
257 equality = false;
258 break;
259 default:
260 return nullptr;
261 }
262
263 switch (left.compareConstant(right)) {
264 case Expression::ComparisonResult::kNotEqual:
265 equality = !equality;
266 [[fallthrough]];
267
268 case Expression::ComparisonResult::kEqual:
269 return std::make_unique<BoolLiteral>(context, left.fOffset, equality);
270
271 case Expression::ComparisonResult::kUnknown:
272 return nullptr;
273 }
274 }
275
276 // We aren't able to constant-fold.
277 #undef RESULT
278 #undef URESULT
279 return nullptr;
280}
281
282} // namespace SkSL