blob: 7bfdce13ffb59b3d162149d2b3576007b08baed8 [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"
19#include "src/sksl/ir/SkSLEnum.h"
20#include "src/sksl/ir/SkSLExpression.h"
21#include "src/sksl/ir/SkSLExpressionStatement.h"
22#include "src/sksl/ir/SkSLFunctionCall.h"
23#include "src/sksl/ir/SkSLIntLiteral.h"
24#include "src/sksl/ir/SkSLModifiersDeclaration.h"
25#include "src/sksl/ir/SkSLNop.h"
26#include "src/sksl/ir/SkSLSymbolTable.h"
27#include "src/sksl/ir/SkSLTernaryExpression.h"
28#include "src/sksl/ir/SkSLUnresolvedFunction.h"
29#include "src/sksl/ir/SkSLVarDeclarations.h"
ethannicholasb3058bd2016-07-01 08:22:01 -070030
Ethan Nicholasa11035b2019-11-26 16:27:47 -050031#if !defined(SKSL_STANDALONE) & SK_SUPPORT_GPU
32#include "include/gpu/GrContextOptions.h"
33#include "src/gpu/GrShaderCaps.h"
34#endif
35
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -040036#ifdef SK_ENABLE_SPIRV_VALIDATION
37#include "spirv-tools/libspirv.hpp"
38#endif
39
ethannicholasb3058bd2016-07-01 08:22:01 -070040// include the built-in shader symbols as static strings
41
Ethan Nicholas79707652017-11-16 11:20:11 -050042#define STRINGIFY(x) #x
43
Ethan Nicholas8da1e652019-05-24 11:01:59 -040044static const char* SKSL_GPU_INCLUDE =
45#include "sksl_gpu.inc"
46;
47
Brian Salomonf8c187c2019-12-19 14:41:57 -050048static const char* SKSL_BLEND_INCLUDE =
49#include "sksl_blend.inc"
50;
51
Ethan Nicholas8da1e652019-05-24 11:01:59 -040052static const char* SKSL_INTERP_INCLUDE =
53#include "sksl_interp.inc"
ethannicholasb3058bd2016-07-01 08:22:01 -070054;
55
ethannicholas5961bc92016-10-12 06:39:56 -070056static const char* SKSL_VERT_INCLUDE =
Ben Wagnera56c4d22018-01-24 17:32:17 -050057#include "sksl_vert.inc"
ethannicholasb3058bd2016-07-01 08:22:01 -070058;
59
ethannicholas5961bc92016-10-12 06:39:56 -070060static const char* SKSL_FRAG_INCLUDE =
Ben Wagnera56c4d22018-01-24 17:32:17 -050061#include "sksl_frag.inc"
ethannicholasb3058bd2016-07-01 08:22:01 -070062;
63
Ethan Nicholas52cad152017-02-16 16:37:32 -050064static const char* SKSL_GEOM_INCLUDE =
Ben Wagnera56c4d22018-01-24 17:32:17 -050065#include "sksl_geom.inc"
Ethan Nicholas52cad152017-02-16 16:37:32 -050066;
67
Ethan Nicholas762466e2017-06-29 10:03:38 -040068static const char* SKSL_FP_INCLUDE =
Ben Wagnera56c4d22018-01-24 17:32:17 -050069#include "sksl_enums.inc"
70#include "sksl_fp.inc"
Ethan Nicholas762466e2017-06-29 10:03:38 -040071;
72
Ethan Nicholas8da1e652019-05-24 11:01:59 -040073static const char* SKSL_PIPELINE_INCLUDE =
74#include "sksl_pipeline.inc"
Ethan Nicholas0d997662019-04-08 09:46:01 -040075;
76
ethannicholasb3058bd2016-07-01 08:22:01 -070077namespace SkSL {
78
Ethan Nicholasdb80f692019-11-22 14:06:12 -050079static void grab_intrinsics(std::vector<std::unique_ptr<ProgramElement>>* src,
Ethan Nicholas99c54f02020-01-21 16:06:47 +000080 std::map<StringFragment, std::pair<std::unique_ptr<ProgramElement>, bool>>* target) {
81 for (auto& element : *src) {
Ethan Nicholasdb80f692019-11-22 14:06:12 -050082 switch (element->fKind) {
83 case ProgramElement::kFunction_Kind: {
84 FunctionDefinition& f = (FunctionDefinition&) *element;
Ethan Nicholas99c54f02020-01-21 16:06:47 +000085 StringFragment name = f.fDeclaration.fName;
86 SkASSERT(target->find(name) == target->end());
87 (*target)[name] = std::make_pair(std::move(element), false);
Ethan Nicholasdb80f692019-11-22 14:06:12 -050088 break;
89 }
90 case ProgramElement::kEnum_Kind: {
91 Enum& e = (Enum&) *element;
92 StringFragment name = e.fTypeName;
93 SkASSERT(target->find(name) == target->end());
94 (*target)[name] = std::make_pair(std::move(element), false);
95 break;
96 }
97 default:
98 printf("unsupported include file element\n");
99 SkASSERT(false);
100 }
101 }
102}
103
104
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -0400105Compiler::Compiler(Flags flags)
106: fFlags(flags)
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400107, fContext(new Context())
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -0400108, fErrorCount(0) {
Ethan Nicholas8feeff92017-03-30 14:11:58 -0400109 auto types = std::shared_ptr<SymbolTable>(new SymbolTable(this));
110 auto symbols = std::shared_ptr<SymbolTable>(new SymbolTable(types, this));
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400111 fIRGenerator = new IRGenerator(fContext.get(), symbols, *this);
ethannicholasb3058bd2016-07-01 08:22:01 -0700112 fTypes = types;
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400113 #define ADD_TYPE(t) types->addWithoutOwnership(fContext->f ## t ## _Type->fName, \
114 fContext->f ## t ## _Type.get())
ethannicholasb3058bd2016-07-01 08:22:01 -0700115 ADD_TYPE(Void);
116 ADD_TYPE(Float);
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400117 ADD_TYPE(Float2);
118 ADD_TYPE(Float3);
119 ADD_TYPE(Float4);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -0400120 ADD_TYPE(Half);
121 ADD_TYPE(Half2);
122 ADD_TYPE(Half3);
123 ADD_TYPE(Half4);
ethannicholasb3058bd2016-07-01 08:22:01 -0700124 ADD_TYPE(Double);
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400125 ADD_TYPE(Double2);
126 ADD_TYPE(Double3);
127 ADD_TYPE(Double4);
ethannicholasb3058bd2016-07-01 08:22:01 -0700128 ADD_TYPE(Int);
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400129 ADD_TYPE(Int2);
130 ADD_TYPE(Int3);
131 ADD_TYPE(Int4);
ethannicholasb3058bd2016-07-01 08:22:01 -0700132 ADD_TYPE(UInt);
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400133 ADD_TYPE(UInt2);
134 ADD_TYPE(UInt3);
135 ADD_TYPE(UInt4);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -0400136 ADD_TYPE(Short);
137 ADD_TYPE(Short2);
138 ADD_TYPE(Short3);
139 ADD_TYPE(Short4);
140 ADD_TYPE(UShort);
141 ADD_TYPE(UShort2);
142 ADD_TYPE(UShort3);
143 ADD_TYPE(UShort4);
Ruiqi Maob609e6d2018-07-17 10:19:38 -0400144 ADD_TYPE(Byte);
145 ADD_TYPE(Byte2);
146 ADD_TYPE(Byte3);
147 ADD_TYPE(Byte4);
148 ADD_TYPE(UByte);
149 ADD_TYPE(UByte2);
150 ADD_TYPE(UByte3);
151 ADD_TYPE(UByte4);
ethannicholasb3058bd2016-07-01 08:22:01 -0700152 ADD_TYPE(Bool);
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400153 ADD_TYPE(Bool2);
154 ADD_TYPE(Bool3);
155 ADD_TYPE(Bool4);
156 ADD_TYPE(Float2x2);
157 ADD_TYPE(Float2x3);
158 ADD_TYPE(Float2x4);
159 ADD_TYPE(Float3x2);
160 ADD_TYPE(Float3x3);
161 ADD_TYPE(Float3x4);
162 ADD_TYPE(Float4x2);
163 ADD_TYPE(Float4x3);
164 ADD_TYPE(Float4x4);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -0400165 ADD_TYPE(Half2x2);
166 ADD_TYPE(Half2x3);
167 ADD_TYPE(Half2x4);
168 ADD_TYPE(Half3x2);
169 ADD_TYPE(Half3x3);
170 ADD_TYPE(Half3x4);
171 ADD_TYPE(Half4x2);
172 ADD_TYPE(Half4x3);
173 ADD_TYPE(Half4x4);
174 ADD_TYPE(Double2x2);
175 ADD_TYPE(Double2x3);
176 ADD_TYPE(Double2x4);
177 ADD_TYPE(Double3x2);
178 ADD_TYPE(Double3x3);
179 ADD_TYPE(Double3x4);
180 ADD_TYPE(Double4x2);
181 ADD_TYPE(Double4x3);
182 ADD_TYPE(Double4x4);
ethannicholasb3058bd2016-07-01 08:22:01 -0700183 ADD_TYPE(GenType);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -0400184 ADD_TYPE(GenHType);
ethannicholasb3058bd2016-07-01 08:22:01 -0700185 ADD_TYPE(GenDType);
186 ADD_TYPE(GenIType);
187 ADD_TYPE(GenUType);
188 ADD_TYPE(GenBType);
189 ADD_TYPE(Mat);
190 ADD_TYPE(Vec);
191 ADD_TYPE(GVec);
192 ADD_TYPE(GVec2);
193 ADD_TYPE(GVec3);
194 ADD_TYPE(GVec4);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -0400195 ADD_TYPE(HVec);
ethannicholasb3058bd2016-07-01 08:22:01 -0700196 ADD_TYPE(DVec);
197 ADD_TYPE(IVec);
198 ADD_TYPE(UVec);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -0400199 ADD_TYPE(SVec);
200 ADD_TYPE(USVec);
Ruiqi Maob609e6d2018-07-17 10:19:38 -0400201 ADD_TYPE(ByteVec);
202 ADD_TYPE(UByteVec);
ethannicholasb3058bd2016-07-01 08:22:01 -0700203 ADD_TYPE(BVec);
204
205 ADD_TYPE(Sampler1D);
206 ADD_TYPE(Sampler2D);
207 ADD_TYPE(Sampler3D);
ethannicholas5961bc92016-10-12 06:39:56 -0700208 ADD_TYPE(SamplerExternalOES);
ethannicholasb3058bd2016-07-01 08:22:01 -0700209 ADD_TYPE(SamplerCube);
210 ADD_TYPE(Sampler2DRect);
211 ADD_TYPE(Sampler1DArray);
212 ADD_TYPE(Sampler2DArray);
213 ADD_TYPE(SamplerCubeArray);
214 ADD_TYPE(SamplerBuffer);
215 ADD_TYPE(Sampler2DMS);
216 ADD_TYPE(Sampler2DMSArray);
217
Brian Salomonbf7b6202016-11-11 16:08:03 -0500218 ADD_TYPE(ISampler2D);
219
Brian Salomon2a51de82016-11-16 12:06:01 -0500220 ADD_TYPE(Image2D);
221 ADD_TYPE(IImage2D);
222
Greg Daniel64773e62016-11-22 09:44:03 -0500223 ADD_TYPE(SubpassInput);
224 ADD_TYPE(SubpassInputMS);
225
ethannicholasb3058bd2016-07-01 08:22:01 -0700226 ADD_TYPE(GSampler1D);
227 ADD_TYPE(GSampler2D);
228 ADD_TYPE(GSampler3D);
229 ADD_TYPE(GSamplerCube);
230 ADD_TYPE(GSampler2DRect);
231 ADD_TYPE(GSampler1DArray);
232 ADD_TYPE(GSampler2DArray);
233 ADD_TYPE(GSamplerCubeArray);
234 ADD_TYPE(GSamplerBuffer);
235 ADD_TYPE(GSampler2DMS);
236 ADD_TYPE(GSampler2DMSArray);
237
238 ADD_TYPE(Sampler1DShadow);
239 ADD_TYPE(Sampler2DShadow);
240 ADD_TYPE(SamplerCubeShadow);
241 ADD_TYPE(Sampler2DRectShadow);
242 ADD_TYPE(Sampler1DArrayShadow);
243 ADD_TYPE(Sampler2DArrayShadow);
244 ADD_TYPE(SamplerCubeArrayShadow);
245 ADD_TYPE(GSampler2DArrayShadow);
246 ADD_TYPE(GSamplerCubeArrayShadow);
Ethan Nicholasc9472af2017-10-10 16:30:21 -0400247 ADD_TYPE(FragmentProcessor);
Stephen Whiteff5d7a22019-07-26 17:42:06 -0400248 ADD_TYPE(Sampler);
249 ADD_TYPE(Texture2D);
ethannicholasb3058bd2016-07-01 08:22:01 -0700250
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700251 StringFragment skCapsName("sk_Caps");
252 Variable* skCaps = new Variable(-1, Modifiers(), skCapsName,
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400253 *fContext->fSkCaps_Type, Variable::kGlobal_Storage);
Ethan Nicholas3605ace2016-11-21 15:59:48 -0500254 fIRGenerator->fSymbolTable->add(skCapsName, std::unique_ptr<Symbol>(skCaps));
255
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700256 StringFragment skArgsName("sk_Args");
257 Variable* skArgs = new Variable(-1, Modifiers(), skArgsName,
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400258 *fContext->fSkArgs_Type, Variable::kGlobal_Storage);
Ethan Nicholas762466e2017-06-29 10:03:38 -0400259 fIRGenerator->fSymbolTable->add(skArgsName, std::unique_ptr<Symbol>(skArgs));
260
Ethan Nicholasdb80f692019-11-22 14:06:12 -0500261 fIRGenerator->fIntrinsics = &fGPUIntrinsics;
262 std::vector<std::unique_ptr<ProgramElement>> gpuIntrinsics;
Ethan Nicholas8da1e652019-05-24 11:01:59 -0400263 this->processIncludeFile(Program::kFragment_Kind, SKSL_GPU_INCLUDE, strlen(SKSL_GPU_INCLUDE),
Ethan Nicholasdb80f692019-11-22 14:06:12 -0500264 symbols, &gpuIntrinsics, &fGpuSymbolTable);
Brian Salomonf8c187c2019-12-19 14:41:57 -0500265 this->processIncludeFile(Program::kFragment_Kind, SKSL_BLEND_INCLUDE,
266 strlen(SKSL_BLEND_INCLUDE), std::move(fGpuSymbolTable), &gpuIntrinsics,
267 &fGpuSymbolTable);
Ethan Nicholasdb80f692019-11-22 14:06:12 -0500268 grab_intrinsics(&gpuIntrinsics, &fGPUIntrinsics);
269 // need to hang on to the source so that FunctionDefinition.fSource pointers in this file
270 // remain valid
271 fGpuIncludeSource = std::move(fIRGenerator->fFile);
Ethan Nicholas8da1e652019-05-24 11:01:59 -0400272 this->processIncludeFile(Program::kVertex_Kind, SKSL_VERT_INCLUDE, strlen(SKSL_VERT_INCLUDE),
273 fGpuSymbolTable, &fVertexInclude, &fVertexSymbolTable);
274 this->processIncludeFile(Program::kFragment_Kind, SKSL_FRAG_INCLUDE, strlen(SKSL_FRAG_INCLUDE),
275 fGpuSymbolTable, &fFragmentInclude, &fFragmentSymbolTable);
276 this->processIncludeFile(Program::kGeometry_Kind, SKSL_GEOM_INCLUDE, strlen(SKSL_GEOM_INCLUDE),
277 fGpuSymbolTable, &fGeometryInclude, &fGeometrySymbolTable);
278 this->processIncludeFile(Program::kPipelineStage_Kind, SKSL_PIPELINE_INCLUDE,
279 strlen(SKSL_PIPELINE_INCLUDE), fGpuSymbolTable, &fPipelineInclude,
280 &fPipelineSymbolTable);
Ethan Nicholas99c54f02020-01-21 16:06:47 +0000281 std::vector<std::unique_ptr<ProgramElement>> interpIntrinsics;
Ethan Nicholas8da1e652019-05-24 11:01:59 -0400282 this->processIncludeFile(Program::kGeneric_Kind, SKSL_INTERP_INCLUDE,
283 strlen(SKSL_INTERP_INCLUDE), symbols, &fInterpreterInclude,
284 &fInterpreterSymbolTable);
Ethan Nicholas99c54f02020-01-21 16:06:47 +0000285 grab_intrinsics(&interpIntrinsics, &fInterpreterIntrinsics);
ethannicholasb3058bd2016-07-01 08:22:01 -0700286}
287
288Compiler::~Compiler() {
289 delete fIRGenerator;
290}
291
Ethan Nicholas8da1e652019-05-24 11:01:59 -0400292void Compiler::processIncludeFile(Program::Kind kind, const char* src, size_t length,
293 std::shared_ptr<SymbolTable> base,
294 std::vector<std::unique_ptr<ProgramElement>>* outElements,
295 std::shared_ptr<SymbolTable>* outSymbolTable) {
Ethan Nicholasa11035b2019-11-26 16:27:47 -0500296#ifdef SK_DEBUG
297 String source(src, length);
298 fSource = &source;
299#endif
Ethan Nicholas8da1e652019-05-24 11:01:59 -0400300 fIRGenerator->fSymbolTable = std::move(base);
301 Program::Settings settings;
Ethan Nicholasa11035b2019-11-26 16:27:47 -0500302#if !defined(SKSL_STANDALONE) & SK_SUPPORT_GPU
303 GrContextOptions opts;
304 GrShaderCaps caps(opts);
305 settings.fCaps = &caps;
306#endif
Ethan Nicholas8da1e652019-05-24 11:01:59 -0400307 fIRGenerator->start(&settings, nullptr);
308 fIRGenerator->convertProgram(kind, src, length, *fTypes, outElements);
309 if (this->fErrorCount) {
310 printf("Unexpected errors: %s\n", this->fErrorText.c_str());
311 }
312 SkASSERT(!fErrorCount);
313 fIRGenerator->fSymbolTable->markAllFunctionsBuiltin();
314 *outSymbolTable = fIRGenerator->fSymbolTable;
Ethan Nicholasa11035b2019-11-26 16:27:47 -0500315#ifdef SK_DEBUG
316 fSource = nullptr;
317#endif
Ethan Nicholas8da1e652019-05-24 11:01:59 -0400318}
319
ethannicholas22f939e2016-10-13 13:25:34 -0700320// add the definition created by assigning to the lvalue to the definition set
Ethan Nicholas86a43402017-01-19 13:32:00 -0500321void Compiler::addDefinition(const Expression* lvalue, std::unique_ptr<Expression>* expr,
322 DefinitionMap* definitions) {
ethannicholas22f939e2016-10-13 13:25:34 -0700323 switch (lvalue->fKind) {
324 case Expression::kVariableReference_Kind: {
325 const Variable& var = ((VariableReference*) lvalue)->fVariable;
326 if (var.fStorage == Variable::kLocal_Storage) {
327 (*definitions)[&var] = expr;
328 }
329 break;
330 }
331 case Expression::kSwizzle_Kind:
332 // We consider the variable written to as long as at least some of its components have
333 // been written to. This will lead to some false negatives (we won't catch it if you
334 // write to foo.x and then read foo.y), but being stricter could lead to false positives
Mike Klein6ad99092016-10-26 10:35:22 -0400335 // (we write to foo.x, and then pass foo to a function which happens to only read foo.x,
336 // 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 -0700337 // more complicated whole-program analysis. This is probably good enough.
Mike Klein6ad99092016-10-26 10:35:22 -0400338 this->addDefinition(((Swizzle*) lvalue)->fBase.get(),
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400339 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
ethannicholas22f939e2016-10-13 13:25:34 -0700340 definitions);
341 break;
342 case Expression::kIndex_Kind:
343 // see comments in Swizzle
Mike Klein6ad99092016-10-26 10:35:22 -0400344 this->addDefinition(((IndexExpression*) lvalue)->fBase.get(),
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400345 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
ethannicholas22f939e2016-10-13 13:25:34 -0700346 definitions);
347 break;
348 case Expression::kFieldAccess_Kind:
349 // see comments in Swizzle
Mike Klein6ad99092016-10-26 10:35:22 -0400350 this->addDefinition(((FieldAccess*) lvalue)->fBase.get(),
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400351 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
ethannicholas22f939e2016-10-13 13:25:34 -0700352 definitions);
353 break;
Ethan Nicholasa583b812018-01-18 13:32:11 -0500354 case Expression::kTernary_Kind:
355 // To simplify analysis, we just pretend that we write to both sides of the ternary.
356 // This allows for false positives (meaning we fail to detect that a variable might not
357 // have been assigned), but is preferable to false negatives.
358 this->addDefinition(((TernaryExpression*) lvalue)->fIfTrue.get(),
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400359 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
Ethan Nicholasa583b812018-01-18 13:32:11 -0500360 definitions);
361 this->addDefinition(((TernaryExpression*) lvalue)->fIfFalse.get(),
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400362 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
Ethan Nicholasa583b812018-01-18 13:32:11 -0500363 definitions);
364 break;
Ethan Nicholas91164d12019-05-15 15:29:54 -0400365 case Expression::kExternalValue_Kind:
366 break;
ethannicholas22f939e2016-10-13 13:25:34 -0700367 default:
368 // not an lvalue, can't happen
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400369 SkASSERT(false);
ethannicholas22f939e2016-10-13 13:25:34 -0700370 }
371}
372
373// add local variables defined by this node to the set
Mike Klein6ad99092016-10-26 10:35:22 -0400374void Compiler::addDefinitions(const BasicBlock::Node& node,
Ethan Nicholas86a43402017-01-19 13:32:00 -0500375 DefinitionMap* definitions) {
ethannicholas22f939e2016-10-13 13:25:34 -0700376 switch (node.fKind) {
377 case BasicBlock::Node::kExpression_Kind: {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400378 SkASSERT(node.expression());
Ethan Nicholascb670962017-04-20 19:31:52 -0400379 const Expression* expr = (Expression*) node.expression()->get();
Ethan Nicholas86a43402017-01-19 13:32:00 -0500380 switch (expr->fKind) {
381 case Expression::kBinary_Kind: {
382 BinaryExpression* b = (BinaryExpression*) expr;
383 if (b->fOperator == Token::EQ) {
384 this->addDefinition(b->fLeft.get(), &b->fRight, definitions);
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700385 } else if (Compiler::IsAssignment(b->fOperator)) {
Ethan Nicholas86a43402017-01-19 13:32:00 -0500386 this->addDefinition(
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400387 b->fLeft.get(),
388 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
389 definitions);
Ethan Nicholas86a43402017-01-19 13:32:00 -0500390
391 }
392 break;
ethannicholas22f939e2016-10-13 13:25:34 -0700393 }
Ethan Nicholasc6a19f12018-03-29 16:46:56 -0400394 case Expression::kFunctionCall_Kind: {
395 const FunctionCall& c = (const FunctionCall&) *expr;
396 for (size_t i = 0; i < c.fFunction.fParameters.size(); ++i) {
397 if (c.fFunction.fParameters[i]->fModifiers.fFlags & Modifiers::kOut_Flag) {
398 this->addDefinition(
399 c.fArguments[i].get(),
400 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
401 definitions);
402 }
403 }
404 break;
405 }
Ethan Nicholas86a43402017-01-19 13:32:00 -0500406 case Expression::kPrefix_Kind: {
407 const PrefixExpression* p = (PrefixExpression*) expr;
408 if (p->fOperator == Token::MINUSMINUS || p->fOperator == Token::PLUSPLUS) {
409 this->addDefinition(
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400410 p->fOperand.get(),
411 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
412 definitions);
Ethan Nicholas86a43402017-01-19 13:32:00 -0500413 }
414 break;
415 }
416 case Expression::kPostfix_Kind: {
417 const PostfixExpression* p = (PostfixExpression*) expr;
418 if (p->fOperator == Token::MINUSMINUS || p->fOperator == Token::PLUSPLUS) {
419 this->addDefinition(
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400420 p->fOperand.get(),
421 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
422 definitions);
Ethan Nicholas86a43402017-01-19 13:32:00 -0500423 }
424 break;
425 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400426 case Expression::kVariableReference_Kind: {
427 const VariableReference* v = (VariableReference*) expr;
428 if (v->fRefKind != VariableReference::kRead_RefKind) {
429 this->addDefinition(
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400430 v,
431 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
432 definitions);
Ethan Nicholascb670962017-04-20 19:31:52 -0400433 }
434 }
Ethan Nicholas86a43402017-01-19 13:32:00 -0500435 default:
436 break;
ethannicholas22f939e2016-10-13 13:25:34 -0700437 }
438 break;
439 }
440 case BasicBlock::Node::kStatement_Kind: {
Ethan Nicholascb670962017-04-20 19:31:52 -0400441 const Statement* stmt = (Statement*) node.statement()->get();
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000442 if (stmt->fKind == Statement::kVarDeclaration_Kind) {
443 VarDeclaration& vd = (VarDeclaration&) *stmt;
444 if (vd.fValue) {
445 (*definitions)[vd.fVar] = &vd.fValue;
ethannicholas22f939e2016-10-13 13:25:34 -0700446 }
447 }
448 break;
449 }
450 }
451}
452
453void Compiler::scanCFG(CFG* cfg, BlockId blockId, std::set<BlockId>* workList) {
454 BasicBlock& block = cfg->fBlocks[blockId];
455
456 // compute definitions after this block
Ethan Nicholas86a43402017-01-19 13:32:00 -0500457 DefinitionMap after = block.fBefore;
ethannicholas22f939e2016-10-13 13:25:34 -0700458 for (const BasicBlock::Node& n : block.fNodes) {
459 this->addDefinitions(n, &after);
460 }
461
462 // propagate definitions to exits
463 for (BlockId exitId : block.fExits) {
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400464 if (exitId == blockId) {
465 continue;
466 }
ethannicholas22f939e2016-10-13 13:25:34 -0700467 BasicBlock& exit = cfg->fBlocks[exitId];
468 for (const auto& pair : after) {
Ethan Nicholas86a43402017-01-19 13:32:00 -0500469 std::unique_ptr<Expression>* e1 = pair.second;
470 auto found = exit.fBefore.find(pair.first);
471 if (found == exit.fBefore.end()) {
472 // exit has no definition for it, just copy it
473 workList->insert(exitId);
ethannicholas22f939e2016-10-13 13:25:34 -0700474 exit.fBefore[pair.first] = e1;
475 } else {
Ethan Nicholas86a43402017-01-19 13:32:00 -0500476 // exit has a (possibly different) value already defined
477 std::unique_ptr<Expression>* e2 = exit.fBefore[pair.first];
ethannicholas22f939e2016-10-13 13:25:34 -0700478 if (e1 != e2) {
479 // definition has changed, merge and add exit block to worklist
480 workList->insert(exitId);
Ethan Nicholasaf197692017-02-27 13:26:45 -0500481 if (e1 && e2) {
482 exit.fBefore[pair.first] =
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400483 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression;
Ethan Nicholasaf197692017-02-27 13:26:45 -0500484 } else {
485 exit.fBefore[pair.first] = nullptr;
486 }
ethannicholas22f939e2016-10-13 13:25:34 -0700487 }
488 }
489 }
490 }
491}
492
493// returns a map which maps all local variables in the function to null, indicating that their value
494// is initially unknown
Ethan Nicholas86a43402017-01-19 13:32:00 -0500495static DefinitionMap compute_start_state(const CFG& cfg) {
496 DefinitionMap result;
Mike Klein6ad99092016-10-26 10:35:22 -0400497 for (const auto& block : cfg.fBlocks) {
498 for (const auto& node : block.fNodes) {
ethannicholas22f939e2016-10-13 13:25:34 -0700499 if (node.fKind == BasicBlock::Node::kStatement_Kind) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400500 SkASSERT(node.statement());
Ethan Nicholascb670962017-04-20 19:31:52 -0400501 const Statement* s = node.statement()->get();
ethannicholas22f939e2016-10-13 13:25:34 -0700502 if (s->fKind == Statement::kVarDeclarations_Kind) {
503 const VarDeclarationsStatement* vd = (const VarDeclarationsStatement*) s;
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000504 for (const auto& decl : vd->fDeclaration->fVars) {
505 if (decl->fKind == Statement::kVarDeclaration_Kind) {
506 result[((VarDeclaration&) *decl).fVar] = nullptr;
507 }
Mike Klein6ad99092016-10-26 10:35:22 -0400508 }
ethannicholas22f939e2016-10-13 13:25:34 -0700509 }
510 }
511 }
512 }
513 return result;
514}
515
Ethan Nicholascb670962017-04-20 19:31:52 -0400516/**
517 * Returns true if assigning to this lvalue has no effect.
518 */
519static bool is_dead(const Expression& lvalue) {
520 switch (lvalue.fKind) {
521 case Expression::kVariableReference_Kind:
522 return ((VariableReference&) lvalue).fVariable.dead();
523 case Expression::kSwizzle_Kind:
524 return is_dead(*((Swizzle&) lvalue).fBase);
525 case Expression::kFieldAccess_Kind:
526 return is_dead(*((FieldAccess&) lvalue).fBase);
527 case Expression::kIndex_Kind: {
528 const IndexExpression& idx = (IndexExpression&) lvalue;
Ethan Nicholas2a099da2020-01-02 14:40:54 -0500529 return is_dead(*idx.fBase) &&
530 !idx.fIndex->hasProperty(Expression::Property::kSideEffects);
Ethan Nicholascb670962017-04-20 19:31:52 -0400531 }
Ethan Nicholasa583b812018-01-18 13:32:11 -0500532 case Expression::kTernary_Kind: {
533 const TernaryExpression& t = (TernaryExpression&) lvalue;
534 return !t.fTest->hasSideEffects() && is_dead(*t.fIfTrue) && is_dead(*t.fIfFalse);
535 }
Ethan Nicholas91164d12019-05-15 15:29:54 -0400536 case Expression::kExternalValue_Kind:
537 return false;
Ethan Nicholascb670962017-04-20 19:31:52 -0400538 default:
Ethan Nicholas2a099da2020-01-02 14:40:54 -0500539#ifdef SK_DEBUG
Ethan Nicholascb670962017-04-20 19:31:52 -0400540 ABORT("invalid lvalue: %s\n", lvalue.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -0500541#endif
542 return false;
Ethan Nicholascb670962017-04-20 19:31:52 -0400543 }
544}
ethannicholas22f939e2016-10-13 13:25:34 -0700545
Ethan Nicholascb670962017-04-20 19:31:52 -0400546/**
547 * Returns true if this is an assignment which can be collapsed down to just the right hand side due
548 * to a dead target and lack of side effects on the left hand side.
549 */
550static bool dead_assignment(const BinaryExpression& b) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700551 if (!Compiler::IsAssignment(b.fOperator)) {
Ethan Nicholascb670962017-04-20 19:31:52 -0400552 return false;
553 }
554 return is_dead(*b.fLeft);
555}
556
557void Compiler::computeDataFlow(CFG* cfg) {
558 cfg->fBlocks[cfg->fStart].fBefore = compute_start_state(*cfg);
ethannicholas22f939e2016-10-13 13:25:34 -0700559 std::set<BlockId> workList;
Ethan Nicholascb670962017-04-20 19:31:52 -0400560 for (BlockId i = 0; i < cfg->fBlocks.size(); i++) {
ethannicholas22f939e2016-10-13 13:25:34 -0700561 workList.insert(i);
562 }
563 while (workList.size()) {
564 BlockId next = *workList.begin();
565 workList.erase(workList.begin());
Ethan Nicholascb670962017-04-20 19:31:52 -0400566 this->scanCFG(cfg, next, &workList);
ethannicholas22f939e2016-10-13 13:25:34 -0700567 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400568}
569
570/**
571 * Attempts to replace the expression pointed to by iter with a new one (in both the CFG and the
572 * IR). If the expression can be cleanly removed, returns true and updates the iterator to point to
573 * the newly-inserted element. Otherwise updates only the IR and returns false (and the CFG will
574 * need to be regenerated).
575 */
576bool try_replace_expression(BasicBlock* b,
577 std::vector<BasicBlock::Node>::iterator* iter,
578 std::unique_ptr<Expression>* newExpression) {
579 std::unique_ptr<Expression>* target = (*iter)->expression();
580 if (!b->tryRemoveExpression(iter)) {
581 *target = std::move(*newExpression);
582 return false;
583 }
584 *target = std::move(*newExpression);
585 return b->tryInsertExpression(iter, target);
586}
587
588/**
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400589 * Returns true if the expression is a constant numeric literal with the specified value, or a
590 * constant vector with all elements equal to the specified value.
Ethan Nicholascb670962017-04-20 19:31:52 -0400591 */
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400592bool is_constant(const Expression& expr, double value) {
Ethan Nicholascb670962017-04-20 19:31:52 -0400593 switch (expr.fKind) {
594 case Expression::kIntLiteral_Kind:
595 return ((IntLiteral&) expr).fValue == value;
596 case Expression::kFloatLiteral_Kind:
597 return ((FloatLiteral&) expr).fValue == value;
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400598 case Expression::kConstructor_Kind: {
599 Constructor& c = (Constructor&) expr;
Ethan Nicholasd188c182019-06-10 15:55:38 -0400600 bool isFloat = c.fType.columns() > 1 ? c.fType.componentType().isFloat()
601 : c.fType.isFloat();
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400602 if (c.fType.kind() == Type::kVector_Kind && c.isConstant()) {
603 for (int i = 0; i < c.fType.columns(); ++i) {
Ethan Nicholasd188c182019-06-10 15:55:38 -0400604 if (isFloat) {
605 if (c.getFVecComponent(i) != value) {
606 return false;
607 }
608 } else if (c.getIVecComponent(i) != value) {
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400609 return false;
610 }
611 }
612 return true;
613 }
614 return false;
615 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400616 default:
617 return false;
618 }
619}
620
621/**
622 * Collapses the binary expression pointed to by iter down to just the right side (in both the IR
623 * and CFG structures).
624 */
625void delete_left(BasicBlock* b,
626 std::vector<BasicBlock::Node>::iterator* iter,
627 bool* outUpdated,
628 bool* outNeedsRescan) {
629 *outUpdated = true;
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400630 std::unique_ptr<Expression>* target = (*iter)->expression();
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400631 SkASSERT((*target)->fKind == Expression::kBinary_Kind);
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400632 BinaryExpression& bin = (BinaryExpression&) **target;
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400633 SkASSERT(!bin.fLeft->hasSideEffects());
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400634 bool result;
635 if (bin.fOperator == Token::EQ) {
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400636 result = b->tryRemoveLValueBefore(iter, bin.fLeft.get());
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400637 } else {
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400638 result = b->tryRemoveExpressionBefore(iter, bin.fLeft.get());
Ethan Nicholascb670962017-04-20 19:31:52 -0400639 }
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400640 *target = std::move(bin.fRight);
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400641 if (!result) {
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400642 *outNeedsRescan = true;
643 return;
644 }
645 if (*iter == b->fNodes.begin()) {
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400646 *outNeedsRescan = true;
647 return;
648 }
649 --(*iter);
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400650 if ((*iter)->fKind != BasicBlock::Node::kExpression_Kind ||
651 (*iter)->expression() != &bin.fRight) {
652 *outNeedsRescan = true;
653 return;
654 }
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400655 *iter = b->fNodes.erase(*iter);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400656 SkASSERT((*iter)->expression() == target);
Ethan Nicholascb670962017-04-20 19:31:52 -0400657}
658
659/**
660 * Collapses the binary expression pointed to by iter down to just the left side (in both the IR and
661 * CFG structures).
662 */
663void delete_right(BasicBlock* b,
664 std::vector<BasicBlock::Node>::iterator* iter,
665 bool* outUpdated,
666 bool* outNeedsRescan) {
667 *outUpdated = true;
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400668 std::unique_ptr<Expression>* target = (*iter)->expression();
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400669 SkASSERT((*target)->fKind == Expression::kBinary_Kind);
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400670 BinaryExpression& bin = (BinaryExpression&) **target;
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400671 SkASSERT(!bin.fRight->hasSideEffects());
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400672 if (!b->tryRemoveExpressionBefore(iter, bin.fRight.get())) {
673 *target = std::move(bin.fLeft);
Ethan Nicholascb670962017-04-20 19:31:52 -0400674 *outNeedsRescan = true;
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400675 return;
Ethan Nicholascb670962017-04-20 19:31:52 -0400676 }
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400677 *target = std::move(bin.fLeft);
678 if (*iter == b->fNodes.begin()) {
679 *outNeedsRescan = true;
680 return;
681 }
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400682 --(*iter);
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400683 if (((*iter)->fKind != BasicBlock::Node::kExpression_Kind ||
684 (*iter)->expression() != &bin.fLeft)) {
685 *outNeedsRescan = true;
686 return;
687 }
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400688 *iter = b->fNodes.erase(*iter);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400689 SkASSERT((*iter)->expression() == target);
Ethan Nicholascb670962017-04-20 19:31:52 -0400690}
691
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400692/**
693 * Constructs the specified type using a single argument.
694 */
695static std::unique_ptr<Expression> construct(const Type& type, std::unique_ptr<Expression> v) {
696 std::vector<std::unique_ptr<Expression>> args;
697 args.push_back(std::move(v));
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700698 auto result = std::unique_ptr<Expression>(new Constructor(-1, type, std::move(args)));
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400699 return result;
700}
701
702/**
703 * Used in the implementations of vectorize_left and vectorize_right. Given a vector type and an
704 * expression x, deletes the expression pointed to by iter and replaces it with <type>(x).
705 */
706static void vectorize(BasicBlock* b,
707 std::vector<BasicBlock::Node>::iterator* iter,
708 const Type& type,
709 std::unique_ptr<Expression>* otherExpression,
710 bool* outUpdated,
711 bool* outNeedsRescan) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400712 SkASSERT((*(*iter)->expression())->fKind == Expression::kBinary_Kind);
713 SkASSERT(type.kind() == Type::kVector_Kind);
714 SkASSERT((*otherExpression)->fType.kind() == Type::kScalar_Kind);
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400715 *outUpdated = true;
716 std::unique_ptr<Expression>* target = (*iter)->expression();
717 if (!b->tryRemoveExpression(iter)) {
718 *target = construct(type, std::move(*otherExpression));
719 *outNeedsRescan = true;
720 } else {
721 *target = construct(type, std::move(*otherExpression));
722 if (!b->tryInsertExpression(iter, target)) {
723 *outNeedsRescan = true;
724 }
725 }
726}
727
728/**
729 * Given a binary expression of the form x <op> vec<n>(y), deletes the right side and vectorizes the
730 * left to yield vec<n>(x).
731 */
732static void vectorize_left(BasicBlock* b,
733 std::vector<BasicBlock::Node>::iterator* iter,
734 bool* outUpdated,
735 bool* outNeedsRescan) {
736 BinaryExpression& bin = (BinaryExpression&) **(*iter)->expression();
737 vectorize(b, iter, bin.fRight->fType, &bin.fLeft, outUpdated, outNeedsRescan);
738}
739
740/**
741 * Given a binary expression of the form vec<n>(x) <op> y, deletes the left side and vectorizes the
742 * right to yield vec<n>(y).
743 */
744static void vectorize_right(BasicBlock* b,
745 std::vector<BasicBlock::Node>::iterator* iter,
746 bool* outUpdated,
747 bool* outNeedsRescan) {
748 BinaryExpression& bin = (BinaryExpression&) **(*iter)->expression();
749 vectorize(b, iter, bin.fLeft->fType, &bin.fRight, outUpdated, outNeedsRescan);
750}
751
752// Mark that an expression which we were writing to is no longer being written to
753void clear_write(const Expression& expr) {
754 switch (expr.fKind) {
755 case Expression::kVariableReference_Kind: {
756 ((VariableReference&) expr).setRefKind(VariableReference::kRead_RefKind);
757 break;
758 }
759 case Expression::kFieldAccess_Kind:
760 clear_write(*((FieldAccess&) expr).fBase);
761 break;
762 case Expression::kSwizzle_Kind:
763 clear_write(*((Swizzle&) expr).fBase);
764 break;
765 case Expression::kIndex_Kind:
766 clear_write(*((IndexExpression&) expr).fBase);
767 break;
768 default:
769 ABORT("shouldn't be writing to this kind of expression\n");
770 break;
771 }
772}
773
Ethan Nicholascb670962017-04-20 19:31:52 -0400774void Compiler::simplifyExpression(DefinitionMap& definitions,
775 BasicBlock& b,
776 std::vector<BasicBlock::Node>::iterator* iter,
777 std::unordered_set<const Variable*>* undefinedVariables,
778 bool* outUpdated,
779 bool* outNeedsRescan) {
780 Expression* expr = (*iter)->expression()->get();
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400781 SkASSERT(expr);
Ethan Nicholascb670962017-04-20 19:31:52 -0400782 if ((*iter)->fConstantPropagation) {
783 std::unique_ptr<Expression> optimized = expr->constantPropagate(*fIRGenerator, definitions);
784 if (optimized) {
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400785 *outUpdated = true;
Ethan Nicholascb670962017-04-20 19:31:52 -0400786 if (!try_replace_expression(&b, iter, &optimized)) {
787 *outNeedsRescan = true;
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400788 return;
Ethan Nicholascb670962017-04-20 19:31:52 -0400789 }
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400790 SkASSERT((*iter)->fKind == BasicBlock::Node::kExpression_Kind);
Ethan Nicholascb670962017-04-20 19:31:52 -0400791 expr = (*iter)->expression()->get();
Ethan Nicholascb670962017-04-20 19:31:52 -0400792 }
793 }
794 switch (expr->fKind) {
795 case Expression::kVariableReference_Kind: {
Ethan Nicholas8f7e28f2018-03-26 14:24:27 -0400796 const VariableReference& ref = (VariableReference&) *expr;
797 const Variable& var = ref.fVariable;
798 if (ref.refKind() != VariableReference::kWrite_RefKind &&
799 ref.refKind() != VariableReference::kPointer_RefKind &&
800 var.fStorage == Variable::kLocal_Storage && !definitions[&var] &&
Ethan Nicholascb670962017-04-20 19:31:52 -0400801 (*undefinedVariables).find(&var) == (*undefinedVariables).end()) {
802 (*undefinedVariables).insert(&var);
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000803 this->error(expr->fOffset,
804 "'" + var.fName + "' has not been assigned");
Ethan Nicholascb670962017-04-20 19:31:52 -0400805 }
806 break;
807 }
808 case Expression::kTernary_Kind: {
809 TernaryExpression* t = (TernaryExpression*) expr;
810 if (t->fTest->fKind == Expression::kBoolLiteral_Kind) {
811 // ternary has a constant test, replace it with either the true or
812 // false branch
813 if (((BoolLiteral&) *t->fTest).fValue) {
814 (*iter)->setExpression(std::move(t->fIfTrue));
815 } else {
816 (*iter)->setExpression(std::move(t->fIfFalse));
817 }
818 *outUpdated = true;
819 *outNeedsRescan = true;
820 }
821 break;
822 }
823 case Expression::kBinary_Kind: {
Ethan Nicholascb670962017-04-20 19:31:52 -0400824 BinaryExpression* bin = (BinaryExpression*) expr;
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400825 if (dead_assignment(*bin)) {
826 delete_left(&b, iter, outUpdated, outNeedsRescan);
827 break;
828 }
829 // collapse useless expressions like x * 1 or x + 0
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400830 if (((bin->fLeft->fType.kind() != Type::kScalar_Kind) &&
831 (bin->fLeft->fType.kind() != Type::kVector_Kind)) ||
832 ((bin->fRight->fType.kind() != Type::kScalar_Kind) &&
833 (bin->fRight->fType.kind() != Type::kVector_Kind))) {
834 break;
835 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400836 switch (bin->fOperator) {
837 case Token::STAR:
838 if (is_constant(*bin->fLeft, 1)) {
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400839 if (bin->fLeft->fType.kind() == Type::kVector_Kind &&
840 bin->fRight->fType.kind() == Type::kScalar_Kind) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400841 // float4(1) * x -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400842 vectorize_right(&b, iter, outUpdated, outNeedsRescan);
843 } else {
844 // 1 * x -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400845 // 1 * float4(x) -> float4(x)
846 // float4(1) * float4(x) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400847 delete_left(&b, iter, outUpdated, outNeedsRescan);
848 }
849 }
850 else if (is_constant(*bin->fLeft, 0)) {
851 if (bin->fLeft->fType.kind() == Type::kScalar_Kind &&
Ethan Nicholas08dae922018-01-23 10:31:56 -0500852 bin->fRight->fType.kind() == Type::kVector_Kind &&
853 !bin->fRight->hasSideEffects()) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400854 // 0 * float4(x) -> float4(0)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400855 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
856 } else {
857 // 0 * x -> 0
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400858 // float4(0) * x -> float4(0)
859 // float4(0) * float4(x) -> float4(0)
Ethan Nicholas51493ee2017-12-11 12:34:33 -0500860 if (!bin->fRight->hasSideEffects()) {
861 delete_right(&b, iter, outUpdated, outNeedsRescan);
862 }
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400863 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400864 }
865 else if (is_constant(*bin->fRight, 1)) {
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400866 if (bin->fLeft->fType.kind() == Type::kScalar_Kind &&
867 bin->fRight->fType.kind() == Type::kVector_Kind) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400868 // x * float4(1) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400869 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
870 } else {
871 // x * 1 -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400872 // float4(x) * 1 -> float4(x)
873 // float4(x) * float4(1) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400874 delete_right(&b, iter, outUpdated, outNeedsRescan);
875 }
876 }
877 else if (is_constant(*bin->fRight, 0)) {
878 if (bin->fLeft->fType.kind() == Type::kVector_Kind &&
Ethan Nicholas08dae922018-01-23 10:31:56 -0500879 bin->fRight->fType.kind() == Type::kScalar_Kind &&
880 !bin->fLeft->hasSideEffects()) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400881 // float4(x) * 0 -> float4(0)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400882 vectorize_right(&b, iter, outUpdated, outNeedsRescan);
883 } else {
884 // x * 0 -> 0
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400885 // x * float4(0) -> float4(0)
886 // float4(x) * float4(0) -> float4(0)
Ethan Nicholas51493ee2017-12-11 12:34:33 -0500887 if (!bin->fLeft->hasSideEffects()) {
888 delete_left(&b, iter, outUpdated, outNeedsRescan);
889 }
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400890 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400891 }
892 break;
Ethan Nicholas56e42712017-04-21 10:23:37 -0400893 case Token::PLUS:
Ethan Nicholascb670962017-04-20 19:31:52 -0400894 if (is_constant(*bin->fLeft, 0)) {
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400895 if (bin->fLeft->fType.kind() == Type::kVector_Kind &&
896 bin->fRight->fType.kind() == Type::kScalar_Kind) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400897 // float4(0) + x -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400898 vectorize_right(&b, iter, outUpdated, outNeedsRescan);
899 } else {
900 // 0 + x -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400901 // 0 + float4(x) -> float4(x)
902 // float4(0) + float4(x) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400903 delete_left(&b, iter, outUpdated, outNeedsRescan);
904 }
905 } else if (is_constant(*bin->fRight, 0)) {
906 if (bin->fLeft->fType.kind() == Type::kScalar_Kind &&
907 bin->fRight->fType.kind() == Type::kVector_Kind) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400908 // x + float4(0) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400909 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
910 } else {
911 // x + 0 -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400912 // float4(x) + 0 -> float4(x)
913 // float4(x) + float4(0) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400914 delete_right(&b, iter, outUpdated, outNeedsRescan);
915 }
Ethan Nicholas56e42712017-04-21 10:23:37 -0400916 }
917 break;
918 case Token::MINUS:
919 if (is_constant(*bin->fRight, 0)) {
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400920 if (bin->fLeft->fType.kind() == Type::kScalar_Kind &&
921 bin->fRight->fType.kind() == Type::kVector_Kind) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400922 // x - float4(0) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400923 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
924 } else {
925 // x - 0 -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400926 // float4(x) - 0 -> float4(x)
927 // float4(x) - float4(0) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400928 delete_right(&b, iter, outUpdated, outNeedsRescan);
929 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400930 }
931 break;
932 case Token::SLASH:
933 if (is_constant(*bin->fRight, 1)) {
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400934 if (bin->fLeft->fType.kind() == Type::kScalar_Kind &&
935 bin->fRight->fType.kind() == Type::kVector_Kind) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400936 // x / float4(1) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400937 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
938 } else {
939 // x / 1 -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400940 // float4(x) / 1 -> float4(x)
941 // float4(x) / float4(1) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400942 delete_right(&b, iter, outUpdated, outNeedsRescan);
943 }
944 } else if (is_constant(*bin->fLeft, 0)) {
945 if (bin->fLeft->fType.kind() == Type::kScalar_Kind &&
Ethan Nicholas08dae922018-01-23 10:31:56 -0500946 bin->fRight->fType.kind() == Type::kVector_Kind &&
947 !bin->fRight->hasSideEffects()) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400948 // 0 / float4(x) -> float4(0)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400949 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
950 } else {
951 // 0 / x -> 0
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400952 // float4(0) / x -> float4(0)
953 // float4(0) / float4(x) -> float4(0)
Ethan Nicholas51493ee2017-12-11 12:34:33 -0500954 if (!bin->fRight->hasSideEffects()) {
955 delete_right(&b, iter, outUpdated, outNeedsRescan);
956 }
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400957 }
958 }
959 break;
960 case Token::PLUSEQ:
961 if (is_constant(*bin->fRight, 0)) {
962 clear_write(*bin->fLeft);
963 delete_right(&b, iter, outUpdated, outNeedsRescan);
964 }
965 break;
966 case Token::MINUSEQ:
967 if (is_constant(*bin->fRight, 0)) {
968 clear_write(*bin->fLeft);
969 delete_right(&b, iter, outUpdated, outNeedsRescan);
970 }
971 break;
972 case Token::STAREQ:
973 if (is_constant(*bin->fRight, 1)) {
974 clear_write(*bin->fLeft);
975 delete_right(&b, iter, outUpdated, outNeedsRescan);
976 }
977 break;
978 case Token::SLASHEQ:
979 if (is_constant(*bin->fRight, 1)) {
980 clear_write(*bin->fLeft);
Ethan Nicholascb670962017-04-20 19:31:52 -0400981 delete_right(&b, iter, outUpdated, outNeedsRescan);
982 }
983 break;
984 default:
985 break;
986 }
Ethan Nicholas409f6f02019-09-17 12:34:39 -0400987 break;
988 }
989 case Expression::kSwizzle_Kind: {
990 Swizzle& s = (Swizzle&) *expr;
991 // detect identity swizzles like foo.rgba
992 if ((int) s.fComponents.size() == s.fBase->fType.columns()) {
993 bool identity = true;
994 for (int i = 0; i < (int) s.fComponents.size(); ++i) {
995 if (s.fComponents[i] != i) {
996 identity = false;
997 break;
998 }
999 }
1000 if (identity) {
1001 *outUpdated = true;
1002 if (!try_replace_expression(&b, iter, &s.fBase)) {
1003 *outNeedsRescan = true;
1004 return;
1005 }
1006 SkASSERT((*iter)->fKind == BasicBlock::Node::kExpression_Kind);
1007 break;
1008 }
1009 }
1010 // detect swizzles of swizzles, e.g. replace foo.argb.r000 with foo.a000
1011 if (s.fBase->fKind == Expression::kSwizzle_Kind) {
1012 Swizzle& base = (Swizzle&) *s.fBase;
1013 std::vector<int> final;
1014 for (int c : s.fComponents) {
1015 if (c == SKSL_SWIZZLE_0 || c == SKSL_SWIZZLE_1) {
1016 final.push_back(c);
1017 } else {
1018 final.push_back(base.fComponents[c]);
1019 }
1020 }
1021 *outUpdated = true;
1022 std::unique_ptr<Expression> replacement(new Swizzle(*fContext, base.fBase->clone(),
1023 std::move(final)));
1024 if (!try_replace_expression(&b, iter, &replacement)) {
1025 *outNeedsRescan = true;
1026 return;
1027 }
1028 SkASSERT((*iter)->fKind == BasicBlock::Node::kExpression_Kind);
1029 break;
1030 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001031 }
1032 default:
1033 break;
1034 }
1035}
1036
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001037// returns true if this statement could potentially execute a break at the current level (we ignore
1038// nested loops and switches, since any breaks inside of them will merely break the loop / switch)
Ethan Nicholas5005a222018-08-24 13:06:27 -04001039static bool contains_conditional_break(Statement& s, bool inConditional) {
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001040 switch (s.fKind) {
1041 case Statement::kBlock_Kind:
1042 for (const auto& sub : ((Block&) s).fStatements) {
Ethan Nicholas5005a222018-08-24 13:06:27 -04001043 if (contains_conditional_break(*sub, inConditional)) {
1044 return true;
1045 }
1046 }
1047 return false;
1048 case Statement::kBreak_Kind:
1049 return inConditional;
1050 case Statement::kIf_Kind: {
1051 const IfStatement& i = (IfStatement&) s;
1052 return contains_conditional_break(*i.fIfTrue, true) ||
1053 (i.fIfFalse && contains_conditional_break(*i.fIfFalse, true));
1054 }
1055 default:
1056 return false;
1057 }
1058}
1059
1060// returns true if this statement definitely executes a break at the current level (we ignore
1061// nested loops and switches, since any breaks inside of them will merely break the loop / switch)
1062static bool contains_unconditional_break(Statement& s) {
1063 switch (s.fKind) {
1064 case Statement::kBlock_Kind:
1065 for (const auto& sub : ((Block&) s).fStatements) {
1066 if (contains_unconditional_break(*sub)) {
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001067 return true;
1068 }
1069 }
1070 return false;
1071 case Statement::kBreak_Kind:
1072 return true;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001073 default:
1074 return false;
1075 }
1076}
1077
1078// Returns a block containing all of the statements that will be run if the given case matches
1079// (which, owing to the statements being owned by unique_ptrs, means the switch itself will be
1080// broken by this call and must then be discarded).
1081// Returns null (and leaves the switch unmodified) if no such simple reduction is possible, such as
1082// when break statements appear inside conditionals.
1083static std::unique_ptr<Statement> block_for_case(SwitchStatement* s, SwitchCase* c) {
1084 bool capturing = false;
1085 std::vector<std::unique_ptr<Statement>*> statementPtrs;
1086 for (const auto& current : s->fCases) {
1087 if (current.get() == c) {
1088 capturing = true;
1089 }
1090 if (capturing) {
1091 for (auto& stmt : current->fStatements) {
Ethan Nicholas5005a222018-08-24 13:06:27 -04001092 if (contains_conditional_break(*stmt, s->fKind == Statement::kIf_Kind)) {
1093 return nullptr;
1094 }
1095 if (contains_unconditional_break(*stmt)) {
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001096 capturing = false;
1097 break;
1098 }
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001099 statementPtrs.push_back(&stmt);
1100 }
1101 if (!capturing) {
1102 break;
1103 }
1104 }
1105 }
1106 std::vector<std::unique_ptr<Statement>> statements;
1107 for (const auto& s : statementPtrs) {
1108 statements.push_back(std::move(*s));
1109 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001110 return std::unique_ptr<Statement>(new Block(-1, std::move(statements), s->fSymbols));
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001111}
1112
Ethan Nicholascb670962017-04-20 19:31:52 -04001113void Compiler::simplifyStatement(DefinitionMap& definitions,
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001114 BasicBlock& b,
1115 std::vector<BasicBlock::Node>::iterator* iter,
1116 std::unordered_set<const Variable*>* undefinedVariables,
1117 bool* outUpdated,
1118 bool* outNeedsRescan) {
Ethan Nicholascb670962017-04-20 19:31:52 -04001119 Statement* stmt = (*iter)->statement()->get();
1120 switch (stmt->fKind) {
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001121 case Statement::kVarDeclaration_Kind: {
1122 const auto& varDecl = (VarDeclaration&) *stmt;
1123 if (varDecl.fVar->dead() &&
1124 (!varDecl.fValue ||
1125 !varDecl.fValue->hasSideEffects())) {
1126 if (varDecl.fValue) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001127 SkASSERT((*iter)->statement()->get() == stmt);
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001128 if (!b.tryRemoveExpressionBefore(iter, varDecl.fValue.get())) {
1129 *outNeedsRescan = true;
Ethan Nicholascb670962017-04-20 19:31:52 -04001130 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001131 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001132 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001133 *outUpdated = true;
Ethan Nicholascb670962017-04-20 19:31:52 -04001134 }
1135 break;
1136 }
1137 case Statement::kIf_Kind: {
1138 IfStatement& i = (IfStatement&) *stmt;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001139 if (i.fTest->fKind == Expression::kBoolLiteral_Kind) {
1140 // constant if, collapse down to a single branch
1141 if (((BoolLiteral&) *i.fTest).fValue) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001142 SkASSERT(i.fIfTrue);
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001143 (*iter)->setStatement(std::move(i.fIfTrue));
1144 } else {
1145 if (i.fIfFalse) {
1146 (*iter)->setStatement(std::move(i.fIfFalse));
1147 } else {
1148 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
1149 }
1150 }
1151 *outUpdated = true;
1152 *outNeedsRescan = true;
1153 break;
1154 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001155 if (i.fIfFalse && i.fIfFalse->isEmpty()) {
1156 // else block doesn't do anything, remove it
1157 i.fIfFalse.reset();
1158 *outUpdated = true;
1159 *outNeedsRescan = true;
1160 }
1161 if (!i.fIfFalse && i.fIfTrue->isEmpty()) {
1162 // if block doesn't do anything, no else block
1163 if (i.fTest->hasSideEffects()) {
1164 // test has side effects, keep it
1165 (*iter)->setStatement(std::unique_ptr<Statement>(
1166 new ExpressionStatement(std::move(i.fTest))));
1167 } else {
1168 // no if, no else, no test side effects, kill the whole if
1169 // statement
1170 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
1171 }
1172 *outUpdated = true;
1173 *outNeedsRescan = true;
1174 }
1175 break;
1176 }
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001177 case Statement::kSwitch_Kind: {
1178 SwitchStatement& s = (SwitchStatement&) *stmt;
1179 if (s.fValue->isConstant()) {
1180 // switch is constant, replace it with the case that matches
1181 bool found = false;
1182 SwitchCase* defaultCase = nullptr;
1183 for (const auto& c : s.fCases) {
1184 if (!c->fValue) {
1185 defaultCase = c.get();
1186 continue;
1187 }
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001188 SkASSERT(c->fValue->fKind == s.fValue->fKind);
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001189 found = c->fValue->compareConstant(*fContext, *s.fValue);
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001190 if (found) {
1191 std::unique_ptr<Statement> newBlock = block_for_case(&s, c.get());
1192 if (newBlock) {
1193 (*iter)->setStatement(std::move(newBlock));
1194 break;
1195 } else {
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -04001196 if (s.fIsStatic && !(fFlags & kPermitInvalidStaticTests_Flag)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001197 this->error(s.fOffset,
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001198 "static switch contains non-static conditional break");
1199 s.fIsStatic = false;
1200 }
1201 return; // can't simplify
1202 }
1203 }
1204 }
1205 if (!found) {
1206 // no matching case. use default if it exists, or kill the whole thing
1207 if (defaultCase) {
1208 std::unique_ptr<Statement> newBlock = block_for_case(&s, defaultCase);
1209 if (newBlock) {
1210 (*iter)->setStatement(std::move(newBlock));
1211 } else {
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -04001212 if (s.fIsStatic && !(fFlags & kPermitInvalidStaticTests_Flag)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001213 this->error(s.fOffset,
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001214 "static switch contains non-static conditional break");
1215 s.fIsStatic = false;
1216 }
1217 return; // can't simplify
1218 }
1219 } else {
1220 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
1221 }
1222 }
1223 *outUpdated = true;
1224 *outNeedsRescan = true;
1225 }
1226 break;
1227 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001228 case Statement::kExpression_Kind: {
1229 ExpressionStatement& e = (ExpressionStatement&) *stmt;
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001230 SkASSERT((*iter)->statement()->get() == &e);
Ethan Nicholascb670962017-04-20 19:31:52 -04001231 if (!e.fExpression->hasSideEffects()) {
1232 // Expression statement with no side effects, kill it
1233 if (!b.tryRemoveExpressionBefore(iter, e.fExpression.get())) {
1234 *outNeedsRescan = true;
1235 }
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001236 SkASSERT((*iter)->statement()->get() == stmt);
Ethan Nicholascb670962017-04-20 19:31:52 -04001237 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
1238 *outUpdated = true;
1239 }
1240 break;
1241 }
1242 default:
1243 break;
1244 }
1245}
1246
1247void Compiler::scanCFG(FunctionDefinition& f) {
1248 CFG cfg = CFGGenerator().getCFG(f);
1249 this->computeDataFlow(&cfg);
ethannicholas22f939e2016-10-13 13:25:34 -07001250
1251 // check for unreachable code
1252 for (size_t i = 0; i < cfg.fBlocks.size(); i++) {
Mike Klein6ad99092016-10-26 10:35:22 -04001253 if (i != cfg.fStart && !cfg.fBlocks[i].fEntrances.size() &&
ethannicholas22f939e2016-10-13 13:25:34 -07001254 cfg.fBlocks[i].fNodes.size()) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001255 int offset;
Ethan Nicholas86a43402017-01-19 13:32:00 -05001256 switch (cfg.fBlocks[i].fNodes[0].fKind) {
1257 case BasicBlock::Node::kStatement_Kind:
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001258 offset = (*cfg.fBlocks[i].fNodes[0].statement())->fOffset;
Ethan Nicholas86a43402017-01-19 13:32:00 -05001259 break;
1260 case BasicBlock::Node::kExpression_Kind:
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001261 offset = (*cfg.fBlocks[i].fNodes[0].expression())->fOffset;
Ethan Nicholas86a43402017-01-19 13:32:00 -05001262 break;
1263 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001264 this->error(offset, String("unreachable"));
ethannicholas22f939e2016-10-13 13:25:34 -07001265 }
1266 }
1267 if (fErrorCount) {
1268 return;
1269 }
1270
Ethan Nicholascb670962017-04-20 19:31:52 -04001271 // check for dead code & undefined variables, perform constant propagation
1272 std::unordered_set<const Variable*> undefinedVariables;
1273 bool updated;
1274 bool needsRescan = false;
1275 do {
1276 if (needsRescan) {
1277 cfg = CFGGenerator().getCFG(f);
1278 this->computeDataFlow(&cfg);
1279 needsRescan = false;
Ethan Nicholas113628d2017-02-02 16:11:39 -05001280 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001281
1282 updated = false;
1283 for (BasicBlock& b : cfg.fBlocks) {
1284 DefinitionMap definitions = b.fBefore;
1285
1286 for (auto iter = b.fNodes.begin(); iter != b.fNodes.end() && !needsRescan; ++iter) {
1287 if (iter->fKind == BasicBlock::Node::kExpression_Kind) {
1288 this->simplifyExpression(definitions, b, &iter, &undefinedVariables, &updated,
1289 &needsRescan);
1290 } else {
1291 this->simplifyStatement(definitions, b, &iter, &undefinedVariables, &updated,
1292 &needsRescan);
1293 }
Ethan Nicholas4b330df2017-05-17 10:52:55 -04001294 if (needsRescan) {
1295 break;
1296 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001297 this->addDefinitions(*iter, &definitions);
1298 }
1299 }
1300 } while (updated);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001301 SkASSERT(!needsRescan);
ethannicholas22f939e2016-10-13 13:25:34 -07001302
Ethan Nicholas91a10532017-06-22 11:24:38 -04001303 // verify static ifs & switches, clean up dead variable decls
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001304 for (BasicBlock& b : cfg.fBlocks) {
1305 DefinitionMap definitions = b.fBefore;
1306
Ethan Nicholas91a10532017-06-22 11:24:38 -04001307 for (auto iter = b.fNodes.begin(); iter != b.fNodes.end() && !needsRescan;) {
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001308 if (iter->fKind == BasicBlock::Node::kStatement_Kind) {
1309 const Statement& s = **iter->statement();
1310 switch (s.fKind) {
1311 case Statement::kIf_Kind:
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -04001312 if (((const IfStatement&) s).fIsStatic &&
1313 !(fFlags & kPermitInvalidStaticTests_Flag)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001314 this->error(s.fOffset, "static if has non-static test");
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001315 }
Ethan Nicholas91a10532017-06-22 11:24:38 -04001316 ++iter;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001317 break;
1318 case Statement::kSwitch_Kind:
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -04001319 if (((const SwitchStatement&) s).fIsStatic &&
1320 !(fFlags & kPermitInvalidStaticTests_Flag)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001321 this->error(s.fOffset, "static switch has non-static test");
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001322 }
Ethan Nicholas91a10532017-06-22 11:24:38 -04001323 ++iter;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001324 break;
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001325 case Statement::kVarDeclarations_Kind: {
1326 VarDeclarations& decls = *((VarDeclarationsStatement&) s).fDeclaration;
1327 for (auto varIter = decls.fVars.begin(); varIter != decls.fVars.end();) {
1328 if ((*varIter)->fKind == Statement::kNop_Kind) {
1329 varIter = decls.fVars.erase(varIter);
1330 } else {
1331 ++varIter;
1332 }
1333 }
1334 if (!decls.fVars.size()) {
1335 iter = b.fNodes.erase(iter);
1336 } else {
1337 ++iter;
1338 }
1339 break;
1340 }
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001341 default:
Ethan Nicholas91a10532017-06-22 11:24:38 -04001342 ++iter;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001343 break;
1344 }
Ethan Nicholas91a10532017-06-22 11:24:38 -04001345 } else {
1346 ++iter;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001347 }
1348 }
1349 }
1350
ethannicholas22f939e2016-10-13 13:25:34 -07001351 // check for missing return
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001352 if (f.fDeclaration.fReturnType != *fContext->fVoid_Type) {
ethannicholas22f939e2016-10-13 13:25:34 -07001353 if (cfg.fBlocks[cfg.fExit].fEntrances.size()) {
Ethan Nicholasdb80f692019-11-22 14:06:12 -05001354 this->error(f.fOffset, String("function '" + String(f.fDeclaration.fName) +
1355 "' can exit without returning a value"));
ethannicholas22f939e2016-10-13 13:25:34 -07001356 }
1357 }
1358}
1359
Ethan Nicholas91164d12019-05-15 15:29:54 -04001360void Compiler::registerExternalValue(ExternalValue* value) {
1361 fIRGenerator->fRootSymbolTable->addWithoutOwnership(value->fName, value);
1362}
1363
1364Symbol* Compiler::takeOwnership(std::unique_ptr<Symbol> symbol) {
1365 return fIRGenerator->fRootSymbolTable->takeOwnership(std::move(symbol));
1366}
1367
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001368std::unique_ptr<Program> Compiler::convertProgram(Program::Kind kind, String text,
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001369 const Program::Settings& settings) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001370 fErrorText = "";
1371 fErrorCount = 0;
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001372 std::vector<std::unique_ptr<ProgramElement>>* inherited;
ethannicholasd598f792016-07-25 10:08:54 -07001373 std::vector<std::unique_ptr<ProgramElement>> elements;
ethannicholasb3058bd2016-07-01 08:22:01 -07001374 switch (kind) {
1375 case Program::kVertex_Kind:
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001376 inherited = &fVertexInclude;
1377 fIRGenerator->fSymbolTable = fVertexSymbolTable;
Ethan Nicholasdb80f692019-11-22 14:06:12 -05001378 fIRGenerator->fIntrinsics = &fGPUIntrinsics;
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001379 fIRGenerator->start(&settings, inherited);
ethannicholasb3058bd2016-07-01 08:22:01 -07001380 break;
1381 case Program::kFragment_Kind:
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001382 inherited = &fFragmentInclude;
1383 fIRGenerator->fSymbolTable = fFragmentSymbolTable;
Ethan Nicholasdb80f692019-11-22 14:06:12 -05001384 fIRGenerator->fIntrinsics = &fGPUIntrinsics;
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001385 fIRGenerator->start(&settings, inherited);
ethannicholasb3058bd2016-07-01 08:22:01 -07001386 break;
Ethan Nicholas52cad152017-02-16 16:37:32 -05001387 case Program::kGeometry_Kind:
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001388 inherited = &fGeometryInclude;
1389 fIRGenerator->fSymbolTable = fGeometrySymbolTable;
Ethan Nicholasdb80f692019-11-22 14:06:12 -05001390 fIRGenerator->fIntrinsics = &fGPUIntrinsics;
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001391 fIRGenerator->start(&settings, inherited);
Ethan Nicholas52cad152017-02-16 16:37:32 -05001392 break;
Ethan Nicholas762466e2017-06-29 10:03:38 -04001393 case Program::kFragmentProcessor_Kind:
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001394 inherited = nullptr;
Ethan Nicholas8da1e652019-05-24 11:01:59 -04001395 fIRGenerator->fSymbolTable = fGpuSymbolTable;
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001396 fIRGenerator->start(&settings, nullptr);
Ethan Nicholasdb80f692019-11-22 14:06:12 -05001397 fIRGenerator->fIntrinsics = &fGPUIntrinsics;
Robert Phillipsfe8da172018-01-24 14:52:02 +00001398 fIRGenerator->convertProgram(kind, SKSL_FP_INCLUDE, strlen(SKSL_FP_INCLUDE), *fTypes,
Ethan Nicholasf7b88202017-09-18 14:10:39 -04001399 &elements);
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001400 fIRGenerator->fSymbolTable->markAllFunctionsBuiltin();
Ethan Nicholas762466e2017-06-29 10:03:38 -04001401 break;
Ethan Nicholas8da1e652019-05-24 11:01:59 -04001402 case Program::kPipelineStage_Kind:
1403 inherited = &fPipelineInclude;
1404 fIRGenerator->fSymbolTable = fPipelineSymbolTable;
Ethan Nicholasdb80f692019-11-22 14:06:12 -05001405 fIRGenerator->fIntrinsics = &fGPUIntrinsics;
Ethan Nicholas8da1e652019-05-24 11:01:59 -04001406 fIRGenerator->start(&settings, inherited);
1407 break;
Ethan Nicholas746035a2019-04-23 13:31:09 -04001408 case Program::kGeneric_Kind:
Ethan Nicholas8da1e652019-05-24 11:01:59 -04001409 inherited = &fInterpreterInclude;
1410 fIRGenerator->fSymbolTable = fInterpreterSymbolTable;
Ethan Nicholasdb80f692019-11-22 14:06:12 -05001411 fIRGenerator->fIntrinsics = &fInterpreterIntrinsics;
Ethan Nicholas8da1e652019-05-24 11:01:59 -04001412 fIRGenerator->start(&settings, inherited);
Ethan Nicholas0d997662019-04-08 09:46:01 -04001413 break;
ethannicholasb3058bd2016-07-01 08:22:01 -07001414 }
Ethan Nicholasaae47c82017-11-10 15:34:03 -05001415 for (auto& element : elements) {
1416 if (element->fKind == ProgramElement::kEnum_Kind) {
1417 ((Enum&) *element).fBuiltin = true;
1418 }
1419 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001420 std::unique_ptr<String> textPtr(new String(std::move(text)));
1421 fSource = textPtr.get();
Robert Phillipsfe8da172018-01-24 14:52:02 +00001422 fIRGenerator->convertProgram(kind, textPtr->c_str(), textPtr->size(), *fTypes, &elements);
Ethan Nicholasf7b88202017-09-18 14:10:39 -04001423 auto result = std::unique_ptr<Program>(new Program(kind,
1424 std::move(textPtr),
1425 settings,
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001426 fContext,
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001427 inherited,
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001428 std::move(elements),
1429 fIRGenerator->fSymbolTable,
1430 fIRGenerator->fInputs));
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001431 if (fErrorCount) {
1432 return nullptr;
1433 }
1434 return result;
1435}
1436
Ethan Nicholas00543112018-07-31 09:44:36 -04001437bool Compiler::optimize(Program& program) {
1438 SkASSERT(!fErrorCount);
1439 if (!program.fIsOptimized) {
1440 program.fIsOptimized = true;
1441 fIRGenerator->fKind = program.fKind;
1442 fIRGenerator->fSettings = &program.fSettings;
1443 for (auto& element : program) {
1444 if (element.fKind == ProgramElement::kFunction_Kind) {
1445 this->scanCFG((FunctionDefinition&) element);
1446 }
1447 }
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001448 if (program.fKind != Program::kFragmentProcessor_Kind) {
1449 for (auto iter = program.fElements.begin(); iter != program.fElements.end();) {
1450 if ((*iter)->fKind == ProgramElement::kVar_Kind) {
1451 VarDeclarations& vars = (VarDeclarations&) **iter;
1452 for (auto varIter = vars.fVars.begin(); varIter != vars.fVars.end();) {
1453 const Variable& var = *((VarDeclaration&) **varIter).fVar;
1454 if (var.dead()) {
1455 varIter = vars.fVars.erase(varIter);
1456 } else {
1457 ++varIter;
1458 }
1459 }
1460 if (vars.fVars.size() == 0) {
1461 iter = program.fElements.erase(iter);
1462 continue;
1463 }
1464 }
1465 ++iter;
1466 }
1467 }
Ethan Nicholas00543112018-07-31 09:44:36 -04001468 }
1469 return fErrorCount == 0;
1470}
1471
1472std::unique_ptr<Program> Compiler::specialize(
1473 Program& program,
1474 const std::unordered_map<SkSL::String, SkSL::Program::Settings::Value>& inputs) {
1475 std::vector<std::unique_ptr<ProgramElement>> elements;
1476 for (const auto& e : program) {
1477 elements.push_back(e.clone());
1478 }
1479 Program::Settings settings;
1480 settings.fCaps = program.fSettings.fCaps;
1481 for (auto iter = inputs.begin(); iter != inputs.end(); ++iter) {
1482 settings.fArgs.insert(*iter);
1483 }
Brian Osman808f0212020-01-21 15:36:47 -05001484 std::unique_ptr<String> sourceCopy(new String(*program.fSource));
Ethan Nicholas00543112018-07-31 09:44:36 -04001485 std::unique_ptr<Program> result(new Program(program.fKind,
Brian Osman808f0212020-01-21 15:36:47 -05001486 std::move(sourceCopy),
Ethan Nicholas00543112018-07-31 09:44:36 -04001487 settings,
1488 program.fContext,
1489 program.fInheritedElements,
1490 std::move(elements),
1491 program.fSymbols,
1492 program.fInputs));
1493 return result;
1494}
1495
Brian Osmanfb32ddf2019-06-18 10:14:20 -04001496#if defined(SKSL_STANDALONE) || SK_SUPPORT_GPU
1497
Ethan Nicholas00543112018-07-31 09:44:36 -04001498bool Compiler::toSPIRV(Program& program, OutputStream& out) {
1499 if (!this->optimize(program)) {
1500 return false;
1501 }
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001502#ifdef SK_ENABLE_SPIRV_VALIDATION
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001503 StringStream buffer;
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001504 fSource = program.fSource.get();
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001505 SPIRVCodeGenerator cg(fContext.get(), &program, this, &buffer);
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001506 bool result = cg.generateCode();
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001507 fSource = nullptr;
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001508 if (result) {
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001509 spvtools::SpirvTools tools(SPV_ENV_VULKAN_1_0);
Ethan Nicholas762466e2017-06-29 10:03:38 -04001510 const String& data = buffer.str();
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001511 SkASSERT(0 == data.size() % 4);
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001512 auto dumpmsg = [](spv_message_level_t, const char*, const spv_position_t&, const char* m) {
1513 SkDebugf("SPIR-V validation error: %s\n", m);
1514 };
1515 tools.SetMessageConsumer(dumpmsg);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001516 // Verify that the SPIR-V we produced is valid. If this SkASSERT fails, check the logs prior
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001517 // to the failure to see the validation errors.
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001518 SkAssertResult(tools.Validate((const uint32_t*) data.c_str(), data.size() / 4));
Ethan Nicholas762466e2017-06-29 10:03:38 -04001519 out.write(data.c_str(), data.size());
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001520 }
1521#else
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001522 fSource = program.fSource.get();
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001523 SPIRVCodeGenerator cg(fContext.get(), &program, this, &out);
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001524 bool result = cg.generateCode();
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001525 fSource = nullptr;
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001526#endif
Ethan Nicholasce33f102016-12-09 17:22:59 -05001527 return result;
1528}
1529
Ethan Nicholas00543112018-07-31 09:44:36 -04001530bool Compiler::toSPIRV(Program& program, String* out) {
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001531 StringStream buffer;
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001532 bool result = this->toSPIRV(program, buffer);
1533 if (result) {
Ethan Nicholas762466e2017-06-29 10:03:38 -04001534 *out = buffer.str();
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001535 }
1536 return result;
1537}
1538
Ethan Nicholas00543112018-07-31 09:44:36 -04001539bool Compiler::toGLSL(Program& program, OutputStream& out) {
1540 if (!this->optimize(program)) {
1541 return false;
1542 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001543 fSource = program.fSource.get();
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001544 GLSLCodeGenerator cg(fContext.get(), &program, this, &out);
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001545 bool result = cg.generateCode();
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001546 fSource = nullptr;
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001547 return result;
1548}
1549
Ethan Nicholas00543112018-07-31 09:44:36 -04001550bool Compiler::toGLSL(Program& program, String* out) {
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001551 StringStream buffer;
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001552 bool result = this->toGLSL(program, buffer);
1553 if (result) {
Ethan Nicholas762466e2017-06-29 10:03:38 -04001554 *out = buffer.str();
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001555 }
1556 return result;
1557}
1558
Ethan Nicholas00543112018-07-31 09:44:36 -04001559bool Compiler::toMetal(Program& program, OutputStream& out) {
1560 if (!this->optimize(program)) {
1561 return false;
1562 }
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001563 MetalCodeGenerator cg(fContext.get(), &program, this, &out);
Ethan Nicholascc305772017-10-13 16:17:45 -04001564 bool result = cg.generateCode();
Ethan Nicholascc305772017-10-13 16:17:45 -04001565 return result;
1566}
1567
Ethan Nicholas00543112018-07-31 09:44:36 -04001568bool Compiler::toMetal(Program& program, String* out) {
1569 if (!this->optimize(program)) {
1570 return false;
1571 }
Timothy Liangb8eeb802018-07-23 16:46:16 -04001572 StringStream buffer;
1573 bool result = this->toMetal(program, buffer);
1574 if (result) {
1575 *out = buffer.str();
1576 }
1577 return result;
1578}
1579
Ethan Nicholas00543112018-07-31 09:44:36 -04001580bool Compiler::toCPP(Program& program, String name, OutputStream& out) {
1581 if (!this->optimize(program)) {
1582 return false;
1583 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001584 fSource = program.fSource.get();
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001585 CPPCodeGenerator cg(fContext.get(), &program, this, name, &out);
Ethan Nicholas762466e2017-06-29 10:03:38 -04001586 bool result = cg.generateCode();
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001587 fSource = nullptr;
Ethan Nicholas762466e2017-06-29 10:03:38 -04001588 return result;
1589}
1590
Ethan Nicholas00543112018-07-31 09:44:36 -04001591bool Compiler::toH(Program& program, String name, OutputStream& out) {
1592 if (!this->optimize(program)) {
1593 return false;
1594 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001595 fSource = program.fSource.get();
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001596 HCodeGenerator cg(fContext.get(), &program, this, name, &out);
Ethan Nicholas762466e2017-06-29 10:03:38 -04001597 bool result = cg.generateCode();
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001598 fSource = nullptr;
Ethan Nicholas00543112018-07-31 09:44:36 -04001599 return result;
1600}
1601
Brian Osman2e29ab52019-09-20 12:19:11 -04001602#endif
1603
1604#if !defined(SKSL_STANDALONE) && SK_SUPPORT_GPU
Brian Osman107c6662019-12-30 15:02:30 -05001605bool Compiler::toPipelineStage(const Program& program, PipelineStageArgs* outArgs) {
Ethan Nicholas00543112018-07-31 09:44:36 -04001606 SkASSERT(program.fIsOptimized);
1607 fSource = program.fSource.get();
1608 StringStream buffer;
Brian Osman107c6662019-12-30 15:02:30 -05001609 PipelineStageCodeGenerator cg(fContext.get(), &program, this, &buffer, &outArgs->fFormatArgs,
1610 &outArgs->fFunctions);
Ethan Nicholas00543112018-07-31 09:44:36 -04001611 bool result = cg.generateCode();
1612 fSource = nullptr;
1613 if (result) {
Brian Osman107c6662019-12-30 15:02:30 -05001614 outArgs->fCode = buffer.str();
Ethan Nicholas00543112018-07-31 09:44:36 -04001615 }
Ethan Nicholas762466e2017-06-29 10:03:38 -04001616 return result;
1617}
Brian Osmanfb32ddf2019-06-18 10:14:20 -04001618#endif
1619
Ethan Nicholas0e9401d2019-03-21 11:05:37 -04001620std::unique_ptr<ByteCode> Compiler::toByteCode(Program& program) {
Brian Osman489cf882019-07-09 10:48:28 -04001621#if defined(SK_ENABLE_SKSL_INTERPRETER)
Ethan Nicholas0e9401d2019-03-21 11:05:37 -04001622 if (!this->optimize(program)) {
1623 return nullptr;
1624 }
Brian Osman808f0212020-01-21 15:36:47 -05001625 fSource = program.fSource.get();
Ethan Nicholas0e9401d2019-03-21 11:05:37 -04001626 std::unique_ptr<ByteCode> result(new ByteCode());
Ethan Nicholas99c54f02020-01-21 16:06:47 +00001627 ByteCodeGenerator cg(fContext.get(), &program, this, result.get());
Brian Osman808f0212020-01-21 15:36:47 -05001628 bool success = cg.generateCode();
1629 fSource = nullptr;
1630 if (success) {
Ethan Nicholas0e9401d2019-03-21 11:05:37 -04001631 return result;
1632 }
Brian Osman489cf882019-07-09 10:48:28 -04001633#else
1634 ABORT("ByteCode interpreter not enabled");
1635#endif
Ethan Nicholas0e9401d2019-03-21 11:05:37 -04001636 return nullptr;
1637}
1638
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001639const char* Compiler::OperatorName(Token::Kind kind) {
1640 switch (kind) {
1641 case Token::PLUS: return "+";
1642 case Token::MINUS: return "-";
1643 case Token::STAR: return "*";
1644 case Token::SLASH: return "/";
1645 case Token::PERCENT: return "%";
1646 case Token::SHL: return "<<";
1647 case Token::SHR: return ">>";
1648 case Token::LOGICALNOT: return "!";
1649 case Token::LOGICALAND: return "&&";
1650 case Token::LOGICALOR: return "||";
1651 case Token::LOGICALXOR: return "^^";
1652 case Token::BITWISENOT: return "~";
1653 case Token::BITWISEAND: return "&";
1654 case Token::BITWISEOR: return "|";
1655 case Token::BITWISEXOR: return "^";
1656 case Token::EQ: return "=";
1657 case Token::EQEQ: return "==";
1658 case Token::NEQ: return "!=";
1659 case Token::LT: return "<";
1660 case Token::GT: return ">";
1661 case Token::LTEQ: return "<=";
1662 case Token::GTEQ: return ">=";
1663 case Token::PLUSEQ: return "+=";
1664 case Token::MINUSEQ: return "-=";
1665 case Token::STAREQ: return "*=";
1666 case Token::SLASHEQ: return "/=";
1667 case Token::PERCENTEQ: return "%=";
1668 case Token::SHLEQ: return "<<=";
1669 case Token::SHREQ: return ">>=";
1670 case Token::LOGICALANDEQ: return "&&=";
1671 case Token::LOGICALOREQ: return "||=";
1672 case Token::LOGICALXOREQ: return "^^=";
1673 case Token::BITWISEANDEQ: return "&=";
1674 case Token::BITWISEOREQ: return "|=";
1675 case Token::BITWISEXOREQ: return "^=";
1676 case Token::PLUSPLUS: return "++";
1677 case Token::MINUSMINUS: return "--";
1678 case Token::COMMA: return ",";
1679 default:
1680 ABORT("unsupported operator: %d\n", kind);
1681 }
1682}
1683
1684
1685bool Compiler::IsAssignment(Token::Kind op) {
1686 switch (op) {
1687 case Token::EQ: // fall through
1688 case Token::PLUSEQ: // fall through
1689 case Token::MINUSEQ: // fall through
1690 case Token::STAREQ: // fall through
1691 case Token::SLASHEQ: // fall through
1692 case Token::PERCENTEQ: // fall through
1693 case Token::SHLEQ: // fall through
1694 case Token::SHREQ: // fall through
1695 case Token::BITWISEOREQ: // fall through
1696 case Token::BITWISEXOREQ: // fall through
1697 case Token::BITWISEANDEQ: // fall through
1698 case Token::LOGICALOREQ: // fall through
1699 case Token::LOGICALXOREQ: // fall through
1700 case Token::LOGICALANDEQ:
1701 return true;
1702 default:
1703 return false;
1704 }
1705}
1706
1707Position Compiler::position(int offset) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001708 SkASSERT(fSource);
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001709 int line = 1;
1710 int column = 1;
1711 for (int i = 0; i < offset; i++) {
1712 if ((*fSource)[i] == '\n') {
1713 ++line;
1714 column = 1;
1715 }
1716 else {
1717 ++column;
1718 }
1719 }
1720 return Position(line, column);
1721}
1722
1723void Compiler::error(int offset, String msg) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001724 fErrorCount++;
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001725 Position pos = this->position(offset);
1726 fErrorText += "error: " + to_string(pos.fLine) + ": " + msg.c_str() + "\n";
ethannicholasb3058bd2016-07-01 08:22:01 -07001727}
1728
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001729String Compiler::errorText() {
Ethan Nicholas00543112018-07-31 09:44:36 -04001730 this->writeErrorCount();
1731 fErrorCount = 0;
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001732 String result = fErrorText;
ethannicholasb3058bd2016-07-01 08:22:01 -07001733 return result;
1734}
1735
1736void Compiler::writeErrorCount() {
1737 if (fErrorCount) {
1738 fErrorText += to_string(fErrorCount) + " error";
1739 if (fErrorCount > 1) {
1740 fErrorText += "s";
1741 }
1742 fErrorText += "\n";
1743 }
1744}
1745
ethannicholasb3058bd2016-07-01 08:22:01 -07001746} // namespace