blob: 65e3923c77452101632670040a53514c62ecdbaa [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 Stilesabc3b782021-02-05 10:07:19 -0500144 // If this is the comma operator, the left side is evaluated but not otherwise used in any way.
145 // So if the left side has no side effects, it can just be eliminated entirely.
146 if (op == Token::Kind::TK_COMMA && !left.hasSideEffects()) {
147 return right.clone();
148 }
149
John Stiles8a9da732021-01-20 14:32:33 -0500150 // Simplify the expression when both sides are constant Boolean literals.
John Stilesdc8ec312021-01-11 11:05:21 -0500151 if (left.is<BoolLiteral>() && right.is<BoolLiteral>()) {
152 bool leftVal = left.as<BoolLiteral>().value();
153 bool rightVal = right.as<BoolLiteral>().value();
154 bool result;
155 switch (op) {
156 case Token::Kind::TK_LOGICALAND: result = leftVal && rightVal; break;
157 case Token::Kind::TK_LOGICALOR: result = leftVal || rightVal; break;
158 case Token::Kind::TK_LOGICALXOR: result = leftVal ^ rightVal; break;
John Stiles26fdcbb2021-01-19 19:00:31 -0500159 case Token::Kind::TK_EQEQ: result = leftVal == rightVal; break;
160 case Token::Kind::TK_NEQ: result = leftVal != rightVal; break;
John Stilesdc8ec312021-01-11 11:05:21 -0500161 default: return nullptr;
162 }
163 return std::make_unique<BoolLiteral>(context, left.fOffset, result);
164 }
165
John Stiles8a9da732021-01-20 14:32:33 -0500166 // If the left side is a Boolean literal, apply short-circuit optimizations.
167 if (left.is<BoolLiteral>()) {
168 return short_circuit_boolean(left, op, right);
169 }
170
171 // If the right side is a Boolean literal...
172 if (right.is<BoolLiteral>()) {
173 // ... and the left side has no side effects...
174 if (!left.hasSideEffects()) {
175 // We can reverse the expressions and short-circuit optimizations are still valid.
176 return short_circuit_boolean(right, op, left);
177 }
178
179 // We can't use short-circuiting, but we can still optimize away no-op Boolean expressions.
180 return eliminate_no_op_boolean(left, op, right);
181 }
182
183 // Other than the short-circuit cases above, constant folding requires both sides to be constant
184 if (!left.isCompileTimeConstant() || !right.isCompileTimeConstant()) {
185 return nullptr;
186 }
187
John Stilesdc8ec312021-01-11 11:05:21 -0500188 // Note that we expressly do not worry about precision and overflow here -- we use the maximum
189 // precision to calculate the results and hope the result makes sense.
190 // TODO: detect and handle integer overflow properly.
Brian Osman21d2b6a2021-02-01 13:48:50 -0500191 using SKSL_UINT = uint64_t;
John Stilesdc8ec312021-01-11 11:05:21 -0500192 #define RESULT(t, op) std::make_unique<t ## Literal>(context, left.fOffset, \
193 leftVal op rightVal)
194 #define URESULT(t, op) std::make_unique<t ## Literal>(context, left.fOffset, \
Brian Osman21d2b6a2021-02-01 13:48:50 -0500195 (SKSL_UINT) leftVal op \
196 (SKSL_UINT) rightVal)
John Stilesdc8ec312021-01-11 11:05:21 -0500197 if (left.is<IntLiteral>() && right.is<IntLiteral>()) {
198 SKSL_INT leftVal = left.as<IntLiteral>().value();
199 SKSL_INT rightVal = right.as<IntLiteral>().value();
200 switch (op) {
201 case Token::Kind::TK_PLUS: return URESULT(Int, +);
202 case Token::Kind::TK_MINUS: return URESULT(Int, -);
203 case Token::Kind::TK_STAR: return URESULT(Int, *);
204 case Token::Kind::TK_SLASH:
205 if (leftVal == std::numeric_limits<SKSL_INT>::min() && rightVal == -1) {
John Stilesb30151e2021-01-11 16:13:08 -0500206 context.fErrors.error(right.fOffset, "arithmetic overflow");
John Stilesdc8ec312021-01-11 11:05:21 -0500207 return nullptr;
208 }
209 if (!rightVal) {
John Stilesb30151e2021-01-11 16:13:08 -0500210 context.fErrors.error(right.fOffset, "division by zero");
John Stilesdc8ec312021-01-11 11:05:21 -0500211 return nullptr;
212 }
213 return RESULT(Int, /);
214 case Token::Kind::TK_PERCENT:
215 if (leftVal == std::numeric_limits<SKSL_INT>::min() && rightVal == -1) {
John Stilesb30151e2021-01-11 16:13:08 -0500216 context.fErrors.error(right.fOffset, "arithmetic overflow");
John Stilesdc8ec312021-01-11 11:05:21 -0500217 return nullptr;
218 }
219 if (!rightVal) {
John Stilesb30151e2021-01-11 16:13:08 -0500220 context.fErrors.error(right.fOffset, "division by zero");
John Stilesdc8ec312021-01-11 11:05:21 -0500221 return nullptr;
222 }
223 return RESULT(Int, %);
224 case Token::Kind::TK_BITWISEAND: return RESULT(Int, &);
225 case Token::Kind::TK_BITWISEOR: return RESULT(Int, |);
226 case Token::Kind::TK_BITWISEXOR: return RESULT(Int, ^);
227 case Token::Kind::TK_EQEQ: return RESULT(Bool, ==);
228 case Token::Kind::TK_NEQ: return RESULT(Bool, !=);
229 case Token::Kind::TK_GT: return RESULT(Bool, >);
230 case Token::Kind::TK_GTEQ: return RESULT(Bool, >=);
231 case Token::Kind::TK_LT: return RESULT(Bool, <);
232 case Token::Kind::TK_LTEQ: return RESULT(Bool, <=);
233 case Token::Kind::TK_SHL:
234 if (rightVal >= 0 && rightVal <= 31) {
Brian Osmana7eb6812021-02-01 11:43:05 -0500235 // Left-shifting a negative (or really, any signed) value is undefined behavior
236 // in C++, but not GLSL. Do the shift on unsigned values, to avoid UBSAN.
237 return URESULT(Int, <<);
John Stilesdc8ec312021-01-11 11:05:21 -0500238 }
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 case Token::Kind::TK_SHR:
242 if (rightVal >= 0 && rightVal <= 31) {
243 return RESULT(Int, >>);
244 }
John Stilesb30151e2021-01-11 16:13:08 -0500245 context.fErrors.error(right.fOffset, "shift value out of range");
John Stilesdc8ec312021-01-11 11:05:21 -0500246 return nullptr;
247
248 default:
249 return nullptr;
250 }
251 }
252
253 // Perform constant folding on pairs of floating-point literals.
254 if (left.is<FloatLiteral>() && right.is<FloatLiteral>()) {
255 SKSL_FLOAT leftVal = left.as<FloatLiteral>().value();
256 SKSL_FLOAT rightVal = right.as<FloatLiteral>().value();
257 switch (op) {
258 case Token::Kind::TK_PLUS: return RESULT(Float, +);
259 case Token::Kind::TK_MINUS: return RESULT(Float, -);
260 case Token::Kind::TK_STAR: return RESULT(Float, *);
261 case Token::Kind::TK_SLASH:
262 if (rightVal) {
263 return RESULT(Float, /);
264 }
John Stilesb30151e2021-01-11 16:13:08 -0500265 context.fErrors.error(right.fOffset, "division by zero");
John Stilesdc8ec312021-01-11 11:05:21 -0500266 return nullptr;
267 case Token::Kind::TK_EQEQ: return RESULT(Bool, ==);
268 case Token::Kind::TK_NEQ: return RESULT(Bool, !=);
269 case Token::Kind::TK_GT: return RESULT(Bool, >);
270 case Token::Kind::TK_GTEQ: return RESULT(Bool, >=);
271 case Token::Kind::TK_LT: return RESULT(Bool, <);
272 case Token::Kind::TK_LTEQ: return RESULT(Bool, <=);
273 default: return nullptr;
274 }
275 }
276
277 // Perform constant folding on pairs of vectors.
278 const Type& leftType = left.type();
279 const Type& rightType = right.type();
280 if (leftType.isVector() && leftType == rightType) {
281 if (leftType.componentType().isFloat()) {
John Stilesb30151e2021-01-11 16:13:08 -0500282 return simplify_vector<SKSL_FLOAT>(context, left, op, right);
John Stilesdc8ec312021-01-11 11:05:21 -0500283 }
284 if (leftType.componentType().isInteger()) {
Brian Osman21d2b6a2021-02-01 13:48:50 -0500285 return simplify_vector<SKSL_INT, SKSL_UINT>(context, left, op, right);
John Stilesdc8ec312021-01-11 11:05:21 -0500286 }
287 return nullptr;
288 }
289
John Stiles508eba72021-01-11 13:07:47 -0500290 // Perform constant folding on vectors against scalars, e.g.: half4(2) + 2
291 if (leftType.isVector() && leftType.componentType() == rightType) {
292 if (rightType.isFloat()) {
John Stilesb30151e2021-01-11 16:13:08 -0500293 return simplify_vector<SKSL_FLOAT>(context, left, op, splat_scalar(right, left.type()));
John Stiles508eba72021-01-11 13:07:47 -0500294 }
295 if (rightType.isInteger()) {
Brian Osman21d2b6a2021-02-01 13:48:50 -0500296 return simplify_vector<SKSL_INT, SKSL_UINT>(context, left, op,
297 splat_scalar(right, left.type()));
John Stiles508eba72021-01-11 13:07:47 -0500298 }
299 return nullptr;
300 }
301
302 // Perform constant folding on scalars against vectors, e.g.: 2 + half4(2)
303 if (rightType.isVector() && rightType.componentType() == leftType) {
304 if (leftType.isFloat()) {
John Stilesb30151e2021-01-11 16:13:08 -0500305 return simplify_vector<SKSL_FLOAT>(context, splat_scalar(left, right.type()), op,
306 right);
John Stiles508eba72021-01-11 13:07:47 -0500307 }
308 if (leftType.isInteger()) {
Brian Osman21d2b6a2021-02-01 13:48:50 -0500309 return simplify_vector<SKSL_INT, SKSL_UINT>(context, splat_scalar(left, right.type()),
310 op, right);
John Stiles508eba72021-01-11 13:07:47 -0500311 }
312 return nullptr;
313 }
314
John Stilesdc8ec312021-01-11 11:05:21 -0500315 // Perform constant folding on pairs of matrices.
316 if (leftType.isMatrix() && rightType.isMatrix()) {
317 bool equality;
318 switch (op) {
319 case Token::Kind::TK_EQEQ:
320 equality = true;
321 break;
322 case Token::Kind::TK_NEQ:
323 equality = false;
324 break;
325 default:
326 return nullptr;
327 }
328
329 switch (left.compareConstant(right)) {
330 case Expression::ComparisonResult::kNotEqual:
331 equality = !equality;
332 [[fallthrough]];
333
334 case Expression::ComparisonResult::kEqual:
335 return std::make_unique<BoolLiteral>(context, left.fOffset, equality);
336
337 case Expression::ComparisonResult::kUnknown:
338 return nullptr;
339 }
340 }
341
342 // We aren't able to constant-fold.
343 #undef RESULT
344 #undef URESULT
345 return nullptr;
346}
347
348} // namespace SkSL