1 /*
2 * Copyright 2021 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/ir/SkSLConstructorArrayCast.h"
9
10 #include "include/core/SkSpan.h"
11 #include "include/core/SkTypes.h"
12 #include "src/sksl/SkSLAnalysis.h"
13 #include "src/sksl/SkSLConstantFolder.h"
14 #include "src/sksl/SkSLDefines.h"
15 #include "src/sksl/ir/SkSLConstructorArray.h"
16 #include "src/sksl/ir/SkSLConstructorCompoundCast.h"
17 #include "src/sksl/ir/SkSLConstructorScalarCast.h"
18 #include "src/sksl/ir/SkSLType.h"
19
20 namespace SkSL {
21
cast_constant_array(const Context & context,Position pos,const Type & destType,std::unique_ptr<Expression> constCtor)22 static std::unique_ptr<Expression> cast_constant_array(const Context& context,
23 Position pos,
24 const Type& destType,
25 std::unique_ptr<Expression> constCtor) {
26 const Type& scalarType = destType.componentType();
27
28 // Create a ConstructorArray(...) which typecasts each argument inside.
29 auto inputArgs = constCtor->as<ConstructorArray>().argumentSpan();
30 ExpressionArray typecastArgs;
31 typecastArgs.reserve_exact(inputArgs.size());
32 for (std::unique_ptr<Expression>& arg : inputArgs) {
33 Position argPos = arg->fPosition;
34 if (arg->type().isScalar()) {
35 typecastArgs.push_back(ConstructorScalarCast::Make(context, argPos, scalarType,
36 std::move(arg)));
37 } else {
38 typecastArgs.push_back(ConstructorCompoundCast::Make(context, argPos, scalarType,
39 std::move(arg)));
40 }
41 }
42
43 return ConstructorArray::Make(context, pos, destType, std::move(typecastArgs));
44 }
45
Make(const Context & context,Position pos,const Type & type,std::unique_ptr<Expression> arg)46 std::unique_ptr<Expression> ConstructorArrayCast::Make(const Context& context,
47 Position pos,
48 const Type& type,
49 std::unique_ptr<Expression> arg) {
50 // Only arrays of the same size are allowed.
51 SkASSERT(type.isArray());
52 SkASSERT(type.isAllowedInES2(context));
53 SkASSERT(arg->type().isArray());
54 SkASSERT(type.columns() == arg->type().columns());
55
56 // If this is a no-op cast, return the expression as-is.
57 if (type.matches(arg->type())) {
58 arg->fPosition = pos;
59 return arg;
60 }
61
62 // Look up the value of constant variables. This allows constant-expressions like `myArray` to
63 // be replaced with the compile-time constant `int[2](0, 1)`.
64 arg = ConstantFolder::MakeConstantValueForVariable(pos, std::move(arg));
65
66 // We can cast a vector of compile-time constants at compile-time.
67 if (Analysis::IsCompileTimeConstant(*arg)) {
68 return cast_constant_array(context, pos, type, std::move(arg));
69 }
70 return std::make_unique<ConstructorArrayCast>(pos, type, std::move(arg));
71 }
72
73 } // namespace SkSL
74