blob: 9a1851a156a216daaa8d317afd020dcea98fa907 [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"
John Stilesb0ce42d2021-04-09 10:39:42 -040017#include "src/sksl/ir/SkSLConstructorCompound.h"
John Stiles2938eea2021-04-01 18:58:25 -040018#include "src/sksl/ir/SkSLConstructorSplat.h"
John Stilesdc8ec312021-01-11 11:05:21 -050019#include "src/sksl/ir/SkSLExpression.h"
20#include "src/sksl/ir/SkSLFloatLiteral.h"
21#include "src/sksl/ir/SkSLIntLiteral.h"
John Stiles8f440b42021-03-05 16:48:56 -050022#include "src/sksl/ir/SkSLPrefixExpression.h"
John Stilesdc8ec312021-01-11 11:05:21 -050023#include "src/sksl/ir/SkSLType.h"
24#include "src/sksl/ir/SkSLVariable.h"
25#include "src/sksl/ir/SkSLVariableReference.h"
26
27namespace SkSL {
28
John Stiles8a9da732021-01-20 14:32:33 -050029static std::unique_ptr<Expression> eliminate_no_op_boolean(const Expression& left,
John Stiles45990502021-02-16 10:55:27 -050030 Operator op,
John Stiles8a9da732021-01-20 14:32:33 -050031 const Expression& right) {
32 SkASSERT(right.is<BoolLiteral>());
33 bool rightVal = right.as<BoolLiteral>().value();
34
35 // Detect no-op Boolean expressions and optimize them away.
John Stiles45990502021-02-16 10:55:27 -050036 if ((op.kind() == Token::Kind::TK_LOGICALAND && rightVal) || // (expr && true) -> (expr)
37 (op.kind() == Token::Kind::TK_LOGICALOR && !rightVal) || // (expr || false) -> (expr)
38 (op.kind() == Token::Kind::TK_LOGICALXOR && !rightVal) || // (expr ^^ false) -> (expr)
39 (op.kind() == Token::Kind::TK_EQEQ && rightVal) || // (expr == true) -> (expr)
40 (op.kind() == Token::Kind::TK_NEQ && !rightVal)) { // (expr != false) -> (expr)
John Stiles8a9da732021-01-20 14:32:33 -050041
42 return left.clone();
43 }
44
45 return nullptr;
46}
47
John Stilesdc8ec312021-01-11 11:05:21 -050048static std::unique_ptr<Expression> short_circuit_boolean(const Expression& left,
John Stiles45990502021-02-16 10:55:27 -050049 Operator op,
John Stilesdc8ec312021-01-11 11:05:21 -050050 const Expression& right) {
51 SkASSERT(left.is<BoolLiteral>());
52 bool leftVal = left.as<BoolLiteral>().value();
53
John Stiles8a9da732021-01-20 14:32:33 -050054 // When the literal is on the left, we can sometimes eliminate the other expression entirely.
John Stiles45990502021-02-16 10:55:27 -050055 if ((op.kind() == Token::Kind::TK_LOGICALAND && !leftVal) || // (false && expr) -> (false)
56 (op.kind() == Token::Kind::TK_LOGICALOR && leftVal)) { // (true || expr) -> (true)
John Stiles8a9da732021-01-20 14:32:33 -050057
58 return left.clone();
John Stilesdc8ec312021-01-11 11:05:21 -050059 }
60
John Stiles8a9da732021-01-20 14:32:33 -050061 // We can't eliminate the right-side expression via short-circuit, but we might still be able to
62 // simplify away a no-op expression.
63 return eliminate_no_op_boolean(right, op, left);
John Stilesdc8ec312021-01-11 11:05:21 -050064}
65
Brian Osman21d2b6a2021-02-01 13:48:50 -050066// 'T' is the actual stored type of the literal data (SKSL_FLOAT or SKSL_INT).
67// 'U' is an unsigned version of that, used to perform addition, subtraction, and multiplication,
68// to avoid signed-integer overflow errors. This mimics the use of URESULT vs. RESULT when doing
69// scalar folding in Simplify, later in this file.
70template <typename T, typename U = T>
John Stilesdc8ec312021-01-11 11:05:21 -050071static std::unique_ptr<Expression> simplify_vector(const Context& context,
John Stilesdc8ec312021-01-11 11:05:21 -050072 const Expression& left,
John Stiles45990502021-02-16 10:55:27 -050073 Operator op,
John Stilesdc8ec312021-01-11 11:05:21 -050074 const Expression& right) {
John Stiles508eba72021-01-11 13:07:47 -050075 SkASSERT(left.type().isVector());
John Stilesdc8ec312021-01-11 11:05:21 -050076 SkASSERT(left.type() == right.type());
77 const Type& type = left.type();
78
79 // Handle boolean operations: == !=
John Stiles45990502021-02-16 10:55:27 -050080 if (op.kind() == Token::Kind::TK_EQEQ || op.kind() == Token::Kind::TK_NEQ) {
81 bool equality = (op.kind() == Token::Kind::TK_EQEQ);
John Stilesdc8ec312021-01-11 11:05:21 -050082
83 switch (left.compareConstant(right)) {
84 case Expression::ComparisonResult::kNotEqual:
85 equality = !equality;
86 [[fallthrough]];
87
88 case Expression::ComparisonResult::kEqual:
John Stiles9ce80f72021-03-11 22:35:19 -050089 return BoolLiteral::Make(context, left.fOffset, equality);
John Stilesdc8ec312021-01-11 11:05:21 -050090
91 case Expression::ComparisonResult::kUnknown:
92 return nullptr;
93 }
94 }
95
96 // Handle floating-point arithmetic: + - * /
John Stiles54f00492021-02-19 11:46:10 -050097 const auto vectorComponentwiseFold = [&](auto foldFn) -> std::unique_ptr<Expression> {
John Stilesdc8ec312021-01-11 11:05:21 -050098 const Type& componentType = type.componentType();
99 ExpressionArray args;
100 args.reserve_back(type.columns());
101 for (int i = 0; i < type.columns(); i++) {
John Stiles21a50ec2021-04-06 14:49:36 -0400102 U value = foldFn(left.getConstantSubexpression(i)->as<Literal<T>>().value(),
103 right.getConstantSubexpression(i)->as<Literal<T>>().value());
John Stiles9ce80f72021-03-11 22:35:19 -0500104 args.push_back(Literal<T>::Make(left.fOffset, value, &componentType));
John Stilesdc8ec312021-01-11 11:05:21 -0500105 }
John Stilesb0ce42d2021-04-09 10:39:42 -0400106 return ConstructorCompound::Make(context, left.fOffset, type, std::move(args));
John Stilesdc8ec312021-01-11 11:05:21 -0500107 };
108
John Stiles45990502021-02-16 10:55:27 -0500109 switch (op.kind()) {
Brian Osman21d2b6a2021-02-01 13:48:50 -0500110 case Token::Kind::TK_PLUS: return vectorComponentwiseFold([](U a, U b) { return a + b; });
111 case Token::Kind::TK_MINUS: return vectorComponentwiseFold([](U a, U b) { return a - b; });
112 case Token::Kind::TK_STAR: return vectorComponentwiseFold([](U a, U b) { return a * b; });
Ethan Nicholasc0f98152021-02-05 16:21:10 -0500113 case Token::Kind::TK_SLASH: return vectorComponentwiseFold([](T a, T b) { return a / b; });
John Stilesdc8ec312021-01-11 11:05:21 -0500114 default:
115 return nullptr;
116 }
117}
118
John Stiles8f440b42021-03-05 16:48:56 -0500119static std::unique_ptr<Expression> cast_expression(const Context& context,
120 const Expression& expr,
121 const Type& type) {
122 ExpressionArray ctorArgs;
123 ctorArgs.push_back(expr.clone());
124 std::unique_ptr<Expression> ctor = Constructor::Convert(context, expr.fOffset, type,
125 std::move(ctorArgs));
126 SkASSERT(ctor);
127 return ctor;
128}
129
John Stiles2938eea2021-04-01 18:58:25 -0400130static ConstructorSplat splat_scalar(const Expression& scalar, const Type& type) {
John Stiles508eba72021-01-11 13:07:47 -0500131 SkASSERT(type.isVector());
132 SkASSERT(type.componentType() == scalar.type());
133
John Stiles2938eea2021-04-01 18:58:25 -0400134 // Use a constructor to splat the scalar expression across a vector.
135 return ConstructorSplat{scalar.fOffset, type, scalar.clone()};
John Stiles508eba72021-01-11 13:07:47 -0500136}
137
Ethan Nicholasc0f98152021-02-05 16:21:10 -0500138bool ConstantFolder::GetConstantInt(const Expression& value, SKSL_INT* out) {
John Stilese80e1692021-03-02 17:02:25 -0500139 const Expression* expr = GetConstantValueForVariable(value);
140 if (!expr->is<IntLiteral>()) {
141 return false;
Ethan Nicholasc0f98152021-02-05 16:21:10 -0500142 }
John Stilese80e1692021-03-02 17:02:25 -0500143 *out = expr->as<IntLiteral>().value();
144 return true;
Ethan Nicholasc0f98152021-02-05 16:21:10 -0500145}
146
147bool ConstantFolder::GetConstantFloat(const Expression& value, SKSL_FLOAT* out) {
John Stilese80e1692021-03-02 17:02:25 -0500148 const Expression* expr = GetConstantValueForVariable(value);
149 if (!expr->is<FloatLiteral>()) {
150 return false;
Ethan Nicholasc0f98152021-02-05 16:21:10 -0500151 }
John Stilese80e1692021-03-02 17:02:25 -0500152 *out = expr->as<FloatLiteral>().value();
153 return true;
Ethan Nicholasc0f98152021-02-05 16:21:10 -0500154}
155
John Stiles8f440b42021-03-05 16:48:56 -0500156static bool is_constant_scalar_value(const Expression& inExpr, float match) {
157 const Expression* expr = ConstantFolder::GetConstantValueForVariable(inExpr);
158 return (expr->is<IntLiteral>() && expr->as<IntLiteral>().value() == match) ||
159 (expr->is<FloatLiteral>() && expr->as<FloatLiteral>().value() == match);
160}
161
Ethan Nicholasc0f98152021-02-05 16:21:10 -0500162static bool contains_constant_zero(const Expression& expr) {
John Stiles2938eea2021-04-01 18:58:25 -0400163 if (expr.isAnyConstructor()) {
164 for (const auto& arg : expr.asAnyConstructor().argumentSpan()) {
Ethan Nicholasc0f98152021-02-05 16:21:10 -0500165 if (contains_constant_zero(*arg)) {
166 return true;
167 }
168 }
169 return false;
170 }
John Stiles8f440b42021-03-05 16:48:56 -0500171 return is_constant_scalar_value(expr, 0.0);
172}
173
174static bool is_constant_value(const Expression& expr, float value) {
175 // This check only supports scalars and vectors (and in particular, not matrices).
176 SkASSERT(expr.type().isScalar() || expr.type().isVector());
177
John Stiles2938eea2021-04-01 18:58:25 -0400178 if (expr.isAnyConstructor()) {
179 for (const auto& arg : expr.asAnyConstructor().argumentSpan()) {
John Stiles8f440b42021-03-05 16:48:56 -0500180 if (!is_constant_value(*arg, value)) {
181 return false;
182 }
183 }
184 return true;
185 }
186 return is_constant_scalar_value(expr, value);
Ethan Nicholasc0f98152021-02-05 16:21:10 -0500187}
188
John Stiles45990502021-02-16 10:55:27 -0500189bool ConstantFolder::ErrorOnDivideByZero(const Context& context, int offset, Operator op,
Ethan Nicholasc0f98152021-02-05 16:21:10 -0500190 const Expression& right) {
John Stiles45990502021-02-16 10:55:27 -0500191 switch (op.kind()) {
Ethan Nicholasc0f98152021-02-05 16:21:10 -0500192 case Token::Kind::TK_SLASH:
193 case Token::Kind::TK_SLASHEQ:
194 case Token::Kind::TK_PERCENT:
195 case Token::Kind::TK_PERCENTEQ:
196 if (contains_constant_zero(right)) {
197 context.fErrors.error(offset, "division by zero");
198 return true;
199 }
200 return false;
201 default:
202 return false;
203 }
204}
205
John Stilese80e1692021-03-02 17:02:25 -0500206const Expression* ConstantFolder::GetConstantValueForVariable(const Expression& inExpr) {
207 for (const Expression* expr = &inExpr;;) {
208 if (!expr->is<VariableReference>()) {
209 break;
210 }
211 const VariableReference& varRef = expr->as<VariableReference>();
212 if (varRef.refKind() != VariableRefKind::kRead) {
213 break;
214 }
215 const Variable& var = *varRef.variable();
216 if (!(var.modifiers().fFlags & Modifiers::kConst_Flag)) {
217 break;
218 }
219 expr = var.initialValue();
John Stilesca65f8f2021-03-29 17:14:39 -0400220 if (!expr) {
221 SkDEBUGFAILF("found a const variable without an initial value (%s)",
222 var.description().c_str());
223 break;
224 }
John Stilese80e1692021-03-02 17:02:25 -0500225 if (expr->isCompileTimeConstant()) {
226 return expr;
227 }
228 if (!expr->is<VariableReference>()) {
229 break;
230 }
231 }
232 // We didn't find a compile-time constant at the end. Return the expression as-is.
233 return &inExpr;
234}
235
John Stilesffba5242021-05-07 10:50:22 -0400236std::unique_ptr<Expression> ConstantFolder::MakeConstantValueForVariable(
237 std::unique_ptr<Expression> expr) {
238 const Expression* constantExpr = GetConstantValueForVariable(*expr);
239 if (constantExpr != expr.get()) {
240 expr = constantExpr->clone();
241 }
242 return expr;
243}
244
John Stiles8f440b42021-03-05 16:48:56 -0500245static std::unique_ptr<Expression> simplify_no_op_arithmetic(const Context& context,
246 const Expression& left,
247 Operator op,
248 const Expression& right,
249 const Type& resultType) {
250 switch (op.kind()) {
251 case Token::Kind::TK_PLUS:
252 if (is_constant_value(right, 0.0)) { // x + 0
253 return cast_expression(context, left, resultType);
254 }
255 if (is_constant_value(left, 0.0)) { // 0 + x
256 return cast_expression(context, right, resultType);
257 }
258 break;
259
260 case Token::Kind::TK_STAR:
261 if (is_constant_value(right, 1.0)) { // x * 1
262 return cast_expression(context, left, resultType);
263 }
264 if (is_constant_value(left, 1.0)) { // 1 * x
265 return cast_expression(context, right, resultType);
266 }
267 if (is_constant_value(right, 0.0) && !left.hasSideEffects()) { // x * 0
268 return cast_expression(context, right, resultType);
269 }
270 if (is_constant_value(left, 0.0) && !right.hasSideEffects()) { // 0 * x
271 return cast_expression(context, left, resultType);
272 }
273 break;
274
275 case Token::Kind::TK_MINUS:
276 if (is_constant_value(right, 0.0)) { // x - 0
277 return cast_expression(context, left, resultType);
278 }
279 if (is_constant_value(left, 0.0)) { // 0 - x (to `-x`)
280 return PrefixExpression::Make(context, Token::Kind::TK_MINUS,
281 cast_expression(context, right, resultType));
282 }
283 break;
284
285 case Token::Kind::TK_SLASH:
286 if (is_constant_value(right, 1.0)) { // x / 1
287 return cast_expression(context, left, resultType);
288 }
289 if (is_constant_value(left, 0.0) &&
290 !is_constant_value(right, 0.0) &&
291 !right.hasSideEffects()) { // 0 / x (where x is not 0)
292 return cast_expression(context, left, resultType);
293 }
294 break;
295
296 case Token::Kind::TK_PLUSEQ:
297 case Token::Kind::TK_MINUSEQ:
298 if (is_constant_value(right, 0.0)) { // x += 0, x -= 0
299 std::unique_ptr<Expression> result = cast_expression(context, left, resultType);
300 Analysis::UpdateRefKind(result.get(), VariableRefKind::kRead);
301 return result;
302 }
303 break;
304
305 case Token::Kind::TK_STAREQ:
306 case Token::Kind::TK_SLASHEQ:
307 if (is_constant_value(right, 1.0)) { // x *= 1, x /= 1
308 std::unique_ptr<Expression> result = cast_expression(context, left, resultType);
309 Analysis::UpdateRefKind(result.get(), VariableRefKind::kRead);
310 return result;
311 }
312 break;
313
314 default:
315 break;
316 }
317
318 return nullptr;
319}
320
John Stilesafaddc92021-05-26 22:21:42 -0400321template <typename T>
322static std::unique_ptr<Expression> fold_float_expression(int offset,
323 T result,
324 const Type* resultType) {
325 // If constant-folding this expression would generate a NaN/infinite result, leave it as-is.
326 if constexpr (std::is_floating_point<T>::value) {
327 if (!std::isfinite(result)) {
328 return nullptr;
329 }
330 }
331
332 return Literal<T>::Make(offset, result, resultType);
333}
334
John Stilesdc8ec312021-01-11 11:05:21 -0500335std::unique_ptr<Expression> ConstantFolder::Simplify(const Context& context,
Ethan Nicholasc0f98152021-02-05 16:21:10 -0500336 int offset,
John Stilese80e1692021-03-02 17:02:25 -0500337 const Expression& leftExpr,
John Stiles45990502021-02-16 10:55:27 -0500338 Operator op,
John Stiles8f440b42021-03-05 16:48:56 -0500339 const Expression& rightExpr,
340 const Type& resultType) {
John Stilesbe6cbf32021-03-09 20:15:17 -0500341 // When optimization is enabled, replace constant variables with trivial initial-values.
342 const Expression* left;
343 const Expression* right;
344 if (context.fConfig->fSettings.fOptimize) {
345 left = GetConstantValueForVariable(leftExpr);
346 right = GetConstantValueForVariable(rightExpr);
347 } else {
348 left = &leftExpr;
349 right = &rightExpr;
350 }
John Stilese80e1692021-03-02 17:02:25 -0500351
John Stilesabc3b782021-02-05 10:07:19 -0500352 // If this is the comma operator, the left side is evaluated but not otherwise used in any way.
353 // So if the left side has no side effects, it can just be eliminated entirely.
John Stilese80e1692021-03-02 17:02:25 -0500354 if (op.kind() == Token::Kind::TK_COMMA && !left->hasSideEffects()) {
355 return right->clone();
John Stilesabc3b782021-02-05 10:07:19 -0500356 }
357
John Stiles95d0bad2021-03-01 17:02:28 -0500358 // If this is the assignment operator, and both sides are the same trivial expression, this is
359 // self-assignment (i.e., `var = var`) and can be reduced to just a variable reference (`var`).
360 // This can happen when other parts of the assignment are optimized away.
John Stiles5676c572021-03-08 17:10:52 -0500361 if (op.kind() == Token::Kind::TK_EQ && Analysis::IsSameExpressionTree(*left, *right)) {
John Stilese80e1692021-03-02 17:02:25 -0500362 return right->clone();
John Stiles95d0bad2021-03-01 17:02:28 -0500363 }
364
John Stiles8a9da732021-01-20 14:32:33 -0500365 // Simplify the expression when both sides are constant Boolean literals.
John Stilese80e1692021-03-02 17:02:25 -0500366 if (left->is<BoolLiteral>() && right->is<BoolLiteral>()) {
367 bool leftVal = left->as<BoolLiteral>().value();
368 bool rightVal = right->as<BoolLiteral>().value();
John Stilesdc8ec312021-01-11 11:05:21 -0500369 bool result;
John Stiles45990502021-02-16 10:55:27 -0500370 switch (op.kind()) {
John Stilesdc8ec312021-01-11 11:05:21 -0500371 case Token::Kind::TK_LOGICALAND: result = leftVal && rightVal; break;
372 case Token::Kind::TK_LOGICALOR: result = leftVal || rightVal; break;
373 case Token::Kind::TK_LOGICALXOR: result = leftVal ^ rightVal; break;
John Stiles26fdcbb2021-01-19 19:00:31 -0500374 case Token::Kind::TK_EQEQ: result = leftVal == rightVal; break;
375 case Token::Kind::TK_NEQ: result = leftVal != rightVal; break;
John Stilesdc8ec312021-01-11 11:05:21 -0500376 default: return nullptr;
377 }
John Stiles9ce80f72021-03-11 22:35:19 -0500378 return BoolLiteral::Make(context, offset, result);
John Stilesdc8ec312021-01-11 11:05:21 -0500379 }
380
John Stiles8a9da732021-01-20 14:32:33 -0500381 // If the left side is a Boolean literal, apply short-circuit optimizations.
John Stilese80e1692021-03-02 17:02:25 -0500382 if (left->is<BoolLiteral>()) {
383 return short_circuit_boolean(*left, op, *right);
John Stiles8a9da732021-01-20 14:32:33 -0500384 }
385
386 // If the right side is a Boolean literal...
John Stilese80e1692021-03-02 17:02:25 -0500387 if (right->is<BoolLiteral>()) {
John Stiles8a9da732021-01-20 14:32:33 -0500388 // ... and the left side has no side effects...
John Stilese80e1692021-03-02 17:02:25 -0500389 if (!left->hasSideEffects()) {
John Stiles8a9da732021-01-20 14:32:33 -0500390 // We can reverse the expressions and short-circuit optimizations are still valid.
John Stilese80e1692021-03-02 17:02:25 -0500391 return short_circuit_boolean(*right, op, *left);
John Stiles8a9da732021-01-20 14:32:33 -0500392 }
393
394 // We can't use short-circuiting, but we can still optimize away no-op Boolean expressions.
John Stilese80e1692021-03-02 17:02:25 -0500395 return eliminate_no_op_boolean(*left, op, *right);
John Stiles8a9da732021-01-20 14:32:33 -0500396 }
397
John Stiles5676c572021-03-08 17:10:52 -0500398 if (op.kind() == Token::Kind::TK_EQEQ && Analysis::IsSameExpressionTree(*left, *right)) {
399 // With == comparison, if both sides are the same trivial expression, this is self-
400 // comparison and is always true. (We are not concerned with NaN.)
John Stiles9ce80f72021-03-11 22:35:19 -0500401 return BoolLiteral::Make(context, leftExpr.fOffset, /*value=*/true);
John Stiles5676c572021-03-08 17:10:52 -0500402 }
403
404 if (op.kind() == Token::Kind::TK_NEQ && Analysis::IsSameExpressionTree(*left, *right)) {
405 // With != comparison, if both sides are the same trivial expression, this is self-
406 // comparison and is always false. (We are not concerned with NaN.)
John Stiles9ce80f72021-03-11 22:35:19 -0500407 return BoolLiteral::Make(context, leftExpr.fOffset, /*value=*/false);
John Stiles5676c572021-03-08 17:10:52 -0500408 }
409
John Stilese80e1692021-03-02 17:02:25 -0500410 if (ErrorOnDivideByZero(context, offset, op, *right)) {
Ethan Nicholasc0f98152021-02-05 16:21:10 -0500411 return nullptr;
412 }
413
John Stiles8f440b42021-03-05 16:48:56 -0500414 // Optimize away no-op arithmetic like `x * 1`, `x *= 1`, `x + 0`, `x * 0`, `0 / x`, etc.
415 const Type& leftType = left->type();
416 const Type& rightType = right->type();
417 if ((leftType.isScalar() || leftType.isVector()) &&
418 (rightType.isScalar() || rightType.isVector())) {
419 std::unique_ptr<Expression> expr = simplify_no_op_arithmetic(context, *left, op, *right,
420 resultType);
421 if (expr) {
422 return expr;
423 }
424 }
425
426 // Other than the cases above, constant folding requires both sides to be constant.
John Stilese80e1692021-03-02 17:02:25 -0500427 if (!left->isCompileTimeConstant() || !right->isCompileTimeConstant()) {
John Stiles8a9da732021-01-20 14:32:33 -0500428 return nullptr;
429 }
430
John Stilesdc8ec312021-01-11 11:05:21 -0500431 // Note that we expressly do not worry about precision and overflow here -- we use the maximum
432 // precision to calculate the results and hope the result makes sense.
John Stiles9ce80f72021-03-11 22:35:19 -0500433 // TODO(skia:10932): detect and handle integer overflow properly.
Brian Osman21d2b6a2021-02-01 13:48:50 -0500434 using SKSL_UINT = uint64_t;
John Stilese80e1692021-03-02 17:02:25 -0500435 if (left->is<IntLiteral>() && right->is<IntLiteral>()) {
John Stilesafaddc92021-05-26 22:21:42 -0400436 #define RESULT(t, op) t ## Literal::Make(offset, leftVal op rightVal, &resultType)
437 #define URESULT(t, op) t ## Literal::Make(offset, (SKSL_UINT)(leftVal) op \
438 (SKSL_UINT)(rightVal), &resultType)
John Stilese80e1692021-03-02 17:02:25 -0500439 SKSL_INT leftVal = left->as<IntLiteral>().value();
440 SKSL_INT rightVal = right->as<IntLiteral>().value();
John Stiles45990502021-02-16 10:55:27 -0500441 switch (op.kind()) {
John Stilesdc8ec312021-01-11 11:05:21 -0500442 case Token::Kind::TK_PLUS: return URESULT(Int, +);
443 case Token::Kind::TK_MINUS: return URESULT(Int, -);
444 case Token::Kind::TK_STAR: return URESULT(Int, *);
445 case Token::Kind::TK_SLASH:
446 if (leftVal == std::numeric_limits<SKSL_INT>::min() && rightVal == -1) {
Ethan Nicholasc0f98152021-02-05 16:21:10 -0500447 context.fErrors.error(offset, "arithmetic overflow");
John Stilesdc8ec312021-01-11 11:05:21 -0500448 return nullptr;
449 }
450 return RESULT(Int, /);
451 case Token::Kind::TK_PERCENT:
452 if (leftVal == std::numeric_limits<SKSL_INT>::min() && rightVal == -1) {
Ethan Nicholasc0f98152021-02-05 16:21:10 -0500453 context.fErrors.error(offset, "arithmetic overflow");
John Stilesdc8ec312021-01-11 11:05:21 -0500454 return nullptr;
455 }
456 return RESULT(Int, %);
457 case Token::Kind::TK_BITWISEAND: return RESULT(Int, &);
458 case Token::Kind::TK_BITWISEOR: return RESULT(Int, |);
459 case Token::Kind::TK_BITWISEXOR: return RESULT(Int, ^);
460 case Token::Kind::TK_EQEQ: return RESULT(Bool, ==);
461 case Token::Kind::TK_NEQ: return RESULT(Bool, !=);
462 case Token::Kind::TK_GT: return RESULT(Bool, >);
463 case Token::Kind::TK_GTEQ: return RESULT(Bool, >=);
464 case Token::Kind::TK_LT: return RESULT(Bool, <);
465 case Token::Kind::TK_LTEQ: return RESULT(Bool, <=);
466 case Token::Kind::TK_SHL:
467 if (rightVal >= 0 && rightVal <= 31) {
Brian Osmana7eb6812021-02-01 11:43:05 -0500468 // Left-shifting a negative (or really, any signed) value is undefined behavior
469 // in C++, but not GLSL. Do the shift on unsigned values, to avoid UBSAN.
470 return URESULT(Int, <<);
John Stilesdc8ec312021-01-11 11:05:21 -0500471 }
Ethan Nicholasc0f98152021-02-05 16:21:10 -0500472 context.fErrors.error(offset, "shift value out of range");
John Stilesdc8ec312021-01-11 11:05:21 -0500473 return nullptr;
474 case Token::Kind::TK_SHR:
475 if (rightVal >= 0 && rightVal <= 31) {
476 return RESULT(Int, >>);
477 }
Ethan Nicholasc0f98152021-02-05 16:21:10 -0500478 context.fErrors.error(offset, "shift value out of range");
John Stilesdc8ec312021-01-11 11:05:21 -0500479 return nullptr;
480
481 default:
482 return nullptr;
483 }
John Stilesafaddc92021-05-26 22:21:42 -0400484 #undef RESULT
485 #undef URESULT
John Stilesdc8ec312021-01-11 11:05:21 -0500486 }
487
488 // Perform constant folding on pairs of floating-point literals.
John Stilese80e1692021-03-02 17:02:25 -0500489 if (left->is<FloatLiteral>() && right->is<FloatLiteral>()) {
490 SKSL_FLOAT leftVal = left->as<FloatLiteral>().value();
491 SKSL_FLOAT rightVal = right->as<FloatLiteral>().value();
John Stilesafaddc92021-05-26 22:21:42 -0400492
493 #define RESULT(Op) fold_float_expression(offset, leftVal Op rightVal, &resultType)
John Stiles45990502021-02-16 10:55:27 -0500494 switch (op.kind()) {
John Stilesafaddc92021-05-26 22:21:42 -0400495 case Token::Kind::TK_PLUS: return RESULT(+);
496 case Token::Kind::TK_MINUS: return RESULT(-);
497 case Token::Kind::TK_STAR: return RESULT(*);
498 case Token::Kind::TK_SLASH: return RESULT(/);
499 case Token::Kind::TK_EQEQ: return RESULT(==);
500 case Token::Kind::TK_NEQ: return RESULT(!=);
501 case Token::Kind::TK_GT: return RESULT(>);
502 case Token::Kind::TK_GTEQ: return RESULT(>=);
503 case Token::Kind::TK_LT: return RESULT(<);
504 case Token::Kind::TK_LTEQ: return RESULT(<=);
505 default: return nullptr;
John Stilesdc8ec312021-01-11 11:05:21 -0500506 }
John Stilesafaddc92021-05-26 22:21:42 -0400507 #undef RESULT
John Stilesdc8ec312021-01-11 11:05:21 -0500508 }
509
510 // Perform constant folding on pairs of vectors.
John Stilesdc8ec312021-01-11 11:05:21 -0500511 if (leftType.isVector() && leftType == rightType) {
512 if (leftType.componentType().isFloat()) {
John Stilese80e1692021-03-02 17:02:25 -0500513 return simplify_vector<SKSL_FLOAT>(context, *left, op, *right);
John Stilesdc8ec312021-01-11 11:05:21 -0500514 }
515 if (leftType.componentType().isInteger()) {
John Stilese80e1692021-03-02 17:02:25 -0500516 return simplify_vector<SKSL_INT, SKSL_UINT>(context, *left, op, *right);
John Stilesdc8ec312021-01-11 11:05:21 -0500517 }
518 return nullptr;
519 }
520
John Stiles508eba72021-01-11 13:07:47 -0500521 // Perform constant folding on vectors against scalars, e.g.: half4(2) + 2
522 if (leftType.isVector() && leftType.componentType() == rightType) {
523 if (rightType.isFloat()) {
John Stilese80e1692021-03-02 17:02:25 -0500524 return simplify_vector<SKSL_FLOAT>(context, *left, op,
525 splat_scalar(*right, left->type()));
John Stiles508eba72021-01-11 13:07:47 -0500526 }
527 if (rightType.isInteger()) {
John Stilese80e1692021-03-02 17:02:25 -0500528 return simplify_vector<SKSL_INT, SKSL_UINT>(context, *left, op,
529 splat_scalar(*right, left->type()));
John Stiles508eba72021-01-11 13:07:47 -0500530 }
531 return nullptr;
532 }
533
534 // Perform constant folding on scalars against vectors, e.g.: 2 + half4(2)
535 if (rightType.isVector() && rightType.componentType() == leftType) {
536 if (leftType.isFloat()) {
John Stilese80e1692021-03-02 17:02:25 -0500537 return simplify_vector<SKSL_FLOAT>(context, splat_scalar(*left, right->type()), op,
538 *right);
John Stiles508eba72021-01-11 13:07:47 -0500539 }
540 if (leftType.isInteger()) {
John Stilese80e1692021-03-02 17:02:25 -0500541 return simplify_vector<SKSL_INT, SKSL_UINT>(context, splat_scalar(*left, right->type()),
542 op, *right);
John Stiles508eba72021-01-11 13:07:47 -0500543 }
544 return nullptr;
545 }
546
John Stiles22a54542021-03-31 11:33:48 -0400547 // Perform constant folding on pairs of matrices or arrays.
548 if ((leftType.isMatrix() && rightType.isMatrix()) ||
549 (leftType.isArray() && rightType.isArray())) {
John Stilesdc8ec312021-01-11 11:05:21 -0500550 bool equality;
John Stiles45990502021-02-16 10:55:27 -0500551 switch (op.kind()) {
John Stilesdc8ec312021-01-11 11:05:21 -0500552 case Token::Kind::TK_EQEQ:
553 equality = true;
554 break;
555 case Token::Kind::TK_NEQ:
556 equality = false;
557 break;
558 default:
559 return nullptr;
560 }
561
John Stilese80e1692021-03-02 17:02:25 -0500562 switch (left->compareConstant(*right)) {
John Stilesdc8ec312021-01-11 11:05:21 -0500563 case Expression::ComparisonResult::kNotEqual:
564 equality = !equality;
565 [[fallthrough]];
566
567 case Expression::ComparisonResult::kEqual:
John Stiles9ce80f72021-03-11 22:35:19 -0500568 return BoolLiteral::Make(context, offset, equality);
John Stilesdc8ec312021-01-11 11:05:21 -0500569
570 case Expression::ComparisonResult::kUnknown:
571 return nullptr;
572 }
573 }
574
575 // We aren't able to constant-fold.
John Stilesdc8ec312021-01-11 11:05:21 -0500576 return nullptr;
577}
578
579} // namespace SkSL