blob: feaafebc79a3b9cff453528fa30b9807241819ca [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
ethannicholas22f939e2016-10-13 13:25:34 -070010#include "SkSLCFGGenerator.h"
Ethan Nicholas762466e2017-06-29 10:03:38 -040011#include "SkSLCPPCodeGenerator.h"
Ethan Nicholas941e7e22016-12-12 15:33:30 -050012#include "SkSLGLSLCodeGenerator.h"
Ethan Nicholas762466e2017-06-29 10:03:38 -040013#include "SkSLHCodeGenerator.h"
ethannicholasb3058bd2016-07-01 08:22:01 -070014#include "SkSLIRGenerator.h"
Ethan Nicholascc305772017-10-13 16:17:45 -040015#include "SkSLMetalCodeGenerator.h"
ethannicholasb3058bd2016-07-01 08:22:01 -070016#include "SkSLSPIRVCodeGenerator.h"
Ethan Nicholasaae47c82017-11-10 15:34:03 -050017#include "ir/SkSLEnum.h"
ethannicholasb3058bd2016-07-01 08:22:01 -070018#include "ir/SkSLExpression.h"
Ethan Nicholascb670962017-04-20 19:31:52 -040019#include "ir/SkSLExpressionStatement.h"
Ethan Nicholasc6a19f12018-03-29 16:46:56 -040020#include "ir/SkSLFunctionCall.h"
ethannicholasb3058bd2016-07-01 08:22:01 -070021#include "ir/SkSLIntLiteral.h"
ethannicholas5961bc92016-10-12 06:39:56 -070022#include "ir/SkSLModifiersDeclaration.h"
Ethan Nicholascb670962017-04-20 19:31:52 -040023#include "ir/SkSLNop.h"
ethannicholasb3058bd2016-07-01 08:22:01 -070024#include "ir/SkSLSymbolTable.h"
Ethan Nicholascb670962017-04-20 19:31:52 -040025#include "ir/SkSLTernaryExpression.h"
ethannicholasddb37d62016-10-20 09:54:00 -070026#include "ir/SkSLUnresolvedFunction.h"
ethannicholas22f939e2016-10-13 13:25:34 -070027#include "ir/SkSLVarDeclarations.h"
ethannicholasb3058bd2016-07-01 08:22:01 -070028
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -040029#ifdef SK_ENABLE_SPIRV_VALIDATION
30#include "spirv-tools/libspirv.hpp"
31#endif
32
ethannicholasb3058bd2016-07-01 08:22:01 -070033// include the built-in shader symbols as static strings
34
Ethan Nicholas79707652017-11-16 11:20:11 -050035#define STRINGIFY(x) #x
36
ethannicholas5961bc92016-10-12 06:39:56 -070037static const char* SKSL_INCLUDE =
Ben Wagnera56c4d22018-01-24 17:32:17 -050038#include "sksl.inc"
ethannicholasb3058bd2016-07-01 08:22:01 -070039;
40
ethannicholas5961bc92016-10-12 06:39:56 -070041static const char* SKSL_VERT_INCLUDE =
Ben Wagnera56c4d22018-01-24 17:32:17 -050042#include "sksl_vert.inc"
ethannicholasb3058bd2016-07-01 08:22:01 -070043;
44
ethannicholas5961bc92016-10-12 06:39:56 -070045static const char* SKSL_FRAG_INCLUDE =
Ben Wagnera56c4d22018-01-24 17:32:17 -050046#include "sksl_frag.inc"
ethannicholasb3058bd2016-07-01 08:22:01 -070047;
48
Ethan Nicholas52cad152017-02-16 16:37:32 -050049static const char* SKSL_GEOM_INCLUDE =
Ben Wagnera56c4d22018-01-24 17:32:17 -050050#include "sksl_geom.inc"
Ethan Nicholas52cad152017-02-16 16:37:32 -050051;
52
Ethan Nicholas762466e2017-06-29 10:03:38 -040053static const char* SKSL_FP_INCLUDE =
Ben Wagnera56c4d22018-01-24 17:32:17 -050054#include "sksl_enums.inc"
55#include "sksl_fp.inc"
Ethan Nicholas762466e2017-06-29 10:03:38 -040056;
57
Kevin Lubickf2030782018-06-19 12:04:18 +000058static const char* SKSL_CPU_INCLUDE =
59#include "sksl_cpu.inc"
Ethan Nicholas26a9aad2018-03-27 14:10:52 -040060;
61
ethannicholasb3058bd2016-07-01 08:22:01 -070062namespace SkSL {
63
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -040064Compiler::Compiler(Flags flags)
65: fFlags(flags)
Ethan Nicholas26a9aad2018-03-27 14:10:52 -040066, fContext(new Context())
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -040067, fErrorCount(0) {
Ethan Nicholas8feeff92017-03-30 14:11:58 -040068 auto types = std::shared_ptr<SymbolTable>(new SymbolTable(this));
69 auto symbols = std::shared_ptr<SymbolTable>(new SymbolTable(types, this));
Ethan Nicholas26a9aad2018-03-27 14:10:52 -040070 fIRGenerator = new IRGenerator(fContext.get(), symbols, *this);
ethannicholasb3058bd2016-07-01 08:22:01 -070071 fTypes = types;
Ethan Nicholas26a9aad2018-03-27 14:10:52 -040072 #define ADD_TYPE(t) types->addWithoutOwnership(fContext->f ## t ## _Type->fName, \
73 fContext->f ## t ## _Type.get())
ethannicholasb3058bd2016-07-01 08:22:01 -070074 ADD_TYPE(Void);
75 ADD_TYPE(Float);
Ethan Nicholas5af9ea32017-07-28 15:19:46 -040076 ADD_TYPE(Float2);
77 ADD_TYPE(Float3);
78 ADD_TYPE(Float4);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -040079 ADD_TYPE(Half);
80 ADD_TYPE(Half2);
81 ADD_TYPE(Half3);
82 ADD_TYPE(Half4);
ethannicholasb3058bd2016-07-01 08:22:01 -070083 ADD_TYPE(Double);
Ethan Nicholas5af9ea32017-07-28 15:19:46 -040084 ADD_TYPE(Double2);
85 ADD_TYPE(Double3);
86 ADD_TYPE(Double4);
ethannicholasb3058bd2016-07-01 08:22:01 -070087 ADD_TYPE(Int);
Ethan Nicholas5af9ea32017-07-28 15:19:46 -040088 ADD_TYPE(Int2);
89 ADD_TYPE(Int3);
90 ADD_TYPE(Int4);
ethannicholasb3058bd2016-07-01 08:22:01 -070091 ADD_TYPE(UInt);
Ethan Nicholas5af9ea32017-07-28 15:19:46 -040092 ADD_TYPE(UInt2);
93 ADD_TYPE(UInt3);
94 ADD_TYPE(UInt4);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -040095 ADD_TYPE(Short);
96 ADD_TYPE(Short2);
97 ADD_TYPE(Short3);
98 ADD_TYPE(Short4);
99 ADD_TYPE(UShort);
100 ADD_TYPE(UShort2);
101 ADD_TYPE(UShort3);
102 ADD_TYPE(UShort4);
Ruiqi Maob609e6d2018-07-17 10:19:38 -0400103 ADD_TYPE(Byte);
104 ADD_TYPE(Byte2);
105 ADD_TYPE(Byte3);
106 ADD_TYPE(Byte4);
107 ADD_TYPE(UByte);
108 ADD_TYPE(UByte2);
109 ADD_TYPE(UByte3);
110 ADD_TYPE(UByte4);
ethannicholasb3058bd2016-07-01 08:22:01 -0700111 ADD_TYPE(Bool);
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400112 ADD_TYPE(Bool2);
113 ADD_TYPE(Bool3);
114 ADD_TYPE(Bool4);
115 ADD_TYPE(Float2x2);
116 ADD_TYPE(Float2x3);
117 ADD_TYPE(Float2x4);
118 ADD_TYPE(Float3x2);
119 ADD_TYPE(Float3x3);
120 ADD_TYPE(Float3x4);
121 ADD_TYPE(Float4x2);
122 ADD_TYPE(Float4x3);
123 ADD_TYPE(Float4x4);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -0400124 ADD_TYPE(Half2x2);
125 ADD_TYPE(Half2x3);
126 ADD_TYPE(Half2x4);
127 ADD_TYPE(Half3x2);
128 ADD_TYPE(Half3x3);
129 ADD_TYPE(Half3x4);
130 ADD_TYPE(Half4x2);
131 ADD_TYPE(Half4x3);
132 ADD_TYPE(Half4x4);
133 ADD_TYPE(Double2x2);
134 ADD_TYPE(Double2x3);
135 ADD_TYPE(Double2x4);
136 ADD_TYPE(Double3x2);
137 ADD_TYPE(Double3x3);
138 ADD_TYPE(Double3x4);
139 ADD_TYPE(Double4x2);
140 ADD_TYPE(Double4x3);
141 ADD_TYPE(Double4x4);
ethannicholasb3058bd2016-07-01 08:22:01 -0700142 ADD_TYPE(GenType);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -0400143 ADD_TYPE(GenHType);
ethannicholasb3058bd2016-07-01 08:22:01 -0700144 ADD_TYPE(GenDType);
145 ADD_TYPE(GenIType);
146 ADD_TYPE(GenUType);
147 ADD_TYPE(GenBType);
148 ADD_TYPE(Mat);
149 ADD_TYPE(Vec);
150 ADD_TYPE(GVec);
151 ADD_TYPE(GVec2);
152 ADD_TYPE(GVec3);
153 ADD_TYPE(GVec4);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -0400154 ADD_TYPE(HVec);
ethannicholasb3058bd2016-07-01 08:22:01 -0700155 ADD_TYPE(DVec);
156 ADD_TYPE(IVec);
157 ADD_TYPE(UVec);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -0400158 ADD_TYPE(SVec);
159 ADD_TYPE(USVec);
Ruiqi Maob609e6d2018-07-17 10:19:38 -0400160 ADD_TYPE(ByteVec);
161 ADD_TYPE(UByteVec);
ethannicholasb3058bd2016-07-01 08:22:01 -0700162 ADD_TYPE(BVec);
163
164 ADD_TYPE(Sampler1D);
165 ADD_TYPE(Sampler2D);
166 ADD_TYPE(Sampler3D);
ethannicholas5961bc92016-10-12 06:39:56 -0700167 ADD_TYPE(SamplerExternalOES);
ethannicholasb3058bd2016-07-01 08:22:01 -0700168 ADD_TYPE(SamplerCube);
169 ADD_TYPE(Sampler2DRect);
170 ADD_TYPE(Sampler1DArray);
171 ADD_TYPE(Sampler2DArray);
172 ADD_TYPE(SamplerCubeArray);
173 ADD_TYPE(SamplerBuffer);
174 ADD_TYPE(Sampler2DMS);
175 ADD_TYPE(Sampler2DMSArray);
176
Brian Salomonbf7b6202016-11-11 16:08:03 -0500177 ADD_TYPE(ISampler2D);
178
Brian Salomon2a51de82016-11-16 12:06:01 -0500179 ADD_TYPE(Image2D);
180 ADD_TYPE(IImage2D);
181
Greg Daniel64773e62016-11-22 09:44:03 -0500182 ADD_TYPE(SubpassInput);
183 ADD_TYPE(SubpassInputMS);
184
ethannicholasb3058bd2016-07-01 08:22:01 -0700185 ADD_TYPE(GSampler1D);
186 ADD_TYPE(GSampler2D);
187 ADD_TYPE(GSampler3D);
188 ADD_TYPE(GSamplerCube);
189 ADD_TYPE(GSampler2DRect);
190 ADD_TYPE(GSampler1DArray);
191 ADD_TYPE(GSampler2DArray);
192 ADD_TYPE(GSamplerCubeArray);
193 ADD_TYPE(GSamplerBuffer);
194 ADD_TYPE(GSampler2DMS);
195 ADD_TYPE(GSampler2DMSArray);
196
197 ADD_TYPE(Sampler1DShadow);
198 ADD_TYPE(Sampler2DShadow);
199 ADD_TYPE(SamplerCubeShadow);
200 ADD_TYPE(Sampler2DRectShadow);
201 ADD_TYPE(Sampler1DArrayShadow);
202 ADD_TYPE(Sampler2DArrayShadow);
203 ADD_TYPE(SamplerCubeArrayShadow);
204 ADD_TYPE(GSampler2DArrayShadow);
205 ADD_TYPE(GSamplerCubeArrayShadow);
Ethan Nicholasc9472af2017-10-10 16:30:21 -0400206 ADD_TYPE(FragmentProcessor);
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400207 ADD_TYPE(SkRasterPipeline);
ethannicholasb3058bd2016-07-01 08:22:01 -0700208
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700209 StringFragment skCapsName("sk_Caps");
210 Variable* skCaps = new Variable(-1, Modifiers(), skCapsName,
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400211 *fContext->fSkCaps_Type, Variable::kGlobal_Storage);
Ethan Nicholas3605ace2016-11-21 15:59:48 -0500212 fIRGenerator->fSymbolTable->add(skCapsName, std::unique_ptr<Symbol>(skCaps));
213
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700214 StringFragment skArgsName("sk_Args");
215 Variable* skArgs = new Variable(-1, Modifiers(), skArgsName,
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400216 *fContext->fSkArgs_Type, Variable::kGlobal_Storage);
Ethan Nicholas762466e2017-06-29 10:03:38 -0400217 fIRGenerator->fSymbolTable->add(skArgsName, std::unique_ptr<Symbol>(skArgs));
218
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400219 std::vector<std::unique_ptr<ProgramElement>> ignored;
Robert Phillipsfe8da172018-01-24 14:52:02 +0000220 fIRGenerator->convertProgram(Program::kFragment_Kind, SKSL_INCLUDE, strlen(SKSL_INCLUDE),
221 *fTypes, &ignored);
ethannicholasddb37d62016-10-20 09:54:00 -0700222 fIRGenerator->fSymbolTable->markAllFunctionsBuiltin();
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700223 if (fErrorCount) {
224 printf("Unexpected errors: %s\n", fErrorText.c_str());
225 }
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400226 SkASSERT(!fErrorCount);
Ethan Nicholas3c6ae622018-04-24 13:06:09 -0400227
228 Program::Settings settings;
229 fIRGenerator->start(&settings, nullptr);
230 fIRGenerator->convertProgram(Program::kFragment_Kind, SKSL_VERT_INCLUDE,
231 strlen(SKSL_VERT_INCLUDE), *fTypes, &fVertexInclude);
232 fIRGenerator->fSymbolTable->markAllFunctionsBuiltin();
233 fVertexSymbolTable = fIRGenerator->fSymbolTable;
Kevin Lubickf2030782018-06-19 12:04:18 +0000234 fIRGenerator->finish();
Ethan Nicholas3c6ae622018-04-24 13:06:09 -0400235
236 fIRGenerator->start(&settings, nullptr);
237 fIRGenerator->convertProgram(Program::kVertex_Kind, SKSL_FRAG_INCLUDE,
238 strlen(SKSL_FRAG_INCLUDE), *fTypes, &fFragmentInclude);
239 fIRGenerator->fSymbolTable->markAllFunctionsBuiltin();
240 fFragmentSymbolTable = fIRGenerator->fSymbolTable;
Kevin Lubickf2030782018-06-19 12:04:18 +0000241 fIRGenerator->finish();
Ethan Nicholas3c6ae622018-04-24 13:06:09 -0400242
243 fIRGenerator->start(&settings, nullptr);
244 fIRGenerator->convertProgram(Program::kGeometry_Kind, SKSL_GEOM_INCLUDE,
245 strlen(SKSL_GEOM_INCLUDE), *fTypes, &fGeometryInclude);
246 fIRGenerator->fSymbolTable->markAllFunctionsBuiltin();
247 fGeometrySymbolTable = fIRGenerator->fSymbolTable;
Kevin Lubickf2030782018-06-19 12:04:18 +0000248 fIRGenerator->finish();
ethannicholasb3058bd2016-07-01 08:22:01 -0700249}
250
251Compiler::~Compiler() {
252 delete fIRGenerator;
253}
254
ethannicholas22f939e2016-10-13 13:25:34 -0700255// add the definition created by assigning to the lvalue to the definition set
Ethan Nicholas86a43402017-01-19 13:32:00 -0500256void Compiler::addDefinition(const Expression* lvalue, std::unique_ptr<Expression>* expr,
257 DefinitionMap* definitions) {
ethannicholas22f939e2016-10-13 13:25:34 -0700258 switch (lvalue->fKind) {
259 case Expression::kVariableReference_Kind: {
260 const Variable& var = ((VariableReference*) lvalue)->fVariable;
261 if (var.fStorage == Variable::kLocal_Storage) {
262 (*definitions)[&var] = expr;
263 }
264 break;
265 }
266 case Expression::kSwizzle_Kind:
267 // We consider the variable written to as long as at least some of its components have
268 // been written to. This will lead to some false negatives (we won't catch it if you
269 // write to foo.x and then read foo.y), but being stricter could lead to false positives
Mike Klein6ad99092016-10-26 10:35:22 -0400270 // (we write to foo.x, and then pass foo to a function which happens to only read foo.x,
271 // 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 -0700272 // more complicated whole-program analysis. This is probably good enough.
Mike Klein6ad99092016-10-26 10:35:22 -0400273 this->addDefinition(((Swizzle*) lvalue)->fBase.get(),
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400274 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
ethannicholas22f939e2016-10-13 13:25:34 -0700275 definitions);
276 break;
277 case Expression::kIndex_Kind:
278 // see comments in Swizzle
Mike Klein6ad99092016-10-26 10:35:22 -0400279 this->addDefinition(((IndexExpression*) lvalue)->fBase.get(),
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400280 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
ethannicholas22f939e2016-10-13 13:25:34 -0700281 definitions);
282 break;
283 case Expression::kFieldAccess_Kind:
284 // see comments in Swizzle
Mike Klein6ad99092016-10-26 10:35:22 -0400285 this->addDefinition(((FieldAccess*) lvalue)->fBase.get(),
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400286 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
ethannicholas22f939e2016-10-13 13:25:34 -0700287 definitions);
288 break;
Ethan Nicholasa583b812018-01-18 13:32:11 -0500289 case Expression::kTernary_Kind:
290 // To simplify analysis, we just pretend that we write to both sides of the ternary.
291 // This allows for false positives (meaning we fail to detect that a variable might not
292 // have been assigned), but is preferable to false negatives.
293 this->addDefinition(((TernaryExpression*) lvalue)->fIfTrue.get(),
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400294 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
Ethan Nicholasa583b812018-01-18 13:32:11 -0500295 definitions);
296 this->addDefinition(((TernaryExpression*) lvalue)->fIfFalse.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 break;
ethannicholas22f939e2016-10-13 13:25:34 -0700300 default:
301 // not an lvalue, can't happen
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400302 SkASSERT(false);
ethannicholas22f939e2016-10-13 13:25:34 -0700303 }
304}
305
306// add local variables defined by this node to the set
Mike Klein6ad99092016-10-26 10:35:22 -0400307void Compiler::addDefinitions(const BasicBlock::Node& node,
Ethan Nicholas86a43402017-01-19 13:32:00 -0500308 DefinitionMap* definitions) {
ethannicholas22f939e2016-10-13 13:25:34 -0700309 switch (node.fKind) {
310 case BasicBlock::Node::kExpression_Kind: {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400311 SkASSERT(node.expression());
Ethan Nicholascb670962017-04-20 19:31:52 -0400312 const Expression* expr = (Expression*) node.expression()->get();
Ethan Nicholas86a43402017-01-19 13:32:00 -0500313 switch (expr->fKind) {
314 case Expression::kBinary_Kind: {
315 BinaryExpression* b = (BinaryExpression*) expr;
316 if (b->fOperator == Token::EQ) {
317 this->addDefinition(b->fLeft.get(), &b->fRight, definitions);
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700318 } else if (Compiler::IsAssignment(b->fOperator)) {
Ethan Nicholas86a43402017-01-19 13:32:00 -0500319 this->addDefinition(
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400320 b->fLeft.get(),
321 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
322 definitions);
Ethan Nicholas86a43402017-01-19 13:32:00 -0500323
324 }
325 break;
ethannicholas22f939e2016-10-13 13:25:34 -0700326 }
Ethan Nicholasc6a19f12018-03-29 16:46:56 -0400327 case Expression::kFunctionCall_Kind: {
328 const FunctionCall& c = (const FunctionCall&) *expr;
329 for (size_t i = 0; i < c.fFunction.fParameters.size(); ++i) {
330 if (c.fFunction.fParameters[i]->fModifiers.fFlags & Modifiers::kOut_Flag) {
331 this->addDefinition(
332 c.fArguments[i].get(),
333 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
334 definitions);
335 }
336 }
337 break;
338 }
Ethan Nicholas86a43402017-01-19 13:32:00 -0500339 case Expression::kPrefix_Kind: {
340 const PrefixExpression* p = (PrefixExpression*) expr;
341 if (p->fOperator == Token::MINUSMINUS || p->fOperator == Token::PLUSPLUS) {
342 this->addDefinition(
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400343 p->fOperand.get(),
344 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
345 definitions);
Ethan Nicholas86a43402017-01-19 13:32:00 -0500346 }
347 break;
348 }
349 case Expression::kPostfix_Kind: {
350 const PostfixExpression* p = (PostfixExpression*) expr;
351 if (p->fOperator == Token::MINUSMINUS || p->fOperator == Token::PLUSPLUS) {
352 this->addDefinition(
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400353 p->fOperand.get(),
354 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
355 definitions);
Ethan Nicholas86a43402017-01-19 13:32:00 -0500356 }
357 break;
358 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400359 case Expression::kVariableReference_Kind: {
360 const VariableReference* v = (VariableReference*) expr;
361 if (v->fRefKind != VariableReference::kRead_RefKind) {
362 this->addDefinition(
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400363 v,
364 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
365 definitions);
Ethan Nicholascb670962017-04-20 19:31:52 -0400366 }
367 }
Ethan Nicholas86a43402017-01-19 13:32:00 -0500368 default:
369 break;
ethannicholas22f939e2016-10-13 13:25:34 -0700370 }
371 break;
372 }
373 case BasicBlock::Node::kStatement_Kind: {
Ethan Nicholascb670962017-04-20 19:31:52 -0400374 const Statement* stmt = (Statement*) node.statement()->get();
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000375 if (stmt->fKind == Statement::kVarDeclaration_Kind) {
376 VarDeclaration& vd = (VarDeclaration&) *stmt;
377 if (vd.fValue) {
378 (*definitions)[vd.fVar] = &vd.fValue;
ethannicholas22f939e2016-10-13 13:25:34 -0700379 }
380 }
381 break;
382 }
383 }
384}
385
386void Compiler::scanCFG(CFG* cfg, BlockId blockId, std::set<BlockId>* workList) {
387 BasicBlock& block = cfg->fBlocks[blockId];
388
389 // compute definitions after this block
Ethan Nicholas86a43402017-01-19 13:32:00 -0500390 DefinitionMap after = block.fBefore;
ethannicholas22f939e2016-10-13 13:25:34 -0700391 for (const BasicBlock::Node& n : block.fNodes) {
392 this->addDefinitions(n, &after);
393 }
394
395 // propagate definitions to exits
396 for (BlockId exitId : block.fExits) {
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400397 if (exitId == blockId) {
398 continue;
399 }
ethannicholas22f939e2016-10-13 13:25:34 -0700400 BasicBlock& exit = cfg->fBlocks[exitId];
401 for (const auto& pair : after) {
Ethan Nicholas86a43402017-01-19 13:32:00 -0500402 std::unique_ptr<Expression>* e1 = pair.second;
403 auto found = exit.fBefore.find(pair.first);
404 if (found == exit.fBefore.end()) {
405 // exit has no definition for it, just copy it
406 workList->insert(exitId);
ethannicholas22f939e2016-10-13 13:25:34 -0700407 exit.fBefore[pair.first] = e1;
408 } else {
Ethan Nicholas86a43402017-01-19 13:32:00 -0500409 // exit has a (possibly different) value already defined
410 std::unique_ptr<Expression>* e2 = exit.fBefore[pair.first];
ethannicholas22f939e2016-10-13 13:25:34 -0700411 if (e1 != e2) {
412 // definition has changed, merge and add exit block to worklist
413 workList->insert(exitId);
Ethan Nicholasaf197692017-02-27 13:26:45 -0500414 if (e1 && e2) {
415 exit.fBefore[pair.first] =
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400416 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression;
Ethan Nicholasaf197692017-02-27 13:26:45 -0500417 } else {
418 exit.fBefore[pair.first] = nullptr;
419 }
ethannicholas22f939e2016-10-13 13:25:34 -0700420 }
421 }
422 }
423 }
424}
425
426// returns a map which maps all local variables in the function to null, indicating that their value
427// is initially unknown
Ethan Nicholas86a43402017-01-19 13:32:00 -0500428static DefinitionMap compute_start_state(const CFG& cfg) {
429 DefinitionMap result;
Mike Klein6ad99092016-10-26 10:35:22 -0400430 for (const auto& block : cfg.fBlocks) {
431 for (const auto& node : block.fNodes) {
ethannicholas22f939e2016-10-13 13:25:34 -0700432 if (node.fKind == BasicBlock::Node::kStatement_Kind) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400433 SkASSERT(node.statement());
Ethan Nicholascb670962017-04-20 19:31:52 -0400434 const Statement* s = node.statement()->get();
ethannicholas22f939e2016-10-13 13:25:34 -0700435 if (s->fKind == Statement::kVarDeclarations_Kind) {
436 const VarDeclarationsStatement* vd = (const VarDeclarationsStatement*) s;
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000437 for (const auto& decl : vd->fDeclaration->fVars) {
438 if (decl->fKind == Statement::kVarDeclaration_Kind) {
439 result[((VarDeclaration&) *decl).fVar] = nullptr;
440 }
Mike Klein6ad99092016-10-26 10:35:22 -0400441 }
ethannicholas22f939e2016-10-13 13:25:34 -0700442 }
443 }
444 }
445 }
446 return result;
447}
448
Ethan Nicholascb670962017-04-20 19:31:52 -0400449/**
450 * Returns true if assigning to this lvalue has no effect.
451 */
452static bool is_dead(const Expression& lvalue) {
453 switch (lvalue.fKind) {
454 case Expression::kVariableReference_Kind:
455 return ((VariableReference&) lvalue).fVariable.dead();
456 case Expression::kSwizzle_Kind:
457 return is_dead(*((Swizzle&) lvalue).fBase);
458 case Expression::kFieldAccess_Kind:
459 return is_dead(*((FieldAccess&) lvalue).fBase);
460 case Expression::kIndex_Kind: {
461 const IndexExpression& idx = (IndexExpression&) lvalue;
462 return is_dead(*idx.fBase) && !idx.fIndex->hasSideEffects();
463 }
Ethan Nicholasa583b812018-01-18 13:32:11 -0500464 case Expression::kTernary_Kind: {
465 const TernaryExpression& t = (TernaryExpression&) lvalue;
466 return !t.fTest->hasSideEffects() && is_dead(*t.fIfTrue) && is_dead(*t.fIfFalse);
467 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400468 default:
469 ABORT("invalid lvalue: %s\n", lvalue.description().c_str());
470 }
471}
ethannicholas22f939e2016-10-13 13:25:34 -0700472
Ethan Nicholascb670962017-04-20 19:31:52 -0400473/**
474 * Returns true if this is an assignment which can be collapsed down to just the right hand side due
475 * to a dead target and lack of side effects on the left hand side.
476 */
477static bool dead_assignment(const BinaryExpression& b) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700478 if (!Compiler::IsAssignment(b.fOperator)) {
Ethan Nicholascb670962017-04-20 19:31:52 -0400479 return false;
480 }
481 return is_dead(*b.fLeft);
482}
483
484void Compiler::computeDataFlow(CFG* cfg) {
485 cfg->fBlocks[cfg->fStart].fBefore = compute_start_state(*cfg);
ethannicholas22f939e2016-10-13 13:25:34 -0700486 std::set<BlockId> workList;
Ethan Nicholascb670962017-04-20 19:31:52 -0400487 for (BlockId i = 0; i < cfg->fBlocks.size(); i++) {
ethannicholas22f939e2016-10-13 13:25:34 -0700488 workList.insert(i);
489 }
490 while (workList.size()) {
491 BlockId next = *workList.begin();
492 workList.erase(workList.begin());
Ethan Nicholascb670962017-04-20 19:31:52 -0400493 this->scanCFG(cfg, next, &workList);
ethannicholas22f939e2016-10-13 13:25:34 -0700494 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400495}
496
497/**
498 * Attempts to replace the expression pointed to by iter with a new one (in both the CFG and the
499 * IR). If the expression can be cleanly removed, returns true and updates the iterator to point to
500 * the newly-inserted element. Otherwise updates only the IR and returns false (and the CFG will
501 * need to be regenerated).
502 */
503bool try_replace_expression(BasicBlock* b,
504 std::vector<BasicBlock::Node>::iterator* iter,
505 std::unique_ptr<Expression>* newExpression) {
506 std::unique_ptr<Expression>* target = (*iter)->expression();
507 if (!b->tryRemoveExpression(iter)) {
508 *target = std::move(*newExpression);
509 return false;
510 }
511 *target = std::move(*newExpression);
512 return b->tryInsertExpression(iter, target);
513}
514
515/**
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400516 * Returns true if the expression is a constant numeric literal with the specified value, or a
517 * constant vector with all elements equal to the specified value.
Ethan Nicholascb670962017-04-20 19:31:52 -0400518 */
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400519bool is_constant(const Expression& expr, double value) {
Ethan Nicholascb670962017-04-20 19:31:52 -0400520 switch (expr.fKind) {
521 case Expression::kIntLiteral_Kind:
522 return ((IntLiteral&) expr).fValue == value;
523 case Expression::kFloatLiteral_Kind:
524 return ((FloatLiteral&) expr).fValue == value;
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400525 case Expression::kConstructor_Kind: {
526 Constructor& c = (Constructor&) expr;
527 if (c.fType.kind() == Type::kVector_Kind && c.isConstant()) {
528 for (int i = 0; i < c.fType.columns(); ++i) {
529 if (!is_constant(c.getVecComponent(i), value)) {
530 return false;
531 }
532 }
533 return true;
534 }
535 return false;
536 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400537 default:
538 return false;
539 }
540}
541
542/**
543 * Collapses the binary expression pointed to by iter down to just the right side (in both the IR
544 * and CFG structures).
545 */
546void delete_left(BasicBlock* b,
547 std::vector<BasicBlock::Node>::iterator* iter,
548 bool* outUpdated,
549 bool* outNeedsRescan) {
550 *outUpdated = true;
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400551 std::unique_ptr<Expression>* target = (*iter)->expression();
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400552 SkASSERT((*target)->fKind == Expression::kBinary_Kind);
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400553 BinaryExpression& bin = (BinaryExpression&) **target;
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400554 SkASSERT(!bin.fLeft->hasSideEffects());
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400555 bool result;
556 if (bin.fOperator == Token::EQ) {
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400557 result = b->tryRemoveLValueBefore(iter, bin.fLeft.get());
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400558 } else {
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400559 result = b->tryRemoveExpressionBefore(iter, bin.fLeft.get());
Ethan Nicholascb670962017-04-20 19:31:52 -0400560 }
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400561 *target = std::move(bin.fRight);
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400562 if (!result) {
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400563 *outNeedsRescan = true;
564 return;
565 }
566 if (*iter == b->fNodes.begin()) {
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400567 *outNeedsRescan = true;
568 return;
569 }
570 --(*iter);
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400571 if ((*iter)->fKind != BasicBlock::Node::kExpression_Kind ||
572 (*iter)->expression() != &bin.fRight) {
573 *outNeedsRescan = true;
574 return;
575 }
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400576 *iter = b->fNodes.erase(*iter);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400577 SkASSERT((*iter)->expression() == target);
Ethan Nicholascb670962017-04-20 19:31:52 -0400578}
579
580/**
581 * Collapses the binary expression pointed to by iter down to just the left side (in both the IR and
582 * CFG structures).
583 */
584void delete_right(BasicBlock* b,
585 std::vector<BasicBlock::Node>::iterator* iter,
586 bool* outUpdated,
587 bool* outNeedsRescan) {
588 *outUpdated = true;
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400589 std::unique_ptr<Expression>* target = (*iter)->expression();
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400590 SkASSERT((*target)->fKind == Expression::kBinary_Kind);
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400591 BinaryExpression& bin = (BinaryExpression&) **target;
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400592 SkASSERT(!bin.fRight->hasSideEffects());
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400593 if (!b->tryRemoveExpressionBefore(iter, bin.fRight.get())) {
594 *target = std::move(bin.fLeft);
Ethan Nicholascb670962017-04-20 19:31:52 -0400595 *outNeedsRescan = true;
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400596 return;
Ethan Nicholascb670962017-04-20 19:31:52 -0400597 }
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400598 *target = std::move(bin.fLeft);
599 if (*iter == b->fNodes.begin()) {
600 *outNeedsRescan = true;
601 return;
602 }
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400603 --(*iter);
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400604 if (((*iter)->fKind != BasicBlock::Node::kExpression_Kind ||
605 (*iter)->expression() != &bin.fLeft)) {
606 *outNeedsRescan = true;
607 return;
608 }
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400609 *iter = b->fNodes.erase(*iter);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400610 SkASSERT((*iter)->expression() == target);
Ethan Nicholascb670962017-04-20 19:31:52 -0400611}
612
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400613/**
614 * Constructs the specified type using a single argument.
615 */
616static std::unique_ptr<Expression> construct(const Type& type, std::unique_ptr<Expression> v) {
617 std::vector<std::unique_ptr<Expression>> args;
618 args.push_back(std::move(v));
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700619 auto result = std::unique_ptr<Expression>(new Constructor(-1, type, std::move(args)));
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400620 return result;
621}
622
623/**
624 * Used in the implementations of vectorize_left and vectorize_right. Given a vector type and an
625 * expression x, deletes the expression pointed to by iter and replaces it with <type>(x).
626 */
627static void vectorize(BasicBlock* b,
628 std::vector<BasicBlock::Node>::iterator* iter,
629 const Type& type,
630 std::unique_ptr<Expression>* otherExpression,
631 bool* outUpdated,
632 bool* outNeedsRescan) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400633 SkASSERT((*(*iter)->expression())->fKind == Expression::kBinary_Kind);
634 SkASSERT(type.kind() == Type::kVector_Kind);
635 SkASSERT((*otherExpression)->fType.kind() == Type::kScalar_Kind);
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400636 *outUpdated = true;
637 std::unique_ptr<Expression>* target = (*iter)->expression();
638 if (!b->tryRemoveExpression(iter)) {
639 *target = construct(type, std::move(*otherExpression));
640 *outNeedsRescan = true;
641 } else {
642 *target = construct(type, std::move(*otherExpression));
643 if (!b->tryInsertExpression(iter, target)) {
644 *outNeedsRescan = true;
645 }
646 }
647}
648
649/**
650 * Given a binary expression of the form x <op> vec<n>(y), deletes the right side and vectorizes the
651 * left to yield vec<n>(x).
652 */
653static void vectorize_left(BasicBlock* b,
654 std::vector<BasicBlock::Node>::iterator* iter,
655 bool* outUpdated,
656 bool* outNeedsRescan) {
657 BinaryExpression& bin = (BinaryExpression&) **(*iter)->expression();
658 vectorize(b, iter, bin.fRight->fType, &bin.fLeft, outUpdated, outNeedsRescan);
659}
660
661/**
662 * Given a binary expression of the form vec<n>(x) <op> y, deletes the left side and vectorizes the
663 * right to yield vec<n>(y).
664 */
665static void vectorize_right(BasicBlock* b,
666 std::vector<BasicBlock::Node>::iterator* iter,
667 bool* outUpdated,
668 bool* outNeedsRescan) {
669 BinaryExpression& bin = (BinaryExpression&) **(*iter)->expression();
670 vectorize(b, iter, bin.fLeft->fType, &bin.fRight, outUpdated, outNeedsRescan);
671}
672
673// Mark that an expression which we were writing to is no longer being written to
674void clear_write(const Expression& expr) {
675 switch (expr.fKind) {
676 case Expression::kVariableReference_Kind: {
677 ((VariableReference&) expr).setRefKind(VariableReference::kRead_RefKind);
678 break;
679 }
680 case Expression::kFieldAccess_Kind:
681 clear_write(*((FieldAccess&) expr).fBase);
682 break;
683 case Expression::kSwizzle_Kind:
684 clear_write(*((Swizzle&) expr).fBase);
685 break;
686 case Expression::kIndex_Kind:
687 clear_write(*((IndexExpression&) expr).fBase);
688 break;
689 default:
690 ABORT("shouldn't be writing to this kind of expression\n");
691 break;
692 }
693}
694
Ethan Nicholascb670962017-04-20 19:31:52 -0400695void Compiler::simplifyExpression(DefinitionMap& definitions,
696 BasicBlock& b,
697 std::vector<BasicBlock::Node>::iterator* iter,
698 std::unordered_set<const Variable*>* undefinedVariables,
699 bool* outUpdated,
700 bool* outNeedsRescan) {
701 Expression* expr = (*iter)->expression()->get();
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400702 SkASSERT(expr);
Ethan Nicholascb670962017-04-20 19:31:52 -0400703 if ((*iter)->fConstantPropagation) {
704 std::unique_ptr<Expression> optimized = expr->constantPropagate(*fIRGenerator, definitions);
705 if (optimized) {
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400706 *outUpdated = true;
Ethan Nicholascb670962017-04-20 19:31:52 -0400707 if (!try_replace_expression(&b, iter, &optimized)) {
708 *outNeedsRescan = true;
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400709 return;
Ethan Nicholascb670962017-04-20 19:31:52 -0400710 }
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400711 SkASSERT((*iter)->fKind == BasicBlock::Node::kExpression_Kind);
Ethan Nicholascb670962017-04-20 19:31:52 -0400712 expr = (*iter)->expression()->get();
Ethan Nicholascb670962017-04-20 19:31:52 -0400713 }
714 }
715 switch (expr->fKind) {
716 case Expression::kVariableReference_Kind: {
Ethan Nicholas8f7e28f2018-03-26 14:24:27 -0400717 const VariableReference& ref = (VariableReference&) *expr;
718 const Variable& var = ref.fVariable;
719 if (ref.refKind() != VariableReference::kWrite_RefKind &&
720 ref.refKind() != VariableReference::kPointer_RefKind &&
721 var.fStorage == Variable::kLocal_Storage && !definitions[&var] &&
Ethan Nicholascb670962017-04-20 19:31:52 -0400722 (*undefinedVariables).find(&var) == (*undefinedVariables).end()) {
723 (*undefinedVariables).insert(&var);
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000724 this->error(expr->fOffset,
725 "'" + var.fName + "' has not been assigned");
Ethan Nicholascb670962017-04-20 19:31:52 -0400726 }
727 break;
728 }
729 case Expression::kTernary_Kind: {
730 TernaryExpression* t = (TernaryExpression*) expr;
731 if (t->fTest->fKind == Expression::kBoolLiteral_Kind) {
732 // ternary has a constant test, replace it with either the true or
733 // false branch
734 if (((BoolLiteral&) *t->fTest).fValue) {
735 (*iter)->setExpression(std::move(t->fIfTrue));
736 } else {
737 (*iter)->setExpression(std::move(t->fIfFalse));
738 }
739 *outUpdated = true;
740 *outNeedsRescan = true;
741 }
742 break;
743 }
744 case Expression::kBinary_Kind: {
Ethan Nicholascb670962017-04-20 19:31:52 -0400745 BinaryExpression* bin = (BinaryExpression*) expr;
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400746 if (dead_assignment(*bin)) {
747 delete_left(&b, iter, outUpdated, outNeedsRescan);
748 break;
749 }
750 // collapse useless expressions like x * 1 or x + 0
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400751 if (((bin->fLeft->fType.kind() != Type::kScalar_Kind) &&
752 (bin->fLeft->fType.kind() != Type::kVector_Kind)) ||
753 ((bin->fRight->fType.kind() != Type::kScalar_Kind) &&
754 (bin->fRight->fType.kind() != Type::kVector_Kind))) {
755 break;
756 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400757 switch (bin->fOperator) {
758 case Token::STAR:
759 if (is_constant(*bin->fLeft, 1)) {
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400760 if (bin->fLeft->fType.kind() == Type::kVector_Kind &&
761 bin->fRight->fType.kind() == Type::kScalar_Kind) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400762 // float4(1) * x -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400763 vectorize_right(&b, iter, outUpdated, outNeedsRescan);
764 } else {
765 // 1 * x -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400766 // 1 * float4(x) -> float4(x)
767 // float4(1) * float4(x) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400768 delete_left(&b, iter, outUpdated, outNeedsRescan);
769 }
770 }
771 else if (is_constant(*bin->fLeft, 0)) {
772 if (bin->fLeft->fType.kind() == Type::kScalar_Kind &&
Ethan Nicholas08dae922018-01-23 10:31:56 -0500773 bin->fRight->fType.kind() == Type::kVector_Kind &&
774 !bin->fRight->hasSideEffects()) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400775 // 0 * float4(x) -> float4(0)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400776 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
777 } else {
778 // 0 * x -> 0
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400779 // float4(0) * x -> float4(0)
780 // float4(0) * float4(x) -> float4(0)
Ethan Nicholas51493ee2017-12-11 12:34:33 -0500781 if (!bin->fRight->hasSideEffects()) {
782 delete_right(&b, iter, outUpdated, outNeedsRescan);
783 }
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400784 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400785 }
786 else if (is_constant(*bin->fRight, 1)) {
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400787 if (bin->fLeft->fType.kind() == Type::kScalar_Kind &&
788 bin->fRight->fType.kind() == Type::kVector_Kind) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400789 // x * float4(1) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400790 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
791 } else {
792 // x * 1 -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400793 // float4(x) * 1 -> float4(x)
794 // float4(x) * float4(1) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400795 delete_right(&b, iter, outUpdated, outNeedsRescan);
796 }
797 }
798 else if (is_constant(*bin->fRight, 0)) {
799 if (bin->fLeft->fType.kind() == Type::kVector_Kind &&
Ethan Nicholas08dae922018-01-23 10:31:56 -0500800 bin->fRight->fType.kind() == Type::kScalar_Kind &&
801 !bin->fLeft->hasSideEffects()) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400802 // float4(x) * 0 -> float4(0)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400803 vectorize_right(&b, iter, outUpdated, outNeedsRescan);
804 } else {
805 // x * 0 -> 0
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400806 // x * float4(0) -> float4(0)
807 // float4(x) * float4(0) -> float4(0)
Ethan Nicholas51493ee2017-12-11 12:34:33 -0500808 if (!bin->fLeft->hasSideEffects()) {
809 delete_left(&b, iter, outUpdated, outNeedsRescan);
810 }
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400811 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400812 }
813 break;
Ethan Nicholas56e42712017-04-21 10:23:37 -0400814 case Token::PLUS:
Ethan Nicholascb670962017-04-20 19:31:52 -0400815 if (is_constant(*bin->fLeft, 0)) {
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400816 if (bin->fLeft->fType.kind() == Type::kVector_Kind &&
817 bin->fRight->fType.kind() == Type::kScalar_Kind) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400818 // float4(0) + x -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400819 vectorize_right(&b, iter, outUpdated, outNeedsRescan);
820 } else {
821 // 0 + x -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400822 // 0 + float4(x) -> float4(x)
823 // float4(0) + float4(x) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400824 delete_left(&b, iter, outUpdated, outNeedsRescan);
825 }
826 } else if (is_constant(*bin->fRight, 0)) {
827 if (bin->fLeft->fType.kind() == Type::kScalar_Kind &&
828 bin->fRight->fType.kind() == Type::kVector_Kind) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400829 // x + float4(0) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400830 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
831 } else {
832 // x + 0 -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400833 // float4(x) + 0 -> float4(x)
834 // float4(x) + float4(0) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400835 delete_right(&b, iter, outUpdated, outNeedsRescan);
836 }
Ethan Nicholas56e42712017-04-21 10:23:37 -0400837 }
838 break;
839 case Token::MINUS:
840 if (is_constant(*bin->fRight, 0)) {
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400841 if (bin->fLeft->fType.kind() == Type::kScalar_Kind &&
842 bin->fRight->fType.kind() == Type::kVector_Kind) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400843 // x - float4(0) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400844 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
845 } else {
846 // x - 0 -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400847 // float4(x) - 0 -> float4(x)
848 // float4(x) - float4(0) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400849 delete_right(&b, iter, outUpdated, outNeedsRescan);
850 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400851 }
852 break;
853 case Token::SLASH:
854 if (is_constant(*bin->fRight, 1)) {
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400855 if (bin->fLeft->fType.kind() == Type::kScalar_Kind &&
856 bin->fRight->fType.kind() == Type::kVector_Kind) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400857 // x / float4(1) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400858 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
859 } else {
860 // x / 1 -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400861 // float4(x) / 1 -> float4(x)
862 // float4(x) / float4(1) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400863 delete_right(&b, iter, outUpdated, outNeedsRescan);
864 }
865 } else if (is_constant(*bin->fLeft, 0)) {
866 if (bin->fLeft->fType.kind() == Type::kScalar_Kind &&
Ethan Nicholas08dae922018-01-23 10:31:56 -0500867 bin->fRight->fType.kind() == Type::kVector_Kind &&
868 !bin->fRight->hasSideEffects()) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400869 // 0 / float4(x) -> float4(0)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400870 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
871 } else {
872 // 0 / x -> 0
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400873 // float4(0) / x -> float4(0)
874 // float4(0) / float4(x) -> float4(0)
Ethan Nicholas51493ee2017-12-11 12:34:33 -0500875 if (!bin->fRight->hasSideEffects()) {
876 delete_right(&b, iter, outUpdated, outNeedsRescan);
877 }
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400878 }
879 }
880 break;
881 case Token::PLUSEQ:
882 if (is_constant(*bin->fRight, 0)) {
883 clear_write(*bin->fLeft);
884 delete_right(&b, iter, outUpdated, outNeedsRescan);
885 }
886 break;
887 case Token::MINUSEQ:
888 if (is_constant(*bin->fRight, 0)) {
889 clear_write(*bin->fLeft);
890 delete_right(&b, iter, outUpdated, outNeedsRescan);
891 }
892 break;
893 case Token::STAREQ:
894 if (is_constant(*bin->fRight, 1)) {
895 clear_write(*bin->fLeft);
896 delete_right(&b, iter, outUpdated, outNeedsRescan);
897 }
898 break;
899 case Token::SLASHEQ:
900 if (is_constant(*bin->fRight, 1)) {
901 clear_write(*bin->fLeft);
Ethan Nicholascb670962017-04-20 19:31:52 -0400902 delete_right(&b, iter, outUpdated, outNeedsRescan);
903 }
904 break;
905 default:
906 break;
907 }
908 }
909 default:
910 break;
911 }
912}
913
Ethan Nicholas5ac13c22017-05-10 15:06:17 -0400914// returns true if this statement could potentially execute a break at the current level (we ignore
915// nested loops and switches, since any breaks inside of them will merely break the loop / switch)
916static bool contains_break(Statement& s) {
917 switch (s.fKind) {
918 case Statement::kBlock_Kind:
919 for (const auto& sub : ((Block&) s).fStatements) {
920 if (contains_break(*sub)) {
921 return true;
922 }
923 }
924 return false;
925 case Statement::kBreak_Kind:
926 return true;
927 case Statement::kIf_Kind: {
928 const IfStatement& i = (IfStatement&) s;
929 return contains_break(*i.fIfTrue) || (i.fIfFalse && contains_break(*i.fIfFalse));
930 }
931 default:
932 return false;
933 }
934}
935
936// Returns a block containing all of the statements that will be run if the given case matches
937// (which, owing to the statements being owned by unique_ptrs, means the switch itself will be
938// broken by this call and must then be discarded).
939// Returns null (and leaves the switch unmodified) if no such simple reduction is possible, such as
940// when break statements appear inside conditionals.
941static std::unique_ptr<Statement> block_for_case(SwitchStatement* s, SwitchCase* c) {
942 bool capturing = false;
943 std::vector<std::unique_ptr<Statement>*> statementPtrs;
944 for (const auto& current : s->fCases) {
945 if (current.get() == c) {
946 capturing = true;
947 }
948 if (capturing) {
949 for (auto& stmt : current->fStatements) {
950 if (stmt->fKind == Statement::kBreak_Kind) {
951 capturing = false;
952 break;
953 }
954 if (contains_break(*stmt)) {
955 return nullptr;
956 }
957 statementPtrs.push_back(&stmt);
958 }
959 if (!capturing) {
960 break;
961 }
962 }
963 }
964 std::vector<std::unique_ptr<Statement>> statements;
965 for (const auto& s : statementPtrs) {
966 statements.push_back(std::move(*s));
967 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700968 return std::unique_ptr<Statement>(new Block(-1, std::move(statements), s->fSymbols));
Ethan Nicholas5ac13c22017-05-10 15:06:17 -0400969}
970
Ethan Nicholascb670962017-04-20 19:31:52 -0400971void Compiler::simplifyStatement(DefinitionMap& definitions,
Ethan Nicholas5ac13c22017-05-10 15:06:17 -0400972 BasicBlock& b,
973 std::vector<BasicBlock::Node>::iterator* iter,
974 std::unordered_set<const Variable*>* undefinedVariables,
975 bool* outUpdated,
976 bool* outNeedsRescan) {
Ethan Nicholascb670962017-04-20 19:31:52 -0400977 Statement* stmt = (*iter)->statement()->get();
978 switch (stmt->fKind) {
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000979 case Statement::kVarDeclaration_Kind: {
980 const auto& varDecl = (VarDeclaration&) *stmt;
981 if (varDecl.fVar->dead() &&
982 (!varDecl.fValue ||
983 !varDecl.fValue->hasSideEffects())) {
984 if (varDecl.fValue) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400985 SkASSERT((*iter)->statement()->get() == stmt);
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000986 if (!b.tryRemoveExpressionBefore(iter, varDecl.fValue.get())) {
987 *outNeedsRescan = true;
Ethan Nicholascb670962017-04-20 19:31:52 -0400988 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400989 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400990 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000991 *outUpdated = true;
Ethan Nicholascb670962017-04-20 19:31:52 -0400992 }
993 break;
994 }
995 case Statement::kIf_Kind: {
996 IfStatement& i = (IfStatement&) *stmt;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -0400997 if (i.fTest->fKind == Expression::kBoolLiteral_Kind) {
998 // constant if, collapse down to a single branch
999 if (((BoolLiteral&) *i.fTest).fValue) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001000 SkASSERT(i.fIfTrue);
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001001 (*iter)->setStatement(std::move(i.fIfTrue));
1002 } else {
1003 if (i.fIfFalse) {
1004 (*iter)->setStatement(std::move(i.fIfFalse));
1005 } else {
1006 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
1007 }
1008 }
1009 *outUpdated = true;
1010 *outNeedsRescan = true;
1011 break;
1012 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001013 if (i.fIfFalse && i.fIfFalse->isEmpty()) {
1014 // else block doesn't do anything, remove it
1015 i.fIfFalse.reset();
1016 *outUpdated = true;
1017 *outNeedsRescan = true;
1018 }
1019 if (!i.fIfFalse && i.fIfTrue->isEmpty()) {
1020 // if block doesn't do anything, no else block
1021 if (i.fTest->hasSideEffects()) {
1022 // test has side effects, keep it
1023 (*iter)->setStatement(std::unique_ptr<Statement>(
1024 new ExpressionStatement(std::move(i.fTest))));
1025 } else {
1026 // no if, no else, no test side effects, kill the whole if
1027 // statement
1028 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
1029 }
1030 *outUpdated = true;
1031 *outNeedsRescan = true;
1032 }
1033 break;
1034 }
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001035 case Statement::kSwitch_Kind: {
1036 SwitchStatement& s = (SwitchStatement&) *stmt;
1037 if (s.fValue->isConstant()) {
1038 // switch is constant, replace it with the case that matches
1039 bool found = false;
1040 SwitchCase* defaultCase = nullptr;
1041 for (const auto& c : s.fCases) {
1042 if (!c->fValue) {
1043 defaultCase = c.get();
1044 continue;
1045 }
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001046 SkASSERT(c->fValue->fKind == s.fValue->fKind);
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001047 found = c->fValue->compareConstant(*fContext, *s.fValue);
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001048 if (found) {
1049 std::unique_ptr<Statement> newBlock = block_for_case(&s, c.get());
1050 if (newBlock) {
1051 (*iter)->setStatement(std::move(newBlock));
1052 break;
1053 } else {
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -04001054 if (s.fIsStatic && !(fFlags & kPermitInvalidStaticTests_Flag)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001055 this->error(s.fOffset,
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001056 "static switch contains non-static conditional break");
1057 s.fIsStatic = false;
1058 }
1059 return; // can't simplify
1060 }
1061 }
1062 }
1063 if (!found) {
1064 // no matching case. use default if it exists, or kill the whole thing
1065 if (defaultCase) {
1066 std::unique_ptr<Statement> newBlock = block_for_case(&s, defaultCase);
1067 if (newBlock) {
1068 (*iter)->setStatement(std::move(newBlock));
1069 } else {
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -04001070 if (s.fIsStatic && !(fFlags & kPermitInvalidStaticTests_Flag)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001071 this->error(s.fOffset,
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001072 "static switch contains non-static conditional break");
1073 s.fIsStatic = false;
1074 }
1075 return; // can't simplify
1076 }
1077 } else {
1078 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
1079 }
1080 }
1081 *outUpdated = true;
1082 *outNeedsRescan = true;
1083 }
1084 break;
1085 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001086 case Statement::kExpression_Kind: {
1087 ExpressionStatement& e = (ExpressionStatement&) *stmt;
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001088 SkASSERT((*iter)->statement()->get() == &e);
Ethan Nicholascb670962017-04-20 19:31:52 -04001089 if (!e.fExpression->hasSideEffects()) {
1090 // Expression statement with no side effects, kill it
1091 if (!b.tryRemoveExpressionBefore(iter, e.fExpression.get())) {
1092 *outNeedsRescan = true;
1093 }
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001094 SkASSERT((*iter)->statement()->get() == stmt);
Ethan Nicholascb670962017-04-20 19:31:52 -04001095 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
1096 *outUpdated = true;
1097 }
1098 break;
1099 }
1100 default:
1101 break;
1102 }
1103}
1104
1105void Compiler::scanCFG(FunctionDefinition& f) {
1106 CFG cfg = CFGGenerator().getCFG(f);
1107 this->computeDataFlow(&cfg);
ethannicholas22f939e2016-10-13 13:25:34 -07001108
1109 // check for unreachable code
1110 for (size_t i = 0; i < cfg.fBlocks.size(); i++) {
Mike Klein6ad99092016-10-26 10:35:22 -04001111 if (i != cfg.fStart && !cfg.fBlocks[i].fEntrances.size() &&
ethannicholas22f939e2016-10-13 13:25:34 -07001112 cfg.fBlocks[i].fNodes.size()) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001113 int offset;
Ethan Nicholas86a43402017-01-19 13:32:00 -05001114 switch (cfg.fBlocks[i].fNodes[0].fKind) {
1115 case BasicBlock::Node::kStatement_Kind:
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001116 offset = (*cfg.fBlocks[i].fNodes[0].statement())->fOffset;
Ethan Nicholas86a43402017-01-19 13:32:00 -05001117 break;
1118 case BasicBlock::Node::kExpression_Kind:
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001119 offset = (*cfg.fBlocks[i].fNodes[0].expression())->fOffset;
Ethan Nicholas86a43402017-01-19 13:32:00 -05001120 break;
1121 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001122 this->error(offset, String("unreachable"));
ethannicholas22f939e2016-10-13 13:25:34 -07001123 }
1124 }
1125 if (fErrorCount) {
1126 return;
1127 }
1128
Ethan Nicholascb670962017-04-20 19:31:52 -04001129 // check for dead code & undefined variables, perform constant propagation
1130 std::unordered_set<const Variable*> undefinedVariables;
1131 bool updated;
1132 bool needsRescan = false;
1133 do {
1134 if (needsRescan) {
1135 cfg = CFGGenerator().getCFG(f);
1136 this->computeDataFlow(&cfg);
1137 needsRescan = false;
Ethan Nicholas113628d2017-02-02 16:11:39 -05001138 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001139
1140 updated = false;
1141 for (BasicBlock& b : cfg.fBlocks) {
1142 DefinitionMap definitions = b.fBefore;
1143
1144 for (auto iter = b.fNodes.begin(); iter != b.fNodes.end() && !needsRescan; ++iter) {
1145 if (iter->fKind == BasicBlock::Node::kExpression_Kind) {
1146 this->simplifyExpression(definitions, b, &iter, &undefinedVariables, &updated,
1147 &needsRescan);
1148 } else {
1149 this->simplifyStatement(definitions, b, &iter, &undefinedVariables, &updated,
1150 &needsRescan);
1151 }
Ethan Nicholas4b330df2017-05-17 10:52:55 -04001152 if (needsRescan) {
1153 break;
1154 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001155 this->addDefinitions(*iter, &definitions);
1156 }
1157 }
1158 } while (updated);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001159 SkASSERT(!needsRescan);
ethannicholas22f939e2016-10-13 13:25:34 -07001160
Ethan Nicholas91a10532017-06-22 11:24:38 -04001161 // verify static ifs & switches, clean up dead variable decls
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001162 for (BasicBlock& b : cfg.fBlocks) {
1163 DefinitionMap definitions = b.fBefore;
1164
Ethan Nicholas91a10532017-06-22 11:24:38 -04001165 for (auto iter = b.fNodes.begin(); iter != b.fNodes.end() && !needsRescan;) {
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001166 if (iter->fKind == BasicBlock::Node::kStatement_Kind) {
1167 const Statement& s = **iter->statement();
1168 switch (s.fKind) {
1169 case Statement::kIf_Kind:
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -04001170 if (((const IfStatement&) s).fIsStatic &&
1171 !(fFlags & kPermitInvalidStaticTests_Flag)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001172 this->error(s.fOffset, "static if has non-static test");
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001173 }
Ethan Nicholas91a10532017-06-22 11:24:38 -04001174 ++iter;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001175 break;
1176 case Statement::kSwitch_Kind:
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -04001177 if (((const SwitchStatement&) s).fIsStatic &&
1178 !(fFlags & kPermitInvalidStaticTests_Flag)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001179 this->error(s.fOffset, "static switch has non-static test");
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001180 }
Ethan Nicholas91a10532017-06-22 11:24:38 -04001181 ++iter;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001182 break;
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001183 case Statement::kVarDeclarations_Kind: {
1184 VarDeclarations& decls = *((VarDeclarationsStatement&) s).fDeclaration;
1185 for (auto varIter = decls.fVars.begin(); varIter != decls.fVars.end();) {
1186 if ((*varIter)->fKind == Statement::kNop_Kind) {
1187 varIter = decls.fVars.erase(varIter);
1188 } else {
1189 ++varIter;
1190 }
1191 }
1192 if (!decls.fVars.size()) {
1193 iter = b.fNodes.erase(iter);
1194 } else {
1195 ++iter;
1196 }
1197 break;
1198 }
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001199 default:
Ethan Nicholas91a10532017-06-22 11:24:38 -04001200 ++iter;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001201 break;
1202 }
Ethan Nicholas91a10532017-06-22 11:24:38 -04001203 } else {
1204 ++iter;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001205 }
1206 }
1207 }
1208
ethannicholas22f939e2016-10-13 13:25:34 -07001209 // check for missing return
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001210 if (f.fDeclaration.fReturnType != *fContext->fVoid_Type) {
ethannicholas22f939e2016-10-13 13:25:34 -07001211 if (cfg.fBlocks[cfg.fExit].fEntrances.size()) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001212 this->error(f.fOffset, String("function can exit without returning a value"));
ethannicholas22f939e2016-10-13 13:25:34 -07001213 }
1214 }
1215}
1216
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001217std::unique_ptr<Program> Compiler::convertProgram(Program::Kind kind, String text,
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001218 const Program::Settings& settings) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001219 fErrorText = "";
1220 fErrorCount = 0;
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001221 std::vector<std::unique_ptr<ProgramElement>>* inherited;
ethannicholasd598f792016-07-25 10:08:54 -07001222 std::vector<std::unique_ptr<ProgramElement>> elements;
ethannicholasb3058bd2016-07-01 08:22:01 -07001223 switch (kind) {
1224 case Program::kVertex_Kind:
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001225 inherited = &fVertexInclude;
1226 fIRGenerator->fSymbolTable = fVertexSymbolTable;
1227 fIRGenerator->start(&settings, inherited);
ethannicholasb3058bd2016-07-01 08:22:01 -07001228 break;
1229 case Program::kFragment_Kind:
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001230 inherited = &fFragmentInclude;
1231 fIRGenerator->fSymbolTable = fFragmentSymbolTable;
1232 fIRGenerator->start(&settings, inherited);
ethannicholasb3058bd2016-07-01 08:22:01 -07001233 break;
Ethan Nicholas52cad152017-02-16 16:37:32 -05001234 case Program::kGeometry_Kind:
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001235 inherited = &fGeometryInclude;
1236 fIRGenerator->fSymbolTable = fGeometrySymbolTable;
1237 fIRGenerator->start(&settings, inherited);
Ethan Nicholas52cad152017-02-16 16:37:32 -05001238 break;
Ethan Nicholas762466e2017-06-29 10:03:38 -04001239 case Program::kFragmentProcessor_Kind:
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001240 inherited = nullptr;
1241 fIRGenerator->start(&settings, nullptr);
Robert Phillipsfe8da172018-01-24 14:52:02 +00001242 fIRGenerator->convertProgram(kind, SKSL_FP_INCLUDE, strlen(SKSL_FP_INCLUDE), *fTypes,
Ethan Nicholasf7b88202017-09-18 14:10:39 -04001243 &elements);
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001244 fIRGenerator->fSymbolTable->markAllFunctionsBuiltin();
Ethan Nicholas762466e2017-06-29 10:03:38 -04001245 break;
Kevin Lubickf2030782018-06-19 12:04:18 +00001246 case Program::kCPU_Kind:
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001247 inherited = nullptr;
1248 fIRGenerator->start(&settings, nullptr);
Kevin Lubickf2030782018-06-19 12:04:18 +00001249 fIRGenerator->convertProgram(kind, SKSL_CPU_INCLUDE, strlen(SKSL_CPU_INCLUDE),
1250 *fTypes, &elements);
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001251 fIRGenerator->fSymbolTable->markAllFunctionsBuiltin();
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001252 break;
ethannicholasb3058bd2016-07-01 08:22:01 -07001253 }
Ethan Nicholasaae47c82017-11-10 15:34:03 -05001254 for (auto& element : elements) {
1255 if (element->fKind == ProgramElement::kEnum_Kind) {
1256 ((Enum&) *element).fBuiltin = true;
1257 }
1258 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001259 std::unique_ptr<String> textPtr(new String(std::move(text)));
1260 fSource = textPtr.get();
Robert Phillipsfe8da172018-01-24 14:52:02 +00001261 fIRGenerator->convertProgram(kind, textPtr->c_str(), textPtr->size(), *fTypes, &elements);
Kevin Lubickf2030782018-06-19 12:04:18 +00001262 if (!fErrorCount) {
1263 for (auto& element : elements) {
1264 if (element->fKind == ProgramElement::kFunction_Kind) {
1265 this->scanCFG((FunctionDefinition&) *element);
1266 }
1267 }
1268 }
Ethan Nicholasf7b88202017-09-18 14:10:39 -04001269 auto result = std::unique_ptr<Program>(new Program(kind,
1270 std::move(textPtr),
1271 settings,
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001272 fContext,
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001273 inherited,
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001274 std::move(elements),
1275 fIRGenerator->fSymbolTable,
1276 fIRGenerator->fInputs));
Kevin Lubickf2030782018-06-19 12:04:18 +00001277 fIRGenerator->finish();
1278 fSource = nullptr;
1279 this->writeErrorCount();
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001280 if (fErrorCount) {
1281 return nullptr;
1282 }
1283 return result;
1284}
1285
Kevin Lubickf2030782018-06-19 12:04:18 +00001286bool Compiler::toSPIRV(const Program& program, OutputStream& out) {
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001287#ifdef SK_ENABLE_SPIRV_VALIDATION
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001288 StringStream buffer;
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001289 fSource = program.fSource.get();
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001290 SPIRVCodeGenerator cg(fContext.get(), &program, this, &buffer);
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001291 bool result = cg.generateCode();
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001292 fSource = nullptr;
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001293 if (result) {
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001294 spvtools::SpirvTools tools(SPV_ENV_VULKAN_1_0);
Ethan Nicholas762466e2017-06-29 10:03:38 -04001295 const String& data = buffer.str();
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001296 SkASSERT(0 == data.size() % 4);
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001297 auto dumpmsg = [](spv_message_level_t, const char*, const spv_position_t&, const char* m) {
1298 SkDebugf("SPIR-V validation error: %s\n", m);
1299 };
1300 tools.SetMessageConsumer(dumpmsg);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001301 // Verify that the SPIR-V we produced is valid. If this SkASSERT fails, check the logs prior
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001302 // to the failure to see the validation errors.
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001303 SkAssertResult(tools.Validate((const uint32_t*) data.c_str(), data.size() / 4));
Ethan Nicholas762466e2017-06-29 10:03:38 -04001304 out.write(data.c_str(), data.size());
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001305 }
1306#else
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001307 fSource = program.fSource.get();
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001308 SPIRVCodeGenerator cg(fContext.get(), &program, this, &out);
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001309 bool result = cg.generateCode();
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001310 fSource = nullptr;
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001311#endif
Kevin Lubickf2030782018-06-19 12:04:18 +00001312 this->writeErrorCount();
Ethan Nicholasce33f102016-12-09 17:22:59 -05001313 return result;
1314}
1315
Kevin Lubickf2030782018-06-19 12:04:18 +00001316bool Compiler::toSPIRV(const Program& program, String* out) {
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001317 StringStream buffer;
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001318 bool result = this->toSPIRV(program, buffer);
1319 if (result) {
Ethan Nicholas762466e2017-06-29 10:03:38 -04001320 *out = buffer.str();
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001321 }
1322 return result;
1323}
1324
Kevin Lubickf2030782018-06-19 12:04:18 +00001325bool Compiler::toGLSL(const Program& program, OutputStream& out) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001326 fSource = program.fSource.get();
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001327 GLSLCodeGenerator cg(fContext.get(), &program, this, &out);
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001328 bool result = cg.generateCode();
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001329 fSource = nullptr;
Kevin Lubickf2030782018-06-19 12:04:18 +00001330 this->writeErrorCount();
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001331 return result;
1332}
1333
Kevin Lubickf2030782018-06-19 12:04:18 +00001334bool Compiler::toGLSL(const Program& program, String* out) {
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001335 StringStream buffer;
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001336 bool result = this->toGLSL(program, buffer);
1337 if (result) {
Ethan Nicholas762466e2017-06-29 10:03:38 -04001338 *out = buffer.str();
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001339 }
1340 return result;
1341}
1342
Kevin Lubickf2030782018-06-19 12:04:18 +00001343bool Compiler::toMetal(const Program& program, OutputStream& out) {
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001344 MetalCodeGenerator cg(fContext.get(), &program, this, &out);
Ethan Nicholascc305772017-10-13 16:17:45 -04001345 bool result = cg.generateCode();
Kevin Lubickf2030782018-06-19 12:04:18 +00001346 this->writeErrorCount();
Ethan Nicholascc305772017-10-13 16:17:45 -04001347 return result;
1348}
1349
Kevin Lubickf2030782018-06-19 12:04:18 +00001350bool Compiler::toCPP(const Program& program, String name, OutputStream& out) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001351 fSource = program.fSource.get();
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001352 CPPCodeGenerator cg(fContext.get(), &program, this, name, &out);
Ethan Nicholas762466e2017-06-29 10:03:38 -04001353 bool result = cg.generateCode();
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001354 fSource = nullptr;
Kevin Lubickf2030782018-06-19 12:04:18 +00001355 this->writeErrorCount();
Ethan Nicholas762466e2017-06-29 10:03:38 -04001356 return result;
1357}
1358
Kevin Lubickf2030782018-06-19 12:04:18 +00001359bool Compiler::toH(const Program& program, String name, OutputStream& out) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001360 fSource = program.fSource.get();
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001361 HCodeGenerator cg(fContext.get(), &program, this, name, &out);
Ethan Nicholas762466e2017-06-29 10:03:38 -04001362 bool result = cg.generateCode();
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001363 fSource = nullptr;
Kevin Lubickf2030782018-06-19 12:04:18 +00001364 this->writeErrorCount();
Ethan Nicholas762466e2017-06-29 10:03:38 -04001365 return result;
1366}
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001367
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001368const char* Compiler::OperatorName(Token::Kind kind) {
1369 switch (kind) {
1370 case Token::PLUS: return "+";
1371 case Token::MINUS: return "-";
1372 case Token::STAR: return "*";
1373 case Token::SLASH: return "/";
1374 case Token::PERCENT: return "%";
1375 case Token::SHL: return "<<";
1376 case Token::SHR: return ">>";
1377 case Token::LOGICALNOT: return "!";
1378 case Token::LOGICALAND: return "&&";
1379 case Token::LOGICALOR: return "||";
1380 case Token::LOGICALXOR: return "^^";
1381 case Token::BITWISENOT: return "~";
1382 case Token::BITWISEAND: return "&";
1383 case Token::BITWISEOR: return "|";
1384 case Token::BITWISEXOR: return "^";
1385 case Token::EQ: return "=";
1386 case Token::EQEQ: return "==";
1387 case Token::NEQ: return "!=";
1388 case Token::LT: return "<";
1389 case Token::GT: return ">";
1390 case Token::LTEQ: return "<=";
1391 case Token::GTEQ: return ">=";
1392 case Token::PLUSEQ: return "+=";
1393 case Token::MINUSEQ: return "-=";
1394 case Token::STAREQ: return "*=";
1395 case Token::SLASHEQ: return "/=";
1396 case Token::PERCENTEQ: return "%=";
1397 case Token::SHLEQ: return "<<=";
1398 case Token::SHREQ: return ">>=";
1399 case Token::LOGICALANDEQ: return "&&=";
1400 case Token::LOGICALOREQ: return "||=";
1401 case Token::LOGICALXOREQ: return "^^=";
1402 case Token::BITWISEANDEQ: return "&=";
1403 case Token::BITWISEOREQ: return "|=";
1404 case Token::BITWISEXOREQ: return "^=";
1405 case Token::PLUSPLUS: return "++";
1406 case Token::MINUSMINUS: return "--";
1407 case Token::COMMA: return ",";
1408 default:
1409 ABORT("unsupported operator: %d\n", kind);
1410 }
1411}
1412
1413
1414bool Compiler::IsAssignment(Token::Kind op) {
1415 switch (op) {
1416 case Token::EQ: // fall through
1417 case Token::PLUSEQ: // fall through
1418 case Token::MINUSEQ: // fall through
1419 case Token::STAREQ: // fall through
1420 case Token::SLASHEQ: // fall through
1421 case Token::PERCENTEQ: // fall through
1422 case Token::SHLEQ: // fall through
1423 case Token::SHREQ: // fall through
1424 case Token::BITWISEOREQ: // fall through
1425 case Token::BITWISEXOREQ: // fall through
1426 case Token::BITWISEANDEQ: // fall through
1427 case Token::LOGICALOREQ: // fall through
1428 case Token::LOGICALXOREQ: // fall through
1429 case Token::LOGICALANDEQ:
1430 return true;
1431 default:
1432 return false;
1433 }
1434}
1435
1436Position Compiler::position(int offset) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001437 SkASSERT(fSource);
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001438 int line = 1;
1439 int column = 1;
1440 for (int i = 0; i < offset; i++) {
1441 if ((*fSource)[i] == '\n') {
1442 ++line;
1443 column = 1;
1444 }
1445 else {
1446 ++column;
1447 }
1448 }
1449 return Position(line, column);
1450}
1451
1452void Compiler::error(int offset, String msg) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001453 fErrorCount++;
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001454 Position pos = this->position(offset);
1455 fErrorText += "error: " + to_string(pos.fLine) + ": " + msg.c_str() + "\n";
ethannicholasb3058bd2016-07-01 08:22:01 -07001456}
1457
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001458String Compiler::errorText() {
1459 String result = fErrorText;
ethannicholasb3058bd2016-07-01 08:22:01 -07001460 return result;
1461}
1462
1463void Compiler::writeErrorCount() {
1464 if (fErrorCount) {
1465 fErrorText += to_string(fErrorCount) + " error";
1466 if (fErrorCount > 1) {
1467 fErrorText += "s";
1468 }
1469 fErrorText += "\n";
1470 }
1471}
1472
ethannicholasb3058bd2016-07-01 08:22:01 -07001473} // namespace