blob: 9d4238f4390059ef4b3feb04a2a8679b900e7c43 [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
ethannicholasb3058bd2016-07-01 08:22:01 -07008#include "SkSLCompiler.h"
9
Ethan Nicholas0e9401d2019-03-21 11:05:37 -040010#include "SkSLByteCodeGenerator.h"
ethannicholas22f939e2016-10-13 13:25:34 -070011#include "SkSLCFGGenerator.h"
Ethan Nicholas762466e2017-06-29 10:03:38 -040012#include "SkSLCPPCodeGenerator.h"
Ethan Nicholas941e7e22016-12-12 15:33:30 -050013#include "SkSLGLSLCodeGenerator.h"
Ethan Nicholas762466e2017-06-29 10:03:38 -040014#include "SkSLHCodeGenerator.h"
ethannicholasb3058bd2016-07-01 08:22:01 -070015#include "SkSLIRGenerator.h"
Ethan Nicholascc305772017-10-13 16:17:45 -040016#include "SkSLMetalCodeGenerator.h"
Ethan Nicholas00543112018-07-31 09:44:36 -040017#include "SkSLPipelineStageCodeGenerator.h"
ethannicholasb3058bd2016-07-01 08:22:01 -070018#include "SkSLSPIRVCodeGenerator.h"
Ethan Nicholasaae47c82017-11-10 15:34:03 -050019#include "ir/SkSLEnum.h"
ethannicholasb3058bd2016-07-01 08:22:01 -070020#include "ir/SkSLExpression.h"
Ethan Nicholascb670962017-04-20 19:31:52 -040021#include "ir/SkSLExpressionStatement.h"
Ethan Nicholasc6a19f12018-03-29 16:46:56 -040022#include "ir/SkSLFunctionCall.h"
ethannicholasb3058bd2016-07-01 08:22:01 -070023#include "ir/SkSLIntLiteral.h"
ethannicholas5961bc92016-10-12 06:39:56 -070024#include "ir/SkSLModifiersDeclaration.h"
Ethan Nicholascb670962017-04-20 19:31:52 -040025#include "ir/SkSLNop.h"
ethannicholasb3058bd2016-07-01 08:22:01 -070026#include "ir/SkSLSymbolTable.h"
Ethan Nicholascb670962017-04-20 19:31:52 -040027#include "ir/SkSLTernaryExpression.h"
ethannicholasddb37d62016-10-20 09:54:00 -070028#include "ir/SkSLUnresolvedFunction.h"
ethannicholas22f939e2016-10-13 13:25:34 -070029#include "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
ethannicholas5961bc92016-10-12 06:39:56 -070039static const char* SKSL_INCLUDE =
Ben Wagnera56c4d22018-01-24 17:32:17 -050040#include "sksl.inc"
ethannicholasb3058bd2016-07-01 08:22:01 -070041;
42
ethannicholas5961bc92016-10-12 06:39:56 -070043static const char* SKSL_VERT_INCLUDE =
Ben Wagnera56c4d22018-01-24 17:32:17 -050044#include "sksl_vert.inc"
ethannicholasb3058bd2016-07-01 08:22:01 -070045;
46
ethannicholas5961bc92016-10-12 06:39:56 -070047static const char* SKSL_FRAG_INCLUDE =
Ben Wagnera56c4d22018-01-24 17:32:17 -050048#include "sksl_frag.inc"
ethannicholasb3058bd2016-07-01 08:22:01 -070049;
50
Ethan Nicholas52cad152017-02-16 16:37:32 -050051static const char* SKSL_GEOM_INCLUDE =
Ben Wagnera56c4d22018-01-24 17:32:17 -050052#include "sksl_geom.inc"
Ethan Nicholas52cad152017-02-16 16:37:32 -050053;
54
Ethan Nicholas762466e2017-06-29 10:03:38 -040055static const char* SKSL_FP_INCLUDE =
Ben Wagnera56c4d22018-01-24 17:32:17 -050056#include "sksl_enums.inc"
57#include "sksl_fp.inc"
Ethan Nicholas762466e2017-06-29 10:03:38 -040058;
59
Ethan Nicholas00543112018-07-31 09:44:36 -040060static const char* SKSL_PIPELINE_STAGE_INCLUDE =
61#include "sksl_pipeline.inc"
Ethan Nicholas26a9aad2018-03-27 14:10:52 -040062;
63
Ethan Nicholas0d997662019-04-08 09:46:01 -040064static const char* SKSL_MIXER_INCLUDE =
65#include "sksl_mixer.inc"
66;
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;
Robert Phillipsfe8da172018-01-24 14:52:02 +0000226 fIRGenerator->convertProgram(Program::kFragment_Kind, SKSL_INCLUDE, strlen(SKSL_INCLUDE),
227 *fTypes, &ignored);
ethannicholasddb37d62016-10-20 09:54:00 -0700228 fIRGenerator->fSymbolTable->markAllFunctionsBuiltin();
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700229 if (fErrorCount) {
230 printf("Unexpected errors: %s\n", fErrorText.c_str());
231 }
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400232 SkASSERT(!fErrorCount);
Ethan Nicholas3c6ae622018-04-24 13:06:09 -0400233
234 Program::Settings settings;
235 fIRGenerator->start(&settings, nullptr);
236 fIRGenerator->convertProgram(Program::kFragment_Kind, SKSL_VERT_INCLUDE,
237 strlen(SKSL_VERT_INCLUDE), *fTypes, &fVertexInclude);
238 fIRGenerator->fSymbolTable->markAllFunctionsBuiltin();
239 fVertexSymbolTable = fIRGenerator->fSymbolTable;
Ethan Nicholas3c6ae622018-04-24 13:06:09 -0400240
241 fIRGenerator->start(&settings, nullptr);
242 fIRGenerator->convertProgram(Program::kVertex_Kind, SKSL_FRAG_INCLUDE,
243 strlen(SKSL_FRAG_INCLUDE), *fTypes, &fFragmentInclude);
244 fIRGenerator->fSymbolTable->markAllFunctionsBuiltin();
245 fFragmentSymbolTable = fIRGenerator->fSymbolTable;
Ethan Nicholas3c6ae622018-04-24 13:06:09 -0400246
247 fIRGenerator->start(&settings, nullptr);
248 fIRGenerator->convertProgram(Program::kGeometry_Kind, SKSL_GEOM_INCLUDE,
249 strlen(SKSL_GEOM_INCLUDE), *fTypes, &fGeometryInclude);
250 fIRGenerator->fSymbolTable->markAllFunctionsBuiltin();
251 fGeometrySymbolTable = fIRGenerator->fSymbolTable;
ethannicholasb3058bd2016-07-01 08:22:01 -0700252}
253
254Compiler::~Compiler() {
255 delete fIRGenerator;
256}
257
ethannicholas22f939e2016-10-13 13:25:34 -0700258// add the definition created by assigning to the lvalue to the definition set
Ethan Nicholas86a43402017-01-19 13:32:00 -0500259void Compiler::addDefinition(const Expression* lvalue, std::unique_ptr<Expression>* expr,
260 DefinitionMap* definitions) {
ethannicholas22f939e2016-10-13 13:25:34 -0700261 switch (lvalue->fKind) {
262 case Expression::kVariableReference_Kind: {
263 const Variable& var = ((VariableReference*) lvalue)->fVariable;
264 if (var.fStorage == Variable::kLocal_Storage) {
265 (*definitions)[&var] = expr;
266 }
267 break;
268 }
269 case Expression::kSwizzle_Kind:
270 // We consider the variable written to as long as at least some of its components have
271 // been written to. This will lead to some false negatives (we won't catch it if you
272 // write to foo.x and then read foo.y), but being stricter could lead to false positives
Mike Klein6ad99092016-10-26 10:35:22 -0400273 // (we write to foo.x, and then pass foo to a function which happens to only read foo.x,
274 // 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 -0700275 // more complicated whole-program analysis. This is probably good enough.
Mike Klein6ad99092016-10-26 10:35:22 -0400276 this->addDefinition(((Swizzle*) lvalue)->fBase.get(),
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400277 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
ethannicholas22f939e2016-10-13 13:25:34 -0700278 definitions);
279 break;
280 case Expression::kIndex_Kind:
281 // see comments in Swizzle
Mike Klein6ad99092016-10-26 10:35:22 -0400282 this->addDefinition(((IndexExpression*) lvalue)->fBase.get(),
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400283 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
ethannicholas22f939e2016-10-13 13:25:34 -0700284 definitions);
285 break;
286 case Expression::kFieldAccess_Kind:
287 // see comments in Swizzle
Mike Klein6ad99092016-10-26 10:35:22 -0400288 this->addDefinition(((FieldAccess*) lvalue)->fBase.get(),
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400289 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
ethannicholas22f939e2016-10-13 13:25:34 -0700290 definitions);
291 break;
Ethan Nicholasa583b812018-01-18 13:32:11 -0500292 case Expression::kTernary_Kind:
293 // To simplify analysis, we just pretend that we write to both sides of the ternary.
294 // This allows for false positives (meaning we fail to detect that a variable might not
295 // have been assigned), but is preferable to false negatives.
296 this->addDefinition(((TernaryExpression*) lvalue)->fIfTrue.get(),
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400297 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
Ethan Nicholasa583b812018-01-18 13:32:11 -0500298 definitions);
299 this->addDefinition(((TernaryExpression*) lvalue)->fIfFalse.get(),
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400300 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
Ethan Nicholasa583b812018-01-18 13:32:11 -0500301 definitions);
302 break;
ethannicholas22f939e2016-10-13 13:25:34 -0700303 default:
304 // not an lvalue, can't happen
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400305 SkASSERT(false);
ethannicholas22f939e2016-10-13 13:25:34 -0700306 }
307}
308
309// add local variables defined by this node to the set
Mike Klein6ad99092016-10-26 10:35:22 -0400310void Compiler::addDefinitions(const BasicBlock::Node& node,
Ethan Nicholas86a43402017-01-19 13:32:00 -0500311 DefinitionMap* definitions) {
ethannicholas22f939e2016-10-13 13:25:34 -0700312 switch (node.fKind) {
313 case BasicBlock::Node::kExpression_Kind: {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400314 SkASSERT(node.expression());
Ethan Nicholascb670962017-04-20 19:31:52 -0400315 const Expression* expr = (Expression*) node.expression()->get();
Ethan Nicholas86a43402017-01-19 13:32:00 -0500316 switch (expr->fKind) {
317 case Expression::kBinary_Kind: {
318 BinaryExpression* b = (BinaryExpression*) expr;
319 if (b->fOperator == Token::EQ) {
320 this->addDefinition(b->fLeft.get(), &b->fRight, definitions);
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700321 } else if (Compiler::IsAssignment(b->fOperator)) {
Ethan Nicholas86a43402017-01-19 13:32:00 -0500322 this->addDefinition(
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400323 b->fLeft.get(),
324 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
325 definitions);
Ethan Nicholas86a43402017-01-19 13:32:00 -0500326
327 }
328 break;
ethannicholas22f939e2016-10-13 13:25:34 -0700329 }
Ethan Nicholasc6a19f12018-03-29 16:46:56 -0400330 case Expression::kFunctionCall_Kind: {
331 const FunctionCall& c = (const FunctionCall&) *expr;
332 for (size_t i = 0; i < c.fFunction.fParameters.size(); ++i) {
333 if (c.fFunction.fParameters[i]->fModifiers.fFlags & Modifiers::kOut_Flag) {
334 this->addDefinition(
335 c.fArguments[i].get(),
336 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
337 definitions);
338 }
339 }
340 break;
341 }
Ethan Nicholas86a43402017-01-19 13:32:00 -0500342 case Expression::kPrefix_Kind: {
343 const PrefixExpression* p = (PrefixExpression*) expr;
344 if (p->fOperator == Token::MINUSMINUS || p->fOperator == Token::PLUSPLUS) {
345 this->addDefinition(
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400346 p->fOperand.get(),
347 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
348 definitions);
Ethan Nicholas86a43402017-01-19 13:32:00 -0500349 }
350 break;
351 }
352 case Expression::kPostfix_Kind: {
353 const PostfixExpression* p = (PostfixExpression*) expr;
354 if (p->fOperator == Token::MINUSMINUS || p->fOperator == Token::PLUSPLUS) {
355 this->addDefinition(
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400356 p->fOperand.get(),
357 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
358 definitions);
Ethan Nicholas86a43402017-01-19 13:32:00 -0500359 }
360 break;
361 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400362 case Expression::kVariableReference_Kind: {
363 const VariableReference* v = (VariableReference*) expr;
364 if (v->fRefKind != VariableReference::kRead_RefKind) {
365 this->addDefinition(
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400366 v,
367 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
368 definitions);
Ethan Nicholascb670962017-04-20 19:31:52 -0400369 }
370 }
Ethan Nicholas86a43402017-01-19 13:32:00 -0500371 default:
372 break;
ethannicholas22f939e2016-10-13 13:25:34 -0700373 }
374 break;
375 }
376 case BasicBlock::Node::kStatement_Kind: {
Ethan Nicholascb670962017-04-20 19:31:52 -0400377 const Statement* stmt = (Statement*) node.statement()->get();
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000378 if (stmt->fKind == Statement::kVarDeclaration_Kind) {
379 VarDeclaration& vd = (VarDeclaration&) *stmt;
380 if (vd.fValue) {
381 (*definitions)[vd.fVar] = &vd.fValue;
ethannicholas22f939e2016-10-13 13:25:34 -0700382 }
383 }
384 break;
385 }
386 }
387}
388
389void Compiler::scanCFG(CFG* cfg, BlockId blockId, std::set<BlockId>* workList) {
390 BasicBlock& block = cfg->fBlocks[blockId];
391
392 // compute definitions after this block
Ethan Nicholas86a43402017-01-19 13:32:00 -0500393 DefinitionMap after = block.fBefore;
ethannicholas22f939e2016-10-13 13:25:34 -0700394 for (const BasicBlock::Node& n : block.fNodes) {
395 this->addDefinitions(n, &after);
396 }
397
398 // propagate definitions to exits
399 for (BlockId exitId : block.fExits) {
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400400 if (exitId == blockId) {
401 continue;
402 }
ethannicholas22f939e2016-10-13 13:25:34 -0700403 BasicBlock& exit = cfg->fBlocks[exitId];
404 for (const auto& pair : after) {
Ethan Nicholas86a43402017-01-19 13:32:00 -0500405 std::unique_ptr<Expression>* e1 = pair.second;
406 auto found = exit.fBefore.find(pair.first);
407 if (found == exit.fBefore.end()) {
408 // exit has no definition for it, just copy it
409 workList->insert(exitId);
ethannicholas22f939e2016-10-13 13:25:34 -0700410 exit.fBefore[pair.first] = e1;
411 } else {
Ethan Nicholas86a43402017-01-19 13:32:00 -0500412 // exit has a (possibly different) value already defined
413 std::unique_ptr<Expression>* e2 = exit.fBefore[pair.first];
ethannicholas22f939e2016-10-13 13:25:34 -0700414 if (e1 != e2) {
415 // definition has changed, merge and add exit block to worklist
416 workList->insert(exitId);
Ethan Nicholasaf197692017-02-27 13:26:45 -0500417 if (e1 && e2) {
418 exit.fBefore[pair.first] =
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400419 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression;
Ethan Nicholasaf197692017-02-27 13:26:45 -0500420 } else {
421 exit.fBefore[pair.first] = nullptr;
422 }
ethannicholas22f939e2016-10-13 13:25:34 -0700423 }
424 }
425 }
426 }
427}
428
429// returns a map which maps all local variables in the function to null, indicating that their value
430// is initially unknown
Ethan Nicholas86a43402017-01-19 13:32:00 -0500431static DefinitionMap compute_start_state(const CFG& cfg) {
432 DefinitionMap result;
Mike Klein6ad99092016-10-26 10:35:22 -0400433 for (const auto& block : cfg.fBlocks) {
434 for (const auto& node : block.fNodes) {
ethannicholas22f939e2016-10-13 13:25:34 -0700435 if (node.fKind == BasicBlock::Node::kStatement_Kind) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400436 SkASSERT(node.statement());
Ethan Nicholascb670962017-04-20 19:31:52 -0400437 const Statement* s = node.statement()->get();
ethannicholas22f939e2016-10-13 13:25:34 -0700438 if (s->fKind == Statement::kVarDeclarations_Kind) {
439 const VarDeclarationsStatement* vd = (const VarDeclarationsStatement*) s;
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000440 for (const auto& decl : vd->fDeclaration->fVars) {
441 if (decl->fKind == Statement::kVarDeclaration_Kind) {
442 result[((VarDeclaration&) *decl).fVar] = nullptr;
443 }
Mike Klein6ad99092016-10-26 10:35:22 -0400444 }
ethannicholas22f939e2016-10-13 13:25:34 -0700445 }
446 }
447 }
448 }
449 return result;
450}
451
Ethan Nicholascb670962017-04-20 19:31:52 -0400452/**
453 * Returns true if assigning to this lvalue has no effect.
454 */
455static bool is_dead(const Expression& lvalue) {
456 switch (lvalue.fKind) {
457 case Expression::kVariableReference_Kind:
458 return ((VariableReference&) lvalue).fVariable.dead();
459 case Expression::kSwizzle_Kind:
460 return is_dead(*((Swizzle&) lvalue).fBase);
461 case Expression::kFieldAccess_Kind:
462 return is_dead(*((FieldAccess&) lvalue).fBase);
463 case Expression::kIndex_Kind: {
464 const IndexExpression& idx = (IndexExpression&) lvalue;
465 return is_dead(*idx.fBase) && !idx.fIndex->hasSideEffects();
466 }
Ethan Nicholasa583b812018-01-18 13:32:11 -0500467 case Expression::kTernary_Kind: {
468 const TernaryExpression& t = (TernaryExpression&) lvalue;
469 return !t.fTest->hasSideEffects() && is_dead(*t.fIfTrue) && is_dead(*t.fIfFalse);
470 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400471 default:
472 ABORT("invalid lvalue: %s\n", lvalue.description().c_str());
473 }
474}
ethannicholas22f939e2016-10-13 13:25:34 -0700475
Ethan Nicholascb670962017-04-20 19:31:52 -0400476/**
477 * Returns true if this is an assignment which can be collapsed down to just the right hand side due
478 * to a dead target and lack of side effects on the left hand side.
479 */
480static bool dead_assignment(const BinaryExpression& b) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700481 if (!Compiler::IsAssignment(b.fOperator)) {
Ethan Nicholascb670962017-04-20 19:31:52 -0400482 return false;
483 }
484 return is_dead(*b.fLeft);
485}
486
487void Compiler::computeDataFlow(CFG* cfg) {
488 cfg->fBlocks[cfg->fStart].fBefore = compute_start_state(*cfg);
ethannicholas22f939e2016-10-13 13:25:34 -0700489 std::set<BlockId> workList;
Ethan Nicholascb670962017-04-20 19:31:52 -0400490 for (BlockId i = 0; i < cfg->fBlocks.size(); i++) {
ethannicholas22f939e2016-10-13 13:25:34 -0700491 workList.insert(i);
492 }
493 while (workList.size()) {
494 BlockId next = *workList.begin();
495 workList.erase(workList.begin());
Ethan Nicholascb670962017-04-20 19:31:52 -0400496 this->scanCFG(cfg, next, &workList);
ethannicholas22f939e2016-10-13 13:25:34 -0700497 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400498}
499
500/**
501 * Attempts to replace the expression pointed to by iter with a new one (in both the CFG and the
502 * IR). If the expression can be cleanly removed, returns true and updates the iterator to point to
503 * the newly-inserted element. Otherwise updates only the IR and returns false (and the CFG will
504 * need to be regenerated).
505 */
506bool try_replace_expression(BasicBlock* b,
507 std::vector<BasicBlock::Node>::iterator* iter,
508 std::unique_ptr<Expression>* newExpression) {
509 std::unique_ptr<Expression>* target = (*iter)->expression();
510 if (!b->tryRemoveExpression(iter)) {
511 *target = std::move(*newExpression);
512 return false;
513 }
514 *target = std::move(*newExpression);
515 return b->tryInsertExpression(iter, target);
516}
517
518/**
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400519 * Returns true if the expression is a constant numeric literal with the specified value, or a
520 * constant vector with all elements equal to the specified value.
Ethan Nicholascb670962017-04-20 19:31:52 -0400521 */
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400522bool is_constant(const Expression& expr, double value) {
Ethan Nicholascb670962017-04-20 19:31:52 -0400523 switch (expr.fKind) {
524 case Expression::kIntLiteral_Kind:
525 return ((IntLiteral&) expr).fValue == value;
526 case Expression::kFloatLiteral_Kind:
527 return ((FloatLiteral&) expr).fValue == value;
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400528 case Expression::kConstructor_Kind: {
529 Constructor& c = (Constructor&) expr;
530 if (c.fType.kind() == Type::kVector_Kind && c.isConstant()) {
531 for (int i = 0; i < c.fType.columns(); ++i) {
532 if (!is_constant(c.getVecComponent(i), value)) {
533 return false;
534 }
535 }
536 return true;
537 }
538 return false;
539 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400540 default:
541 return false;
542 }
543}
544
545/**
546 * Collapses the binary expression pointed to by iter down to just the right side (in both the IR
547 * and CFG structures).
548 */
549void delete_left(BasicBlock* b,
550 std::vector<BasicBlock::Node>::iterator* iter,
551 bool* outUpdated,
552 bool* outNeedsRescan) {
553 *outUpdated = true;
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400554 std::unique_ptr<Expression>* target = (*iter)->expression();
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400555 SkASSERT((*target)->fKind == Expression::kBinary_Kind);
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400556 BinaryExpression& bin = (BinaryExpression&) **target;
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400557 SkASSERT(!bin.fLeft->hasSideEffects());
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400558 bool result;
559 if (bin.fOperator == Token::EQ) {
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400560 result = b->tryRemoveLValueBefore(iter, bin.fLeft.get());
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400561 } else {
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400562 result = b->tryRemoveExpressionBefore(iter, bin.fLeft.get());
Ethan Nicholascb670962017-04-20 19:31:52 -0400563 }
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400564 *target = std::move(bin.fRight);
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400565 if (!result) {
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400566 *outNeedsRescan = true;
567 return;
568 }
569 if (*iter == b->fNodes.begin()) {
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400570 *outNeedsRescan = true;
571 return;
572 }
573 --(*iter);
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400574 if ((*iter)->fKind != BasicBlock::Node::kExpression_Kind ||
575 (*iter)->expression() != &bin.fRight) {
576 *outNeedsRescan = true;
577 return;
578 }
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400579 *iter = b->fNodes.erase(*iter);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400580 SkASSERT((*iter)->expression() == target);
Ethan Nicholascb670962017-04-20 19:31:52 -0400581}
582
583/**
584 * Collapses the binary expression pointed to by iter down to just the left side (in both the IR and
585 * CFG structures).
586 */
587void delete_right(BasicBlock* b,
588 std::vector<BasicBlock::Node>::iterator* iter,
589 bool* outUpdated,
590 bool* outNeedsRescan) {
591 *outUpdated = true;
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400592 std::unique_ptr<Expression>* target = (*iter)->expression();
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400593 SkASSERT((*target)->fKind == Expression::kBinary_Kind);
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400594 BinaryExpression& bin = (BinaryExpression&) **target;
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400595 SkASSERT(!bin.fRight->hasSideEffects());
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400596 if (!b->tryRemoveExpressionBefore(iter, bin.fRight.get())) {
597 *target = std::move(bin.fLeft);
Ethan Nicholascb670962017-04-20 19:31:52 -0400598 *outNeedsRescan = true;
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400599 return;
Ethan Nicholascb670962017-04-20 19:31:52 -0400600 }
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400601 *target = std::move(bin.fLeft);
602 if (*iter == b->fNodes.begin()) {
603 *outNeedsRescan = true;
604 return;
605 }
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400606 --(*iter);
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400607 if (((*iter)->fKind != BasicBlock::Node::kExpression_Kind ||
608 (*iter)->expression() != &bin.fLeft)) {
609 *outNeedsRescan = true;
610 return;
611 }
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400612 *iter = b->fNodes.erase(*iter);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400613 SkASSERT((*iter)->expression() == target);
Ethan Nicholascb670962017-04-20 19:31:52 -0400614}
615
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400616/**
617 * Constructs the specified type using a single argument.
618 */
619static std::unique_ptr<Expression> construct(const Type& type, std::unique_ptr<Expression> v) {
620 std::vector<std::unique_ptr<Expression>> args;
621 args.push_back(std::move(v));
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700622 auto result = std::unique_ptr<Expression>(new Constructor(-1, type, std::move(args)));
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400623 return result;
624}
625
626/**
627 * Used in the implementations of vectorize_left and vectorize_right. Given a vector type and an
628 * expression x, deletes the expression pointed to by iter and replaces it with <type>(x).
629 */
630static void vectorize(BasicBlock* b,
631 std::vector<BasicBlock::Node>::iterator* iter,
632 const Type& type,
633 std::unique_ptr<Expression>* otherExpression,
634 bool* outUpdated,
635 bool* outNeedsRescan) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400636 SkASSERT((*(*iter)->expression())->fKind == Expression::kBinary_Kind);
637 SkASSERT(type.kind() == Type::kVector_Kind);
638 SkASSERT((*otherExpression)->fType.kind() == Type::kScalar_Kind);
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400639 *outUpdated = true;
640 std::unique_ptr<Expression>* target = (*iter)->expression();
641 if (!b->tryRemoveExpression(iter)) {
642 *target = construct(type, std::move(*otherExpression));
643 *outNeedsRescan = true;
644 } else {
645 *target = construct(type, std::move(*otherExpression));
646 if (!b->tryInsertExpression(iter, target)) {
647 *outNeedsRescan = true;
648 }
649 }
650}
651
652/**
653 * Given a binary expression of the form x <op> vec<n>(y), deletes the right side and vectorizes the
654 * left to yield vec<n>(x).
655 */
656static void vectorize_left(BasicBlock* b,
657 std::vector<BasicBlock::Node>::iterator* iter,
658 bool* outUpdated,
659 bool* outNeedsRescan) {
660 BinaryExpression& bin = (BinaryExpression&) **(*iter)->expression();
661 vectorize(b, iter, bin.fRight->fType, &bin.fLeft, outUpdated, outNeedsRescan);
662}
663
664/**
665 * Given a binary expression of the form vec<n>(x) <op> y, deletes the left side and vectorizes the
666 * right to yield vec<n>(y).
667 */
668static void vectorize_right(BasicBlock* b,
669 std::vector<BasicBlock::Node>::iterator* iter,
670 bool* outUpdated,
671 bool* outNeedsRescan) {
672 BinaryExpression& bin = (BinaryExpression&) **(*iter)->expression();
673 vectorize(b, iter, bin.fLeft->fType, &bin.fRight, outUpdated, outNeedsRescan);
674}
675
676// Mark that an expression which we were writing to is no longer being written to
677void clear_write(const Expression& expr) {
678 switch (expr.fKind) {
679 case Expression::kVariableReference_Kind: {
680 ((VariableReference&) expr).setRefKind(VariableReference::kRead_RefKind);
681 break;
682 }
683 case Expression::kFieldAccess_Kind:
684 clear_write(*((FieldAccess&) expr).fBase);
685 break;
686 case Expression::kSwizzle_Kind:
687 clear_write(*((Swizzle&) expr).fBase);
688 break;
689 case Expression::kIndex_Kind:
690 clear_write(*((IndexExpression&) expr).fBase);
691 break;
692 default:
693 ABORT("shouldn't be writing to this kind of expression\n");
694 break;
695 }
696}
697
Ethan Nicholascb670962017-04-20 19:31:52 -0400698void Compiler::simplifyExpression(DefinitionMap& definitions,
699 BasicBlock& b,
700 std::vector<BasicBlock::Node>::iterator* iter,
701 std::unordered_set<const Variable*>* undefinedVariables,
702 bool* outUpdated,
703 bool* outNeedsRescan) {
704 Expression* expr = (*iter)->expression()->get();
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400705 SkASSERT(expr);
Ethan Nicholascb670962017-04-20 19:31:52 -0400706 if ((*iter)->fConstantPropagation) {
707 std::unique_ptr<Expression> optimized = expr->constantPropagate(*fIRGenerator, definitions);
708 if (optimized) {
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400709 *outUpdated = true;
Ethan Nicholascb670962017-04-20 19:31:52 -0400710 if (!try_replace_expression(&b, iter, &optimized)) {
711 *outNeedsRescan = true;
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400712 return;
Ethan Nicholascb670962017-04-20 19:31:52 -0400713 }
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400714 SkASSERT((*iter)->fKind == BasicBlock::Node::kExpression_Kind);
Ethan Nicholascb670962017-04-20 19:31:52 -0400715 expr = (*iter)->expression()->get();
Ethan Nicholascb670962017-04-20 19:31:52 -0400716 }
717 }
718 switch (expr->fKind) {
719 case Expression::kVariableReference_Kind: {
Ethan Nicholas8f7e28f2018-03-26 14:24:27 -0400720 const VariableReference& ref = (VariableReference&) *expr;
721 const Variable& var = ref.fVariable;
722 if (ref.refKind() != VariableReference::kWrite_RefKind &&
723 ref.refKind() != VariableReference::kPointer_RefKind &&
724 var.fStorage == Variable::kLocal_Storage && !definitions[&var] &&
Ethan Nicholascb670962017-04-20 19:31:52 -0400725 (*undefinedVariables).find(&var) == (*undefinedVariables).end()) {
726 (*undefinedVariables).insert(&var);
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000727 this->error(expr->fOffset,
728 "'" + var.fName + "' has not been assigned");
Ethan Nicholascb670962017-04-20 19:31:52 -0400729 }
730 break;
731 }
732 case Expression::kTernary_Kind: {
733 TernaryExpression* t = (TernaryExpression*) expr;
734 if (t->fTest->fKind == Expression::kBoolLiteral_Kind) {
735 // ternary has a constant test, replace it with either the true or
736 // false branch
737 if (((BoolLiteral&) *t->fTest).fValue) {
738 (*iter)->setExpression(std::move(t->fIfTrue));
739 } else {
740 (*iter)->setExpression(std::move(t->fIfFalse));
741 }
742 *outUpdated = true;
743 *outNeedsRescan = true;
744 }
745 break;
746 }
747 case Expression::kBinary_Kind: {
Ethan Nicholascb670962017-04-20 19:31:52 -0400748 BinaryExpression* bin = (BinaryExpression*) expr;
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400749 if (dead_assignment(*bin)) {
750 delete_left(&b, iter, outUpdated, outNeedsRescan);
751 break;
752 }
753 // collapse useless expressions like x * 1 or x + 0
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400754 if (((bin->fLeft->fType.kind() != Type::kScalar_Kind) &&
755 (bin->fLeft->fType.kind() != Type::kVector_Kind)) ||
756 ((bin->fRight->fType.kind() != Type::kScalar_Kind) &&
757 (bin->fRight->fType.kind() != Type::kVector_Kind))) {
758 break;
759 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400760 switch (bin->fOperator) {
761 case Token::STAR:
762 if (is_constant(*bin->fLeft, 1)) {
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400763 if (bin->fLeft->fType.kind() == Type::kVector_Kind &&
764 bin->fRight->fType.kind() == Type::kScalar_Kind) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400765 // float4(1) * x -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400766 vectorize_right(&b, iter, outUpdated, outNeedsRescan);
767 } else {
768 // 1 * x -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400769 // 1 * float4(x) -> float4(x)
770 // float4(1) * float4(x) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400771 delete_left(&b, iter, outUpdated, outNeedsRescan);
772 }
773 }
774 else if (is_constant(*bin->fLeft, 0)) {
775 if (bin->fLeft->fType.kind() == Type::kScalar_Kind &&
Ethan Nicholas08dae922018-01-23 10:31:56 -0500776 bin->fRight->fType.kind() == Type::kVector_Kind &&
777 !bin->fRight->hasSideEffects()) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400778 // 0 * float4(x) -> float4(0)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400779 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
780 } else {
781 // 0 * x -> 0
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400782 // float4(0) * x -> float4(0)
783 // float4(0) * float4(x) -> float4(0)
Ethan Nicholas51493ee2017-12-11 12:34:33 -0500784 if (!bin->fRight->hasSideEffects()) {
785 delete_right(&b, iter, outUpdated, outNeedsRescan);
786 }
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400787 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400788 }
789 else if (is_constant(*bin->fRight, 1)) {
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400790 if (bin->fLeft->fType.kind() == Type::kScalar_Kind &&
791 bin->fRight->fType.kind() == Type::kVector_Kind) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400792 // x * float4(1) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400793 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
794 } else {
795 // x * 1 -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400796 // float4(x) * 1 -> float4(x)
797 // float4(x) * float4(1) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400798 delete_right(&b, iter, outUpdated, outNeedsRescan);
799 }
800 }
801 else if (is_constant(*bin->fRight, 0)) {
802 if (bin->fLeft->fType.kind() == Type::kVector_Kind &&
Ethan Nicholas08dae922018-01-23 10:31:56 -0500803 bin->fRight->fType.kind() == Type::kScalar_Kind &&
804 !bin->fLeft->hasSideEffects()) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400805 // float4(x) * 0 -> float4(0)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400806 vectorize_right(&b, iter, outUpdated, outNeedsRescan);
807 } else {
808 // x * 0 -> 0
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400809 // x * float4(0) -> float4(0)
810 // float4(x) * float4(0) -> float4(0)
Ethan Nicholas51493ee2017-12-11 12:34:33 -0500811 if (!bin->fLeft->hasSideEffects()) {
812 delete_left(&b, iter, outUpdated, outNeedsRescan);
813 }
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400814 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400815 }
816 break;
Ethan Nicholas56e42712017-04-21 10:23:37 -0400817 case Token::PLUS:
Ethan Nicholascb670962017-04-20 19:31:52 -0400818 if (is_constant(*bin->fLeft, 0)) {
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400819 if (bin->fLeft->fType.kind() == Type::kVector_Kind &&
820 bin->fRight->fType.kind() == Type::kScalar_Kind) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400821 // float4(0) + x -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400822 vectorize_right(&b, iter, outUpdated, outNeedsRescan);
823 } else {
824 // 0 + x -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400825 // 0 + float4(x) -> float4(x)
826 // float4(0) + float4(x) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400827 delete_left(&b, iter, outUpdated, outNeedsRescan);
828 }
829 } else if (is_constant(*bin->fRight, 0)) {
830 if (bin->fLeft->fType.kind() == Type::kScalar_Kind &&
831 bin->fRight->fType.kind() == Type::kVector_Kind) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400832 // x + float4(0) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400833 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
834 } else {
835 // x + 0 -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400836 // float4(x) + 0 -> float4(x)
837 // float4(x) + float4(0) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400838 delete_right(&b, iter, outUpdated, outNeedsRescan);
839 }
Ethan Nicholas56e42712017-04-21 10:23:37 -0400840 }
841 break;
842 case Token::MINUS:
843 if (is_constant(*bin->fRight, 0)) {
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400844 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 Nicholascb670962017-04-20 19:31:52 -0400854 }
855 break;
856 case Token::SLASH:
857 if (is_constant(*bin->fRight, 1)) {
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(1) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400861 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
862 } else {
863 // x / 1 -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400864 // float4(x) / 1 -> float4(x)
865 // float4(x) / float4(1) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400866 delete_right(&b, iter, outUpdated, outNeedsRescan);
867 }
868 } else if (is_constant(*bin->fLeft, 0)) {
869 if (bin->fLeft->fType.kind() == Type::kScalar_Kind &&
Ethan Nicholas08dae922018-01-23 10:31:56 -0500870 bin->fRight->fType.kind() == Type::kVector_Kind &&
871 !bin->fRight->hasSideEffects()) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400872 // 0 / float4(x) -> float4(0)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400873 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
874 } else {
875 // 0 / x -> 0
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400876 // float4(0) / x -> float4(0)
877 // float4(0) / float4(x) -> float4(0)
Ethan Nicholas51493ee2017-12-11 12:34:33 -0500878 if (!bin->fRight->hasSideEffects()) {
879 delete_right(&b, iter, outUpdated, outNeedsRescan);
880 }
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400881 }
882 }
883 break;
884 case Token::PLUSEQ:
885 if (is_constant(*bin->fRight, 0)) {
886 clear_write(*bin->fLeft);
887 delete_right(&b, iter, outUpdated, outNeedsRescan);
888 }
889 break;
890 case Token::MINUSEQ:
891 if (is_constant(*bin->fRight, 0)) {
892 clear_write(*bin->fLeft);
893 delete_right(&b, iter, outUpdated, outNeedsRescan);
894 }
895 break;
896 case Token::STAREQ:
897 if (is_constant(*bin->fRight, 1)) {
898 clear_write(*bin->fLeft);
899 delete_right(&b, iter, outUpdated, outNeedsRescan);
900 }
901 break;
902 case Token::SLASHEQ:
903 if (is_constant(*bin->fRight, 1)) {
904 clear_write(*bin->fLeft);
Ethan Nicholascb670962017-04-20 19:31:52 -0400905 delete_right(&b, iter, outUpdated, outNeedsRescan);
906 }
907 break;
908 default:
909 break;
910 }
911 }
912 default:
913 break;
914 }
915}
916
Ethan Nicholas5ac13c22017-05-10 15:06:17 -0400917// returns true if this statement could potentially execute a break at the current level (we ignore
918// nested loops and switches, since any breaks inside of them will merely break the loop / switch)
Ethan Nicholas5005a222018-08-24 13:06:27 -0400919static bool contains_conditional_break(Statement& s, bool inConditional) {
Ethan Nicholas5ac13c22017-05-10 15:06:17 -0400920 switch (s.fKind) {
921 case Statement::kBlock_Kind:
922 for (const auto& sub : ((Block&) s).fStatements) {
Ethan Nicholas5005a222018-08-24 13:06:27 -0400923 if (contains_conditional_break(*sub, inConditional)) {
924 return true;
925 }
926 }
927 return false;
928 case Statement::kBreak_Kind:
929 return inConditional;
930 case Statement::kIf_Kind: {
931 const IfStatement& i = (IfStatement&) s;
932 return contains_conditional_break(*i.fIfTrue, true) ||
933 (i.fIfFalse && contains_conditional_break(*i.fIfFalse, true));
934 }
935 default:
936 return false;
937 }
938}
939
940// returns true if this statement definitely executes a break at the current level (we ignore
941// nested loops and switches, since any breaks inside of them will merely break the loop / switch)
942static bool contains_unconditional_break(Statement& s) {
943 switch (s.fKind) {
944 case Statement::kBlock_Kind:
945 for (const auto& sub : ((Block&) s).fStatements) {
946 if (contains_unconditional_break(*sub)) {
Ethan Nicholas5ac13c22017-05-10 15:06:17 -0400947 return true;
948 }
949 }
950 return false;
951 case Statement::kBreak_Kind:
952 return true;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -0400953 default:
954 return false;
955 }
956}
957
958// Returns a block containing all of the statements that will be run if the given case matches
959// (which, owing to the statements being owned by unique_ptrs, means the switch itself will be
960// broken by this call and must then be discarded).
961// Returns null (and leaves the switch unmodified) if no such simple reduction is possible, such as
962// when break statements appear inside conditionals.
963static std::unique_ptr<Statement> block_for_case(SwitchStatement* s, SwitchCase* c) {
964 bool capturing = false;
965 std::vector<std::unique_ptr<Statement>*> statementPtrs;
966 for (const auto& current : s->fCases) {
967 if (current.get() == c) {
968 capturing = true;
969 }
970 if (capturing) {
971 for (auto& stmt : current->fStatements) {
Ethan Nicholas5005a222018-08-24 13:06:27 -0400972 if (contains_conditional_break(*stmt, s->fKind == Statement::kIf_Kind)) {
973 return nullptr;
974 }
975 if (contains_unconditional_break(*stmt)) {
Ethan Nicholas5ac13c22017-05-10 15:06:17 -0400976 capturing = false;
977 break;
978 }
Ethan Nicholas5ac13c22017-05-10 15:06:17 -0400979 statementPtrs.push_back(&stmt);
980 }
981 if (!capturing) {
982 break;
983 }
984 }
985 }
986 std::vector<std::unique_ptr<Statement>> statements;
987 for (const auto& s : statementPtrs) {
988 statements.push_back(std::move(*s));
989 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700990 return std::unique_ptr<Statement>(new Block(-1, std::move(statements), s->fSymbols));
Ethan Nicholas5ac13c22017-05-10 15:06:17 -0400991}
992
Ethan Nicholascb670962017-04-20 19:31:52 -0400993void Compiler::simplifyStatement(DefinitionMap& definitions,
Ethan Nicholas5ac13c22017-05-10 15:06:17 -0400994 BasicBlock& b,
995 std::vector<BasicBlock::Node>::iterator* iter,
996 std::unordered_set<const Variable*>* undefinedVariables,
997 bool* outUpdated,
998 bool* outNeedsRescan) {
Ethan Nicholascb670962017-04-20 19:31:52 -0400999 Statement* stmt = (*iter)->statement()->get();
1000 switch (stmt->fKind) {
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001001 case Statement::kVarDeclaration_Kind: {
1002 const auto& varDecl = (VarDeclaration&) *stmt;
1003 if (varDecl.fVar->dead() &&
1004 (!varDecl.fValue ||
1005 !varDecl.fValue->hasSideEffects())) {
1006 if (varDecl.fValue) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001007 SkASSERT((*iter)->statement()->get() == stmt);
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001008 if (!b.tryRemoveExpressionBefore(iter, varDecl.fValue.get())) {
1009 *outNeedsRescan = true;
Ethan Nicholascb670962017-04-20 19:31:52 -04001010 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001011 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001012 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001013 *outUpdated = true;
Ethan Nicholascb670962017-04-20 19:31:52 -04001014 }
1015 break;
1016 }
1017 case Statement::kIf_Kind: {
1018 IfStatement& i = (IfStatement&) *stmt;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001019 if (i.fTest->fKind == Expression::kBoolLiteral_Kind) {
1020 // constant if, collapse down to a single branch
1021 if (((BoolLiteral&) *i.fTest).fValue) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001022 SkASSERT(i.fIfTrue);
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001023 (*iter)->setStatement(std::move(i.fIfTrue));
1024 } else {
1025 if (i.fIfFalse) {
1026 (*iter)->setStatement(std::move(i.fIfFalse));
1027 } else {
1028 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
1029 }
1030 }
1031 *outUpdated = true;
1032 *outNeedsRescan = true;
1033 break;
1034 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001035 if (i.fIfFalse && i.fIfFalse->isEmpty()) {
1036 // else block doesn't do anything, remove it
1037 i.fIfFalse.reset();
1038 *outUpdated = true;
1039 *outNeedsRescan = true;
1040 }
1041 if (!i.fIfFalse && i.fIfTrue->isEmpty()) {
1042 // if block doesn't do anything, no else block
1043 if (i.fTest->hasSideEffects()) {
1044 // test has side effects, keep it
1045 (*iter)->setStatement(std::unique_ptr<Statement>(
1046 new ExpressionStatement(std::move(i.fTest))));
1047 } else {
1048 // no if, no else, no test side effects, kill the whole if
1049 // statement
1050 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
1051 }
1052 *outUpdated = true;
1053 *outNeedsRescan = true;
1054 }
1055 break;
1056 }
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001057 case Statement::kSwitch_Kind: {
1058 SwitchStatement& s = (SwitchStatement&) *stmt;
1059 if (s.fValue->isConstant()) {
1060 // switch is constant, replace it with the case that matches
1061 bool found = false;
1062 SwitchCase* defaultCase = nullptr;
1063 for (const auto& c : s.fCases) {
1064 if (!c->fValue) {
1065 defaultCase = c.get();
1066 continue;
1067 }
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001068 SkASSERT(c->fValue->fKind == s.fValue->fKind);
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001069 found = c->fValue->compareConstant(*fContext, *s.fValue);
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001070 if (found) {
1071 std::unique_ptr<Statement> newBlock = block_for_case(&s, c.get());
1072 if (newBlock) {
1073 (*iter)->setStatement(std::move(newBlock));
1074 break;
1075 } else {
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -04001076 if (s.fIsStatic && !(fFlags & kPermitInvalidStaticTests_Flag)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001077 this->error(s.fOffset,
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001078 "static switch contains non-static conditional break");
1079 s.fIsStatic = false;
1080 }
1081 return; // can't simplify
1082 }
1083 }
1084 }
1085 if (!found) {
1086 // no matching case. use default if it exists, or kill the whole thing
1087 if (defaultCase) {
1088 std::unique_ptr<Statement> newBlock = block_for_case(&s, defaultCase);
1089 if (newBlock) {
1090 (*iter)->setStatement(std::move(newBlock));
1091 } else {
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -04001092 if (s.fIsStatic && !(fFlags & kPermitInvalidStaticTests_Flag)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001093 this->error(s.fOffset,
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001094 "static switch contains non-static conditional break");
1095 s.fIsStatic = false;
1096 }
1097 return; // can't simplify
1098 }
1099 } else {
1100 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
1101 }
1102 }
1103 *outUpdated = true;
1104 *outNeedsRescan = true;
1105 }
1106 break;
1107 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001108 case Statement::kExpression_Kind: {
1109 ExpressionStatement& e = (ExpressionStatement&) *stmt;
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001110 SkASSERT((*iter)->statement()->get() == &e);
Ethan Nicholascb670962017-04-20 19:31:52 -04001111 if (!e.fExpression->hasSideEffects()) {
1112 // Expression statement with no side effects, kill it
1113 if (!b.tryRemoveExpressionBefore(iter, e.fExpression.get())) {
1114 *outNeedsRescan = true;
1115 }
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001116 SkASSERT((*iter)->statement()->get() == stmt);
Ethan Nicholascb670962017-04-20 19:31:52 -04001117 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
1118 *outUpdated = true;
1119 }
1120 break;
1121 }
1122 default:
1123 break;
1124 }
1125}
1126
1127void Compiler::scanCFG(FunctionDefinition& f) {
1128 CFG cfg = CFGGenerator().getCFG(f);
1129 this->computeDataFlow(&cfg);
ethannicholas22f939e2016-10-13 13:25:34 -07001130
1131 // check for unreachable code
1132 for (size_t i = 0; i < cfg.fBlocks.size(); i++) {
Mike Klein6ad99092016-10-26 10:35:22 -04001133 if (i != cfg.fStart && !cfg.fBlocks[i].fEntrances.size() &&
ethannicholas22f939e2016-10-13 13:25:34 -07001134 cfg.fBlocks[i].fNodes.size()) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001135 int offset;
Ethan Nicholas86a43402017-01-19 13:32:00 -05001136 switch (cfg.fBlocks[i].fNodes[0].fKind) {
1137 case BasicBlock::Node::kStatement_Kind:
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001138 offset = (*cfg.fBlocks[i].fNodes[0].statement())->fOffset;
Ethan Nicholas86a43402017-01-19 13:32:00 -05001139 break;
1140 case BasicBlock::Node::kExpression_Kind:
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001141 offset = (*cfg.fBlocks[i].fNodes[0].expression())->fOffset;
Ethan Nicholas86a43402017-01-19 13:32:00 -05001142 break;
1143 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001144 this->error(offset, String("unreachable"));
ethannicholas22f939e2016-10-13 13:25:34 -07001145 }
1146 }
1147 if (fErrorCount) {
1148 return;
1149 }
1150
Ethan Nicholascb670962017-04-20 19:31:52 -04001151 // check for dead code & undefined variables, perform constant propagation
1152 std::unordered_set<const Variable*> undefinedVariables;
1153 bool updated;
1154 bool needsRescan = false;
1155 do {
1156 if (needsRescan) {
1157 cfg = CFGGenerator().getCFG(f);
1158 this->computeDataFlow(&cfg);
1159 needsRescan = false;
Ethan Nicholas113628d2017-02-02 16:11:39 -05001160 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001161
1162 updated = false;
1163 for (BasicBlock& b : cfg.fBlocks) {
1164 DefinitionMap definitions = b.fBefore;
1165
1166 for (auto iter = b.fNodes.begin(); iter != b.fNodes.end() && !needsRescan; ++iter) {
1167 if (iter->fKind == BasicBlock::Node::kExpression_Kind) {
1168 this->simplifyExpression(definitions, b, &iter, &undefinedVariables, &updated,
1169 &needsRescan);
1170 } else {
1171 this->simplifyStatement(definitions, b, &iter, &undefinedVariables, &updated,
1172 &needsRescan);
1173 }
Ethan Nicholas4b330df2017-05-17 10:52:55 -04001174 if (needsRescan) {
1175 break;
1176 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001177 this->addDefinitions(*iter, &definitions);
1178 }
1179 }
1180 } while (updated);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001181 SkASSERT(!needsRescan);
ethannicholas22f939e2016-10-13 13:25:34 -07001182
Ethan Nicholas91a10532017-06-22 11:24:38 -04001183 // verify static ifs & switches, clean up dead variable decls
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001184 for (BasicBlock& b : cfg.fBlocks) {
1185 DefinitionMap definitions = b.fBefore;
1186
Ethan Nicholas91a10532017-06-22 11:24:38 -04001187 for (auto iter = b.fNodes.begin(); iter != b.fNodes.end() && !needsRescan;) {
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001188 if (iter->fKind == BasicBlock::Node::kStatement_Kind) {
1189 const Statement& s = **iter->statement();
1190 switch (s.fKind) {
1191 case Statement::kIf_Kind:
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -04001192 if (((const IfStatement&) s).fIsStatic &&
1193 !(fFlags & kPermitInvalidStaticTests_Flag)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001194 this->error(s.fOffset, "static if has non-static test");
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001195 }
Ethan Nicholas91a10532017-06-22 11:24:38 -04001196 ++iter;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001197 break;
1198 case Statement::kSwitch_Kind:
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -04001199 if (((const SwitchStatement&) s).fIsStatic &&
1200 !(fFlags & kPermitInvalidStaticTests_Flag)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001201 this->error(s.fOffset, "static switch has non-static test");
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001202 }
Ethan Nicholas91a10532017-06-22 11:24:38 -04001203 ++iter;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001204 break;
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001205 case Statement::kVarDeclarations_Kind: {
1206 VarDeclarations& decls = *((VarDeclarationsStatement&) s).fDeclaration;
1207 for (auto varIter = decls.fVars.begin(); varIter != decls.fVars.end();) {
1208 if ((*varIter)->fKind == Statement::kNop_Kind) {
1209 varIter = decls.fVars.erase(varIter);
1210 } else {
1211 ++varIter;
1212 }
1213 }
1214 if (!decls.fVars.size()) {
1215 iter = b.fNodes.erase(iter);
1216 } else {
1217 ++iter;
1218 }
1219 break;
1220 }
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001221 default:
Ethan Nicholas91a10532017-06-22 11:24:38 -04001222 ++iter;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001223 break;
1224 }
Ethan Nicholas91a10532017-06-22 11:24:38 -04001225 } else {
1226 ++iter;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001227 }
1228 }
1229 }
1230
ethannicholas22f939e2016-10-13 13:25:34 -07001231 // check for missing return
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001232 if (f.fDeclaration.fReturnType != *fContext->fVoid_Type) {
ethannicholas22f939e2016-10-13 13:25:34 -07001233 if (cfg.fBlocks[cfg.fExit].fEntrances.size()) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001234 this->error(f.fOffset, String("function can exit without returning a value"));
ethannicholas22f939e2016-10-13 13:25:34 -07001235 }
1236 }
1237}
1238
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001239std::unique_ptr<Program> Compiler::convertProgram(Program::Kind kind, String text,
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001240 const Program::Settings& settings) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001241 fErrorText = "";
1242 fErrorCount = 0;
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001243 std::vector<std::unique_ptr<ProgramElement>>* inherited;
ethannicholasd598f792016-07-25 10:08:54 -07001244 std::vector<std::unique_ptr<ProgramElement>> elements;
ethannicholasb3058bd2016-07-01 08:22:01 -07001245 switch (kind) {
1246 case Program::kVertex_Kind:
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001247 inherited = &fVertexInclude;
1248 fIRGenerator->fSymbolTable = fVertexSymbolTable;
1249 fIRGenerator->start(&settings, inherited);
ethannicholasb3058bd2016-07-01 08:22:01 -07001250 break;
1251 case Program::kFragment_Kind:
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001252 inherited = &fFragmentInclude;
1253 fIRGenerator->fSymbolTable = fFragmentSymbolTable;
1254 fIRGenerator->start(&settings, inherited);
ethannicholasb3058bd2016-07-01 08:22:01 -07001255 break;
Ethan Nicholas52cad152017-02-16 16:37:32 -05001256 case Program::kGeometry_Kind:
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001257 inherited = &fGeometryInclude;
1258 fIRGenerator->fSymbolTable = fGeometrySymbolTable;
1259 fIRGenerator->start(&settings, inherited);
Ethan Nicholas52cad152017-02-16 16:37:32 -05001260 break;
Ethan Nicholas762466e2017-06-29 10:03:38 -04001261 case Program::kFragmentProcessor_Kind:
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001262 inherited = nullptr;
1263 fIRGenerator->start(&settings, nullptr);
Robert Phillipsfe8da172018-01-24 14:52:02 +00001264 fIRGenerator->convertProgram(kind, SKSL_FP_INCLUDE, strlen(SKSL_FP_INCLUDE), *fTypes,
Ethan Nicholasf7b88202017-09-18 14:10:39 -04001265 &elements);
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001266 fIRGenerator->fSymbolTable->markAllFunctionsBuiltin();
Ethan Nicholas762466e2017-06-29 10:03:38 -04001267 break;
Ethan Nicholas00543112018-07-31 09:44:36 -04001268 case Program::kPipelineStage_Kind:
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001269 inherited = nullptr;
1270 fIRGenerator->start(&settings, nullptr);
Ethan Nicholas00543112018-07-31 09:44:36 -04001271 fIRGenerator->convertProgram(kind, SKSL_PIPELINE_STAGE_INCLUDE,
1272 strlen(SKSL_PIPELINE_STAGE_INCLUDE), *fTypes, &elements);
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001273 fIRGenerator->fSymbolTable->markAllFunctionsBuiltin();
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001274 break;
Ethan Nicholas0d997662019-04-08 09:46:01 -04001275 case Program::kMixer_Kind:
1276 inherited = nullptr;
1277 fIRGenerator->start(&settings, nullptr);
1278 fIRGenerator->convertProgram(kind, SKSL_MIXER_INCLUDE, strlen(SKSL_MIXER_INCLUDE),
1279 *fTypes, &elements);
1280 fIRGenerator->fSymbolTable->markAllFunctionsBuiltin();
1281 break;
ethannicholasb3058bd2016-07-01 08:22:01 -07001282 }
Ethan Nicholasaae47c82017-11-10 15:34:03 -05001283 for (auto& element : elements) {
1284 if (element->fKind == ProgramElement::kEnum_Kind) {
1285 ((Enum&) *element).fBuiltin = true;
1286 }
1287 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001288 std::unique_ptr<String> textPtr(new String(std::move(text)));
1289 fSource = textPtr.get();
Robert Phillipsfe8da172018-01-24 14:52:02 +00001290 fIRGenerator->convertProgram(kind, textPtr->c_str(), textPtr->size(), *fTypes, &elements);
Ethan Nicholasf7b88202017-09-18 14:10:39 -04001291 auto result = std::unique_ptr<Program>(new Program(kind,
1292 std::move(textPtr),
1293 settings,
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001294 fContext,
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001295 inherited,
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001296 std::move(elements),
1297 fIRGenerator->fSymbolTable,
1298 fIRGenerator->fInputs));
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001299 if (fErrorCount) {
1300 return nullptr;
1301 }
1302 return result;
1303}
1304
Ethan Nicholas00543112018-07-31 09:44:36 -04001305bool Compiler::optimize(Program& program) {
1306 SkASSERT(!fErrorCount);
1307 if (!program.fIsOptimized) {
1308 program.fIsOptimized = true;
1309 fIRGenerator->fKind = program.fKind;
1310 fIRGenerator->fSettings = &program.fSettings;
1311 for (auto& element : program) {
1312 if (element.fKind == ProgramElement::kFunction_Kind) {
1313 this->scanCFG((FunctionDefinition&) element);
1314 }
1315 }
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001316 if (program.fKind != Program::kFragmentProcessor_Kind) {
1317 for (auto iter = program.fElements.begin(); iter != program.fElements.end();) {
1318 if ((*iter)->fKind == ProgramElement::kVar_Kind) {
1319 VarDeclarations& vars = (VarDeclarations&) **iter;
1320 for (auto varIter = vars.fVars.begin(); varIter != vars.fVars.end();) {
1321 const Variable& var = *((VarDeclaration&) **varIter).fVar;
1322 if (var.dead()) {
1323 varIter = vars.fVars.erase(varIter);
1324 } else {
1325 ++varIter;
1326 }
1327 }
1328 if (vars.fVars.size() == 0) {
1329 iter = program.fElements.erase(iter);
1330 continue;
1331 }
1332 }
1333 ++iter;
1334 }
1335 }
Ethan Nicholas00543112018-07-31 09:44:36 -04001336 }
1337 return fErrorCount == 0;
1338}
1339
1340std::unique_ptr<Program> Compiler::specialize(
1341 Program& program,
1342 const std::unordered_map<SkSL::String, SkSL::Program::Settings::Value>& inputs) {
1343 std::vector<std::unique_ptr<ProgramElement>> elements;
1344 for (const auto& e : program) {
1345 elements.push_back(e.clone());
1346 }
1347 Program::Settings settings;
1348 settings.fCaps = program.fSettings.fCaps;
1349 for (auto iter = inputs.begin(); iter != inputs.end(); ++iter) {
1350 settings.fArgs.insert(*iter);
1351 }
1352 std::unique_ptr<Program> result(new Program(program.fKind,
1353 nullptr,
1354 settings,
1355 program.fContext,
1356 program.fInheritedElements,
1357 std::move(elements),
1358 program.fSymbols,
1359 program.fInputs));
1360 return result;
1361}
1362
1363bool Compiler::toSPIRV(Program& program, OutputStream& out) {
1364 if (!this->optimize(program)) {
1365 return false;
1366 }
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001367#ifdef SK_ENABLE_SPIRV_VALIDATION
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001368 StringStream buffer;
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001369 fSource = program.fSource.get();
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001370 SPIRVCodeGenerator cg(fContext.get(), &program, this, &buffer);
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001371 bool result = cg.generateCode();
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001372 fSource = nullptr;
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001373 if (result) {
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001374 spvtools::SpirvTools tools(SPV_ENV_VULKAN_1_0);
Ethan Nicholas762466e2017-06-29 10:03:38 -04001375 const String& data = buffer.str();
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001376 SkASSERT(0 == data.size() % 4);
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001377 auto dumpmsg = [](spv_message_level_t, const char*, const spv_position_t&, const char* m) {
1378 SkDebugf("SPIR-V validation error: %s\n", m);
1379 };
1380 tools.SetMessageConsumer(dumpmsg);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001381 // Verify that the SPIR-V we produced is valid. If this SkASSERT fails, check the logs prior
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001382 // to the failure to see the validation errors.
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001383 SkAssertResult(tools.Validate((const uint32_t*) data.c_str(), data.size() / 4));
Ethan Nicholas762466e2017-06-29 10:03:38 -04001384 out.write(data.c_str(), data.size());
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001385 }
1386#else
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001387 fSource = program.fSource.get();
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001388 SPIRVCodeGenerator cg(fContext.get(), &program, this, &out);
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001389 bool result = cg.generateCode();
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001390 fSource = nullptr;
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001391#endif
Ethan Nicholasce33f102016-12-09 17:22:59 -05001392 return result;
1393}
1394
Ethan Nicholas00543112018-07-31 09:44:36 -04001395bool Compiler::toSPIRV(Program& program, String* out) {
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001396 StringStream buffer;
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001397 bool result = this->toSPIRV(program, buffer);
1398 if (result) {
Ethan Nicholas762466e2017-06-29 10:03:38 -04001399 *out = buffer.str();
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001400 }
1401 return result;
1402}
1403
Ethan Nicholas00543112018-07-31 09:44:36 -04001404bool Compiler::toGLSL(Program& program, OutputStream& out) {
1405 if (!this->optimize(program)) {
1406 return false;
1407 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001408 fSource = program.fSource.get();
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001409 GLSLCodeGenerator 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 Nicholas941e7e22016-12-12 15:33:30 -05001412 return result;
1413}
1414
Ethan Nicholas00543112018-07-31 09:44:36 -04001415bool Compiler::toGLSL(Program& program, String* out) {
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001416 StringStream buffer;
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001417 bool result = this->toGLSL(program, buffer);
1418 if (result) {
Ethan Nicholas762466e2017-06-29 10:03:38 -04001419 *out = buffer.str();
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001420 }
1421 return result;
1422}
1423
Ethan Nicholas00543112018-07-31 09:44:36 -04001424bool Compiler::toMetal(Program& program, OutputStream& out) {
1425 if (!this->optimize(program)) {
1426 return false;
1427 }
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001428 MetalCodeGenerator cg(fContext.get(), &program, this, &out);
Ethan Nicholascc305772017-10-13 16:17:45 -04001429 bool result = cg.generateCode();
Ethan Nicholascc305772017-10-13 16:17:45 -04001430 return result;
1431}
1432
Ethan Nicholas00543112018-07-31 09:44:36 -04001433bool Compiler::toMetal(Program& program, String* out) {
1434 if (!this->optimize(program)) {
1435 return false;
1436 }
Timothy Liangb8eeb802018-07-23 16:46:16 -04001437 StringStream buffer;
1438 bool result = this->toMetal(program, buffer);
1439 if (result) {
1440 *out = buffer.str();
1441 }
1442 return result;
1443}
1444
Ethan Nicholas00543112018-07-31 09:44:36 -04001445bool Compiler::toCPP(Program& program, String name, OutputStream& out) {
1446 if (!this->optimize(program)) {
1447 return false;
1448 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001449 fSource = program.fSource.get();
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001450 CPPCodeGenerator cg(fContext.get(), &program, this, name, &out);
Ethan Nicholas762466e2017-06-29 10:03:38 -04001451 bool result = cg.generateCode();
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001452 fSource = nullptr;
Ethan Nicholas762466e2017-06-29 10:03:38 -04001453 return result;
1454}
1455
Ethan Nicholas00543112018-07-31 09:44:36 -04001456bool Compiler::toH(Program& program, String name, OutputStream& out) {
1457 if (!this->optimize(program)) {
1458 return false;
1459 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001460 fSource = program.fSource.get();
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001461 HCodeGenerator cg(fContext.get(), &program, this, name, &out);
Ethan Nicholas762466e2017-06-29 10:03:38 -04001462 bool result = cg.generateCode();
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001463 fSource = nullptr;
Ethan Nicholas00543112018-07-31 09:44:36 -04001464 return result;
1465}
1466
1467bool Compiler::toPipelineStage(const Program& program, String* out,
1468 std::vector<FormatArg>* outFormatArgs) {
1469 SkASSERT(program.fIsOptimized);
1470 fSource = program.fSource.get();
1471 StringStream buffer;
1472 PipelineStageCodeGenerator cg(fContext.get(), &program, this, &buffer, outFormatArgs);
1473 bool result = cg.generateCode();
1474 fSource = nullptr;
1475 if (result) {
1476 *out = buffer.str();
1477 }
Ethan Nicholas762466e2017-06-29 10:03:38 -04001478 return result;
1479}
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001480
Ethan Nicholas0e9401d2019-03-21 11:05:37 -04001481std::unique_ptr<ByteCode> Compiler::toByteCode(Program& program) {
1482 if (!this->optimize(program)) {
1483 return nullptr;
1484 }
1485 std::unique_ptr<ByteCode> result(new ByteCode());
1486 ByteCodeGenerator cg(fContext.get(), &program, this, result.get());
1487 if (cg.generateCode()) {
1488 return result;
1489 }
1490 return nullptr;
1491}
1492
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001493const char* Compiler::OperatorName(Token::Kind kind) {
1494 switch (kind) {
1495 case Token::PLUS: return "+";
1496 case Token::MINUS: return "-";
1497 case Token::STAR: return "*";
1498 case Token::SLASH: return "/";
1499 case Token::PERCENT: return "%";
1500 case Token::SHL: return "<<";
1501 case Token::SHR: return ">>";
1502 case Token::LOGICALNOT: return "!";
1503 case Token::LOGICALAND: return "&&";
1504 case Token::LOGICALOR: return "||";
1505 case Token::LOGICALXOR: return "^^";
1506 case Token::BITWISENOT: return "~";
1507 case Token::BITWISEAND: return "&";
1508 case Token::BITWISEOR: return "|";
1509 case Token::BITWISEXOR: return "^";
1510 case Token::EQ: return "=";
1511 case Token::EQEQ: return "==";
1512 case Token::NEQ: return "!=";
1513 case Token::LT: return "<";
1514 case Token::GT: return ">";
1515 case Token::LTEQ: return "<=";
1516 case Token::GTEQ: return ">=";
1517 case Token::PLUSEQ: return "+=";
1518 case Token::MINUSEQ: return "-=";
1519 case Token::STAREQ: return "*=";
1520 case Token::SLASHEQ: return "/=";
1521 case Token::PERCENTEQ: return "%=";
1522 case Token::SHLEQ: return "<<=";
1523 case Token::SHREQ: return ">>=";
1524 case Token::LOGICALANDEQ: return "&&=";
1525 case Token::LOGICALOREQ: return "||=";
1526 case Token::LOGICALXOREQ: return "^^=";
1527 case Token::BITWISEANDEQ: return "&=";
1528 case Token::BITWISEOREQ: return "|=";
1529 case Token::BITWISEXOREQ: return "^=";
1530 case Token::PLUSPLUS: return "++";
1531 case Token::MINUSMINUS: return "--";
1532 case Token::COMMA: return ",";
1533 default:
1534 ABORT("unsupported operator: %d\n", kind);
1535 }
1536}
1537
1538
1539bool Compiler::IsAssignment(Token::Kind op) {
1540 switch (op) {
1541 case Token::EQ: // fall through
1542 case Token::PLUSEQ: // fall through
1543 case Token::MINUSEQ: // fall through
1544 case Token::STAREQ: // fall through
1545 case Token::SLASHEQ: // fall through
1546 case Token::PERCENTEQ: // fall through
1547 case Token::SHLEQ: // fall through
1548 case Token::SHREQ: // fall through
1549 case Token::BITWISEOREQ: // fall through
1550 case Token::BITWISEXOREQ: // fall through
1551 case Token::BITWISEANDEQ: // fall through
1552 case Token::LOGICALOREQ: // fall through
1553 case Token::LOGICALXOREQ: // fall through
1554 case Token::LOGICALANDEQ:
1555 return true;
1556 default:
1557 return false;
1558 }
1559}
1560
1561Position Compiler::position(int offset) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001562 SkASSERT(fSource);
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001563 int line = 1;
1564 int column = 1;
1565 for (int i = 0; i < offset; i++) {
1566 if ((*fSource)[i] == '\n') {
1567 ++line;
1568 column = 1;
1569 }
1570 else {
1571 ++column;
1572 }
1573 }
1574 return Position(line, column);
1575}
1576
1577void Compiler::error(int offset, String msg) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001578 fErrorCount++;
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001579 Position pos = this->position(offset);
1580 fErrorText += "error: " + to_string(pos.fLine) + ": " + msg.c_str() + "\n";
ethannicholasb3058bd2016-07-01 08:22:01 -07001581}
1582
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001583String Compiler::errorText() {
Ethan Nicholas00543112018-07-31 09:44:36 -04001584 this->writeErrorCount();
1585 fErrorCount = 0;
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001586 String result = fErrorText;
ethannicholasb3058bd2016-07-01 08:22:01 -07001587 return result;
1588}
1589
1590void Compiler::writeErrorCount() {
1591 if (fErrorCount) {
1592 fErrorText += to_string(fErrorCount) + " error";
1593 if (fErrorCount > 1) {
1594 fErrorText += "s";
1595 }
1596 fErrorText += "\n";
1597 }
1598}
1599
ethannicholasb3058bd2016-07-01 08:22:01 -07001600} // namespace