blob: a59343d0a4c41db4f7962db8abde38415fe049c1 [file] [log] [blame]
ethannicholasb3058bd2016-07-01 08:22:01 -07001/*
2 * Copyright 2016 Google Inc.
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
Mike Klein6ad99092016-10-26 10:35:22 -04007
Mike Kleinc0bd9f92019-04-23 12:05:21 -05008#include "src/sksl/SkSLCompiler.h"
ethannicholasb3058bd2016-07-01 08:22:01 -07009
Mike Kleinc0bd9f92019-04-23 12:05:21 -050010#include "src/sksl/SkSLByteCodeGenerator.h"
11#include "src/sksl/SkSLCFGGenerator.h"
12#include "src/sksl/SkSLCPPCodeGenerator.h"
13#include "src/sksl/SkSLGLSLCodeGenerator.h"
14#include "src/sksl/SkSLHCodeGenerator.h"
15#include "src/sksl/SkSLIRGenerator.h"
16#include "src/sksl/SkSLMetalCodeGenerator.h"
17#include "src/sksl/SkSLPipelineStageCodeGenerator.h"
18#include "src/sksl/SkSLSPIRVCodeGenerator.h"
Brian Osmanc0243912020-02-19 15:35:26 -050019#include "src/sksl/SkSLSPIRVtoHLSL.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050020#include "src/sksl/ir/SkSLEnum.h"
21#include "src/sksl/ir/SkSLExpression.h"
22#include "src/sksl/ir/SkSLExpressionStatement.h"
23#include "src/sksl/ir/SkSLFunctionCall.h"
24#include "src/sksl/ir/SkSLIntLiteral.h"
25#include "src/sksl/ir/SkSLModifiersDeclaration.h"
26#include "src/sksl/ir/SkSLNop.h"
27#include "src/sksl/ir/SkSLSymbolTable.h"
28#include "src/sksl/ir/SkSLTernaryExpression.h"
29#include "src/sksl/ir/SkSLUnresolvedFunction.h"
30#include "src/sksl/ir/SkSLVarDeclarations.h"
ethannicholasb3058bd2016-07-01 08:22:01 -070031
Ethan Nicholasa11035b2019-11-26 16:27:47 -050032#if !defined(SKSL_STANDALONE) & SK_SUPPORT_GPU
33#include "include/gpu/GrContextOptions.h"
34#include "src/gpu/GrShaderCaps.h"
35#endif
36
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -040037#ifdef SK_ENABLE_SPIRV_VALIDATION
38#include "spirv-tools/libspirv.hpp"
39#endif
40
ethannicholasb3058bd2016-07-01 08:22:01 -070041// include the built-in shader symbols as static strings
42
Ethan Nicholas79707652017-11-16 11:20:11 -050043#define STRINGIFY(x) #x
44
Ethan Nicholas8da1e652019-05-24 11:01:59 -040045static const char* SKSL_GPU_INCLUDE =
46#include "sksl_gpu.inc"
47;
48
Brian Salomonf8c187c2019-12-19 14:41:57 -050049static const char* SKSL_BLEND_INCLUDE =
50#include "sksl_blend.inc"
51;
52
Ethan Nicholas8da1e652019-05-24 11:01:59 -040053static const char* SKSL_INTERP_INCLUDE =
54#include "sksl_interp.inc"
ethannicholasb3058bd2016-07-01 08:22:01 -070055;
56
ethannicholas5961bc92016-10-12 06:39:56 -070057static const char* SKSL_VERT_INCLUDE =
Ben Wagnera56c4d22018-01-24 17:32:17 -050058#include "sksl_vert.inc"
ethannicholasb3058bd2016-07-01 08:22:01 -070059;
60
ethannicholas5961bc92016-10-12 06:39:56 -070061static const char* SKSL_FRAG_INCLUDE =
Ben Wagnera56c4d22018-01-24 17:32:17 -050062#include "sksl_frag.inc"
ethannicholasb3058bd2016-07-01 08:22:01 -070063;
64
Ethan Nicholas52cad152017-02-16 16:37:32 -050065static const char* SKSL_GEOM_INCLUDE =
Ben Wagnera56c4d22018-01-24 17:32:17 -050066#include "sksl_geom.inc"
Ethan Nicholas52cad152017-02-16 16:37:32 -050067;
68
Ethan Nicholas762466e2017-06-29 10:03:38 -040069static const char* SKSL_FP_INCLUDE =
Ben Wagnera56c4d22018-01-24 17:32:17 -050070#include "sksl_enums.inc"
71#include "sksl_fp.inc"
Ethan Nicholas762466e2017-06-29 10:03:38 -040072;
73
Ethan Nicholas8da1e652019-05-24 11:01:59 -040074static const char* SKSL_PIPELINE_INCLUDE =
75#include "sksl_pipeline.inc"
Ethan Nicholas0d997662019-04-08 09:46:01 -040076;
77
ethannicholasb3058bd2016-07-01 08:22:01 -070078namespace SkSL {
79
Ethan Nicholasdb80f692019-11-22 14:06:12 -050080static void grab_intrinsics(std::vector<std::unique_ptr<ProgramElement>>* src,
Brian Osman08f986d2020-05-13 17:06:46 -040081 std::map<String, std::pair<std::unique_ptr<ProgramElement>, bool>>* target) {
82 for (auto iter = src->begin(); iter != src->end(); ) {
83 std::unique_ptr<ProgramElement>& element = *iter;
Ethan Nicholasdb80f692019-11-22 14:06:12 -050084 switch (element->fKind) {
85 case ProgramElement::kFunction_Kind: {
86 FunctionDefinition& f = (FunctionDefinition&) *element;
Brian Osman08f986d2020-05-13 17:06:46 -040087 SkASSERT(f.fDeclaration.fBuiltin);
88 String key = f.fDeclaration.declaration();
89 SkASSERT(target->find(key) == target->end());
90 (*target)[key] = std::make_pair(std::move(element), false);
91 iter = src->erase(iter);
Ethan Nicholasdb80f692019-11-22 14:06:12 -050092 break;
93 }
94 case ProgramElement::kEnum_Kind: {
95 Enum& e = (Enum&) *element;
96 StringFragment name = e.fTypeName;
97 SkASSERT(target->find(name) == target->end());
98 (*target)[name] = std::make_pair(std::move(element), false);
Brian Osman08f986d2020-05-13 17:06:46 -040099 iter = src->erase(iter);
Ethan Nicholasdb80f692019-11-22 14:06:12 -0500100 break;
101 }
102 default:
103 printf("unsupported include file element\n");
104 SkASSERT(false);
105 }
106 }
107}
108
109
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -0400110Compiler::Compiler(Flags flags)
111: fFlags(flags)
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400112, fContext(new Context())
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -0400113, fErrorCount(0) {
Ethan Nicholas8feeff92017-03-30 14:11:58 -0400114 auto types = std::shared_ptr<SymbolTable>(new SymbolTable(this));
115 auto symbols = std::shared_ptr<SymbolTable>(new SymbolTable(types, this));
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400116 fIRGenerator = new IRGenerator(fContext.get(), symbols, *this);
ethannicholasb3058bd2016-07-01 08:22:01 -0700117 fTypes = types;
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400118 #define ADD_TYPE(t) types->addWithoutOwnership(fContext->f ## t ## _Type->fName, \
119 fContext->f ## t ## _Type.get())
ethannicholasb3058bd2016-07-01 08:22:01 -0700120 ADD_TYPE(Void);
121 ADD_TYPE(Float);
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400122 ADD_TYPE(Float2);
123 ADD_TYPE(Float3);
124 ADD_TYPE(Float4);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -0400125 ADD_TYPE(Half);
126 ADD_TYPE(Half2);
127 ADD_TYPE(Half3);
128 ADD_TYPE(Half4);
ethannicholasb3058bd2016-07-01 08:22:01 -0700129 ADD_TYPE(Int);
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400130 ADD_TYPE(Int2);
131 ADD_TYPE(Int3);
132 ADD_TYPE(Int4);
ethannicholasb3058bd2016-07-01 08:22:01 -0700133 ADD_TYPE(UInt);
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400134 ADD_TYPE(UInt2);
135 ADD_TYPE(UInt3);
136 ADD_TYPE(UInt4);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -0400137 ADD_TYPE(Short);
138 ADD_TYPE(Short2);
139 ADD_TYPE(Short3);
140 ADD_TYPE(Short4);
141 ADD_TYPE(UShort);
142 ADD_TYPE(UShort2);
143 ADD_TYPE(UShort3);
144 ADD_TYPE(UShort4);
Ruiqi Maob609e6d2018-07-17 10:19:38 -0400145 ADD_TYPE(Byte);
146 ADD_TYPE(Byte2);
147 ADD_TYPE(Byte3);
148 ADD_TYPE(Byte4);
149 ADD_TYPE(UByte);
150 ADD_TYPE(UByte2);
151 ADD_TYPE(UByte3);
152 ADD_TYPE(UByte4);
ethannicholasb3058bd2016-07-01 08:22:01 -0700153 ADD_TYPE(Bool);
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400154 ADD_TYPE(Bool2);
155 ADD_TYPE(Bool3);
156 ADD_TYPE(Bool4);
157 ADD_TYPE(Float2x2);
158 ADD_TYPE(Float2x3);
159 ADD_TYPE(Float2x4);
160 ADD_TYPE(Float3x2);
161 ADD_TYPE(Float3x3);
162 ADD_TYPE(Float3x4);
163 ADD_TYPE(Float4x2);
164 ADD_TYPE(Float4x3);
165 ADD_TYPE(Float4x4);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -0400166 ADD_TYPE(Half2x2);
167 ADD_TYPE(Half2x3);
168 ADD_TYPE(Half2x4);
169 ADD_TYPE(Half3x2);
170 ADD_TYPE(Half3x3);
171 ADD_TYPE(Half3x4);
172 ADD_TYPE(Half4x2);
173 ADD_TYPE(Half4x3);
174 ADD_TYPE(Half4x4);
ethannicholasb3058bd2016-07-01 08:22:01 -0700175 ADD_TYPE(GenType);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -0400176 ADD_TYPE(GenHType);
ethannicholasb3058bd2016-07-01 08:22:01 -0700177 ADD_TYPE(GenIType);
178 ADD_TYPE(GenUType);
179 ADD_TYPE(GenBType);
180 ADD_TYPE(Mat);
181 ADD_TYPE(Vec);
182 ADD_TYPE(GVec);
183 ADD_TYPE(GVec2);
184 ADD_TYPE(GVec3);
185 ADD_TYPE(GVec4);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -0400186 ADD_TYPE(HVec);
ethannicholasb3058bd2016-07-01 08:22:01 -0700187 ADD_TYPE(IVec);
188 ADD_TYPE(UVec);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -0400189 ADD_TYPE(SVec);
190 ADD_TYPE(USVec);
Ruiqi Maob609e6d2018-07-17 10:19:38 -0400191 ADD_TYPE(ByteVec);
192 ADD_TYPE(UByteVec);
ethannicholasb3058bd2016-07-01 08:22:01 -0700193 ADD_TYPE(BVec);
194
195 ADD_TYPE(Sampler1D);
196 ADD_TYPE(Sampler2D);
197 ADD_TYPE(Sampler3D);
ethannicholas5961bc92016-10-12 06:39:56 -0700198 ADD_TYPE(SamplerExternalOES);
ethannicholasb3058bd2016-07-01 08:22:01 -0700199 ADD_TYPE(SamplerCube);
200 ADD_TYPE(Sampler2DRect);
201 ADD_TYPE(Sampler1DArray);
202 ADD_TYPE(Sampler2DArray);
203 ADD_TYPE(SamplerCubeArray);
204 ADD_TYPE(SamplerBuffer);
205 ADD_TYPE(Sampler2DMS);
206 ADD_TYPE(Sampler2DMSArray);
207
Brian Salomonbf7b6202016-11-11 16:08:03 -0500208 ADD_TYPE(ISampler2D);
209
Brian Salomon2a51de82016-11-16 12:06:01 -0500210 ADD_TYPE(Image2D);
211 ADD_TYPE(IImage2D);
212
Greg Daniel64773e62016-11-22 09:44:03 -0500213 ADD_TYPE(SubpassInput);
214 ADD_TYPE(SubpassInputMS);
215
ethannicholasb3058bd2016-07-01 08:22:01 -0700216 ADD_TYPE(GSampler1D);
217 ADD_TYPE(GSampler2D);
218 ADD_TYPE(GSampler3D);
219 ADD_TYPE(GSamplerCube);
220 ADD_TYPE(GSampler2DRect);
221 ADD_TYPE(GSampler1DArray);
222 ADD_TYPE(GSampler2DArray);
223 ADD_TYPE(GSamplerCubeArray);
224 ADD_TYPE(GSamplerBuffer);
225 ADD_TYPE(GSampler2DMS);
226 ADD_TYPE(GSampler2DMSArray);
227
228 ADD_TYPE(Sampler1DShadow);
229 ADD_TYPE(Sampler2DShadow);
230 ADD_TYPE(SamplerCubeShadow);
231 ADD_TYPE(Sampler2DRectShadow);
232 ADD_TYPE(Sampler1DArrayShadow);
233 ADD_TYPE(Sampler2DArrayShadow);
234 ADD_TYPE(SamplerCubeArrayShadow);
235 ADD_TYPE(GSampler2DArrayShadow);
236 ADD_TYPE(GSamplerCubeArrayShadow);
Ethan Nicholasc9472af2017-10-10 16:30:21 -0400237 ADD_TYPE(FragmentProcessor);
Stephen Whiteff5d7a22019-07-26 17:42:06 -0400238 ADD_TYPE(Sampler);
239 ADD_TYPE(Texture2D);
ethannicholasb3058bd2016-07-01 08:22:01 -0700240
Brian Osman28590d52020-03-23 16:59:08 -0400241 StringFragment fpAliasName("shader");
242 fTypes->addWithoutOwnership(fpAliasName, fContext->fFragmentProcessor_Type.get());
243
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700244 StringFragment skCapsName("sk_Caps");
245 Variable* skCaps = new Variable(-1, Modifiers(), skCapsName,
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400246 *fContext->fSkCaps_Type, Variable::kGlobal_Storage);
Ethan Nicholas3605ace2016-11-21 15:59:48 -0500247 fIRGenerator->fSymbolTable->add(skCapsName, std::unique_ptr<Symbol>(skCaps));
248
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700249 StringFragment skArgsName("sk_Args");
250 Variable* skArgs = new Variable(-1, Modifiers(), skArgsName,
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400251 *fContext->fSkArgs_Type, Variable::kGlobal_Storage);
Ethan Nicholas762466e2017-06-29 10:03:38 -0400252 fIRGenerator->fSymbolTable->add(skArgsName, std::unique_ptr<Symbol>(skArgs));
253
Ethan Nicholasdb80f692019-11-22 14:06:12 -0500254 fIRGenerator->fIntrinsics = &fGPUIntrinsics;
255 std::vector<std::unique_ptr<ProgramElement>> gpuIntrinsics;
Ethan Nicholas8da1e652019-05-24 11:01:59 -0400256 this->processIncludeFile(Program::kFragment_Kind, SKSL_GPU_INCLUDE, strlen(SKSL_GPU_INCLUDE),
Ethan Nicholasdb80f692019-11-22 14:06:12 -0500257 symbols, &gpuIntrinsics, &fGpuSymbolTable);
Brian Salomonf8c187c2019-12-19 14:41:57 -0500258 this->processIncludeFile(Program::kFragment_Kind, SKSL_BLEND_INCLUDE,
259 strlen(SKSL_BLEND_INCLUDE), std::move(fGpuSymbolTable), &gpuIntrinsics,
260 &fGpuSymbolTable);
Ethan Nicholasdb80f692019-11-22 14:06:12 -0500261 grab_intrinsics(&gpuIntrinsics, &fGPUIntrinsics);
262 // need to hang on to the source so that FunctionDefinition.fSource pointers in this file
263 // remain valid
264 fGpuIncludeSource = std::move(fIRGenerator->fFile);
Ethan Nicholas8da1e652019-05-24 11:01:59 -0400265 this->processIncludeFile(Program::kVertex_Kind, SKSL_VERT_INCLUDE, strlen(SKSL_VERT_INCLUDE),
266 fGpuSymbolTable, &fVertexInclude, &fVertexSymbolTable);
267 this->processIncludeFile(Program::kFragment_Kind, SKSL_FRAG_INCLUDE, strlen(SKSL_FRAG_INCLUDE),
268 fGpuSymbolTable, &fFragmentInclude, &fFragmentSymbolTable);
269 this->processIncludeFile(Program::kGeometry_Kind, SKSL_GEOM_INCLUDE, strlen(SKSL_GEOM_INCLUDE),
270 fGpuSymbolTable, &fGeometryInclude, &fGeometrySymbolTable);
271 this->processIncludeFile(Program::kPipelineStage_Kind, SKSL_PIPELINE_INCLUDE,
272 strlen(SKSL_PIPELINE_INCLUDE), fGpuSymbolTable, &fPipelineInclude,
273 &fPipelineSymbolTable);
Brian Osmanb08cc022020-04-02 11:38:40 -0400274 std::vector<std::unique_ptr<ProgramElement>> interpIntrinsics;
Ethan Nicholas8da1e652019-05-24 11:01:59 -0400275 this->processIncludeFile(Program::kGeneric_Kind, SKSL_INTERP_INCLUDE,
276 strlen(SKSL_INTERP_INCLUDE), symbols, &fInterpreterInclude,
277 &fInterpreterSymbolTable);
Brian Osmanb08cc022020-04-02 11:38:40 -0400278 grab_intrinsics(&interpIntrinsics, &fInterpreterIntrinsics);
ethannicholasb3058bd2016-07-01 08:22:01 -0700279}
280
281Compiler::~Compiler() {
282 delete fIRGenerator;
283}
284
Ethan Nicholas8da1e652019-05-24 11:01:59 -0400285void Compiler::processIncludeFile(Program::Kind kind, const char* src, size_t length,
286 std::shared_ptr<SymbolTable> base,
287 std::vector<std::unique_ptr<ProgramElement>>* outElements,
288 std::shared_ptr<SymbolTable>* outSymbolTable) {
Ethan Nicholasa11035b2019-11-26 16:27:47 -0500289#ifdef SK_DEBUG
290 String source(src, length);
291 fSource = &source;
292#endif
Ethan Nicholas8da1e652019-05-24 11:01:59 -0400293 fIRGenerator->fSymbolTable = std::move(base);
294 Program::Settings settings;
Ethan Nicholasa11035b2019-11-26 16:27:47 -0500295#if !defined(SKSL_STANDALONE) & SK_SUPPORT_GPU
296 GrContextOptions opts;
297 GrShaderCaps caps(opts);
298 settings.fCaps = &caps;
299#endif
Ethan Nicholas8da1e652019-05-24 11:01:59 -0400300 fIRGenerator->start(&settings, nullptr);
301 fIRGenerator->convertProgram(kind, src, length, *fTypes, outElements);
302 if (this->fErrorCount) {
303 printf("Unexpected errors: %s\n", this->fErrorText.c_str());
304 }
305 SkASSERT(!fErrorCount);
306 fIRGenerator->fSymbolTable->markAllFunctionsBuiltin();
307 *outSymbolTable = fIRGenerator->fSymbolTable;
Ethan Nicholasa11035b2019-11-26 16:27:47 -0500308#ifdef SK_DEBUG
309 fSource = nullptr;
310#endif
Ethan Nicholas8da1e652019-05-24 11:01:59 -0400311}
312
ethannicholas22f939e2016-10-13 13:25:34 -0700313// add the definition created by assigning to the lvalue to the definition set
Ethan Nicholas86a43402017-01-19 13:32:00 -0500314void Compiler::addDefinition(const Expression* lvalue, std::unique_ptr<Expression>* expr,
315 DefinitionMap* definitions) {
ethannicholas22f939e2016-10-13 13:25:34 -0700316 switch (lvalue->fKind) {
317 case Expression::kVariableReference_Kind: {
318 const Variable& var = ((VariableReference*) lvalue)->fVariable;
319 if (var.fStorage == Variable::kLocal_Storage) {
320 (*definitions)[&var] = expr;
321 }
322 break;
323 }
324 case Expression::kSwizzle_Kind:
325 // We consider the variable written to as long as at least some of its components have
326 // been written to. This will lead to some false negatives (we won't catch it if you
327 // write to foo.x and then read foo.y), but being stricter could lead to false positives
Mike Klein6ad99092016-10-26 10:35:22 -0400328 // (we write to foo.x, and then pass foo to a function which happens to only read foo.x,
329 // but since we pass foo as a whole it is flagged as an error) unless we perform a much
ethannicholas22f939e2016-10-13 13:25:34 -0700330 // more complicated whole-program analysis. This is probably good enough.
Mike Klein6ad99092016-10-26 10:35:22 -0400331 this->addDefinition(((Swizzle*) lvalue)->fBase.get(),
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400332 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
ethannicholas22f939e2016-10-13 13:25:34 -0700333 definitions);
334 break;
335 case Expression::kIndex_Kind:
336 // see comments in Swizzle
Mike Klein6ad99092016-10-26 10:35:22 -0400337 this->addDefinition(((IndexExpression*) lvalue)->fBase.get(),
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400338 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
ethannicholas22f939e2016-10-13 13:25:34 -0700339 definitions);
340 break;
341 case Expression::kFieldAccess_Kind:
342 // see comments in Swizzle
Mike Klein6ad99092016-10-26 10:35:22 -0400343 this->addDefinition(((FieldAccess*) lvalue)->fBase.get(),
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400344 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
ethannicholas22f939e2016-10-13 13:25:34 -0700345 definitions);
346 break;
Ethan Nicholasa583b812018-01-18 13:32:11 -0500347 case Expression::kTernary_Kind:
348 // To simplify analysis, we just pretend that we write to both sides of the ternary.
349 // This allows for false positives (meaning we fail to detect that a variable might not
350 // have been assigned), but is preferable to false negatives.
351 this->addDefinition(((TernaryExpression*) lvalue)->fIfTrue.get(),
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400352 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
Ethan Nicholasa583b812018-01-18 13:32:11 -0500353 definitions);
354 this->addDefinition(((TernaryExpression*) lvalue)->fIfFalse.get(),
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400355 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
Ethan Nicholasa583b812018-01-18 13:32:11 -0500356 definitions);
357 break;
Ethan Nicholas91164d12019-05-15 15:29:54 -0400358 case Expression::kExternalValue_Kind:
359 break;
ethannicholas22f939e2016-10-13 13:25:34 -0700360 default:
361 // not an lvalue, can't happen
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400362 SkASSERT(false);
ethannicholas22f939e2016-10-13 13:25:34 -0700363 }
364}
365
366// add local variables defined by this node to the set
Mike Klein6ad99092016-10-26 10:35:22 -0400367void Compiler::addDefinitions(const BasicBlock::Node& node,
Ethan Nicholas86a43402017-01-19 13:32:00 -0500368 DefinitionMap* definitions) {
ethannicholas22f939e2016-10-13 13:25:34 -0700369 switch (node.fKind) {
370 case BasicBlock::Node::kExpression_Kind: {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400371 SkASSERT(node.expression());
Ethan Nicholascb670962017-04-20 19:31:52 -0400372 const Expression* expr = (Expression*) node.expression()->get();
Ethan Nicholas86a43402017-01-19 13:32:00 -0500373 switch (expr->fKind) {
374 case Expression::kBinary_Kind: {
375 BinaryExpression* b = (BinaryExpression*) expr;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400376 if (b->fOperator == Token::Kind::TK_EQ) {
Ethan Nicholas86a43402017-01-19 13:32:00 -0500377 this->addDefinition(b->fLeft.get(), &b->fRight, definitions);
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700378 } else if (Compiler::IsAssignment(b->fOperator)) {
Ethan Nicholas86a43402017-01-19 13:32:00 -0500379 this->addDefinition(
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400380 b->fLeft.get(),
381 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
382 definitions);
Ethan Nicholas86a43402017-01-19 13:32:00 -0500383
384 }
385 break;
ethannicholas22f939e2016-10-13 13:25:34 -0700386 }
Ethan Nicholasc6a19f12018-03-29 16:46:56 -0400387 case Expression::kFunctionCall_Kind: {
388 const FunctionCall& c = (const FunctionCall&) *expr;
389 for (size_t i = 0; i < c.fFunction.fParameters.size(); ++i) {
390 if (c.fFunction.fParameters[i]->fModifiers.fFlags & Modifiers::kOut_Flag) {
391 this->addDefinition(
392 c.fArguments[i].get(),
393 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
394 definitions);
395 }
396 }
397 break;
398 }
Ethan Nicholas86a43402017-01-19 13:32:00 -0500399 case Expression::kPrefix_Kind: {
400 const PrefixExpression* p = (PrefixExpression*) expr;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400401 if (p->fOperator == Token::Kind::TK_MINUSMINUS ||
402 p->fOperator == Token::Kind::TK_PLUSPLUS) {
Ethan Nicholas86a43402017-01-19 13:32:00 -0500403 this->addDefinition(
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400404 p->fOperand.get(),
405 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
406 definitions);
Ethan Nicholas86a43402017-01-19 13:32:00 -0500407 }
408 break;
409 }
410 case Expression::kPostfix_Kind: {
411 const PostfixExpression* p = (PostfixExpression*) expr;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400412 if (p->fOperator == Token::Kind::TK_MINUSMINUS ||
413 p->fOperator == Token::Kind::TK_PLUSPLUS) {
Ethan Nicholas86a43402017-01-19 13:32:00 -0500414 this->addDefinition(
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400415 p->fOperand.get(),
416 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
417 definitions);
Ethan Nicholas86a43402017-01-19 13:32:00 -0500418 }
419 break;
420 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400421 case Expression::kVariableReference_Kind: {
422 const VariableReference* v = (VariableReference*) expr;
423 if (v->fRefKind != VariableReference::kRead_RefKind) {
424 this->addDefinition(
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400425 v,
426 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
427 definitions);
Ethan Nicholascb670962017-04-20 19:31:52 -0400428 }
John Stiles30212b72020-06-11 17:55:07 -0400429 break;
Ethan Nicholascb670962017-04-20 19:31:52 -0400430 }
Ethan Nicholas86a43402017-01-19 13:32:00 -0500431 default:
432 break;
ethannicholas22f939e2016-10-13 13:25:34 -0700433 }
434 break;
435 }
436 case BasicBlock::Node::kStatement_Kind: {
Ethan Nicholascb670962017-04-20 19:31:52 -0400437 const Statement* stmt = (Statement*) node.statement()->get();
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000438 if (stmt->fKind == Statement::kVarDeclaration_Kind) {
439 VarDeclaration& vd = (VarDeclaration&) *stmt;
440 if (vd.fValue) {
441 (*definitions)[vd.fVar] = &vd.fValue;
ethannicholas22f939e2016-10-13 13:25:34 -0700442 }
443 }
444 break;
445 }
446 }
447}
448
449void Compiler::scanCFG(CFG* cfg, BlockId blockId, std::set<BlockId>* workList) {
450 BasicBlock& block = cfg->fBlocks[blockId];
451
452 // compute definitions after this block
Ethan Nicholas86a43402017-01-19 13:32:00 -0500453 DefinitionMap after = block.fBefore;
ethannicholas22f939e2016-10-13 13:25:34 -0700454 for (const BasicBlock::Node& n : block.fNodes) {
455 this->addDefinitions(n, &after);
456 }
457
458 // propagate definitions to exits
459 for (BlockId exitId : block.fExits) {
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400460 if (exitId == blockId) {
461 continue;
462 }
ethannicholas22f939e2016-10-13 13:25:34 -0700463 BasicBlock& exit = cfg->fBlocks[exitId];
464 for (const auto& pair : after) {
Ethan Nicholas86a43402017-01-19 13:32:00 -0500465 std::unique_ptr<Expression>* e1 = pair.second;
466 auto found = exit.fBefore.find(pair.first);
467 if (found == exit.fBefore.end()) {
468 // exit has no definition for it, just copy it
469 workList->insert(exitId);
ethannicholas22f939e2016-10-13 13:25:34 -0700470 exit.fBefore[pair.first] = e1;
471 } else {
Ethan Nicholas86a43402017-01-19 13:32:00 -0500472 // exit has a (possibly different) value already defined
473 std::unique_ptr<Expression>* e2 = exit.fBefore[pair.first];
ethannicholas22f939e2016-10-13 13:25:34 -0700474 if (e1 != e2) {
475 // definition has changed, merge and add exit block to worklist
476 workList->insert(exitId);
Ethan Nicholasaf197692017-02-27 13:26:45 -0500477 if (e1 && e2) {
478 exit.fBefore[pair.first] =
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400479 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression;
Ethan Nicholasaf197692017-02-27 13:26:45 -0500480 } else {
481 exit.fBefore[pair.first] = nullptr;
482 }
ethannicholas22f939e2016-10-13 13:25:34 -0700483 }
484 }
485 }
486 }
487}
488
489// returns a map which maps all local variables in the function to null, indicating that their value
490// is initially unknown
Ethan Nicholas86a43402017-01-19 13:32:00 -0500491static DefinitionMap compute_start_state(const CFG& cfg) {
492 DefinitionMap result;
Mike Klein6ad99092016-10-26 10:35:22 -0400493 for (const auto& block : cfg.fBlocks) {
494 for (const auto& node : block.fNodes) {
ethannicholas22f939e2016-10-13 13:25:34 -0700495 if (node.fKind == BasicBlock::Node::kStatement_Kind) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400496 SkASSERT(node.statement());
Ethan Nicholascb670962017-04-20 19:31:52 -0400497 const Statement* s = node.statement()->get();
ethannicholas22f939e2016-10-13 13:25:34 -0700498 if (s->fKind == Statement::kVarDeclarations_Kind) {
499 const VarDeclarationsStatement* vd = (const VarDeclarationsStatement*) s;
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000500 for (const auto& decl : vd->fDeclaration->fVars) {
501 if (decl->fKind == Statement::kVarDeclaration_Kind) {
502 result[((VarDeclaration&) *decl).fVar] = nullptr;
503 }
Mike Klein6ad99092016-10-26 10:35:22 -0400504 }
ethannicholas22f939e2016-10-13 13:25:34 -0700505 }
506 }
507 }
508 }
509 return result;
510}
511
Ethan Nicholascb670962017-04-20 19:31:52 -0400512/**
513 * Returns true if assigning to this lvalue has no effect.
514 */
515static bool is_dead(const Expression& lvalue) {
516 switch (lvalue.fKind) {
517 case Expression::kVariableReference_Kind:
518 return ((VariableReference&) lvalue).fVariable.dead();
519 case Expression::kSwizzle_Kind:
520 return is_dead(*((Swizzle&) lvalue).fBase);
521 case Expression::kFieldAccess_Kind:
522 return is_dead(*((FieldAccess&) lvalue).fBase);
523 case Expression::kIndex_Kind: {
524 const IndexExpression& idx = (IndexExpression&) lvalue;
Ethan Nicholas2a099da2020-01-02 14:40:54 -0500525 return is_dead(*idx.fBase) &&
526 !idx.fIndex->hasProperty(Expression::Property::kSideEffects);
Ethan Nicholascb670962017-04-20 19:31:52 -0400527 }
Ethan Nicholasa583b812018-01-18 13:32:11 -0500528 case Expression::kTernary_Kind: {
529 const TernaryExpression& t = (TernaryExpression&) lvalue;
530 return !t.fTest->hasSideEffects() && is_dead(*t.fIfTrue) && is_dead(*t.fIfFalse);
531 }
Ethan Nicholas91164d12019-05-15 15:29:54 -0400532 case Expression::kExternalValue_Kind:
533 return false;
Ethan Nicholascb670962017-04-20 19:31:52 -0400534 default:
Ethan Nicholas2a099da2020-01-02 14:40:54 -0500535#ifdef SK_DEBUG
Ethan Nicholascb670962017-04-20 19:31:52 -0400536 ABORT("invalid lvalue: %s\n", lvalue.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -0500537#endif
538 return false;
Ethan Nicholascb670962017-04-20 19:31:52 -0400539 }
540}
ethannicholas22f939e2016-10-13 13:25:34 -0700541
Ethan Nicholascb670962017-04-20 19:31:52 -0400542/**
543 * Returns true if this is an assignment which can be collapsed down to just the right hand side due
544 * to a dead target and lack of side effects on the left hand side.
545 */
546static bool dead_assignment(const BinaryExpression& b) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700547 if (!Compiler::IsAssignment(b.fOperator)) {
Ethan Nicholascb670962017-04-20 19:31:52 -0400548 return false;
549 }
550 return is_dead(*b.fLeft);
551}
552
553void Compiler::computeDataFlow(CFG* cfg) {
554 cfg->fBlocks[cfg->fStart].fBefore = compute_start_state(*cfg);
ethannicholas22f939e2016-10-13 13:25:34 -0700555 std::set<BlockId> workList;
Ethan Nicholascb670962017-04-20 19:31:52 -0400556 for (BlockId i = 0; i < cfg->fBlocks.size(); i++) {
ethannicholas22f939e2016-10-13 13:25:34 -0700557 workList.insert(i);
558 }
559 while (workList.size()) {
560 BlockId next = *workList.begin();
561 workList.erase(workList.begin());
Ethan Nicholascb670962017-04-20 19:31:52 -0400562 this->scanCFG(cfg, next, &workList);
ethannicholas22f939e2016-10-13 13:25:34 -0700563 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400564}
565
566/**
567 * Attempts to replace the expression pointed to by iter with a new one (in both the CFG and the
568 * IR). If the expression can be cleanly removed, returns true and updates the iterator to point to
569 * the newly-inserted element. Otherwise updates only the IR and returns false (and the CFG will
570 * need to be regenerated).
571 */
572bool try_replace_expression(BasicBlock* b,
573 std::vector<BasicBlock::Node>::iterator* iter,
574 std::unique_ptr<Expression>* newExpression) {
575 std::unique_ptr<Expression>* target = (*iter)->expression();
576 if (!b->tryRemoveExpression(iter)) {
577 *target = std::move(*newExpression);
578 return false;
579 }
580 *target = std::move(*newExpression);
581 return b->tryInsertExpression(iter, target);
582}
583
584/**
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400585 * Returns true if the expression is a constant numeric literal with the specified value, or a
586 * constant vector with all elements equal to the specified value.
Ethan Nicholascb670962017-04-20 19:31:52 -0400587 */
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400588bool is_constant(const Expression& expr, double value) {
Ethan Nicholascb670962017-04-20 19:31:52 -0400589 switch (expr.fKind) {
590 case Expression::kIntLiteral_Kind:
591 return ((IntLiteral&) expr).fValue == value;
592 case Expression::kFloatLiteral_Kind:
593 return ((FloatLiteral&) expr).fValue == value;
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400594 case Expression::kConstructor_Kind: {
595 Constructor& c = (Constructor&) expr;
Ethan Nicholasd188c182019-06-10 15:55:38 -0400596 bool isFloat = c.fType.columns() > 1 ? c.fType.componentType().isFloat()
597 : c.fType.isFloat();
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400598 if (c.fType.kind() == Type::kVector_Kind && c.isConstant()) {
599 for (int i = 0; i < c.fType.columns(); ++i) {
Ethan Nicholasd188c182019-06-10 15:55:38 -0400600 if (isFloat) {
601 if (c.getFVecComponent(i) != value) {
602 return false;
603 }
604 } else if (c.getIVecComponent(i) != value) {
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400605 return false;
606 }
607 }
608 return true;
609 }
610 return false;
611 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400612 default:
613 return false;
614 }
615}
616
617/**
618 * Collapses the binary expression pointed to by iter down to just the right side (in both the IR
619 * and CFG structures).
620 */
621void delete_left(BasicBlock* b,
622 std::vector<BasicBlock::Node>::iterator* iter,
623 bool* outUpdated,
624 bool* outNeedsRescan) {
625 *outUpdated = true;
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400626 std::unique_ptr<Expression>* target = (*iter)->expression();
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400627 SkASSERT((*target)->fKind == Expression::kBinary_Kind);
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400628 BinaryExpression& bin = (BinaryExpression&) **target;
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400629 SkASSERT(!bin.fLeft->hasSideEffects());
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400630 bool result;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400631 if (bin.fOperator == Token::Kind::TK_EQ) {
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400632 result = b->tryRemoveLValueBefore(iter, bin.fLeft.get());
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400633 } else {
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400634 result = b->tryRemoveExpressionBefore(iter, bin.fLeft.get());
Ethan Nicholascb670962017-04-20 19:31:52 -0400635 }
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400636 *target = std::move(bin.fRight);
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400637 if (!result) {
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400638 *outNeedsRescan = true;
639 return;
640 }
641 if (*iter == b->fNodes.begin()) {
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400642 *outNeedsRescan = true;
643 return;
644 }
645 --(*iter);
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400646 if ((*iter)->fKind != BasicBlock::Node::kExpression_Kind ||
647 (*iter)->expression() != &bin.fRight) {
648 *outNeedsRescan = true;
649 return;
650 }
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400651 *iter = b->fNodes.erase(*iter);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400652 SkASSERT((*iter)->expression() == target);
Ethan Nicholascb670962017-04-20 19:31:52 -0400653}
654
655/**
656 * Collapses the binary expression pointed to by iter down to just the left side (in both the IR and
657 * CFG structures).
658 */
659void delete_right(BasicBlock* b,
660 std::vector<BasicBlock::Node>::iterator* iter,
661 bool* outUpdated,
662 bool* outNeedsRescan) {
663 *outUpdated = true;
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400664 std::unique_ptr<Expression>* target = (*iter)->expression();
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400665 SkASSERT((*target)->fKind == Expression::kBinary_Kind);
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400666 BinaryExpression& bin = (BinaryExpression&) **target;
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400667 SkASSERT(!bin.fRight->hasSideEffects());
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400668 if (!b->tryRemoveExpressionBefore(iter, bin.fRight.get())) {
669 *target = std::move(bin.fLeft);
Ethan Nicholascb670962017-04-20 19:31:52 -0400670 *outNeedsRescan = true;
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400671 return;
Ethan Nicholascb670962017-04-20 19:31:52 -0400672 }
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400673 *target = std::move(bin.fLeft);
674 if (*iter == b->fNodes.begin()) {
675 *outNeedsRescan = true;
676 return;
677 }
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400678 --(*iter);
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400679 if (((*iter)->fKind != BasicBlock::Node::kExpression_Kind ||
680 (*iter)->expression() != &bin.fLeft)) {
681 *outNeedsRescan = true;
682 return;
683 }
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400684 *iter = b->fNodes.erase(*iter);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400685 SkASSERT((*iter)->expression() == target);
Ethan Nicholascb670962017-04-20 19:31:52 -0400686}
687
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400688/**
689 * Constructs the specified type using a single argument.
690 */
691static std::unique_ptr<Expression> construct(const Type& type, std::unique_ptr<Expression> v) {
692 std::vector<std::unique_ptr<Expression>> args;
693 args.push_back(std::move(v));
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700694 auto result = std::unique_ptr<Expression>(new Constructor(-1, type, std::move(args)));
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400695 return result;
696}
697
698/**
699 * Used in the implementations of vectorize_left and vectorize_right. Given a vector type and an
700 * expression x, deletes the expression pointed to by iter and replaces it with <type>(x).
701 */
702static void vectorize(BasicBlock* b,
703 std::vector<BasicBlock::Node>::iterator* iter,
704 const Type& type,
705 std::unique_ptr<Expression>* otherExpression,
706 bool* outUpdated,
707 bool* outNeedsRescan) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400708 SkASSERT((*(*iter)->expression())->fKind == Expression::kBinary_Kind);
709 SkASSERT(type.kind() == Type::kVector_Kind);
710 SkASSERT((*otherExpression)->fType.kind() == Type::kScalar_Kind);
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400711 *outUpdated = true;
712 std::unique_ptr<Expression>* target = (*iter)->expression();
713 if (!b->tryRemoveExpression(iter)) {
714 *target = construct(type, std::move(*otherExpression));
715 *outNeedsRescan = true;
716 } else {
717 *target = construct(type, std::move(*otherExpression));
718 if (!b->tryInsertExpression(iter, target)) {
719 *outNeedsRescan = true;
720 }
721 }
722}
723
724/**
725 * Given a binary expression of the form x <op> vec<n>(y), deletes the right side and vectorizes the
726 * left to yield vec<n>(x).
727 */
728static void vectorize_left(BasicBlock* b,
729 std::vector<BasicBlock::Node>::iterator* iter,
730 bool* outUpdated,
731 bool* outNeedsRescan) {
732 BinaryExpression& bin = (BinaryExpression&) **(*iter)->expression();
733 vectorize(b, iter, bin.fRight->fType, &bin.fLeft, outUpdated, outNeedsRescan);
734}
735
736/**
737 * Given a binary expression of the form vec<n>(x) <op> y, deletes the left side and vectorizes the
738 * right to yield vec<n>(y).
739 */
740static void vectorize_right(BasicBlock* b,
741 std::vector<BasicBlock::Node>::iterator* iter,
742 bool* outUpdated,
743 bool* outNeedsRescan) {
744 BinaryExpression& bin = (BinaryExpression&) **(*iter)->expression();
745 vectorize(b, iter, bin.fLeft->fType, &bin.fRight, outUpdated, outNeedsRescan);
746}
747
748// Mark that an expression which we were writing to is no longer being written to
749void clear_write(const Expression& expr) {
750 switch (expr.fKind) {
751 case Expression::kVariableReference_Kind: {
752 ((VariableReference&) expr).setRefKind(VariableReference::kRead_RefKind);
753 break;
754 }
755 case Expression::kFieldAccess_Kind:
756 clear_write(*((FieldAccess&) expr).fBase);
757 break;
758 case Expression::kSwizzle_Kind:
759 clear_write(*((Swizzle&) expr).fBase);
760 break;
761 case Expression::kIndex_Kind:
762 clear_write(*((IndexExpression&) expr).fBase);
763 break;
764 default:
765 ABORT("shouldn't be writing to this kind of expression\n");
766 break;
767 }
768}
769
Ethan Nicholascb670962017-04-20 19:31:52 -0400770void Compiler::simplifyExpression(DefinitionMap& definitions,
771 BasicBlock& b,
772 std::vector<BasicBlock::Node>::iterator* iter,
773 std::unordered_set<const Variable*>* undefinedVariables,
774 bool* outUpdated,
775 bool* outNeedsRescan) {
776 Expression* expr = (*iter)->expression()->get();
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400777 SkASSERT(expr);
Ethan Nicholascb670962017-04-20 19:31:52 -0400778 if ((*iter)->fConstantPropagation) {
779 std::unique_ptr<Expression> optimized = expr->constantPropagate(*fIRGenerator, definitions);
780 if (optimized) {
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400781 *outUpdated = true;
Ethan Nicholascb670962017-04-20 19:31:52 -0400782 if (!try_replace_expression(&b, iter, &optimized)) {
783 *outNeedsRescan = true;
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400784 return;
Ethan Nicholascb670962017-04-20 19:31:52 -0400785 }
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400786 SkASSERT((*iter)->fKind == BasicBlock::Node::kExpression_Kind);
Ethan Nicholascb670962017-04-20 19:31:52 -0400787 expr = (*iter)->expression()->get();
Ethan Nicholascb670962017-04-20 19:31:52 -0400788 }
789 }
790 switch (expr->fKind) {
791 case Expression::kVariableReference_Kind: {
Ethan Nicholas8f7e28f2018-03-26 14:24:27 -0400792 const VariableReference& ref = (VariableReference&) *expr;
793 const Variable& var = ref.fVariable;
794 if (ref.refKind() != VariableReference::kWrite_RefKind &&
795 ref.refKind() != VariableReference::kPointer_RefKind &&
796 var.fStorage == Variable::kLocal_Storage && !definitions[&var] &&
Ethan Nicholascb670962017-04-20 19:31:52 -0400797 (*undefinedVariables).find(&var) == (*undefinedVariables).end()) {
798 (*undefinedVariables).insert(&var);
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000799 this->error(expr->fOffset,
800 "'" + var.fName + "' has not been assigned");
Ethan Nicholascb670962017-04-20 19:31:52 -0400801 }
802 break;
803 }
804 case Expression::kTernary_Kind: {
805 TernaryExpression* t = (TernaryExpression*) expr;
806 if (t->fTest->fKind == Expression::kBoolLiteral_Kind) {
807 // ternary has a constant test, replace it with either the true or
808 // false branch
809 if (((BoolLiteral&) *t->fTest).fValue) {
810 (*iter)->setExpression(std::move(t->fIfTrue));
811 } else {
812 (*iter)->setExpression(std::move(t->fIfFalse));
813 }
814 *outUpdated = true;
815 *outNeedsRescan = true;
816 }
817 break;
818 }
819 case Expression::kBinary_Kind: {
Ethan Nicholascb670962017-04-20 19:31:52 -0400820 BinaryExpression* bin = (BinaryExpression*) expr;
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400821 if (dead_assignment(*bin)) {
822 delete_left(&b, iter, outUpdated, outNeedsRescan);
823 break;
824 }
825 // collapse useless expressions like x * 1 or x + 0
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400826 if (((bin->fLeft->fType.kind() != Type::kScalar_Kind) &&
827 (bin->fLeft->fType.kind() != Type::kVector_Kind)) ||
828 ((bin->fRight->fType.kind() != Type::kScalar_Kind) &&
829 (bin->fRight->fType.kind() != Type::kVector_Kind))) {
830 break;
831 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400832 switch (bin->fOperator) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400833 case Token::Kind::TK_STAR:
Ethan Nicholascb670962017-04-20 19:31:52 -0400834 if (is_constant(*bin->fLeft, 1)) {
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400835 if (bin->fLeft->fType.kind() == Type::kVector_Kind &&
836 bin->fRight->fType.kind() == Type::kScalar_Kind) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400837 // float4(1) * x -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400838 vectorize_right(&b, iter, outUpdated, outNeedsRescan);
839 } else {
840 // 1 * x -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400841 // 1 * float4(x) -> float4(x)
842 // float4(1) * float4(x) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400843 delete_left(&b, iter, outUpdated, outNeedsRescan);
844 }
845 }
846 else if (is_constant(*bin->fLeft, 0)) {
847 if (bin->fLeft->fType.kind() == Type::kScalar_Kind &&
Ethan Nicholas08dae922018-01-23 10:31:56 -0500848 bin->fRight->fType.kind() == Type::kVector_Kind &&
849 !bin->fRight->hasSideEffects()) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400850 // 0 * float4(x) -> float4(0)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400851 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
852 } else {
853 // 0 * x -> 0
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400854 // float4(0) * x -> float4(0)
855 // float4(0) * float4(x) -> float4(0)
Ethan Nicholas51493ee2017-12-11 12:34:33 -0500856 if (!bin->fRight->hasSideEffects()) {
857 delete_right(&b, iter, outUpdated, outNeedsRescan);
858 }
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400859 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400860 }
861 else if (is_constant(*bin->fRight, 1)) {
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400862 if (bin->fLeft->fType.kind() == Type::kScalar_Kind &&
863 bin->fRight->fType.kind() == Type::kVector_Kind) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400864 // x * float4(1) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400865 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
866 } else {
867 // x * 1 -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400868 // float4(x) * 1 -> float4(x)
869 // float4(x) * float4(1) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400870 delete_right(&b, iter, outUpdated, outNeedsRescan);
871 }
872 }
873 else if (is_constant(*bin->fRight, 0)) {
874 if (bin->fLeft->fType.kind() == Type::kVector_Kind &&
Ethan Nicholas08dae922018-01-23 10:31:56 -0500875 bin->fRight->fType.kind() == Type::kScalar_Kind &&
876 !bin->fLeft->hasSideEffects()) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400877 // float4(x) * 0 -> float4(0)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400878 vectorize_right(&b, iter, outUpdated, outNeedsRescan);
879 } else {
880 // x * 0 -> 0
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400881 // x * float4(0) -> float4(0)
882 // float4(x) * float4(0) -> float4(0)
Ethan Nicholas51493ee2017-12-11 12:34:33 -0500883 if (!bin->fLeft->hasSideEffects()) {
884 delete_left(&b, iter, outUpdated, outNeedsRescan);
885 }
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400886 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400887 }
888 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400889 case Token::Kind::TK_PLUS:
Ethan Nicholascb670962017-04-20 19:31:52 -0400890 if (is_constant(*bin->fLeft, 0)) {
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400891 if (bin->fLeft->fType.kind() == Type::kVector_Kind &&
892 bin->fRight->fType.kind() == Type::kScalar_Kind) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400893 // float4(0) + x -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400894 vectorize_right(&b, iter, outUpdated, outNeedsRescan);
895 } else {
896 // 0 + x -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400897 // 0 + float4(x) -> float4(x)
898 // float4(0) + float4(x) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400899 delete_left(&b, iter, outUpdated, outNeedsRescan);
900 }
901 } else if (is_constant(*bin->fRight, 0)) {
902 if (bin->fLeft->fType.kind() == Type::kScalar_Kind &&
903 bin->fRight->fType.kind() == Type::kVector_Kind) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400904 // x + float4(0) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400905 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
906 } else {
907 // x + 0 -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400908 // float4(x) + 0 -> float4(x)
909 // float4(x) + float4(0) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400910 delete_right(&b, iter, outUpdated, outNeedsRescan);
911 }
Ethan Nicholas56e42712017-04-21 10:23:37 -0400912 }
913 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400914 case Token::Kind::TK_MINUS:
Ethan Nicholas56e42712017-04-21 10:23:37 -0400915 if (is_constant(*bin->fRight, 0)) {
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400916 if (bin->fLeft->fType.kind() == Type::kScalar_Kind &&
917 bin->fRight->fType.kind() == Type::kVector_Kind) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400918 // x - float4(0) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400919 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
920 } else {
921 // x - 0 -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400922 // float4(x) - 0 -> float4(x)
923 // float4(x) - float4(0) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400924 delete_right(&b, iter, outUpdated, outNeedsRescan);
925 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400926 }
927 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400928 case Token::Kind::TK_SLASH:
Ethan Nicholascb670962017-04-20 19:31:52 -0400929 if (is_constant(*bin->fRight, 1)) {
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400930 if (bin->fLeft->fType.kind() == Type::kScalar_Kind &&
931 bin->fRight->fType.kind() == Type::kVector_Kind) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400932 // x / float4(1) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400933 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
934 } else {
935 // x / 1 -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400936 // float4(x) / 1 -> float4(x)
937 // float4(x) / float4(1) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400938 delete_right(&b, iter, outUpdated, outNeedsRescan);
939 }
940 } else if (is_constant(*bin->fLeft, 0)) {
941 if (bin->fLeft->fType.kind() == Type::kScalar_Kind &&
Ethan Nicholas08dae922018-01-23 10:31:56 -0500942 bin->fRight->fType.kind() == Type::kVector_Kind &&
943 !bin->fRight->hasSideEffects()) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400944 // 0 / float4(x) -> float4(0)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400945 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
946 } else {
947 // 0 / x -> 0
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400948 // float4(0) / x -> float4(0)
949 // float4(0) / float4(x) -> float4(0)
Ethan Nicholas51493ee2017-12-11 12:34:33 -0500950 if (!bin->fRight->hasSideEffects()) {
951 delete_right(&b, iter, outUpdated, outNeedsRescan);
952 }
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400953 }
954 }
955 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400956 case Token::Kind::TK_PLUSEQ:
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400957 if (is_constant(*bin->fRight, 0)) {
958 clear_write(*bin->fLeft);
959 delete_right(&b, iter, outUpdated, outNeedsRescan);
960 }
961 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400962 case Token::Kind::TK_MINUSEQ:
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400963 if (is_constant(*bin->fRight, 0)) {
964 clear_write(*bin->fLeft);
965 delete_right(&b, iter, outUpdated, outNeedsRescan);
966 }
967 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400968 case Token::Kind::TK_STAREQ:
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400969 if (is_constant(*bin->fRight, 1)) {
970 clear_write(*bin->fLeft);
971 delete_right(&b, iter, outUpdated, outNeedsRescan);
972 }
973 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400974 case Token::Kind::TK_SLASHEQ:
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400975 if (is_constant(*bin->fRight, 1)) {
976 clear_write(*bin->fLeft);
Ethan Nicholascb670962017-04-20 19:31:52 -0400977 delete_right(&b, iter, outUpdated, outNeedsRescan);
978 }
979 break;
980 default:
981 break;
982 }
Ethan Nicholas409f6f02019-09-17 12:34:39 -0400983 break;
984 }
985 case Expression::kSwizzle_Kind: {
986 Swizzle& s = (Swizzle&) *expr;
987 // detect identity swizzles like foo.rgba
988 if ((int) s.fComponents.size() == s.fBase->fType.columns()) {
989 bool identity = true;
990 for (int i = 0; i < (int) s.fComponents.size(); ++i) {
991 if (s.fComponents[i] != i) {
992 identity = false;
993 break;
994 }
995 }
996 if (identity) {
997 *outUpdated = true;
998 if (!try_replace_expression(&b, iter, &s.fBase)) {
999 *outNeedsRescan = true;
1000 return;
1001 }
1002 SkASSERT((*iter)->fKind == BasicBlock::Node::kExpression_Kind);
1003 break;
1004 }
1005 }
1006 // detect swizzles of swizzles, e.g. replace foo.argb.r000 with foo.a000
1007 if (s.fBase->fKind == Expression::kSwizzle_Kind) {
1008 Swizzle& base = (Swizzle&) *s.fBase;
1009 std::vector<int> final;
1010 for (int c : s.fComponents) {
1011 if (c == SKSL_SWIZZLE_0 || c == SKSL_SWIZZLE_1) {
1012 final.push_back(c);
1013 } else {
1014 final.push_back(base.fComponents[c]);
1015 }
1016 }
1017 *outUpdated = true;
1018 std::unique_ptr<Expression> replacement(new Swizzle(*fContext, base.fBase->clone(),
1019 std::move(final)));
1020 if (!try_replace_expression(&b, iter, &replacement)) {
1021 *outNeedsRescan = true;
1022 return;
1023 }
1024 SkASSERT((*iter)->fKind == BasicBlock::Node::kExpression_Kind);
Ethan Nicholas409f6f02019-09-17 12:34:39 -04001025 }
John Stiles30212b72020-06-11 17:55:07 -04001026 break;
Ethan Nicholascb670962017-04-20 19:31:52 -04001027 }
1028 default:
1029 break;
1030 }
1031}
1032
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001033// returns true if this statement could potentially execute a break at the current level (we ignore
1034// nested loops and switches, since any breaks inside of them will merely break the loop / switch)
Ethan Nicholas5005a222018-08-24 13:06:27 -04001035static bool contains_conditional_break(Statement& s, bool inConditional) {
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001036 switch (s.fKind) {
1037 case Statement::kBlock_Kind:
1038 for (const auto& sub : ((Block&) s).fStatements) {
Ethan Nicholas5005a222018-08-24 13:06:27 -04001039 if (contains_conditional_break(*sub, inConditional)) {
1040 return true;
1041 }
1042 }
1043 return false;
1044 case Statement::kBreak_Kind:
1045 return inConditional;
1046 case Statement::kIf_Kind: {
1047 const IfStatement& i = (IfStatement&) s;
1048 return contains_conditional_break(*i.fIfTrue, true) ||
1049 (i.fIfFalse && contains_conditional_break(*i.fIfFalse, true));
1050 }
1051 default:
1052 return false;
1053 }
1054}
1055
1056// returns true if this statement definitely executes a break at the current level (we ignore
1057// nested loops and switches, since any breaks inside of them will merely break the loop / switch)
1058static bool contains_unconditional_break(Statement& s) {
1059 switch (s.fKind) {
1060 case Statement::kBlock_Kind:
1061 for (const auto& sub : ((Block&) s).fStatements) {
1062 if (contains_unconditional_break(*sub)) {
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001063 return true;
1064 }
1065 }
1066 return false;
1067 case Statement::kBreak_Kind:
1068 return true;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001069 default:
1070 return false;
1071 }
1072}
1073
Ethan Nicholas739e1ca2020-06-11 12:16:14 -04001074static void copy_all_but_break(std::unique_ptr<Statement>& stmt,
1075 std::vector<std::unique_ptr<Statement>*>* target) {
1076 switch (stmt->fKind) {
1077 case Statement::kBlock_Kind:
1078 for (auto& s : ((Block&) *stmt).fStatements) {
1079 copy_all_but_break(s, target);
1080 }
1081 break;
1082 case Statement::kBreak_Kind:
1083 return;
1084 default:
1085 target->push_back(&stmt);
1086 }
1087}
1088
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001089// Returns a block containing all of the statements that will be run if the given case matches
1090// (which, owing to the statements being owned by unique_ptrs, means the switch itself will be
1091// broken by this call and must then be discarded).
1092// Returns null (and leaves the switch unmodified) if no such simple reduction is possible, such as
1093// when break statements appear inside conditionals.
1094static std::unique_ptr<Statement> block_for_case(SwitchStatement* s, SwitchCase* c) {
1095 bool capturing = false;
1096 std::vector<std::unique_ptr<Statement>*> statementPtrs;
1097 for (const auto& current : s->fCases) {
1098 if (current.get() == c) {
1099 capturing = true;
1100 }
1101 if (capturing) {
1102 for (auto& stmt : current->fStatements) {
Ethan Nicholas5005a222018-08-24 13:06:27 -04001103 if (contains_conditional_break(*stmt, s->fKind == Statement::kIf_Kind)) {
1104 return nullptr;
1105 }
1106 if (contains_unconditional_break(*stmt)) {
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001107 capturing = false;
Ethan Nicholas739e1ca2020-06-11 12:16:14 -04001108 copy_all_but_break(stmt, &statementPtrs);
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001109 break;
1110 }
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001111 statementPtrs.push_back(&stmt);
1112 }
1113 if (!capturing) {
1114 break;
1115 }
1116 }
1117 }
1118 std::vector<std::unique_ptr<Statement>> statements;
1119 for (const auto& s : statementPtrs) {
1120 statements.push_back(std::move(*s));
1121 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001122 return std::unique_ptr<Statement>(new Block(-1, std::move(statements), s->fSymbols));
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001123}
1124
Ethan Nicholascb670962017-04-20 19:31:52 -04001125void Compiler::simplifyStatement(DefinitionMap& definitions,
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001126 BasicBlock& b,
1127 std::vector<BasicBlock::Node>::iterator* iter,
1128 std::unordered_set<const Variable*>* undefinedVariables,
1129 bool* outUpdated,
1130 bool* outNeedsRescan) {
Ethan Nicholascb670962017-04-20 19:31:52 -04001131 Statement* stmt = (*iter)->statement()->get();
1132 switch (stmt->fKind) {
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001133 case Statement::kVarDeclaration_Kind: {
1134 const auto& varDecl = (VarDeclaration&) *stmt;
1135 if (varDecl.fVar->dead() &&
1136 (!varDecl.fValue ||
1137 !varDecl.fValue->hasSideEffects())) {
1138 if (varDecl.fValue) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001139 SkASSERT((*iter)->statement()->get() == stmt);
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001140 if (!b.tryRemoveExpressionBefore(iter, varDecl.fValue.get())) {
1141 *outNeedsRescan = true;
Ethan Nicholascb670962017-04-20 19:31:52 -04001142 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001143 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001144 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001145 *outUpdated = true;
Ethan Nicholascb670962017-04-20 19:31:52 -04001146 }
1147 break;
1148 }
1149 case Statement::kIf_Kind: {
1150 IfStatement& i = (IfStatement&) *stmt;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001151 if (i.fTest->fKind == Expression::kBoolLiteral_Kind) {
1152 // constant if, collapse down to a single branch
1153 if (((BoolLiteral&) *i.fTest).fValue) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001154 SkASSERT(i.fIfTrue);
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001155 (*iter)->setStatement(std::move(i.fIfTrue));
1156 } else {
1157 if (i.fIfFalse) {
1158 (*iter)->setStatement(std::move(i.fIfFalse));
1159 } else {
1160 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
1161 }
1162 }
1163 *outUpdated = true;
1164 *outNeedsRescan = true;
1165 break;
1166 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001167 if (i.fIfFalse && i.fIfFalse->isEmpty()) {
1168 // else block doesn't do anything, remove it
1169 i.fIfFalse.reset();
1170 *outUpdated = true;
1171 *outNeedsRescan = true;
1172 }
1173 if (!i.fIfFalse && i.fIfTrue->isEmpty()) {
1174 // if block doesn't do anything, no else block
1175 if (i.fTest->hasSideEffects()) {
1176 // test has side effects, keep it
1177 (*iter)->setStatement(std::unique_ptr<Statement>(
1178 new ExpressionStatement(std::move(i.fTest))));
1179 } else {
1180 // no if, no else, no test side effects, kill the whole if
1181 // statement
1182 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
1183 }
1184 *outUpdated = true;
1185 *outNeedsRescan = true;
1186 }
1187 break;
1188 }
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001189 case Statement::kSwitch_Kind: {
1190 SwitchStatement& s = (SwitchStatement&) *stmt;
1191 if (s.fValue->isConstant()) {
1192 // switch is constant, replace it with the case that matches
1193 bool found = false;
1194 SwitchCase* defaultCase = nullptr;
1195 for (const auto& c : s.fCases) {
1196 if (!c->fValue) {
1197 defaultCase = c.get();
1198 continue;
1199 }
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001200 SkASSERT(c->fValue->fKind == s.fValue->fKind);
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001201 found = c->fValue->compareConstant(*fContext, *s.fValue);
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001202 if (found) {
1203 std::unique_ptr<Statement> newBlock = block_for_case(&s, c.get());
1204 if (newBlock) {
1205 (*iter)->setStatement(std::move(newBlock));
1206 break;
1207 } else {
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -04001208 if (s.fIsStatic && !(fFlags & kPermitInvalidStaticTests_Flag)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001209 this->error(s.fOffset,
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001210 "static switch contains non-static conditional break");
1211 s.fIsStatic = false;
1212 }
1213 return; // can't simplify
1214 }
1215 }
1216 }
1217 if (!found) {
1218 // no matching case. use default if it exists, or kill the whole thing
1219 if (defaultCase) {
1220 std::unique_ptr<Statement> newBlock = block_for_case(&s, defaultCase);
1221 if (newBlock) {
1222 (*iter)->setStatement(std::move(newBlock));
1223 } else {
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -04001224 if (s.fIsStatic && !(fFlags & kPermitInvalidStaticTests_Flag)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001225 this->error(s.fOffset,
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001226 "static switch contains non-static conditional break");
1227 s.fIsStatic = false;
1228 }
1229 return; // can't simplify
1230 }
1231 } else {
1232 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
1233 }
1234 }
1235 *outUpdated = true;
1236 *outNeedsRescan = true;
1237 }
1238 break;
1239 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001240 case Statement::kExpression_Kind: {
1241 ExpressionStatement& e = (ExpressionStatement&) *stmt;
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001242 SkASSERT((*iter)->statement()->get() == &e);
Ethan Nicholascb670962017-04-20 19:31:52 -04001243 if (!e.fExpression->hasSideEffects()) {
1244 // Expression statement with no side effects, kill it
1245 if (!b.tryRemoveExpressionBefore(iter, e.fExpression.get())) {
1246 *outNeedsRescan = true;
1247 }
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001248 SkASSERT((*iter)->statement()->get() == stmt);
Ethan Nicholascb670962017-04-20 19:31:52 -04001249 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
1250 *outUpdated = true;
1251 }
1252 break;
1253 }
1254 default:
1255 break;
1256 }
1257}
1258
1259void Compiler::scanCFG(FunctionDefinition& f) {
1260 CFG cfg = CFGGenerator().getCFG(f);
1261 this->computeDataFlow(&cfg);
ethannicholas22f939e2016-10-13 13:25:34 -07001262
1263 // check for unreachable code
1264 for (size_t i = 0; i < cfg.fBlocks.size(); i++) {
Mike Klein6ad99092016-10-26 10:35:22 -04001265 if (i != cfg.fStart && !cfg.fBlocks[i].fEntrances.size() &&
ethannicholas22f939e2016-10-13 13:25:34 -07001266 cfg.fBlocks[i].fNodes.size()) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001267 int offset;
Ethan Nicholas86a43402017-01-19 13:32:00 -05001268 switch (cfg.fBlocks[i].fNodes[0].fKind) {
1269 case BasicBlock::Node::kStatement_Kind:
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001270 offset = (*cfg.fBlocks[i].fNodes[0].statement())->fOffset;
Ethan Nicholas86a43402017-01-19 13:32:00 -05001271 break;
1272 case BasicBlock::Node::kExpression_Kind:
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001273 offset = (*cfg.fBlocks[i].fNodes[0].expression())->fOffset;
Ethan Nicholas70728ef2020-05-28 07:09:00 -04001274 if ((*cfg.fBlocks[i].fNodes[0].expression())->fKind ==
1275 Expression::kBoolLiteral_Kind) {
1276 // Function inlining can generate do { ... } while(false) loops which always
1277 // break, so the boolean condition is considered unreachable. Since not
1278 // being able to reach a literal is a non-issue in the first place, we
1279 // don't report an error in this case.
1280 continue;
1281 }
Ethan Nicholas86a43402017-01-19 13:32:00 -05001282 break;
1283 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001284 this->error(offset, String("unreachable"));
ethannicholas22f939e2016-10-13 13:25:34 -07001285 }
1286 }
1287 if (fErrorCount) {
1288 return;
1289 }
1290
Ethan Nicholascb670962017-04-20 19:31:52 -04001291 // check for dead code & undefined variables, perform constant propagation
1292 std::unordered_set<const Variable*> undefinedVariables;
1293 bool updated;
1294 bool needsRescan = false;
1295 do {
1296 if (needsRescan) {
1297 cfg = CFGGenerator().getCFG(f);
1298 this->computeDataFlow(&cfg);
1299 needsRescan = false;
Ethan Nicholas113628d2017-02-02 16:11:39 -05001300 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001301
1302 updated = false;
1303 for (BasicBlock& b : cfg.fBlocks) {
1304 DefinitionMap definitions = b.fBefore;
1305
1306 for (auto iter = b.fNodes.begin(); iter != b.fNodes.end() && !needsRescan; ++iter) {
1307 if (iter->fKind == BasicBlock::Node::kExpression_Kind) {
1308 this->simplifyExpression(definitions, b, &iter, &undefinedVariables, &updated,
1309 &needsRescan);
1310 } else {
1311 this->simplifyStatement(definitions, b, &iter, &undefinedVariables, &updated,
1312 &needsRescan);
1313 }
Ethan Nicholas4b330df2017-05-17 10:52:55 -04001314 if (needsRescan) {
1315 break;
1316 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001317 this->addDefinitions(*iter, &definitions);
1318 }
1319 }
1320 } while (updated);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001321 SkASSERT(!needsRescan);
ethannicholas22f939e2016-10-13 13:25:34 -07001322
Ethan Nicholas91a10532017-06-22 11:24:38 -04001323 // verify static ifs & switches, clean up dead variable decls
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001324 for (BasicBlock& b : cfg.fBlocks) {
1325 DefinitionMap definitions = b.fBefore;
1326
Ethan Nicholas91a10532017-06-22 11:24:38 -04001327 for (auto iter = b.fNodes.begin(); iter != b.fNodes.end() && !needsRescan;) {
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001328 if (iter->fKind == BasicBlock::Node::kStatement_Kind) {
1329 const Statement& s = **iter->statement();
1330 switch (s.fKind) {
1331 case Statement::kIf_Kind:
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -04001332 if (((const IfStatement&) s).fIsStatic &&
1333 !(fFlags & kPermitInvalidStaticTests_Flag)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001334 this->error(s.fOffset, "static if has non-static test");
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001335 }
Ethan Nicholas91a10532017-06-22 11:24:38 -04001336 ++iter;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001337 break;
1338 case Statement::kSwitch_Kind:
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -04001339 if (((const SwitchStatement&) s).fIsStatic &&
1340 !(fFlags & kPermitInvalidStaticTests_Flag)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001341 this->error(s.fOffset, "static switch has non-static test");
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001342 }
Ethan Nicholas91a10532017-06-22 11:24:38 -04001343 ++iter;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001344 break;
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001345 case Statement::kVarDeclarations_Kind: {
1346 VarDeclarations& decls = *((VarDeclarationsStatement&) s).fDeclaration;
1347 for (auto varIter = decls.fVars.begin(); varIter != decls.fVars.end();) {
1348 if ((*varIter)->fKind == Statement::kNop_Kind) {
1349 varIter = decls.fVars.erase(varIter);
1350 } else {
1351 ++varIter;
1352 }
1353 }
1354 if (!decls.fVars.size()) {
1355 iter = b.fNodes.erase(iter);
1356 } else {
1357 ++iter;
1358 }
1359 break;
1360 }
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001361 default:
Ethan Nicholas91a10532017-06-22 11:24:38 -04001362 ++iter;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001363 break;
1364 }
Ethan Nicholas91a10532017-06-22 11:24:38 -04001365 } else {
1366 ++iter;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001367 }
1368 }
1369 }
1370
ethannicholas22f939e2016-10-13 13:25:34 -07001371 // check for missing return
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001372 if (f.fDeclaration.fReturnType != *fContext->fVoid_Type) {
ethannicholas22f939e2016-10-13 13:25:34 -07001373 if (cfg.fBlocks[cfg.fExit].fEntrances.size()) {
Ethan Nicholasdb80f692019-11-22 14:06:12 -05001374 this->error(f.fOffset, String("function '" + String(f.fDeclaration.fName) +
1375 "' can exit without returning a value"));
ethannicholas22f939e2016-10-13 13:25:34 -07001376 }
1377 }
1378}
1379
Ethan Nicholas91164d12019-05-15 15:29:54 -04001380void Compiler::registerExternalValue(ExternalValue* value) {
1381 fIRGenerator->fRootSymbolTable->addWithoutOwnership(value->fName, value);
1382}
1383
1384Symbol* Compiler::takeOwnership(std::unique_ptr<Symbol> symbol) {
1385 return fIRGenerator->fRootSymbolTable->takeOwnership(std::move(symbol));
1386}
1387
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001388std::unique_ptr<Program> Compiler::convertProgram(Program::Kind kind, String text,
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001389 const Program::Settings& settings) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001390 fErrorText = "";
1391 fErrorCount = 0;
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001392 std::vector<std::unique_ptr<ProgramElement>>* inherited;
ethannicholasd598f792016-07-25 10:08:54 -07001393 std::vector<std::unique_ptr<ProgramElement>> elements;
ethannicholasb3058bd2016-07-01 08:22:01 -07001394 switch (kind) {
1395 case Program::kVertex_Kind:
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001396 inherited = &fVertexInclude;
1397 fIRGenerator->fSymbolTable = fVertexSymbolTable;
Ethan Nicholasdb80f692019-11-22 14:06:12 -05001398 fIRGenerator->fIntrinsics = &fGPUIntrinsics;
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001399 fIRGenerator->start(&settings, inherited);
ethannicholasb3058bd2016-07-01 08:22:01 -07001400 break;
1401 case Program::kFragment_Kind:
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001402 inherited = &fFragmentInclude;
1403 fIRGenerator->fSymbolTable = fFragmentSymbolTable;
Ethan Nicholasdb80f692019-11-22 14:06:12 -05001404 fIRGenerator->fIntrinsics = &fGPUIntrinsics;
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001405 fIRGenerator->start(&settings, inherited);
ethannicholasb3058bd2016-07-01 08:22:01 -07001406 break;
Ethan Nicholas52cad152017-02-16 16:37:32 -05001407 case Program::kGeometry_Kind:
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001408 inherited = &fGeometryInclude;
1409 fIRGenerator->fSymbolTable = fGeometrySymbolTable;
Ethan Nicholasdb80f692019-11-22 14:06:12 -05001410 fIRGenerator->fIntrinsics = &fGPUIntrinsics;
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001411 fIRGenerator->start(&settings, inherited);
Ethan Nicholas52cad152017-02-16 16:37:32 -05001412 break;
Ethan Nicholas762466e2017-06-29 10:03:38 -04001413 case Program::kFragmentProcessor_Kind:
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001414 inherited = nullptr;
Ethan Nicholas8da1e652019-05-24 11:01:59 -04001415 fIRGenerator->fSymbolTable = fGpuSymbolTable;
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001416 fIRGenerator->start(&settings, nullptr);
Ethan Nicholasdb80f692019-11-22 14:06:12 -05001417 fIRGenerator->fIntrinsics = &fGPUIntrinsics;
Robert Phillipsfe8da172018-01-24 14:52:02 +00001418 fIRGenerator->convertProgram(kind, SKSL_FP_INCLUDE, strlen(SKSL_FP_INCLUDE), *fTypes,
Ethan Nicholasf7b88202017-09-18 14:10:39 -04001419 &elements);
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001420 fIRGenerator->fSymbolTable->markAllFunctionsBuiltin();
Ethan Nicholas762466e2017-06-29 10:03:38 -04001421 break;
Ethan Nicholas8da1e652019-05-24 11:01:59 -04001422 case Program::kPipelineStage_Kind:
1423 inherited = &fPipelineInclude;
1424 fIRGenerator->fSymbolTable = fPipelineSymbolTable;
Ethan Nicholasdb80f692019-11-22 14:06:12 -05001425 fIRGenerator->fIntrinsics = &fGPUIntrinsics;
Ethan Nicholas8da1e652019-05-24 11:01:59 -04001426 fIRGenerator->start(&settings, inherited);
1427 break;
Ethan Nicholas746035a2019-04-23 13:31:09 -04001428 case Program::kGeneric_Kind:
Ethan Nicholas8da1e652019-05-24 11:01:59 -04001429 inherited = &fInterpreterInclude;
1430 fIRGenerator->fSymbolTable = fInterpreterSymbolTable;
Ethan Nicholasdb80f692019-11-22 14:06:12 -05001431 fIRGenerator->fIntrinsics = &fInterpreterIntrinsics;
Ethan Nicholas8da1e652019-05-24 11:01:59 -04001432 fIRGenerator->start(&settings, inherited);
Ethan Nicholas0d997662019-04-08 09:46:01 -04001433 break;
ethannicholasb3058bd2016-07-01 08:22:01 -07001434 }
Ethan Nicholasaae47c82017-11-10 15:34:03 -05001435 for (auto& element : elements) {
1436 if (element->fKind == ProgramElement::kEnum_Kind) {
1437 ((Enum&) *element).fBuiltin = true;
1438 }
1439 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001440 std::unique_ptr<String> textPtr(new String(std::move(text)));
1441 fSource = textPtr.get();
Robert Phillipsfe8da172018-01-24 14:52:02 +00001442 fIRGenerator->convertProgram(kind, textPtr->c_str(), textPtr->size(), *fTypes, &elements);
Ethan Nicholasf7b88202017-09-18 14:10:39 -04001443 auto result = std::unique_ptr<Program>(new Program(kind,
1444 std::move(textPtr),
1445 settings,
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001446 fContext,
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001447 inherited,
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001448 std::move(elements),
1449 fIRGenerator->fSymbolTable,
1450 fIRGenerator->fInputs));
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001451 if (fErrorCount) {
1452 return nullptr;
1453 }
1454 return result;
1455}
1456
Ethan Nicholas00543112018-07-31 09:44:36 -04001457bool Compiler::optimize(Program& program) {
1458 SkASSERT(!fErrorCount);
1459 if (!program.fIsOptimized) {
1460 program.fIsOptimized = true;
1461 fIRGenerator->fKind = program.fKind;
1462 fIRGenerator->fSettings = &program.fSettings;
1463 for (auto& element : program) {
1464 if (element.fKind == ProgramElement::kFunction_Kind) {
1465 this->scanCFG((FunctionDefinition&) element);
1466 }
1467 }
Ethan Nicholase8ad02c2020-06-03 16:58:20 -04001468 // we wait until after analysis to remove dead functions so that we still report errors
1469 // even in unused code
1470 if (program.fSettings.fRemoveDeadFunctions) {
1471 for (auto iter = program.fElements.begin(); iter != program.fElements.end(); ) {
1472 if ((*iter)->fKind == ProgramElement::kFunction_Kind) {
1473 const FunctionDefinition& f = (const FunctionDefinition&) **iter;
1474 if (!f.fDeclaration.fCallCount && f.fDeclaration.fName != "main") {
1475 iter = program.fElements.erase(iter);
1476 continue;
1477 }
1478 }
1479 ++iter;
1480 }
1481 }
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001482 if (program.fKind != Program::kFragmentProcessor_Kind) {
1483 for (auto iter = program.fElements.begin(); iter != program.fElements.end();) {
1484 if ((*iter)->fKind == ProgramElement::kVar_Kind) {
1485 VarDeclarations& vars = (VarDeclarations&) **iter;
1486 for (auto varIter = vars.fVars.begin(); varIter != vars.fVars.end();) {
1487 const Variable& var = *((VarDeclaration&) **varIter).fVar;
1488 if (var.dead()) {
1489 varIter = vars.fVars.erase(varIter);
1490 } else {
1491 ++varIter;
1492 }
1493 }
1494 if (vars.fVars.size() == 0) {
1495 iter = program.fElements.erase(iter);
1496 continue;
1497 }
1498 }
1499 ++iter;
1500 }
1501 }
Ethan Nicholas00543112018-07-31 09:44:36 -04001502 }
1503 return fErrorCount == 0;
1504}
1505
1506std::unique_ptr<Program> Compiler::specialize(
1507 Program& program,
1508 const std::unordered_map<SkSL::String, SkSL::Program::Settings::Value>& inputs) {
1509 std::vector<std::unique_ptr<ProgramElement>> elements;
1510 for (const auto& e : program) {
1511 elements.push_back(e.clone());
1512 }
1513 Program::Settings settings;
1514 settings.fCaps = program.fSettings.fCaps;
1515 for (auto iter = inputs.begin(); iter != inputs.end(); ++iter) {
1516 settings.fArgs.insert(*iter);
1517 }
Brian Osman808f0212020-01-21 15:36:47 -05001518 std::unique_ptr<String> sourceCopy(new String(*program.fSource));
Ethan Nicholas00543112018-07-31 09:44:36 -04001519 std::unique_ptr<Program> result(new Program(program.fKind,
Brian Osman808f0212020-01-21 15:36:47 -05001520 std::move(sourceCopy),
Ethan Nicholas00543112018-07-31 09:44:36 -04001521 settings,
1522 program.fContext,
1523 program.fInheritedElements,
1524 std::move(elements),
1525 program.fSymbols,
1526 program.fInputs));
1527 return result;
1528}
1529
Brian Osmanfb32ddf2019-06-18 10:14:20 -04001530#if defined(SKSL_STANDALONE) || SK_SUPPORT_GPU
1531
Ethan Nicholas00543112018-07-31 09:44:36 -04001532bool Compiler::toSPIRV(Program& program, OutputStream& out) {
1533 if (!this->optimize(program)) {
1534 return false;
1535 }
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001536#ifdef SK_ENABLE_SPIRV_VALIDATION
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001537 StringStream buffer;
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001538 fSource = program.fSource.get();
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001539 SPIRVCodeGenerator cg(fContext.get(), &program, this, &buffer);
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001540 bool result = cg.generateCode();
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001541 fSource = nullptr;
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001542 if (result) {
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001543 spvtools::SpirvTools tools(SPV_ENV_VULKAN_1_0);
Ethan Nicholas762466e2017-06-29 10:03:38 -04001544 const String& data = buffer.str();
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001545 SkASSERT(0 == data.size() % 4);
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001546 auto dumpmsg = [](spv_message_level_t, const char*, const spv_position_t&, const char* m) {
1547 SkDebugf("SPIR-V validation error: %s\n", m);
1548 };
1549 tools.SetMessageConsumer(dumpmsg);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001550 // Verify that the SPIR-V we produced is valid. If this SkASSERT fails, check the logs prior
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001551 // to the failure to see the validation errors.
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001552 SkAssertResult(tools.Validate((const uint32_t*) data.c_str(), data.size() / 4));
Ethan Nicholas762466e2017-06-29 10:03:38 -04001553 out.write(data.c_str(), data.size());
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001554 }
1555#else
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001556 fSource = program.fSource.get();
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001557 SPIRVCodeGenerator cg(fContext.get(), &program, this, &out);
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001558 bool result = cg.generateCode();
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001559 fSource = nullptr;
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001560#endif
Ethan Nicholasce33f102016-12-09 17:22:59 -05001561 return result;
1562}
1563
Ethan Nicholas00543112018-07-31 09:44:36 -04001564bool Compiler::toSPIRV(Program& program, String* out) {
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001565 StringStream buffer;
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001566 bool result = this->toSPIRV(program, buffer);
1567 if (result) {
Ethan Nicholas762466e2017-06-29 10:03:38 -04001568 *out = buffer.str();
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001569 }
1570 return result;
1571}
1572
Ethan Nicholas00543112018-07-31 09:44:36 -04001573bool Compiler::toGLSL(Program& program, OutputStream& out) {
1574 if (!this->optimize(program)) {
1575 return false;
1576 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001577 fSource = program.fSource.get();
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001578 GLSLCodeGenerator cg(fContext.get(), &program, this, &out);
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001579 bool result = cg.generateCode();
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001580 fSource = nullptr;
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001581 return result;
1582}
1583
Ethan Nicholas00543112018-07-31 09:44:36 -04001584bool Compiler::toGLSL(Program& program, String* out) {
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001585 StringStream buffer;
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001586 bool result = this->toGLSL(program, buffer);
1587 if (result) {
Ethan Nicholas762466e2017-06-29 10:03:38 -04001588 *out = buffer.str();
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001589 }
1590 return result;
1591}
1592
Brian Osmanc0243912020-02-19 15:35:26 -05001593bool Compiler::toHLSL(Program& program, String* out) {
1594 String spirv;
1595 if (!this->toSPIRV(program, &spirv)) {
1596 return false;
1597 }
1598
1599 return SPIRVtoHLSL(spirv, out);
1600}
1601
Ethan Nicholas00543112018-07-31 09:44:36 -04001602bool Compiler::toMetal(Program& program, OutputStream& out) {
1603 if (!this->optimize(program)) {
1604 return false;
1605 }
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001606 MetalCodeGenerator cg(fContext.get(), &program, this, &out);
Ethan Nicholascc305772017-10-13 16:17:45 -04001607 bool result = cg.generateCode();
Ethan Nicholascc305772017-10-13 16:17:45 -04001608 return result;
1609}
1610
Ethan Nicholas00543112018-07-31 09:44:36 -04001611bool Compiler::toMetal(Program& program, String* out) {
1612 if (!this->optimize(program)) {
1613 return false;
1614 }
Timothy Liangb8eeb802018-07-23 16:46:16 -04001615 StringStream buffer;
1616 bool result = this->toMetal(program, buffer);
1617 if (result) {
1618 *out = buffer.str();
1619 }
1620 return result;
1621}
1622
Ethan Nicholas00543112018-07-31 09:44:36 -04001623bool Compiler::toCPP(Program& program, String name, OutputStream& out) {
1624 if (!this->optimize(program)) {
1625 return false;
1626 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001627 fSource = program.fSource.get();
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001628 CPPCodeGenerator cg(fContext.get(), &program, this, name, &out);
Ethan Nicholas762466e2017-06-29 10:03:38 -04001629 bool result = cg.generateCode();
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001630 fSource = nullptr;
Ethan Nicholas762466e2017-06-29 10:03:38 -04001631 return result;
1632}
1633
Ethan Nicholas00543112018-07-31 09:44:36 -04001634bool Compiler::toH(Program& program, String name, OutputStream& out) {
1635 if (!this->optimize(program)) {
1636 return false;
1637 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001638 fSource = program.fSource.get();
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001639 HCodeGenerator cg(fContext.get(), &program, this, name, &out);
Ethan Nicholas762466e2017-06-29 10:03:38 -04001640 bool result = cg.generateCode();
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001641 fSource = nullptr;
Ethan Nicholas00543112018-07-31 09:44:36 -04001642 return result;
1643}
1644
Brian Osman2e29ab52019-09-20 12:19:11 -04001645#endif
1646
1647#if !defined(SKSL_STANDALONE) && SK_SUPPORT_GPU
Brian Osman107c6662019-12-30 15:02:30 -05001648bool Compiler::toPipelineStage(const Program& program, PipelineStageArgs* outArgs) {
Ethan Nicholas00543112018-07-31 09:44:36 -04001649 SkASSERT(program.fIsOptimized);
1650 fSource = program.fSource.get();
1651 StringStream buffer;
Brian Osman300fe1d2020-01-23 15:42:43 -05001652 PipelineStageCodeGenerator cg(fContext.get(), &program, this, &buffer, outArgs);
Ethan Nicholas00543112018-07-31 09:44:36 -04001653 bool result = cg.generateCode();
1654 fSource = nullptr;
1655 if (result) {
Brian Osman107c6662019-12-30 15:02:30 -05001656 outArgs->fCode = buffer.str();
Ethan Nicholas00543112018-07-31 09:44:36 -04001657 }
Ethan Nicholas762466e2017-06-29 10:03:38 -04001658 return result;
1659}
Brian Osmanfb32ddf2019-06-18 10:14:20 -04001660#endif
1661
Ethan Nicholas0e9401d2019-03-21 11:05:37 -04001662std::unique_ptr<ByteCode> Compiler::toByteCode(Program& program) {
Brian Osman489cf882019-07-09 10:48:28 -04001663#if defined(SK_ENABLE_SKSL_INTERPRETER)
Ethan Nicholas0e9401d2019-03-21 11:05:37 -04001664 if (!this->optimize(program)) {
1665 return nullptr;
1666 }
Brian Osman808f0212020-01-21 15:36:47 -05001667 fSource = program.fSource.get();
Ethan Nicholas0e9401d2019-03-21 11:05:37 -04001668 std::unique_ptr<ByteCode> result(new ByteCode());
Brian Osmanb08cc022020-04-02 11:38:40 -04001669 ByteCodeGenerator cg(fContext.get(), &program, this, result.get());
1670 bool success = cg.generateCode();
1671 fSource = nullptr;
1672 if (success) {
Ethan Nicholas0e9401d2019-03-21 11:05:37 -04001673 return result;
1674 }
Brian Osman489cf882019-07-09 10:48:28 -04001675#else
1676 ABORT("ByteCode interpreter not enabled");
1677#endif
Ethan Nicholas0e9401d2019-03-21 11:05:37 -04001678 return nullptr;
1679}
1680
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001681const char* Compiler::OperatorName(Token::Kind kind) {
1682 switch (kind) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001683 case Token::Kind::TK_PLUS: return "+";
1684 case Token::Kind::TK_MINUS: return "-";
1685 case Token::Kind::TK_STAR: return "*";
1686 case Token::Kind::TK_SLASH: return "/";
1687 case Token::Kind::TK_PERCENT: return "%";
1688 case Token::Kind::TK_SHL: return "<<";
1689 case Token::Kind::TK_SHR: return ">>";
1690 case Token::Kind::TK_LOGICALNOT: return "!";
1691 case Token::Kind::TK_LOGICALAND: return "&&";
1692 case Token::Kind::TK_LOGICALOR: return "||";
1693 case Token::Kind::TK_LOGICALXOR: return "^^";
1694 case Token::Kind::TK_BITWISENOT: return "~";
1695 case Token::Kind::TK_BITWISEAND: return "&";
1696 case Token::Kind::TK_BITWISEOR: return "|";
1697 case Token::Kind::TK_BITWISEXOR: return "^";
1698 case Token::Kind::TK_EQ: return "=";
1699 case Token::Kind::TK_EQEQ: return "==";
1700 case Token::Kind::TK_NEQ: return "!=";
1701 case Token::Kind::TK_LT: return "<";
1702 case Token::Kind::TK_GT: return ">";
1703 case Token::Kind::TK_LTEQ: return "<=";
1704 case Token::Kind::TK_GTEQ: return ">=";
1705 case Token::Kind::TK_PLUSEQ: return "+=";
1706 case Token::Kind::TK_MINUSEQ: return "-=";
1707 case Token::Kind::TK_STAREQ: return "*=";
1708 case Token::Kind::TK_SLASHEQ: return "/=";
1709 case Token::Kind::TK_PERCENTEQ: return "%=";
1710 case Token::Kind::TK_SHLEQ: return "<<=";
1711 case Token::Kind::TK_SHREQ: return ">>=";
1712 case Token::Kind::TK_LOGICALANDEQ: return "&&=";
1713 case Token::Kind::TK_LOGICALOREQ: return "||=";
1714 case Token::Kind::TK_LOGICALXOREQ: return "^^=";
1715 case Token::Kind::TK_BITWISEANDEQ: return "&=";
1716 case Token::Kind::TK_BITWISEOREQ: return "|=";
1717 case Token::Kind::TK_BITWISEXOREQ: return "^=";
1718 case Token::Kind::TK_PLUSPLUS: return "++";
1719 case Token::Kind::TK_MINUSMINUS: return "--";
1720 case Token::Kind::TK_COMMA: return ",";
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001721 default:
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001722 ABORT("unsupported operator: %d\n", (int) kind);
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001723 }
1724}
1725
1726
1727bool Compiler::IsAssignment(Token::Kind op) {
1728 switch (op) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001729 case Token::Kind::TK_EQ: // fall through
1730 case Token::Kind::TK_PLUSEQ: // fall through
1731 case Token::Kind::TK_MINUSEQ: // fall through
1732 case Token::Kind::TK_STAREQ: // fall through
1733 case Token::Kind::TK_SLASHEQ: // fall through
1734 case Token::Kind::TK_PERCENTEQ: // fall through
1735 case Token::Kind::TK_SHLEQ: // fall through
1736 case Token::Kind::TK_SHREQ: // fall through
1737 case Token::Kind::TK_BITWISEOREQ: // fall through
1738 case Token::Kind::TK_BITWISEXOREQ: // fall through
1739 case Token::Kind::TK_BITWISEANDEQ: // fall through
1740 case Token::Kind::TK_LOGICALOREQ: // fall through
1741 case Token::Kind::TK_LOGICALXOREQ: // fall through
1742 case Token::Kind::TK_LOGICALANDEQ:
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001743 return true;
1744 default:
1745 return false;
1746 }
1747}
1748
1749Position Compiler::position(int offset) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001750 SkASSERT(fSource);
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001751 int line = 1;
1752 int column = 1;
1753 for (int i = 0; i < offset; i++) {
1754 if ((*fSource)[i] == '\n') {
1755 ++line;
1756 column = 1;
1757 }
1758 else {
1759 ++column;
1760 }
1761 }
1762 return Position(line, column);
1763}
1764
1765void Compiler::error(int offset, String msg) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001766 fErrorCount++;
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001767 Position pos = this->position(offset);
1768 fErrorText += "error: " + to_string(pos.fLine) + ": " + msg.c_str() + "\n";
ethannicholasb3058bd2016-07-01 08:22:01 -07001769}
1770
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001771String Compiler::errorText() {
Ethan Nicholas00543112018-07-31 09:44:36 -04001772 this->writeErrorCount();
1773 fErrorCount = 0;
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001774 String result = fErrorText;
ethannicholasb3058bd2016-07-01 08:22:01 -07001775 return result;
1776}
1777
1778void Compiler::writeErrorCount() {
1779 if (fErrorCount) {
1780 fErrorText += to_string(fErrorCount) + " error";
1781 if (fErrorCount > 1) {
1782 fErrorText += "s";
1783 }
1784 fErrorText += "\n";
1785 }
1786}
1787
ethannicholasb3058bd2016-07-01 08:22:01 -07001788} // namespace