blob: 28190dc9befe6f9892a75c3854f8826f66d0a2bc [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 Nicholasa6ae1f72017-03-16 09:56:54 -040031#ifdef SK_ENABLE_SPIRV_VALIDATION
32#include "spirv-tools/libspirv.hpp"
33#endif
34
ethannicholasb3058bd2016-07-01 08:22:01 -070035// include the built-in shader symbols as static strings
36
Ethan Nicholas79707652017-11-16 11:20:11 -050037#define STRINGIFY(x) #x
38
Ethan Nicholas8da1e652019-05-24 11:01:59 -040039static const char* SKSL_GPU_INCLUDE =
40#include "sksl_gpu.inc"
41;
42
43static const char* SKSL_INTERP_INCLUDE =
44#include "sksl_interp.inc"
ethannicholasb3058bd2016-07-01 08:22:01 -070045;
46
ethannicholas5961bc92016-10-12 06:39:56 -070047static const char* SKSL_VERT_INCLUDE =
Ben Wagnera56c4d22018-01-24 17:32:17 -050048#include "sksl_vert.inc"
ethannicholasb3058bd2016-07-01 08:22:01 -070049;
50
ethannicholas5961bc92016-10-12 06:39:56 -070051static const char* SKSL_FRAG_INCLUDE =
Ben Wagnera56c4d22018-01-24 17:32:17 -050052#include "sksl_frag.inc"
ethannicholasb3058bd2016-07-01 08:22:01 -070053;
54
Ethan Nicholas52cad152017-02-16 16:37:32 -050055static const char* SKSL_GEOM_INCLUDE =
Ben Wagnera56c4d22018-01-24 17:32:17 -050056#include "sksl_geom.inc"
Ethan Nicholas52cad152017-02-16 16:37:32 -050057;
58
Ethan Nicholas762466e2017-06-29 10:03:38 -040059static const char* SKSL_FP_INCLUDE =
Ben Wagnera56c4d22018-01-24 17:32:17 -050060#include "sksl_enums.inc"
61#include "sksl_fp.inc"
Ethan Nicholas762466e2017-06-29 10:03:38 -040062;
63
Ethan Nicholas8da1e652019-05-24 11:01:59 -040064static const char* SKSL_PIPELINE_INCLUDE =
65#include "sksl_pipeline.inc"
Ethan Nicholas0d997662019-04-08 09:46:01 -040066;
67
ethannicholasb3058bd2016-07-01 08:22:01 -070068namespace SkSL {
69
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -040070Compiler::Compiler(Flags flags)
71: fFlags(flags)
Ethan Nicholas26a9aad2018-03-27 14:10:52 -040072, fContext(new Context())
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -040073, fErrorCount(0) {
Ethan Nicholas8feeff92017-03-30 14:11:58 -040074 auto types = std::shared_ptr<SymbolTable>(new SymbolTable(this));
75 auto symbols = std::shared_ptr<SymbolTable>(new SymbolTable(types, this));
Ethan Nicholas26a9aad2018-03-27 14:10:52 -040076 fIRGenerator = new IRGenerator(fContext.get(), symbols, *this);
ethannicholasb3058bd2016-07-01 08:22:01 -070077 fTypes = types;
Ethan Nicholas26a9aad2018-03-27 14:10:52 -040078 #define ADD_TYPE(t) types->addWithoutOwnership(fContext->f ## t ## _Type->fName, \
79 fContext->f ## t ## _Type.get())
ethannicholasb3058bd2016-07-01 08:22:01 -070080 ADD_TYPE(Void);
81 ADD_TYPE(Float);
Ethan Nicholas5af9ea32017-07-28 15:19:46 -040082 ADD_TYPE(Float2);
83 ADD_TYPE(Float3);
84 ADD_TYPE(Float4);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -040085 ADD_TYPE(Half);
86 ADD_TYPE(Half2);
87 ADD_TYPE(Half3);
88 ADD_TYPE(Half4);
ethannicholasb3058bd2016-07-01 08:22:01 -070089 ADD_TYPE(Double);
Ethan Nicholas5af9ea32017-07-28 15:19:46 -040090 ADD_TYPE(Double2);
91 ADD_TYPE(Double3);
92 ADD_TYPE(Double4);
ethannicholasb3058bd2016-07-01 08:22:01 -070093 ADD_TYPE(Int);
Ethan Nicholas5af9ea32017-07-28 15:19:46 -040094 ADD_TYPE(Int2);
95 ADD_TYPE(Int3);
96 ADD_TYPE(Int4);
ethannicholasb3058bd2016-07-01 08:22:01 -070097 ADD_TYPE(UInt);
Ethan Nicholas5af9ea32017-07-28 15:19:46 -040098 ADD_TYPE(UInt2);
99 ADD_TYPE(UInt3);
100 ADD_TYPE(UInt4);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -0400101 ADD_TYPE(Short);
102 ADD_TYPE(Short2);
103 ADD_TYPE(Short3);
104 ADD_TYPE(Short4);
105 ADD_TYPE(UShort);
106 ADD_TYPE(UShort2);
107 ADD_TYPE(UShort3);
108 ADD_TYPE(UShort4);
Ruiqi Maob609e6d2018-07-17 10:19:38 -0400109 ADD_TYPE(Byte);
110 ADD_TYPE(Byte2);
111 ADD_TYPE(Byte3);
112 ADD_TYPE(Byte4);
113 ADD_TYPE(UByte);
114 ADD_TYPE(UByte2);
115 ADD_TYPE(UByte3);
116 ADD_TYPE(UByte4);
ethannicholasb3058bd2016-07-01 08:22:01 -0700117 ADD_TYPE(Bool);
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400118 ADD_TYPE(Bool2);
119 ADD_TYPE(Bool3);
120 ADD_TYPE(Bool4);
121 ADD_TYPE(Float2x2);
122 ADD_TYPE(Float2x3);
123 ADD_TYPE(Float2x4);
124 ADD_TYPE(Float3x2);
125 ADD_TYPE(Float3x3);
126 ADD_TYPE(Float3x4);
127 ADD_TYPE(Float4x2);
128 ADD_TYPE(Float4x3);
129 ADD_TYPE(Float4x4);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -0400130 ADD_TYPE(Half2x2);
131 ADD_TYPE(Half2x3);
132 ADD_TYPE(Half2x4);
133 ADD_TYPE(Half3x2);
134 ADD_TYPE(Half3x3);
135 ADD_TYPE(Half3x4);
136 ADD_TYPE(Half4x2);
137 ADD_TYPE(Half4x3);
138 ADD_TYPE(Half4x4);
139 ADD_TYPE(Double2x2);
140 ADD_TYPE(Double2x3);
141 ADD_TYPE(Double2x4);
142 ADD_TYPE(Double3x2);
143 ADD_TYPE(Double3x3);
144 ADD_TYPE(Double3x4);
145 ADD_TYPE(Double4x2);
146 ADD_TYPE(Double4x3);
147 ADD_TYPE(Double4x4);
ethannicholasb3058bd2016-07-01 08:22:01 -0700148 ADD_TYPE(GenType);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -0400149 ADD_TYPE(GenHType);
ethannicholasb3058bd2016-07-01 08:22:01 -0700150 ADD_TYPE(GenDType);
151 ADD_TYPE(GenIType);
152 ADD_TYPE(GenUType);
153 ADD_TYPE(GenBType);
154 ADD_TYPE(Mat);
155 ADD_TYPE(Vec);
156 ADD_TYPE(GVec);
157 ADD_TYPE(GVec2);
158 ADD_TYPE(GVec3);
159 ADD_TYPE(GVec4);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -0400160 ADD_TYPE(HVec);
ethannicholasb3058bd2016-07-01 08:22:01 -0700161 ADD_TYPE(DVec);
162 ADD_TYPE(IVec);
163 ADD_TYPE(UVec);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -0400164 ADD_TYPE(SVec);
165 ADD_TYPE(USVec);
Ruiqi Maob609e6d2018-07-17 10:19:38 -0400166 ADD_TYPE(ByteVec);
167 ADD_TYPE(UByteVec);
ethannicholasb3058bd2016-07-01 08:22:01 -0700168 ADD_TYPE(BVec);
169
170 ADD_TYPE(Sampler1D);
171 ADD_TYPE(Sampler2D);
172 ADD_TYPE(Sampler3D);
ethannicholas5961bc92016-10-12 06:39:56 -0700173 ADD_TYPE(SamplerExternalOES);
ethannicholasb3058bd2016-07-01 08:22:01 -0700174 ADD_TYPE(SamplerCube);
175 ADD_TYPE(Sampler2DRect);
176 ADD_TYPE(Sampler1DArray);
177 ADD_TYPE(Sampler2DArray);
178 ADD_TYPE(SamplerCubeArray);
179 ADD_TYPE(SamplerBuffer);
180 ADD_TYPE(Sampler2DMS);
181 ADD_TYPE(Sampler2DMSArray);
182
Brian Salomonbf7b6202016-11-11 16:08:03 -0500183 ADD_TYPE(ISampler2D);
184
Brian Salomon2a51de82016-11-16 12:06:01 -0500185 ADD_TYPE(Image2D);
186 ADD_TYPE(IImage2D);
187
Greg Daniel64773e62016-11-22 09:44:03 -0500188 ADD_TYPE(SubpassInput);
189 ADD_TYPE(SubpassInputMS);
190
ethannicholasb3058bd2016-07-01 08:22:01 -0700191 ADD_TYPE(GSampler1D);
192 ADD_TYPE(GSampler2D);
193 ADD_TYPE(GSampler3D);
194 ADD_TYPE(GSamplerCube);
195 ADD_TYPE(GSampler2DRect);
196 ADD_TYPE(GSampler1DArray);
197 ADD_TYPE(GSampler2DArray);
198 ADD_TYPE(GSamplerCubeArray);
199 ADD_TYPE(GSamplerBuffer);
200 ADD_TYPE(GSampler2DMS);
201 ADD_TYPE(GSampler2DMSArray);
202
203 ADD_TYPE(Sampler1DShadow);
204 ADD_TYPE(Sampler2DShadow);
205 ADD_TYPE(SamplerCubeShadow);
206 ADD_TYPE(Sampler2DRectShadow);
207 ADD_TYPE(Sampler1DArrayShadow);
208 ADD_TYPE(Sampler2DArrayShadow);
209 ADD_TYPE(SamplerCubeArrayShadow);
210 ADD_TYPE(GSampler2DArrayShadow);
211 ADD_TYPE(GSamplerCubeArrayShadow);
Ethan Nicholasc9472af2017-10-10 16:30:21 -0400212 ADD_TYPE(FragmentProcessor);
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400213 ADD_TYPE(SkRasterPipeline);
ethannicholasb3058bd2016-07-01 08:22:01 -0700214
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700215 StringFragment skCapsName("sk_Caps");
216 Variable* skCaps = new Variable(-1, Modifiers(), skCapsName,
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400217 *fContext->fSkCaps_Type, Variable::kGlobal_Storage);
Ethan Nicholas3605ace2016-11-21 15:59:48 -0500218 fIRGenerator->fSymbolTable->add(skCapsName, std::unique_ptr<Symbol>(skCaps));
219
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700220 StringFragment skArgsName("sk_Args");
221 Variable* skArgs = new Variable(-1, Modifiers(), skArgsName,
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400222 *fContext->fSkArgs_Type, Variable::kGlobal_Storage);
Ethan Nicholas762466e2017-06-29 10:03:38 -0400223 fIRGenerator->fSymbolTable->add(skArgsName, std::unique_ptr<Symbol>(skArgs));
224
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400225 std::vector<std::unique_ptr<ProgramElement>> ignored;
Ethan Nicholas8da1e652019-05-24 11:01:59 -0400226 this->processIncludeFile(Program::kFragment_Kind, SKSL_GPU_INCLUDE, strlen(SKSL_GPU_INCLUDE),
227 symbols, &ignored, &fGpuSymbolTable);
228 this->processIncludeFile(Program::kVertex_Kind, SKSL_VERT_INCLUDE, strlen(SKSL_VERT_INCLUDE),
229 fGpuSymbolTable, &fVertexInclude, &fVertexSymbolTable);
230 this->processIncludeFile(Program::kFragment_Kind, SKSL_FRAG_INCLUDE, strlen(SKSL_FRAG_INCLUDE),
231 fGpuSymbolTable, &fFragmentInclude, &fFragmentSymbolTable);
232 this->processIncludeFile(Program::kGeometry_Kind, SKSL_GEOM_INCLUDE, strlen(SKSL_GEOM_INCLUDE),
233 fGpuSymbolTable, &fGeometryInclude, &fGeometrySymbolTable);
234 this->processIncludeFile(Program::kPipelineStage_Kind, SKSL_PIPELINE_INCLUDE,
235 strlen(SKSL_PIPELINE_INCLUDE), fGpuSymbolTable, &fPipelineInclude,
236 &fPipelineSymbolTable);
237 this->processIncludeFile(Program::kGeneric_Kind, SKSL_INTERP_INCLUDE,
238 strlen(SKSL_INTERP_INCLUDE), symbols, &fInterpreterInclude,
239 &fInterpreterSymbolTable);
ethannicholasb3058bd2016-07-01 08:22:01 -0700240}
241
242Compiler::~Compiler() {
243 delete fIRGenerator;
244}
245
Ethan Nicholas8da1e652019-05-24 11:01:59 -0400246void Compiler::processIncludeFile(Program::Kind kind, const char* src, size_t length,
247 std::shared_ptr<SymbolTable> base,
248 std::vector<std::unique_ptr<ProgramElement>>* outElements,
249 std::shared_ptr<SymbolTable>* outSymbolTable) {
250 fIRGenerator->fSymbolTable = std::move(base);
251 Program::Settings settings;
252 fIRGenerator->start(&settings, nullptr);
253 fIRGenerator->convertProgram(kind, src, length, *fTypes, outElements);
254 if (this->fErrorCount) {
255 printf("Unexpected errors: %s\n", this->fErrorText.c_str());
256 }
257 SkASSERT(!fErrorCount);
258 fIRGenerator->fSymbolTable->markAllFunctionsBuiltin();
259 *outSymbolTable = fIRGenerator->fSymbolTable;
260}
261
ethannicholas22f939e2016-10-13 13:25:34 -0700262// add the definition created by assigning to the lvalue to the definition set
Ethan Nicholas86a43402017-01-19 13:32:00 -0500263void Compiler::addDefinition(const Expression* lvalue, std::unique_ptr<Expression>* expr,
264 DefinitionMap* definitions) {
ethannicholas22f939e2016-10-13 13:25:34 -0700265 switch (lvalue->fKind) {
266 case Expression::kVariableReference_Kind: {
267 const Variable& var = ((VariableReference*) lvalue)->fVariable;
268 if (var.fStorage == Variable::kLocal_Storage) {
269 (*definitions)[&var] = expr;
270 }
271 break;
272 }
273 case Expression::kSwizzle_Kind:
274 // We consider the variable written to as long as at least some of its components have
275 // been written to. This will lead to some false negatives (we won't catch it if you
276 // write to foo.x and then read foo.y), but being stricter could lead to false positives
Mike Klein6ad99092016-10-26 10:35:22 -0400277 // (we write to foo.x, and then pass foo to a function which happens to only read foo.x,
278 // 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 -0700279 // more complicated whole-program analysis. This is probably good enough.
Mike Klein6ad99092016-10-26 10:35:22 -0400280 this->addDefinition(((Swizzle*) lvalue)->fBase.get(),
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400281 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
ethannicholas22f939e2016-10-13 13:25:34 -0700282 definitions);
283 break;
284 case Expression::kIndex_Kind:
285 // see comments in Swizzle
Mike Klein6ad99092016-10-26 10:35:22 -0400286 this->addDefinition(((IndexExpression*) lvalue)->fBase.get(),
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400287 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
ethannicholas22f939e2016-10-13 13:25:34 -0700288 definitions);
289 break;
290 case Expression::kFieldAccess_Kind:
291 // see comments in Swizzle
Mike Klein6ad99092016-10-26 10:35:22 -0400292 this->addDefinition(((FieldAccess*) lvalue)->fBase.get(),
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400293 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
ethannicholas22f939e2016-10-13 13:25:34 -0700294 definitions);
295 break;
Ethan Nicholasa583b812018-01-18 13:32:11 -0500296 case Expression::kTernary_Kind:
297 // To simplify analysis, we just pretend that we write to both sides of the ternary.
298 // This allows for false positives (meaning we fail to detect that a variable might not
299 // have been assigned), but is preferable to false negatives.
300 this->addDefinition(((TernaryExpression*) lvalue)->fIfTrue.get(),
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400301 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
Ethan Nicholasa583b812018-01-18 13:32:11 -0500302 definitions);
303 this->addDefinition(((TernaryExpression*) lvalue)->fIfFalse.get(),
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400304 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
Ethan Nicholasa583b812018-01-18 13:32:11 -0500305 definitions);
306 break;
Ethan Nicholas91164d12019-05-15 15:29:54 -0400307 case Expression::kExternalValue_Kind:
308 break;
ethannicholas22f939e2016-10-13 13:25:34 -0700309 default:
310 // not an lvalue, can't happen
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400311 SkASSERT(false);
ethannicholas22f939e2016-10-13 13:25:34 -0700312 }
313}
314
315// add local variables defined by this node to the set
Mike Klein6ad99092016-10-26 10:35:22 -0400316void Compiler::addDefinitions(const BasicBlock::Node& node,
Ethan Nicholas86a43402017-01-19 13:32:00 -0500317 DefinitionMap* definitions) {
ethannicholas22f939e2016-10-13 13:25:34 -0700318 switch (node.fKind) {
319 case BasicBlock::Node::kExpression_Kind: {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400320 SkASSERT(node.expression());
Ethan Nicholascb670962017-04-20 19:31:52 -0400321 const Expression* expr = (Expression*) node.expression()->get();
Ethan Nicholas86a43402017-01-19 13:32:00 -0500322 switch (expr->fKind) {
323 case Expression::kBinary_Kind: {
324 BinaryExpression* b = (BinaryExpression*) expr;
325 if (b->fOperator == Token::EQ) {
326 this->addDefinition(b->fLeft.get(), &b->fRight, definitions);
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700327 } else if (Compiler::IsAssignment(b->fOperator)) {
Ethan Nicholas86a43402017-01-19 13:32:00 -0500328 this->addDefinition(
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400329 b->fLeft.get(),
330 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
331 definitions);
Ethan Nicholas86a43402017-01-19 13:32:00 -0500332
333 }
334 break;
ethannicholas22f939e2016-10-13 13:25:34 -0700335 }
Ethan Nicholasc6a19f12018-03-29 16:46:56 -0400336 case Expression::kFunctionCall_Kind: {
337 const FunctionCall& c = (const FunctionCall&) *expr;
338 for (size_t i = 0; i < c.fFunction.fParameters.size(); ++i) {
339 if (c.fFunction.fParameters[i]->fModifiers.fFlags & Modifiers::kOut_Flag) {
340 this->addDefinition(
341 c.fArguments[i].get(),
342 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
343 definitions);
344 }
345 }
346 break;
347 }
Ethan Nicholas86a43402017-01-19 13:32:00 -0500348 case Expression::kPrefix_Kind: {
349 const PrefixExpression* p = (PrefixExpression*) expr;
350 if (p->fOperator == Token::MINUSMINUS || p->fOperator == Token::PLUSPLUS) {
351 this->addDefinition(
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400352 p->fOperand.get(),
353 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
354 definitions);
Ethan Nicholas86a43402017-01-19 13:32:00 -0500355 }
356 break;
357 }
358 case Expression::kPostfix_Kind: {
359 const PostfixExpression* p = (PostfixExpression*) expr;
360 if (p->fOperator == Token::MINUSMINUS || p->fOperator == Token::PLUSPLUS) {
361 this->addDefinition(
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400362 p->fOperand.get(),
363 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
364 definitions);
Ethan Nicholas86a43402017-01-19 13:32:00 -0500365 }
366 break;
367 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400368 case Expression::kVariableReference_Kind: {
369 const VariableReference* v = (VariableReference*) expr;
370 if (v->fRefKind != VariableReference::kRead_RefKind) {
371 this->addDefinition(
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400372 v,
373 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
374 definitions);
Ethan Nicholascb670962017-04-20 19:31:52 -0400375 }
376 }
Ethan Nicholas86a43402017-01-19 13:32:00 -0500377 default:
378 break;
ethannicholas22f939e2016-10-13 13:25:34 -0700379 }
380 break;
381 }
382 case BasicBlock::Node::kStatement_Kind: {
Ethan Nicholascb670962017-04-20 19:31:52 -0400383 const Statement* stmt = (Statement*) node.statement()->get();
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000384 if (stmt->fKind == Statement::kVarDeclaration_Kind) {
385 VarDeclaration& vd = (VarDeclaration&) *stmt;
386 if (vd.fValue) {
387 (*definitions)[vd.fVar] = &vd.fValue;
ethannicholas22f939e2016-10-13 13:25:34 -0700388 }
389 }
390 break;
391 }
392 }
393}
394
395void Compiler::scanCFG(CFG* cfg, BlockId blockId, std::set<BlockId>* workList) {
396 BasicBlock& block = cfg->fBlocks[blockId];
397
398 // compute definitions after this block
Ethan Nicholas86a43402017-01-19 13:32:00 -0500399 DefinitionMap after = block.fBefore;
ethannicholas22f939e2016-10-13 13:25:34 -0700400 for (const BasicBlock::Node& n : block.fNodes) {
401 this->addDefinitions(n, &after);
402 }
403
404 // propagate definitions to exits
405 for (BlockId exitId : block.fExits) {
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400406 if (exitId == blockId) {
407 continue;
408 }
ethannicholas22f939e2016-10-13 13:25:34 -0700409 BasicBlock& exit = cfg->fBlocks[exitId];
410 for (const auto& pair : after) {
Ethan Nicholas86a43402017-01-19 13:32:00 -0500411 std::unique_ptr<Expression>* e1 = pair.second;
412 auto found = exit.fBefore.find(pair.first);
413 if (found == exit.fBefore.end()) {
414 // exit has no definition for it, just copy it
415 workList->insert(exitId);
ethannicholas22f939e2016-10-13 13:25:34 -0700416 exit.fBefore[pair.first] = e1;
417 } else {
Ethan Nicholas86a43402017-01-19 13:32:00 -0500418 // exit has a (possibly different) value already defined
419 std::unique_ptr<Expression>* e2 = exit.fBefore[pair.first];
ethannicholas22f939e2016-10-13 13:25:34 -0700420 if (e1 != e2) {
421 // definition has changed, merge and add exit block to worklist
422 workList->insert(exitId);
Ethan Nicholasaf197692017-02-27 13:26:45 -0500423 if (e1 && e2) {
424 exit.fBefore[pair.first] =
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400425 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression;
Ethan Nicholasaf197692017-02-27 13:26:45 -0500426 } else {
427 exit.fBefore[pair.first] = nullptr;
428 }
ethannicholas22f939e2016-10-13 13:25:34 -0700429 }
430 }
431 }
432 }
433}
434
435// returns a map which maps all local variables in the function to null, indicating that their value
436// is initially unknown
Ethan Nicholas86a43402017-01-19 13:32:00 -0500437static DefinitionMap compute_start_state(const CFG& cfg) {
438 DefinitionMap result;
Mike Klein6ad99092016-10-26 10:35:22 -0400439 for (const auto& block : cfg.fBlocks) {
440 for (const auto& node : block.fNodes) {
ethannicholas22f939e2016-10-13 13:25:34 -0700441 if (node.fKind == BasicBlock::Node::kStatement_Kind) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400442 SkASSERT(node.statement());
Ethan Nicholascb670962017-04-20 19:31:52 -0400443 const Statement* s = node.statement()->get();
ethannicholas22f939e2016-10-13 13:25:34 -0700444 if (s->fKind == Statement::kVarDeclarations_Kind) {
445 const VarDeclarationsStatement* vd = (const VarDeclarationsStatement*) s;
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000446 for (const auto& decl : vd->fDeclaration->fVars) {
447 if (decl->fKind == Statement::kVarDeclaration_Kind) {
448 result[((VarDeclaration&) *decl).fVar] = nullptr;
449 }
Mike Klein6ad99092016-10-26 10:35:22 -0400450 }
ethannicholas22f939e2016-10-13 13:25:34 -0700451 }
452 }
453 }
454 }
455 return result;
456}
457
Ethan Nicholascb670962017-04-20 19:31:52 -0400458/**
459 * Returns true if assigning to this lvalue has no effect.
460 */
461static bool is_dead(const Expression& lvalue) {
462 switch (lvalue.fKind) {
463 case Expression::kVariableReference_Kind:
464 return ((VariableReference&) lvalue).fVariable.dead();
465 case Expression::kSwizzle_Kind:
466 return is_dead(*((Swizzle&) lvalue).fBase);
467 case Expression::kFieldAccess_Kind:
468 return is_dead(*((FieldAccess&) lvalue).fBase);
469 case Expression::kIndex_Kind: {
470 const IndexExpression& idx = (IndexExpression&) lvalue;
471 return is_dead(*idx.fBase) && !idx.fIndex->hasSideEffects();
472 }
Ethan Nicholasa583b812018-01-18 13:32:11 -0500473 case Expression::kTernary_Kind: {
474 const TernaryExpression& t = (TernaryExpression&) lvalue;
475 return !t.fTest->hasSideEffects() && is_dead(*t.fIfTrue) && is_dead(*t.fIfFalse);
476 }
Ethan Nicholas91164d12019-05-15 15:29:54 -0400477 case Expression::kExternalValue_Kind:
478 return false;
Ethan Nicholascb670962017-04-20 19:31:52 -0400479 default:
480 ABORT("invalid lvalue: %s\n", lvalue.description().c_str());
481 }
482}
ethannicholas22f939e2016-10-13 13:25:34 -0700483
Ethan Nicholascb670962017-04-20 19:31:52 -0400484/**
485 * Returns true if this is an assignment which can be collapsed down to just the right hand side due
486 * to a dead target and lack of side effects on the left hand side.
487 */
488static bool dead_assignment(const BinaryExpression& b) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700489 if (!Compiler::IsAssignment(b.fOperator)) {
Ethan Nicholascb670962017-04-20 19:31:52 -0400490 return false;
491 }
492 return is_dead(*b.fLeft);
493}
494
495void Compiler::computeDataFlow(CFG* cfg) {
496 cfg->fBlocks[cfg->fStart].fBefore = compute_start_state(*cfg);
ethannicholas22f939e2016-10-13 13:25:34 -0700497 std::set<BlockId> workList;
Ethan Nicholascb670962017-04-20 19:31:52 -0400498 for (BlockId i = 0; i < cfg->fBlocks.size(); i++) {
ethannicholas22f939e2016-10-13 13:25:34 -0700499 workList.insert(i);
500 }
501 while (workList.size()) {
502 BlockId next = *workList.begin();
503 workList.erase(workList.begin());
Ethan Nicholascb670962017-04-20 19:31:52 -0400504 this->scanCFG(cfg, next, &workList);
ethannicholas22f939e2016-10-13 13:25:34 -0700505 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400506}
507
508/**
509 * Attempts to replace the expression pointed to by iter with a new one (in both the CFG and the
510 * IR). If the expression can be cleanly removed, returns true and updates the iterator to point to
511 * the newly-inserted element. Otherwise updates only the IR and returns false (and the CFG will
512 * need to be regenerated).
513 */
514bool try_replace_expression(BasicBlock* b,
515 std::vector<BasicBlock::Node>::iterator* iter,
516 std::unique_ptr<Expression>* newExpression) {
517 std::unique_ptr<Expression>* target = (*iter)->expression();
518 if (!b->tryRemoveExpression(iter)) {
519 *target = std::move(*newExpression);
520 return false;
521 }
522 *target = std::move(*newExpression);
523 return b->tryInsertExpression(iter, target);
524}
525
526/**
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400527 * Returns true if the expression is a constant numeric literal with the specified value, or a
528 * constant vector with all elements equal to the specified value.
Ethan Nicholascb670962017-04-20 19:31:52 -0400529 */
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400530bool is_constant(const Expression& expr, double value) {
Ethan Nicholascb670962017-04-20 19:31:52 -0400531 switch (expr.fKind) {
532 case Expression::kIntLiteral_Kind:
533 return ((IntLiteral&) expr).fValue == value;
534 case Expression::kFloatLiteral_Kind:
535 return ((FloatLiteral&) expr).fValue == value;
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400536 case Expression::kConstructor_Kind: {
537 Constructor& c = (Constructor&) expr;
Ethan Nicholasd188c182019-06-10 15:55:38 -0400538 bool isFloat = c.fType.columns() > 1 ? c.fType.componentType().isFloat()
539 : c.fType.isFloat();
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400540 if (c.fType.kind() == Type::kVector_Kind && c.isConstant()) {
541 for (int i = 0; i < c.fType.columns(); ++i) {
Ethan Nicholasd188c182019-06-10 15:55:38 -0400542 if (isFloat) {
543 if (c.getFVecComponent(i) != value) {
544 return false;
545 }
546 } else if (c.getIVecComponent(i) != value) {
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400547 return false;
548 }
549 }
550 return true;
551 }
552 return false;
553 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400554 default:
555 return false;
556 }
557}
558
559/**
560 * Collapses the binary expression pointed to by iter down to just the right side (in both the IR
561 * and CFG structures).
562 */
563void delete_left(BasicBlock* b,
564 std::vector<BasicBlock::Node>::iterator* iter,
565 bool* outUpdated,
566 bool* outNeedsRescan) {
567 *outUpdated = true;
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400568 std::unique_ptr<Expression>* target = (*iter)->expression();
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400569 SkASSERT((*target)->fKind == Expression::kBinary_Kind);
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400570 BinaryExpression& bin = (BinaryExpression&) **target;
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400571 SkASSERT(!bin.fLeft->hasSideEffects());
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400572 bool result;
573 if (bin.fOperator == Token::EQ) {
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400574 result = b->tryRemoveLValueBefore(iter, bin.fLeft.get());
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400575 } else {
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400576 result = b->tryRemoveExpressionBefore(iter, bin.fLeft.get());
Ethan Nicholascb670962017-04-20 19:31:52 -0400577 }
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400578 *target = std::move(bin.fRight);
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400579 if (!result) {
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400580 *outNeedsRescan = true;
581 return;
582 }
583 if (*iter == b->fNodes.begin()) {
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400584 *outNeedsRescan = true;
585 return;
586 }
587 --(*iter);
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400588 if ((*iter)->fKind != BasicBlock::Node::kExpression_Kind ||
589 (*iter)->expression() != &bin.fRight) {
590 *outNeedsRescan = true;
591 return;
592 }
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400593 *iter = b->fNodes.erase(*iter);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400594 SkASSERT((*iter)->expression() == target);
Ethan Nicholascb670962017-04-20 19:31:52 -0400595}
596
597/**
598 * Collapses the binary expression pointed to by iter down to just the left side (in both the IR and
599 * CFG structures).
600 */
601void delete_right(BasicBlock* b,
602 std::vector<BasicBlock::Node>::iterator* iter,
603 bool* outUpdated,
604 bool* outNeedsRescan) {
605 *outUpdated = true;
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400606 std::unique_ptr<Expression>* target = (*iter)->expression();
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400607 SkASSERT((*target)->fKind == Expression::kBinary_Kind);
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400608 BinaryExpression& bin = (BinaryExpression&) **target;
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400609 SkASSERT(!bin.fRight->hasSideEffects());
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400610 if (!b->tryRemoveExpressionBefore(iter, bin.fRight.get())) {
611 *target = std::move(bin.fLeft);
Ethan Nicholascb670962017-04-20 19:31:52 -0400612 *outNeedsRescan = true;
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400613 return;
Ethan Nicholascb670962017-04-20 19:31:52 -0400614 }
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400615 *target = std::move(bin.fLeft);
616 if (*iter == b->fNodes.begin()) {
617 *outNeedsRescan = true;
618 return;
619 }
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400620 --(*iter);
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400621 if (((*iter)->fKind != BasicBlock::Node::kExpression_Kind ||
622 (*iter)->expression() != &bin.fLeft)) {
623 *outNeedsRescan = true;
624 return;
625 }
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400626 *iter = b->fNodes.erase(*iter);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400627 SkASSERT((*iter)->expression() == target);
Ethan Nicholascb670962017-04-20 19:31:52 -0400628}
629
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400630/**
631 * Constructs the specified type using a single argument.
632 */
633static std::unique_ptr<Expression> construct(const Type& type, std::unique_ptr<Expression> v) {
634 std::vector<std::unique_ptr<Expression>> args;
635 args.push_back(std::move(v));
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700636 auto result = std::unique_ptr<Expression>(new Constructor(-1, type, std::move(args)));
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400637 return result;
638}
639
640/**
641 * Used in the implementations of vectorize_left and vectorize_right. Given a vector type and an
642 * expression x, deletes the expression pointed to by iter and replaces it with <type>(x).
643 */
644static void vectorize(BasicBlock* b,
645 std::vector<BasicBlock::Node>::iterator* iter,
646 const Type& type,
647 std::unique_ptr<Expression>* otherExpression,
648 bool* outUpdated,
649 bool* outNeedsRescan) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400650 SkASSERT((*(*iter)->expression())->fKind == Expression::kBinary_Kind);
651 SkASSERT(type.kind() == Type::kVector_Kind);
652 SkASSERT((*otherExpression)->fType.kind() == Type::kScalar_Kind);
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400653 *outUpdated = true;
654 std::unique_ptr<Expression>* target = (*iter)->expression();
655 if (!b->tryRemoveExpression(iter)) {
656 *target = construct(type, std::move(*otherExpression));
657 *outNeedsRescan = true;
658 } else {
659 *target = construct(type, std::move(*otherExpression));
660 if (!b->tryInsertExpression(iter, target)) {
661 *outNeedsRescan = true;
662 }
663 }
664}
665
666/**
667 * Given a binary expression of the form x <op> vec<n>(y), deletes the right side and vectorizes the
668 * left to yield vec<n>(x).
669 */
670static void vectorize_left(BasicBlock* b,
671 std::vector<BasicBlock::Node>::iterator* iter,
672 bool* outUpdated,
673 bool* outNeedsRescan) {
674 BinaryExpression& bin = (BinaryExpression&) **(*iter)->expression();
675 vectorize(b, iter, bin.fRight->fType, &bin.fLeft, outUpdated, outNeedsRescan);
676}
677
678/**
679 * Given a binary expression of the form vec<n>(x) <op> y, deletes the left side and vectorizes the
680 * right to yield vec<n>(y).
681 */
682static void vectorize_right(BasicBlock* b,
683 std::vector<BasicBlock::Node>::iterator* iter,
684 bool* outUpdated,
685 bool* outNeedsRescan) {
686 BinaryExpression& bin = (BinaryExpression&) **(*iter)->expression();
687 vectorize(b, iter, bin.fLeft->fType, &bin.fRight, outUpdated, outNeedsRescan);
688}
689
690// Mark that an expression which we were writing to is no longer being written to
691void clear_write(const Expression& expr) {
692 switch (expr.fKind) {
693 case Expression::kVariableReference_Kind: {
694 ((VariableReference&) expr).setRefKind(VariableReference::kRead_RefKind);
695 break;
696 }
697 case Expression::kFieldAccess_Kind:
698 clear_write(*((FieldAccess&) expr).fBase);
699 break;
700 case Expression::kSwizzle_Kind:
701 clear_write(*((Swizzle&) expr).fBase);
702 break;
703 case Expression::kIndex_Kind:
704 clear_write(*((IndexExpression&) expr).fBase);
705 break;
706 default:
707 ABORT("shouldn't be writing to this kind of expression\n");
708 break;
709 }
710}
711
Ethan Nicholascb670962017-04-20 19:31:52 -0400712void Compiler::simplifyExpression(DefinitionMap& definitions,
713 BasicBlock& b,
714 std::vector<BasicBlock::Node>::iterator* iter,
715 std::unordered_set<const Variable*>* undefinedVariables,
716 bool* outUpdated,
717 bool* outNeedsRescan) {
718 Expression* expr = (*iter)->expression()->get();
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400719 SkASSERT(expr);
Ethan Nicholascb670962017-04-20 19:31:52 -0400720 if ((*iter)->fConstantPropagation) {
721 std::unique_ptr<Expression> optimized = expr->constantPropagate(*fIRGenerator, definitions);
722 if (optimized) {
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400723 *outUpdated = true;
Ethan Nicholascb670962017-04-20 19:31:52 -0400724 if (!try_replace_expression(&b, iter, &optimized)) {
725 *outNeedsRescan = true;
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400726 return;
Ethan Nicholascb670962017-04-20 19:31:52 -0400727 }
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400728 SkASSERT((*iter)->fKind == BasicBlock::Node::kExpression_Kind);
Ethan Nicholascb670962017-04-20 19:31:52 -0400729 expr = (*iter)->expression()->get();
Ethan Nicholascb670962017-04-20 19:31:52 -0400730 }
731 }
732 switch (expr->fKind) {
733 case Expression::kVariableReference_Kind: {
Ethan Nicholas8f7e28f2018-03-26 14:24:27 -0400734 const VariableReference& ref = (VariableReference&) *expr;
735 const Variable& var = ref.fVariable;
736 if (ref.refKind() != VariableReference::kWrite_RefKind &&
737 ref.refKind() != VariableReference::kPointer_RefKind &&
738 var.fStorage == Variable::kLocal_Storage && !definitions[&var] &&
Ethan Nicholascb670962017-04-20 19:31:52 -0400739 (*undefinedVariables).find(&var) == (*undefinedVariables).end()) {
740 (*undefinedVariables).insert(&var);
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000741 this->error(expr->fOffset,
742 "'" + var.fName + "' has not been assigned");
Ethan Nicholascb670962017-04-20 19:31:52 -0400743 }
744 break;
745 }
746 case Expression::kTernary_Kind: {
747 TernaryExpression* t = (TernaryExpression*) expr;
748 if (t->fTest->fKind == Expression::kBoolLiteral_Kind) {
749 // ternary has a constant test, replace it with either the true or
750 // false branch
751 if (((BoolLiteral&) *t->fTest).fValue) {
752 (*iter)->setExpression(std::move(t->fIfTrue));
753 } else {
754 (*iter)->setExpression(std::move(t->fIfFalse));
755 }
756 *outUpdated = true;
757 *outNeedsRescan = true;
758 }
759 break;
760 }
761 case Expression::kBinary_Kind: {
Ethan Nicholascb670962017-04-20 19:31:52 -0400762 BinaryExpression* bin = (BinaryExpression*) expr;
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400763 if (dead_assignment(*bin)) {
764 delete_left(&b, iter, outUpdated, outNeedsRescan);
765 break;
766 }
767 // collapse useless expressions like x * 1 or x + 0
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400768 if (((bin->fLeft->fType.kind() != Type::kScalar_Kind) &&
769 (bin->fLeft->fType.kind() != Type::kVector_Kind)) ||
770 ((bin->fRight->fType.kind() != Type::kScalar_Kind) &&
771 (bin->fRight->fType.kind() != Type::kVector_Kind))) {
772 break;
773 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400774 switch (bin->fOperator) {
775 case Token::STAR:
776 if (is_constant(*bin->fLeft, 1)) {
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400777 if (bin->fLeft->fType.kind() == Type::kVector_Kind &&
778 bin->fRight->fType.kind() == Type::kScalar_Kind) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400779 // float4(1) * x -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400780 vectorize_right(&b, iter, outUpdated, outNeedsRescan);
781 } else {
782 // 1 * x -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400783 // 1 * float4(x) -> float4(x)
784 // float4(1) * float4(x) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400785 delete_left(&b, iter, outUpdated, outNeedsRescan);
786 }
787 }
788 else if (is_constant(*bin->fLeft, 0)) {
789 if (bin->fLeft->fType.kind() == Type::kScalar_Kind &&
Ethan Nicholas08dae922018-01-23 10:31:56 -0500790 bin->fRight->fType.kind() == Type::kVector_Kind &&
791 !bin->fRight->hasSideEffects()) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400792 // 0 * float4(x) -> float4(0)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400793 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
794 } else {
795 // 0 * x -> 0
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400796 // float4(0) * x -> float4(0)
797 // float4(0) * float4(x) -> float4(0)
Ethan Nicholas51493ee2017-12-11 12:34:33 -0500798 if (!bin->fRight->hasSideEffects()) {
799 delete_right(&b, iter, outUpdated, outNeedsRescan);
800 }
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400801 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400802 }
803 else if (is_constant(*bin->fRight, 1)) {
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400804 if (bin->fLeft->fType.kind() == Type::kScalar_Kind &&
805 bin->fRight->fType.kind() == Type::kVector_Kind) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400806 // x * float4(1) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400807 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
808 } else {
809 // x * 1 -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400810 // float4(x) * 1 -> float4(x)
811 // float4(x) * float4(1) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400812 delete_right(&b, iter, outUpdated, outNeedsRescan);
813 }
814 }
815 else if (is_constant(*bin->fRight, 0)) {
816 if (bin->fLeft->fType.kind() == Type::kVector_Kind &&
Ethan Nicholas08dae922018-01-23 10:31:56 -0500817 bin->fRight->fType.kind() == Type::kScalar_Kind &&
818 !bin->fLeft->hasSideEffects()) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400819 // float4(x) * 0 -> float4(0)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400820 vectorize_right(&b, iter, outUpdated, outNeedsRescan);
821 } else {
822 // x * 0 -> 0
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400823 // x * float4(0) -> float4(0)
824 // float4(x) * float4(0) -> float4(0)
Ethan Nicholas51493ee2017-12-11 12:34:33 -0500825 if (!bin->fLeft->hasSideEffects()) {
826 delete_left(&b, iter, outUpdated, outNeedsRescan);
827 }
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400828 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400829 }
830 break;
Ethan Nicholas56e42712017-04-21 10:23:37 -0400831 case Token::PLUS:
Ethan Nicholascb670962017-04-20 19:31:52 -0400832 if (is_constant(*bin->fLeft, 0)) {
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400833 if (bin->fLeft->fType.kind() == Type::kVector_Kind &&
834 bin->fRight->fType.kind() == Type::kScalar_Kind) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400835 // float4(0) + x -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400836 vectorize_right(&b, iter, outUpdated, outNeedsRescan);
837 } else {
838 // 0 + x -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400839 // 0 + float4(x) -> float4(x)
840 // float4(0) + float4(x) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400841 delete_left(&b, iter, outUpdated, outNeedsRescan);
842 }
843 } else if (is_constant(*bin->fRight, 0)) {
844 if (bin->fLeft->fType.kind() == Type::kScalar_Kind &&
845 bin->fRight->fType.kind() == Type::kVector_Kind) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400846 // x + float4(0) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400847 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
848 } else {
849 // x + 0 -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400850 // float4(x) + 0 -> float4(x)
851 // float4(x) + float4(0) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400852 delete_right(&b, iter, outUpdated, outNeedsRescan);
853 }
Ethan Nicholas56e42712017-04-21 10:23:37 -0400854 }
855 break;
856 case Token::MINUS:
857 if (is_constant(*bin->fRight, 0)) {
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400858 if (bin->fLeft->fType.kind() == Type::kScalar_Kind &&
859 bin->fRight->fType.kind() == Type::kVector_Kind) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400860 // x - float4(0) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400861 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
862 } else {
863 // x - 0 -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400864 // float4(x) - 0 -> float4(x)
865 // float4(x) - float4(0) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400866 delete_right(&b, iter, outUpdated, outNeedsRescan);
867 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400868 }
869 break;
870 case Token::SLASH:
871 if (is_constant(*bin->fRight, 1)) {
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400872 if (bin->fLeft->fType.kind() == Type::kScalar_Kind &&
873 bin->fRight->fType.kind() == Type::kVector_Kind) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400874 // x / float4(1) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400875 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
876 } else {
877 // x / 1 -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400878 // float4(x) / 1 -> float4(x)
879 // float4(x) / float4(1) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400880 delete_right(&b, iter, outUpdated, outNeedsRescan);
881 }
882 } else if (is_constant(*bin->fLeft, 0)) {
883 if (bin->fLeft->fType.kind() == Type::kScalar_Kind &&
Ethan Nicholas08dae922018-01-23 10:31:56 -0500884 bin->fRight->fType.kind() == Type::kVector_Kind &&
885 !bin->fRight->hasSideEffects()) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400886 // 0 / float4(x) -> float4(0)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400887 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
888 } else {
889 // 0 / x -> 0
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400890 // float4(0) / x -> float4(0)
891 // float4(0) / float4(x) -> float4(0)
Ethan Nicholas51493ee2017-12-11 12:34:33 -0500892 if (!bin->fRight->hasSideEffects()) {
893 delete_right(&b, iter, outUpdated, outNeedsRescan);
894 }
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400895 }
896 }
897 break;
898 case Token::PLUSEQ:
899 if (is_constant(*bin->fRight, 0)) {
900 clear_write(*bin->fLeft);
901 delete_right(&b, iter, outUpdated, outNeedsRescan);
902 }
903 break;
904 case Token::MINUSEQ:
905 if (is_constant(*bin->fRight, 0)) {
906 clear_write(*bin->fLeft);
907 delete_right(&b, iter, outUpdated, outNeedsRescan);
908 }
909 break;
910 case Token::STAREQ:
911 if (is_constant(*bin->fRight, 1)) {
912 clear_write(*bin->fLeft);
913 delete_right(&b, iter, outUpdated, outNeedsRescan);
914 }
915 break;
916 case Token::SLASHEQ:
917 if (is_constant(*bin->fRight, 1)) {
918 clear_write(*bin->fLeft);
Ethan Nicholascb670962017-04-20 19:31:52 -0400919 delete_right(&b, iter, outUpdated, outNeedsRescan);
920 }
921 break;
922 default:
923 break;
924 }
925 }
926 default:
927 break;
928 }
929}
930
Ethan Nicholas5ac13c22017-05-10 15:06:17 -0400931// returns true if this statement could potentially execute a break at the current level (we ignore
932// nested loops and switches, since any breaks inside of them will merely break the loop / switch)
Ethan Nicholas5005a222018-08-24 13:06:27 -0400933static bool contains_conditional_break(Statement& s, bool inConditional) {
Ethan Nicholas5ac13c22017-05-10 15:06:17 -0400934 switch (s.fKind) {
935 case Statement::kBlock_Kind:
936 for (const auto& sub : ((Block&) s).fStatements) {
Ethan Nicholas5005a222018-08-24 13:06:27 -0400937 if (contains_conditional_break(*sub, inConditional)) {
938 return true;
939 }
940 }
941 return false;
942 case Statement::kBreak_Kind:
943 return inConditional;
944 case Statement::kIf_Kind: {
945 const IfStatement& i = (IfStatement&) s;
946 return contains_conditional_break(*i.fIfTrue, true) ||
947 (i.fIfFalse && contains_conditional_break(*i.fIfFalse, true));
948 }
949 default:
950 return false;
951 }
952}
953
954// returns true if this statement definitely executes a break at the current level (we ignore
955// nested loops and switches, since any breaks inside of them will merely break the loop / switch)
956static bool contains_unconditional_break(Statement& s) {
957 switch (s.fKind) {
958 case Statement::kBlock_Kind:
959 for (const auto& sub : ((Block&) s).fStatements) {
960 if (contains_unconditional_break(*sub)) {
Ethan Nicholas5ac13c22017-05-10 15:06:17 -0400961 return true;
962 }
963 }
964 return false;
965 case Statement::kBreak_Kind:
966 return true;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -0400967 default:
968 return false;
969 }
970}
971
972// Returns a block containing all of the statements that will be run if the given case matches
973// (which, owing to the statements being owned by unique_ptrs, means the switch itself will be
974// broken by this call and must then be discarded).
975// Returns null (and leaves the switch unmodified) if no such simple reduction is possible, such as
976// when break statements appear inside conditionals.
977static std::unique_ptr<Statement> block_for_case(SwitchStatement* s, SwitchCase* c) {
978 bool capturing = false;
979 std::vector<std::unique_ptr<Statement>*> statementPtrs;
980 for (const auto& current : s->fCases) {
981 if (current.get() == c) {
982 capturing = true;
983 }
984 if (capturing) {
985 for (auto& stmt : current->fStatements) {
Ethan Nicholas5005a222018-08-24 13:06:27 -0400986 if (contains_conditional_break(*stmt, s->fKind == Statement::kIf_Kind)) {
987 return nullptr;
988 }
989 if (contains_unconditional_break(*stmt)) {
Ethan Nicholas5ac13c22017-05-10 15:06:17 -0400990 capturing = false;
991 break;
992 }
Ethan Nicholas5ac13c22017-05-10 15:06:17 -0400993 statementPtrs.push_back(&stmt);
994 }
995 if (!capturing) {
996 break;
997 }
998 }
999 }
1000 std::vector<std::unique_ptr<Statement>> statements;
1001 for (const auto& s : statementPtrs) {
1002 statements.push_back(std::move(*s));
1003 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001004 return std::unique_ptr<Statement>(new Block(-1, std::move(statements), s->fSymbols));
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001005}
1006
Ethan Nicholascb670962017-04-20 19:31:52 -04001007void Compiler::simplifyStatement(DefinitionMap& definitions,
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001008 BasicBlock& b,
1009 std::vector<BasicBlock::Node>::iterator* iter,
1010 std::unordered_set<const Variable*>* undefinedVariables,
1011 bool* outUpdated,
1012 bool* outNeedsRescan) {
Ethan Nicholascb670962017-04-20 19:31:52 -04001013 Statement* stmt = (*iter)->statement()->get();
1014 switch (stmt->fKind) {
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001015 case Statement::kVarDeclaration_Kind: {
1016 const auto& varDecl = (VarDeclaration&) *stmt;
1017 if (varDecl.fVar->dead() &&
1018 (!varDecl.fValue ||
1019 !varDecl.fValue->hasSideEffects())) {
1020 if (varDecl.fValue) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001021 SkASSERT((*iter)->statement()->get() == stmt);
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001022 if (!b.tryRemoveExpressionBefore(iter, varDecl.fValue.get())) {
1023 *outNeedsRescan = true;
Ethan Nicholascb670962017-04-20 19:31:52 -04001024 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001025 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001026 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001027 *outUpdated = true;
Ethan Nicholascb670962017-04-20 19:31:52 -04001028 }
1029 break;
1030 }
1031 case Statement::kIf_Kind: {
1032 IfStatement& i = (IfStatement&) *stmt;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001033 if (i.fTest->fKind == Expression::kBoolLiteral_Kind) {
1034 // constant if, collapse down to a single branch
1035 if (((BoolLiteral&) *i.fTest).fValue) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001036 SkASSERT(i.fIfTrue);
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001037 (*iter)->setStatement(std::move(i.fIfTrue));
1038 } else {
1039 if (i.fIfFalse) {
1040 (*iter)->setStatement(std::move(i.fIfFalse));
1041 } else {
1042 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
1043 }
1044 }
1045 *outUpdated = true;
1046 *outNeedsRescan = true;
1047 break;
1048 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001049 if (i.fIfFalse && i.fIfFalse->isEmpty()) {
1050 // else block doesn't do anything, remove it
1051 i.fIfFalse.reset();
1052 *outUpdated = true;
1053 *outNeedsRescan = true;
1054 }
1055 if (!i.fIfFalse && i.fIfTrue->isEmpty()) {
1056 // if block doesn't do anything, no else block
1057 if (i.fTest->hasSideEffects()) {
1058 // test has side effects, keep it
1059 (*iter)->setStatement(std::unique_ptr<Statement>(
1060 new ExpressionStatement(std::move(i.fTest))));
1061 } else {
1062 // no if, no else, no test side effects, kill the whole if
1063 // statement
1064 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
1065 }
1066 *outUpdated = true;
1067 *outNeedsRescan = true;
1068 }
1069 break;
1070 }
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001071 case Statement::kSwitch_Kind: {
1072 SwitchStatement& s = (SwitchStatement&) *stmt;
1073 if (s.fValue->isConstant()) {
1074 // switch is constant, replace it with the case that matches
1075 bool found = false;
1076 SwitchCase* defaultCase = nullptr;
1077 for (const auto& c : s.fCases) {
1078 if (!c->fValue) {
1079 defaultCase = c.get();
1080 continue;
1081 }
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001082 SkASSERT(c->fValue->fKind == s.fValue->fKind);
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001083 found = c->fValue->compareConstant(*fContext, *s.fValue);
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001084 if (found) {
1085 std::unique_ptr<Statement> newBlock = block_for_case(&s, c.get());
1086 if (newBlock) {
1087 (*iter)->setStatement(std::move(newBlock));
1088 break;
1089 } else {
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -04001090 if (s.fIsStatic && !(fFlags & kPermitInvalidStaticTests_Flag)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001091 this->error(s.fOffset,
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001092 "static switch contains non-static conditional break");
1093 s.fIsStatic = false;
1094 }
1095 return; // can't simplify
1096 }
1097 }
1098 }
1099 if (!found) {
1100 // no matching case. use default if it exists, or kill the whole thing
1101 if (defaultCase) {
1102 std::unique_ptr<Statement> newBlock = block_for_case(&s, defaultCase);
1103 if (newBlock) {
1104 (*iter)->setStatement(std::move(newBlock));
1105 } else {
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -04001106 if (s.fIsStatic && !(fFlags & kPermitInvalidStaticTests_Flag)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001107 this->error(s.fOffset,
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001108 "static switch contains non-static conditional break");
1109 s.fIsStatic = false;
1110 }
1111 return; // can't simplify
1112 }
1113 } else {
1114 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
1115 }
1116 }
1117 *outUpdated = true;
1118 *outNeedsRescan = true;
1119 }
1120 break;
1121 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001122 case Statement::kExpression_Kind: {
1123 ExpressionStatement& e = (ExpressionStatement&) *stmt;
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001124 SkASSERT((*iter)->statement()->get() == &e);
Ethan Nicholascb670962017-04-20 19:31:52 -04001125 if (!e.fExpression->hasSideEffects()) {
1126 // Expression statement with no side effects, kill it
1127 if (!b.tryRemoveExpressionBefore(iter, e.fExpression.get())) {
1128 *outNeedsRescan = true;
1129 }
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001130 SkASSERT((*iter)->statement()->get() == stmt);
Ethan Nicholascb670962017-04-20 19:31:52 -04001131 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
1132 *outUpdated = true;
1133 }
1134 break;
1135 }
1136 default:
1137 break;
1138 }
1139}
1140
1141void Compiler::scanCFG(FunctionDefinition& f) {
1142 CFG cfg = CFGGenerator().getCFG(f);
1143 this->computeDataFlow(&cfg);
ethannicholas22f939e2016-10-13 13:25:34 -07001144
1145 // check for unreachable code
1146 for (size_t i = 0; i < cfg.fBlocks.size(); i++) {
Mike Klein6ad99092016-10-26 10:35:22 -04001147 if (i != cfg.fStart && !cfg.fBlocks[i].fEntrances.size() &&
ethannicholas22f939e2016-10-13 13:25:34 -07001148 cfg.fBlocks[i].fNodes.size()) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001149 int offset;
Ethan Nicholas86a43402017-01-19 13:32:00 -05001150 switch (cfg.fBlocks[i].fNodes[0].fKind) {
1151 case BasicBlock::Node::kStatement_Kind:
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001152 offset = (*cfg.fBlocks[i].fNodes[0].statement())->fOffset;
Ethan Nicholas86a43402017-01-19 13:32:00 -05001153 break;
1154 case BasicBlock::Node::kExpression_Kind:
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001155 offset = (*cfg.fBlocks[i].fNodes[0].expression())->fOffset;
Ethan Nicholas86a43402017-01-19 13:32:00 -05001156 break;
1157 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001158 this->error(offset, String("unreachable"));
ethannicholas22f939e2016-10-13 13:25:34 -07001159 }
1160 }
1161 if (fErrorCount) {
1162 return;
1163 }
1164
Ethan Nicholascb670962017-04-20 19:31:52 -04001165 // check for dead code & undefined variables, perform constant propagation
1166 std::unordered_set<const Variable*> undefinedVariables;
1167 bool updated;
1168 bool needsRescan = false;
1169 do {
1170 if (needsRescan) {
1171 cfg = CFGGenerator().getCFG(f);
1172 this->computeDataFlow(&cfg);
1173 needsRescan = false;
Ethan Nicholas113628d2017-02-02 16:11:39 -05001174 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001175
1176 updated = false;
1177 for (BasicBlock& b : cfg.fBlocks) {
1178 DefinitionMap definitions = b.fBefore;
1179
1180 for (auto iter = b.fNodes.begin(); iter != b.fNodes.end() && !needsRescan; ++iter) {
1181 if (iter->fKind == BasicBlock::Node::kExpression_Kind) {
1182 this->simplifyExpression(definitions, b, &iter, &undefinedVariables, &updated,
1183 &needsRescan);
1184 } else {
1185 this->simplifyStatement(definitions, b, &iter, &undefinedVariables, &updated,
1186 &needsRescan);
1187 }
Ethan Nicholas4b330df2017-05-17 10:52:55 -04001188 if (needsRescan) {
1189 break;
1190 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001191 this->addDefinitions(*iter, &definitions);
1192 }
1193 }
1194 } while (updated);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001195 SkASSERT(!needsRescan);
ethannicholas22f939e2016-10-13 13:25:34 -07001196
Ethan Nicholas91a10532017-06-22 11:24:38 -04001197 // verify static ifs & switches, clean up dead variable decls
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001198 for (BasicBlock& b : cfg.fBlocks) {
1199 DefinitionMap definitions = b.fBefore;
1200
Ethan Nicholas91a10532017-06-22 11:24:38 -04001201 for (auto iter = b.fNodes.begin(); iter != b.fNodes.end() && !needsRescan;) {
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001202 if (iter->fKind == BasicBlock::Node::kStatement_Kind) {
1203 const Statement& s = **iter->statement();
1204 switch (s.fKind) {
1205 case Statement::kIf_Kind:
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -04001206 if (((const IfStatement&) s).fIsStatic &&
1207 !(fFlags & kPermitInvalidStaticTests_Flag)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001208 this->error(s.fOffset, "static if has non-static test");
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001209 }
Ethan Nicholas91a10532017-06-22 11:24:38 -04001210 ++iter;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001211 break;
1212 case Statement::kSwitch_Kind:
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -04001213 if (((const SwitchStatement&) s).fIsStatic &&
1214 !(fFlags & kPermitInvalidStaticTests_Flag)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001215 this->error(s.fOffset, "static switch has non-static test");
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001216 }
Ethan Nicholas91a10532017-06-22 11:24:38 -04001217 ++iter;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001218 break;
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001219 case Statement::kVarDeclarations_Kind: {
1220 VarDeclarations& decls = *((VarDeclarationsStatement&) s).fDeclaration;
1221 for (auto varIter = decls.fVars.begin(); varIter != decls.fVars.end();) {
1222 if ((*varIter)->fKind == Statement::kNop_Kind) {
1223 varIter = decls.fVars.erase(varIter);
1224 } else {
1225 ++varIter;
1226 }
1227 }
1228 if (!decls.fVars.size()) {
1229 iter = b.fNodes.erase(iter);
1230 } else {
1231 ++iter;
1232 }
1233 break;
1234 }
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001235 default:
Ethan Nicholas91a10532017-06-22 11:24:38 -04001236 ++iter;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001237 break;
1238 }
Ethan Nicholas91a10532017-06-22 11:24:38 -04001239 } else {
1240 ++iter;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001241 }
1242 }
1243 }
1244
ethannicholas22f939e2016-10-13 13:25:34 -07001245 // check for missing return
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001246 if (f.fDeclaration.fReturnType != *fContext->fVoid_Type) {
ethannicholas22f939e2016-10-13 13:25:34 -07001247 if (cfg.fBlocks[cfg.fExit].fEntrances.size()) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001248 this->error(f.fOffset, String("function can exit without returning a value"));
ethannicholas22f939e2016-10-13 13:25:34 -07001249 }
1250 }
1251}
1252
Ethan Nicholas91164d12019-05-15 15:29:54 -04001253void Compiler::registerExternalValue(ExternalValue* value) {
1254 fIRGenerator->fRootSymbolTable->addWithoutOwnership(value->fName, value);
1255}
1256
1257Symbol* Compiler::takeOwnership(std::unique_ptr<Symbol> symbol) {
1258 return fIRGenerator->fRootSymbolTable->takeOwnership(std::move(symbol));
1259}
1260
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001261std::unique_ptr<Program> Compiler::convertProgram(Program::Kind kind, String text,
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001262 const Program::Settings& settings) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001263 fErrorText = "";
1264 fErrorCount = 0;
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001265 std::vector<std::unique_ptr<ProgramElement>>* inherited;
ethannicholasd598f792016-07-25 10:08:54 -07001266 std::vector<std::unique_ptr<ProgramElement>> elements;
ethannicholasb3058bd2016-07-01 08:22:01 -07001267 switch (kind) {
1268 case Program::kVertex_Kind:
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001269 inherited = &fVertexInclude;
1270 fIRGenerator->fSymbolTable = fVertexSymbolTable;
1271 fIRGenerator->start(&settings, inherited);
ethannicholasb3058bd2016-07-01 08:22:01 -07001272 break;
1273 case Program::kFragment_Kind:
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001274 inherited = &fFragmentInclude;
1275 fIRGenerator->fSymbolTable = fFragmentSymbolTable;
1276 fIRGenerator->start(&settings, inherited);
ethannicholasb3058bd2016-07-01 08:22:01 -07001277 break;
Ethan Nicholas52cad152017-02-16 16:37:32 -05001278 case Program::kGeometry_Kind:
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001279 inherited = &fGeometryInclude;
1280 fIRGenerator->fSymbolTable = fGeometrySymbolTable;
1281 fIRGenerator->start(&settings, inherited);
Ethan Nicholas52cad152017-02-16 16:37:32 -05001282 break;
Ethan Nicholas762466e2017-06-29 10:03:38 -04001283 case Program::kFragmentProcessor_Kind:
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001284 inherited = nullptr;
Ethan Nicholas8da1e652019-05-24 11:01:59 -04001285 fIRGenerator->fSymbolTable = fGpuSymbolTable;
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001286 fIRGenerator->start(&settings, nullptr);
Robert Phillipsfe8da172018-01-24 14:52:02 +00001287 fIRGenerator->convertProgram(kind, SKSL_FP_INCLUDE, strlen(SKSL_FP_INCLUDE), *fTypes,
Ethan Nicholasf7b88202017-09-18 14:10:39 -04001288 &elements);
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001289 fIRGenerator->fSymbolTable->markAllFunctionsBuiltin();
Ethan Nicholas762466e2017-06-29 10:03:38 -04001290 break;
Ethan Nicholas8da1e652019-05-24 11:01:59 -04001291 case Program::kPipelineStage_Kind:
1292 inherited = &fPipelineInclude;
1293 fIRGenerator->fSymbolTable = fPipelineSymbolTable;
1294 fIRGenerator->start(&settings, inherited);
1295 break;
Ethan Nicholas746035a2019-04-23 13:31:09 -04001296 case Program::kGeneric_Kind:
Ethan Nicholas8da1e652019-05-24 11:01:59 -04001297 inherited = &fInterpreterInclude;
1298 fIRGenerator->fSymbolTable = fInterpreterSymbolTable;
1299 fIRGenerator->start(&settings, inherited);
Ethan Nicholas0d997662019-04-08 09:46:01 -04001300 break;
ethannicholasb3058bd2016-07-01 08:22:01 -07001301 }
Ethan Nicholasaae47c82017-11-10 15:34:03 -05001302 for (auto& element : elements) {
1303 if (element->fKind == ProgramElement::kEnum_Kind) {
1304 ((Enum&) *element).fBuiltin = true;
1305 }
1306 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001307 std::unique_ptr<String> textPtr(new String(std::move(text)));
1308 fSource = textPtr.get();
Robert Phillipsfe8da172018-01-24 14:52:02 +00001309 fIRGenerator->convertProgram(kind, textPtr->c_str(), textPtr->size(), *fTypes, &elements);
Ethan Nicholasf7b88202017-09-18 14:10:39 -04001310 auto result = std::unique_ptr<Program>(new Program(kind,
1311 std::move(textPtr),
1312 settings,
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001313 fContext,
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001314 inherited,
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001315 std::move(elements),
1316 fIRGenerator->fSymbolTable,
1317 fIRGenerator->fInputs));
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001318 if (fErrorCount) {
1319 return nullptr;
1320 }
1321 return result;
1322}
1323
Ethan Nicholas00543112018-07-31 09:44:36 -04001324bool Compiler::optimize(Program& program) {
1325 SkASSERT(!fErrorCount);
1326 if (!program.fIsOptimized) {
1327 program.fIsOptimized = true;
1328 fIRGenerator->fKind = program.fKind;
1329 fIRGenerator->fSettings = &program.fSettings;
1330 for (auto& element : program) {
1331 if (element.fKind == ProgramElement::kFunction_Kind) {
1332 this->scanCFG((FunctionDefinition&) element);
1333 }
1334 }
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001335 if (program.fKind != Program::kFragmentProcessor_Kind) {
1336 for (auto iter = program.fElements.begin(); iter != program.fElements.end();) {
1337 if ((*iter)->fKind == ProgramElement::kVar_Kind) {
1338 VarDeclarations& vars = (VarDeclarations&) **iter;
1339 for (auto varIter = vars.fVars.begin(); varIter != vars.fVars.end();) {
1340 const Variable& var = *((VarDeclaration&) **varIter).fVar;
1341 if (var.dead()) {
1342 varIter = vars.fVars.erase(varIter);
1343 } else {
1344 ++varIter;
1345 }
1346 }
1347 if (vars.fVars.size() == 0) {
1348 iter = program.fElements.erase(iter);
1349 continue;
1350 }
1351 }
1352 ++iter;
1353 }
1354 }
Ethan Nicholas00543112018-07-31 09:44:36 -04001355 }
1356 return fErrorCount == 0;
1357}
1358
1359std::unique_ptr<Program> Compiler::specialize(
1360 Program& program,
1361 const std::unordered_map<SkSL::String, SkSL::Program::Settings::Value>& inputs) {
1362 std::vector<std::unique_ptr<ProgramElement>> elements;
1363 for (const auto& e : program) {
1364 elements.push_back(e.clone());
1365 }
1366 Program::Settings settings;
1367 settings.fCaps = program.fSettings.fCaps;
1368 for (auto iter = inputs.begin(); iter != inputs.end(); ++iter) {
1369 settings.fArgs.insert(*iter);
1370 }
1371 std::unique_ptr<Program> result(new Program(program.fKind,
1372 nullptr,
1373 settings,
1374 program.fContext,
1375 program.fInheritedElements,
1376 std::move(elements),
1377 program.fSymbols,
1378 program.fInputs));
1379 return result;
1380}
1381
Brian Osmanfb32ddf2019-06-18 10:14:20 -04001382#if defined(SKSL_STANDALONE) || SK_SUPPORT_GPU
1383
Ethan Nicholas00543112018-07-31 09:44:36 -04001384bool Compiler::toSPIRV(Program& program, OutputStream& out) {
1385 if (!this->optimize(program)) {
1386 return false;
1387 }
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001388#ifdef SK_ENABLE_SPIRV_VALIDATION
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001389 StringStream buffer;
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001390 fSource = program.fSource.get();
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001391 SPIRVCodeGenerator cg(fContext.get(), &program, this, &buffer);
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001392 bool result = cg.generateCode();
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001393 fSource = nullptr;
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001394 if (result) {
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001395 spvtools::SpirvTools tools(SPV_ENV_VULKAN_1_0);
Ethan Nicholas762466e2017-06-29 10:03:38 -04001396 const String& data = buffer.str();
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001397 SkASSERT(0 == data.size() % 4);
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001398 auto dumpmsg = [](spv_message_level_t, const char*, const spv_position_t&, const char* m) {
1399 SkDebugf("SPIR-V validation error: %s\n", m);
1400 };
1401 tools.SetMessageConsumer(dumpmsg);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001402 // Verify that the SPIR-V we produced is valid. If this SkASSERT fails, check the logs prior
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001403 // to the failure to see the validation errors.
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001404 SkAssertResult(tools.Validate((const uint32_t*) data.c_str(), data.size() / 4));
Ethan Nicholas762466e2017-06-29 10:03:38 -04001405 out.write(data.c_str(), data.size());
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001406 }
1407#else
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001408 fSource = program.fSource.get();
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001409 SPIRVCodeGenerator cg(fContext.get(), &program, this, &out);
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001410 bool result = cg.generateCode();
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001411 fSource = nullptr;
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001412#endif
Ethan Nicholasce33f102016-12-09 17:22:59 -05001413 return result;
1414}
1415
Ethan Nicholas00543112018-07-31 09:44:36 -04001416bool Compiler::toSPIRV(Program& program, String* out) {
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001417 StringStream buffer;
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001418 bool result = this->toSPIRV(program, buffer);
1419 if (result) {
Ethan Nicholas762466e2017-06-29 10:03:38 -04001420 *out = buffer.str();
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001421 }
1422 return result;
1423}
1424
Ethan Nicholas00543112018-07-31 09:44:36 -04001425bool Compiler::toGLSL(Program& program, OutputStream& out) {
1426 if (!this->optimize(program)) {
1427 return false;
1428 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001429 fSource = program.fSource.get();
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001430 GLSLCodeGenerator cg(fContext.get(), &program, this, &out);
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001431 bool result = cg.generateCode();
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001432 fSource = nullptr;
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001433 return result;
1434}
1435
Ethan Nicholas00543112018-07-31 09:44:36 -04001436bool Compiler::toGLSL(Program& program, String* out) {
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001437 StringStream buffer;
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001438 bool result = this->toGLSL(program, buffer);
1439 if (result) {
Ethan Nicholas762466e2017-06-29 10:03:38 -04001440 *out = buffer.str();
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001441 }
1442 return result;
1443}
1444
Ethan Nicholas00543112018-07-31 09:44:36 -04001445bool Compiler::toMetal(Program& program, OutputStream& out) {
1446 if (!this->optimize(program)) {
1447 return false;
1448 }
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001449 MetalCodeGenerator cg(fContext.get(), &program, this, &out);
Ethan Nicholascc305772017-10-13 16:17:45 -04001450 bool result = cg.generateCode();
Ethan Nicholascc305772017-10-13 16:17:45 -04001451 return result;
1452}
1453
Ethan Nicholas00543112018-07-31 09:44:36 -04001454bool Compiler::toMetal(Program& program, String* out) {
1455 if (!this->optimize(program)) {
1456 return false;
1457 }
Timothy Liangb8eeb802018-07-23 16:46:16 -04001458 StringStream buffer;
1459 bool result = this->toMetal(program, buffer);
1460 if (result) {
1461 *out = buffer.str();
1462 }
1463 return result;
1464}
1465
Ethan Nicholas00543112018-07-31 09:44:36 -04001466bool Compiler::toCPP(Program& program, String name, OutputStream& out) {
1467 if (!this->optimize(program)) {
1468 return false;
1469 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001470 fSource = program.fSource.get();
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001471 CPPCodeGenerator cg(fContext.get(), &program, this, name, &out);
Ethan Nicholas762466e2017-06-29 10:03:38 -04001472 bool result = cg.generateCode();
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001473 fSource = nullptr;
Ethan Nicholas762466e2017-06-29 10:03:38 -04001474 return result;
1475}
1476
Ethan Nicholas00543112018-07-31 09:44:36 -04001477bool Compiler::toH(Program& program, String name, OutputStream& out) {
1478 if (!this->optimize(program)) {
1479 return false;
1480 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001481 fSource = program.fSource.get();
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001482 HCodeGenerator cg(fContext.get(), &program, this, name, &out);
Ethan Nicholas762466e2017-06-29 10:03:38 -04001483 bool result = cg.generateCode();
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001484 fSource = nullptr;
Ethan Nicholas00543112018-07-31 09:44:36 -04001485 return result;
1486}
1487
1488bool Compiler::toPipelineStage(const Program& program, String* out,
1489 std::vector<FormatArg>* outFormatArgs) {
1490 SkASSERT(program.fIsOptimized);
1491 fSource = program.fSource.get();
1492 StringStream buffer;
1493 PipelineStageCodeGenerator cg(fContext.get(), &program, this, &buffer, outFormatArgs);
1494 bool result = cg.generateCode();
1495 fSource = nullptr;
1496 if (result) {
1497 *out = buffer.str();
1498 }
Ethan Nicholas762466e2017-06-29 10:03:38 -04001499 return result;
1500}
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001501
Brian Osmanfb32ddf2019-06-18 10:14:20 -04001502#endif
1503
Ethan Nicholas0e9401d2019-03-21 11:05:37 -04001504std::unique_ptr<ByteCode> Compiler::toByteCode(Program& program) {
1505 if (!this->optimize(program)) {
1506 return nullptr;
1507 }
1508 std::unique_ptr<ByteCode> result(new ByteCode());
1509 ByteCodeGenerator cg(fContext.get(), &program, this, result.get());
1510 if (cg.generateCode()) {
1511 return result;
1512 }
1513 return nullptr;
1514}
1515
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001516const char* Compiler::OperatorName(Token::Kind kind) {
1517 switch (kind) {
1518 case Token::PLUS: return "+";
1519 case Token::MINUS: return "-";
1520 case Token::STAR: return "*";
1521 case Token::SLASH: return "/";
1522 case Token::PERCENT: return "%";
1523 case Token::SHL: return "<<";
1524 case Token::SHR: return ">>";
1525 case Token::LOGICALNOT: return "!";
1526 case Token::LOGICALAND: return "&&";
1527 case Token::LOGICALOR: return "||";
1528 case Token::LOGICALXOR: return "^^";
1529 case Token::BITWISENOT: return "~";
1530 case Token::BITWISEAND: return "&";
1531 case Token::BITWISEOR: return "|";
1532 case Token::BITWISEXOR: return "^";
1533 case Token::EQ: return "=";
1534 case Token::EQEQ: return "==";
1535 case Token::NEQ: return "!=";
1536 case Token::LT: return "<";
1537 case Token::GT: return ">";
1538 case Token::LTEQ: return "<=";
1539 case Token::GTEQ: return ">=";
1540 case Token::PLUSEQ: return "+=";
1541 case Token::MINUSEQ: return "-=";
1542 case Token::STAREQ: return "*=";
1543 case Token::SLASHEQ: return "/=";
1544 case Token::PERCENTEQ: return "%=";
1545 case Token::SHLEQ: return "<<=";
1546 case Token::SHREQ: return ">>=";
1547 case Token::LOGICALANDEQ: return "&&=";
1548 case Token::LOGICALOREQ: return "||=";
1549 case Token::LOGICALXOREQ: return "^^=";
1550 case Token::BITWISEANDEQ: return "&=";
1551 case Token::BITWISEOREQ: return "|=";
1552 case Token::BITWISEXOREQ: return "^=";
1553 case Token::PLUSPLUS: return "++";
1554 case Token::MINUSMINUS: return "--";
1555 case Token::COMMA: return ",";
1556 default:
1557 ABORT("unsupported operator: %d\n", kind);
1558 }
1559}
1560
1561
1562bool Compiler::IsAssignment(Token::Kind op) {
1563 switch (op) {
1564 case Token::EQ: // fall through
1565 case Token::PLUSEQ: // fall through
1566 case Token::MINUSEQ: // fall through
1567 case Token::STAREQ: // fall through
1568 case Token::SLASHEQ: // fall through
1569 case Token::PERCENTEQ: // fall through
1570 case Token::SHLEQ: // fall through
1571 case Token::SHREQ: // fall through
1572 case Token::BITWISEOREQ: // fall through
1573 case Token::BITWISEXOREQ: // fall through
1574 case Token::BITWISEANDEQ: // fall through
1575 case Token::LOGICALOREQ: // fall through
1576 case Token::LOGICALXOREQ: // fall through
1577 case Token::LOGICALANDEQ:
1578 return true;
1579 default:
1580 return false;
1581 }
1582}
1583
1584Position Compiler::position(int offset) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001585 SkASSERT(fSource);
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001586 int line = 1;
1587 int column = 1;
1588 for (int i = 0; i < offset; i++) {
1589 if ((*fSource)[i] == '\n') {
1590 ++line;
1591 column = 1;
1592 }
1593 else {
1594 ++column;
1595 }
1596 }
1597 return Position(line, column);
1598}
1599
1600void Compiler::error(int offset, String msg) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001601 fErrorCount++;
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001602 Position pos = this->position(offset);
1603 fErrorText += "error: " + to_string(pos.fLine) + ": " + msg.c_str() + "\n";
ethannicholasb3058bd2016-07-01 08:22:01 -07001604}
1605
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001606String Compiler::errorText() {
Ethan Nicholas00543112018-07-31 09:44:36 -04001607 this->writeErrorCount();
1608 fErrorCount = 0;
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001609 String result = fErrorText;
ethannicholasb3058bd2016-07-01 08:22:01 -07001610 return result;
1611}
1612
1613void Compiler::writeErrorCount() {
1614 if (fErrorCount) {
1615 fErrorText += to_string(fErrorCount) + " error";
1616 if (fErrorCount > 1) {
1617 fErrorText += "s";
1618 }
1619 fErrorText += "\n";
1620 }
1621}
1622
ethannicholasb3058bd2016-07-01 08:22:01 -07001623} // namespace