blob: 3e04f0fbd9e912769d12a173565269cc7e98a9db [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
John Stiles8a9da732021-01-20 14:32:33 -050026static std::unique_ptr<Expression> eliminate_no_op_boolean(const Expression& left,
27 Token::Kind op,
28 const Expression& right) {
29 SkASSERT(right.is<BoolLiteral>());
30 bool rightVal = right.as<BoolLiteral>().value();
31
32 // Detect no-op Boolean expressions and optimize them away.
33 if ((op == Token::Kind::TK_LOGICALAND && rightVal) || // (expr && true) -> (expr)
34 (op == Token::Kind::TK_LOGICALOR && !rightVal) || // (expr || false) -> (expr)
35 (op == Token::Kind::TK_LOGICALXOR && !rightVal) || // (expr ^^ false) -> (expr)
36 (op == Token::Kind::TK_EQEQ && rightVal) || // (expr == true) -> (expr)
37 (op == Token::Kind::TK_NEQ && !rightVal)) { // (expr != false) -> (expr)
38
39 return left.clone();
40 }
41
42 return nullptr;
43}
44
John Stilesdc8ec312021-01-11 11:05:21 -050045static std::unique_ptr<Expression> short_circuit_boolean(const Expression& left,
46 Token::Kind op,
47 const Expression& right) {
48 SkASSERT(left.is<BoolLiteral>());
49 bool leftVal = left.as<BoolLiteral>().value();
50
John Stiles8a9da732021-01-20 14:32:33 -050051 // When the literal is on the left, we can sometimes eliminate the other expression entirely.
52 if ((op == Token::Kind::TK_LOGICALAND && !leftVal) || // (false && expr) -> (false)
53 (op == Token::Kind::TK_LOGICALOR && leftVal)) { // (true || expr) -> (true)
54
55 return left.clone();
John Stilesdc8ec312021-01-11 11:05:21 -050056 }
57
John Stiles8a9da732021-01-20 14:32:33 -050058 // We can't eliminate the right-side expression via short-circuit, but we might still be able to
59 // simplify away a no-op expression.
60 return eliminate_no_op_boolean(right, op, left);
John Stilesdc8ec312021-01-11 11:05:21 -050061}
62
Brian Osman21d2b6a2021-02-01 13:48:50 -050063// 'T' is the actual stored type of the literal data (SKSL_FLOAT or SKSL_INT).
64// 'U' is an unsigned version of that, used to perform addition, subtraction, and multiplication,
65// to avoid signed-integer overflow errors. This mimics the use of URESULT vs. RESULT when doing
66// scalar folding in Simplify, later in this file.
67template <typename T, typename U = T>
John Stilesdc8ec312021-01-11 11:05:21 -050068static std::unique_ptr<Expression> simplify_vector(const Context& context,
John Stilesdc8ec312021-01-11 11:05:21 -050069 const Expression& left,
70 Token::Kind op,
71 const Expression& right) {
John Stiles508eba72021-01-11 13:07:47 -050072 SkASSERT(left.type().isVector());
John Stilesdc8ec312021-01-11 11:05:21 -050073 SkASSERT(left.type() == right.type());
74 const Type& type = left.type();
75
76 // Handle boolean operations: == !=
77 if (op == Token::Kind::TK_EQEQ || op == Token::Kind::TK_NEQ) {
78 bool equality = (op == Token::Kind::TK_EQEQ);
79
80 switch (left.compareConstant(right)) {
81 case Expression::ComparisonResult::kNotEqual:
82 equality = !equality;
83 [[fallthrough]];
84
85 case Expression::ComparisonResult::kEqual:
86 return std::make_unique<BoolLiteral>(context, left.fOffset, equality);
87
88 case Expression::ComparisonResult::kUnknown:
89 return nullptr;
90 }
91 }
92
93 // Handle floating-point arithmetic: + - * /
94 const auto vectorComponentwiseFold = [&](auto foldFn) -> std::unique_ptr<Constructor> {
95 const Type& componentType = type.componentType();
96 ExpressionArray args;
97 args.reserve_back(type.columns());
98 for (int i = 0; i < type.columns(); i++) {
Brian Osman21d2b6a2021-02-01 13:48:50 -050099 U value = foldFn(left.getVecComponent<T>(i), right.getVecComponent<T>(i));
John Stilesdc8ec312021-01-11 11:05:21 -0500100 args.push_back(std::make_unique<Literal<T>>(left.fOffset, value, &componentType));
101 }
102 return std::make_unique<Constructor>(left.fOffset, &type, std::move(args));
103 };
104
105 const auto isVectorDivisionByZero = [&]() -> bool {
106 for (int i = 0; i < type.columns(); i++) {
107 if (right.getVecComponent<T>(i) == 0) {
108 return true;
109 }
110 }
111 return false;
112 };
113
114 switch (op) {
Brian Osman21d2b6a2021-02-01 13:48:50 -0500115 case Token::Kind::TK_PLUS: return vectorComponentwiseFold([](U a, U b) { return a + b; });
116 case Token::Kind::TK_MINUS: return vectorComponentwiseFold([](U a, U b) { return a - b; });
117 case Token::Kind::TK_STAR: return vectorComponentwiseFold([](U a, U b) { return a * b; });
John Stilesdc8ec312021-01-11 11:05:21 -0500118 case Token::Kind::TK_SLASH: {
119 if (isVectorDivisionByZero()) {
John Stilesb30151e2021-01-11 16:13:08 -0500120 context.fErrors.error(right.fOffset, "division by zero");
John Stilesdc8ec312021-01-11 11:05:21 -0500121 return nullptr;
122 }
123 return vectorComponentwiseFold([](T a, T b) { return a / b; });
124 }
125 default:
126 return nullptr;
127 }
128}
129
John Stiles508eba72021-01-11 13:07:47 -0500130static Constructor splat_scalar(const Expression& scalar, const Type& type) {
131 SkASSERT(type.isVector());
132 SkASSERT(type.componentType() == scalar.type());
133
134 // Use a Constructor to splat the scalar expression across a vector.
135 ExpressionArray arg;
136 arg.push_back(scalar.clone());
137 return Constructor{scalar.fOffset, &type, std::move(arg)};
138}
139
John Stilesdc8ec312021-01-11 11:05:21 -0500140std::unique_ptr<Expression> ConstantFolder::Simplify(const Context& context,
John Stilesdc8ec312021-01-11 11:05:21 -0500141 const Expression& left,
142 Token::Kind op,
143 const Expression& right) {
John Stiles8a9da732021-01-20 14:32:33 -0500144 // Simplify the expression when both sides are constant Boolean literals.
John Stilesdc8ec312021-01-11 11:05:21 -0500145 if (left.is<BoolLiteral>() && right.is<BoolLiteral>()) {
146 bool leftVal = left.as<BoolLiteral>().value();
147 bool rightVal = right.as<BoolLiteral>().value();
148 bool result;
149 switch (op) {
150 case Token::Kind::TK_LOGICALAND: result = leftVal && rightVal; break;
151 case Token::Kind::TK_LOGICALOR: result = leftVal || rightVal; break;
152 case Token::Kind::TK_LOGICALXOR: result = leftVal ^ rightVal; break;
John Stiles26fdcbb2021-01-19 19:00:31 -0500153 case Token::Kind::TK_EQEQ: result = leftVal == rightVal; break;
154 case Token::Kind::TK_NEQ: result = leftVal != rightVal; break;
John Stilesdc8ec312021-01-11 11:05:21 -0500155 default: return nullptr;
156 }
157 return std::make_unique<BoolLiteral>(context, left.fOffset, result);
158 }
159
John Stiles8a9da732021-01-20 14:32:33 -0500160 // If the left side is a Boolean literal, apply short-circuit optimizations.
161 if (left.is<BoolLiteral>()) {
162 return short_circuit_boolean(left, op, right);
163 }
164
165 // If the right side is a Boolean literal...
166 if (right.is<BoolLiteral>()) {
167 // ... and the left side has no side effects...
168 if (!left.hasSideEffects()) {
169 // We can reverse the expressions and short-circuit optimizations are still valid.
170 return short_circuit_boolean(right, op, left);
171 }
172
173 // We can't use short-circuiting, but we can still optimize away no-op Boolean expressions.
174 return eliminate_no_op_boolean(left, op, right);
175 }
176
177 // Other than the short-circuit cases above, constant folding requires both sides to be constant
178 if (!left.isCompileTimeConstant() || !right.isCompileTimeConstant()) {
179 return nullptr;
180 }
181
John Stilesdc8ec312021-01-11 11:05:21 -0500182 // Note that we expressly do not worry about precision and overflow here -- we use the maximum
183 // precision to calculate the results and hope the result makes sense.
184 // TODO: detect and handle integer overflow properly.
Brian Osman21d2b6a2021-02-01 13:48:50 -0500185 using SKSL_UINT = uint64_t;
John Stilesdc8ec312021-01-11 11:05:21 -0500186 #define RESULT(t, op) std::make_unique<t ## Literal>(context, left.fOffset, \
187 leftVal op rightVal)
188 #define URESULT(t, op) std::make_unique<t ## Literal>(context, left.fOffset, \
Brian Osman21d2b6a2021-02-01 13:48:50 -0500189 (SKSL_UINT) leftVal op \
190 (SKSL_UINT) rightVal)
John Stilesdc8ec312021-01-11 11:05:21 -0500191 if (left.is<IntLiteral>() && right.is<IntLiteral>()) {
192 SKSL_INT leftVal = left.as<IntLiteral>().value();
193 SKSL_INT rightVal = right.as<IntLiteral>().value();
194 switch (op) {
195 case Token::Kind::TK_PLUS: return URESULT(Int, +);
196 case Token::Kind::TK_MINUS: return URESULT(Int, -);
197 case Token::Kind::TK_STAR: return URESULT(Int, *);
198 case Token::Kind::TK_SLASH:
199 if (leftVal == std::numeric_limits<SKSL_INT>::min() && rightVal == -1) {
John Stilesb30151e2021-01-11 16:13:08 -0500200 context.fErrors.error(right.fOffset, "arithmetic overflow");
John Stilesdc8ec312021-01-11 11:05:21 -0500201 return nullptr;
202 }
203 if (!rightVal) {
John Stilesb30151e2021-01-11 16:13:08 -0500204 context.fErrors.error(right.fOffset, "division by zero");
John Stilesdc8ec312021-01-11 11:05:21 -0500205 return nullptr;
206 }
207 return RESULT(Int, /);
208 case Token::Kind::TK_PERCENT:
209 if (leftVal == std::numeric_limits<SKSL_INT>::min() && rightVal == -1) {
John Stilesb30151e2021-01-11 16:13:08 -0500210 context.fErrors.error(right.fOffset, "arithmetic overflow");
John Stilesdc8ec312021-01-11 11:05:21 -0500211 return nullptr;
212 }
213 if (!rightVal) {
John Stilesb30151e2021-01-11 16:13:08 -0500214 context.fErrors.error(right.fOffset, "division by zero");
John Stilesdc8ec312021-01-11 11:05:21 -0500215 return nullptr;
216 }
217 return RESULT(Int, %);
218 case Token::Kind::TK_BITWISEAND: return RESULT(Int, &);
219 case Token::Kind::TK_BITWISEOR: return RESULT(Int, |);
220 case Token::Kind::TK_BITWISEXOR: return RESULT(Int, ^);
221 case Token::Kind::TK_EQEQ: return RESULT(Bool, ==);
222 case Token::Kind::TK_NEQ: return RESULT(Bool, !=);
223 case Token::Kind::TK_GT: return RESULT(Bool, >);
224 case Token::Kind::TK_GTEQ: return RESULT(Bool, >=);
225 case Token::Kind::TK_LT: return RESULT(Bool, <);
226 case Token::Kind::TK_LTEQ: return RESULT(Bool, <=);
227 case Token::Kind::TK_SHL:
228 if (rightVal >= 0 && rightVal <= 31) {
Brian Osmana7eb6812021-02-01 11:43:05 -0500229 // Left-shifting a negative (or really, any signed) value is undefined behavior
230 // in C++, but not GLSL. Do the shift on unsigned values, to avoid UBSAN.
231 return URESULT(Int, <<);
John Stilesdc8ec312021-01-11 11:05:21 -0500232 }
John Stilesb30151e2021-01-11 16:13:08 -0500233 context.fErrors.error(right.fOffset, "shift value out of range");
John Stilesdc8ec312021-01-11 11:05:21 -0500234 return nullptr;
235 case Token::Kind::TK_SHR:
236 if (rightVal >= 0 && rightVal <= 31) {
237 return RESULT(Int, >>);
238 }
John Stilesb30151e2021-01-11 16:13:08 -0500239 context.fErrors.error(right.fOffset, "shift value out of range");
John Stilesdc8ec312021-01-11 11:05:21 -0500240 return nullptr;
241
242 default:
243 return nullptr;
244 }
245 }
246
247 // Perform constant folding on pairs of floating-point literals.
248 if (left.is<FloatLiteral>() && right.is<FloatLiteral>()) {
249 SKSL_FLOAT leftVal = left.as<FloatLiteral>().value();
250 SKSL_FLOAT rightVal = right.as<FloatLiteral>().value();
251 switch (op) {
252 case Token::Kind::TK_PLUS: return RESULT(Float, +);
253 case Token::Kind::TK_MINUS: return RESULT(Float, -);
254 case Token::Kind::TK_STAR: return RESULT(Float, *);
255 case Token::Kind::TK_SLASH:
256 if (rightVal) {
257 return RESULT(Float, /);
258 }
John Stilesb30151e2021-01-11 16:13:08 -0500259 context.fErrors.error(right.fOffset, "division by zero");
John Stilesdc8ec312021-01-11 11:05:21 -0500260 return nullptr;
261 case Token::Kind::TK_EQEQ: return RESULT(Bool, ==);
262 case Token::Kind::TK_NEQ: return RESULT(Bool, !=);
263 case Token::Kind::TK_GT: return RESULT(Bool, >);
264 case Token::Kind::TK_GTEQ: return RESULT(Bool, >=);
265 case Token::Kind::TK_LT: return RESULT(Bool, <);
266 case Token::Kind::TK_LTEQ: return RESULT(Bool, <=);
267 default: return nullptr;
268 }
269 }
270
271 // Perform constant folding on pairs of vectors.
272 const Type& leftType = left.type();
273 const Type& rightType = right.type();
274 if (leftType.isVector() && leftType == rightType) {
275 if (leftType.componentType().isFloat()) {
John Stilesb30151e2021-01-11 16:13:08 -0500276 return simplify_vector<SKSL_FLOAT>(context, left, op, right);
John Stilesdc8ec312021-01-11 11:05:21 -0500277 }
278 if (leftType.componentType().isInteger()) {
Brian Osman21d2b6a2021-02-01 13:48:50 -0500279 return simplify_vector<SKSL_INT, SKSL_UINT>(context, left, op, right);
John Stilesdc8ec312021-01-11 11:05:21 -0500280 }
281 return nullptr;
282 }
283
John Stiles508eba72021-01-11 13:07:47 -0500284 // Perform constant folding on vectors against scalars, e.g.: half4(2) + 2
285 if (leftType.isVector() && leftType.componentType() == rightType) {
286 if (rightType.isFloat()) {
John Stilesb30151e2021-01-11 16:13:08 -0500287 return simplify_vector<SKSL_FLOAT>(context, left, op, splat_scalar(right, left.type()));
John Stiles508eba72021-01-11 13:07:47 -0500288 }
289 if (rightType.isInteger()) {
Brian Osman21d2b6a2021-02-01 13:48:50 -0500290 return simplify_vector<SKSL_INT, SKSL_UINT>(context, left, op,
291 splat_scalar(right, left.type()));
John Stiles508eba72021-01-11 13:07:47 -0500292 }
293 return nullptr;
294 }
295
296 // Perform constant folding on scalars against vectors, e.g.: 2 + half4(2)
297 if (rightType.isVector() && rightType.componentType() == leftType) {
298 if (leftType.isFloat()) {
John Stilesb30151e2021-01-11 16:13:08 -0500299 return simplify_vector<SKSL_FLOAT>(context, splat_scalar(left, right.type()), op,
300 right);
John Stiles508eba72021-01-11 13:07:47 -0500301 }
302 if (leftType.isInteger()) {
Brian Osman21d2b6a2021-02-01 13:48:50 -0500303 return simplify_vector<SKSL_INT, SKSL_UINT>(context, splat_scalar(left, right.type()),
304 op, right);
John Stiles508eba72021-01-11 13:07:47 -0500305 }
306 return nullptr;
307 }
308
John Stilesdc8ec312021-01-11 11:05:21 -0500309 // Perform constant folding on pairs of matrices.
310 if (leftType.isMatrix() && rightType.isMatrix()) {
311 bool equality;
312 switch (op) {
313 case Token::Kind::TK_EQEQ:
314 equality = true;
315 break;
316 case Token::Kind::TK_NEQ:
317 equality = false;
318 break;
319 default:
320 return nullptr;
321 }
322
323 switch (left.compareConstant(right)) {
324 case Expression::ComparisonResult::kNotEqual:
325 equality = !equality;
326 [[fallthrough]];
327
328 case Expression::ComparisonResult::kEqual:
329 return std::make_unique<BoolLiteral>(context, left.fOffset, equality);
330
331 case Expression::ComparisonResult::kUnknown:
332 return nullptr;
333 }
334 }
335
336 // We aren't able to constant-fold.
337 #undef RESULT
338 #undef URESULT
339 return nullptr;
340}
341
342} // namespace SkSL