blob: 39ac31532e2d4c13bc60a2a596e5f396f5543610 [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 Nicholas941e7e22016-12-12 15:33:30 -050011#include "SkSLGLSLCodeGenerator.h"
ethannicholasb3058bd2016-07-01 08:22:01 -070012#include "SkSLIRGenerator.h"
ethannicholasb3058bd2016-07-01 08:22:01 -070013#include "SkSLSPIRVCodeGenerator.h"
14#include "ir/SkSLExpression.h"
Ethan Nicholascb670962017-04-20 19:31:52 -040015#include "ir/SkSLExpressionStatement.h"
ethannicholasb3058bd2016-07-01 08:22:01 -070016#include "ir/SkSLIntLiteral.h"
ethannicholas5961bc92016-10-12 06:39:56 -070017#include "ir/SkSLModifiersDeclaration.h"
Ethan Nicholascb670962017-04-20 19:31:52 -040018#include "ir/SkSLNop.h"
ethannicholasb3058bd2016-07-01 08:22:01 -070019#include "ir/SkSLSymbolTable.h"
Ethan Nicholascb670962017-04-20 19:31:52 -040020#include "ir/SkSLTernaryExpression.h"
ethannicholasddb37d62016-10-20 09:54:00 -070021#include "ir/SkSLUnresolvedFunction.h"
ethannicholas22f939e2016-10-13 13:25:34 -070022#include "ir/SkSLVarDeclarations.h"
ethannicholasb3058bd2016-07-01 08:22:01 -070023
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -040024#ifdef SK_ENABLE_SPIRV_VALIDATION
25#include "spirv-tools/libspirv.hpp"
26#endif
27
ethannicholasb3058bd2016-07-01 08:22:01 -070028#define STRINGIFY(x) #x
29
30// include the built-in shader symbols as static strings
31
ethannicholas5961bc92016-10-12 06:39:56 -070032static const char* SKSL_INCLUDE =
ethannicholasb3058bd2016-07-01 08:22:01 -070033#include "sksl.include"
34;
35
ethannicholas5961bc92016-10-12 06:39:56 -070036static const char* SKSL_VERT_INCLUDE =
ethannicholasb3058bd2016-07-01 08:22:01 -070037#include "sksl_vert.include"
38;
39
ethannicholas5961bc92016-10-12 06:39:56 -070040static const char* SKSL_FRAG_INCLUDE =
ethannicholasb3058bd2016-07-01 08:22:01 -070041#include "sksl_frag.include"
42;
43
Ethan Nicholas52cad152017-02-16 16:37:32 -050044static const char* SKSL_GEOM_INCLUDE =
45#include "sksl_geom.include"
46;
47
ethannicholasb3058bd2016-07-01 08:22:01 -070048namespace SkSL {
49
Mike Klein6ad99092016-10-26 10:35:22 -040050Compiler::Compiler()
ethannicholasb3058bd2016-07-01 08:22:01 -070051: fErrorCount(0) {
Ethan Nicholas8feeff92017-03-30 14:11:58 -040052 auto types = std::shared_ptr<SymbolTable>(new SymbolTable(this));
53 auto symbols = std::shared_ptr<SymbolTable>(new SymbolTable(types, this));
ethannicholasd598f792016-07-25 10:08:54 -070054 fIRGenerator = new IRGenerator(&fContext, symbols, *this);
ethannicholasb3058bd2016-07-01 08:22:01 -070055 fTypes = types;
ethannicholasd598f792016-07-25 10:08:54 -070056 #define ADD_TYPE(t) types->addWithoutOwnership(fContext.f ## t ## _Type->fName, \
57 fContext.f ## t ## _Type.get())
ethannicholasb3058bd2016-07-01 08:22:01 -070058 ADD_TYPE(Void);
59 ADD_TYPE(Float);
60 ADD_TYPE(Vec2);
61 ADD_TYPE(Vec3);
62 ADD_TYPE(Vec4);
63 ADD_TYPE(Double);
64 ADD_TYPE(DVec2);
65 ADD_TYPE(DVec3);
66 ADD_TYPE(DVec4);
67 ADD_TYPE(Int);
68 ADD_TYPE(IVec2);
69 ADD_TYPE(IVec3);
70 ADD_TYPE(IVec4);
71 ADD_TYPE(UInt);
72 ADD_TYPE(UVec2);
73 ADD_TYPE(UVec3);
74 ADD_TYPE(UVec4);
75 ADD_TYPE(Bool);
76 ADD_TYPE(BVec2);
77 ADD_TYPE(BVec3);
78 ADD_TYPE(BVec4);
79 ADD_TYPE(Mat2x2);
Ethan Nicholas0df1b042017-03-31 13:56:23 -040080 types->addWithoutOwnership(String("mat2x2"), fContext.fMat2x2_Type.get());
ethannicholasb3058bd2016-07-01 08:22:01 -070081 ADD_TYPE(Mat2x3);
82 ADD_TYPE(Mat2x4);
83 ADD_TYPE(Mat3x2);
84 ADD_TYPE(Mat3x3);
Ethan Nicholas0df1b042017-03-31 13:56:23 -040085 types->addWithoutOwnership(String("mat3x3"), fContext.fMat3x3_Type.get());
ethannicholasb3058bd2016-07-01 08:22:01 -070086 ADD_TYPE(Mat3x4);
87 ADD_TYPE(Mat4x2);
88 ADD_TYPE(Mat4x3);
89 ADD_TYPE(Mat4x4);
Ethan Nicholas0df1b042017-03-31 13:56:23 -040090 types->addWithoutOwnership(String("mat4x4"), fContext.fMat4x4_Type.get());
ethannicholasb3058bd2016-07-01 08:22:01 -070091 ADD_TYPE(GenType);
92 ADD_TYPE(GenDType);
93 ADD_TYPE(GenIType);
94 ADD_TYPE(GenUType);
95 ADD_TYPE(GenBType);
96 ADD_TYPE(Mat);
97 ADD_TYPE(Vec);
98 ADD_TYPE(GVec);
99 ADD_TYPE(GVec2);
100 ADD_TYPE(GVec3);
101 ADD_TYPE(GVec4);
102 ADD_TYPE(DVec);
103 ADD_TYPE(IVec);
104 ADD_TYPE(UVec);
105 ADD_TYPE(BVec);
106
107 ADD_TYPE(Sampler1D);
108 ADD_TYPE(Sampler2D);
109 ADD_TYPE(Sampler3D);
ethannicholas5961bc92016-10-12 06:39:56 -0700110 ADD_TYPE(SamplerExternalOES);
ethannicholasb3058bd2016-07-01 08:22:01 -0700111 ADD_TYPE(SamplerCube);
112 ADD_TYPE(Sampler2DRect);
113 ADD_TYPE(Sampler1DArray);
114 ADD_TYPE(Sampler2DArray);
115 ADD_TYPE(SamplerCubeArray);
116 ADD_TYPE(SamplerBuffer);
117 ADD_TYPE(Sampler2DMS);
118 ADD_TYPE(Sampler2DMSArray);
119
Brian Salomonbf7b6202016-11-11 16:08:03 -0500120 ADD_TYPE(ISampler2D);
121
Brian Salomon2a51de82016-11-16 12:06:01 -0500122 ADD_TYPE(Image2D);
123 ADD_TYPE(IImage2D);
124
Greg Daniel64773e62016-11-22 09:44:03 -0500125 ADD_TYPE(SubpassInput);
126 ADD_TYPE(SubpassInputMS);
127
ethannicholasb3058bd2016-07-01 08:22:01 -0700128 ADD_TYPE(GSampler1D);
129 ADD_TYPE(GSampler2D);
130 ADD_TYPE(GSampler3D);
131 ADD_TYPE(GSamplerCube);
132 ADD_TYPE(GSampler2DRect);
133 ADD_TYPE(GSampler1DArray);
134 ADD_TYPE(GSampler2DArray);
135 ADD_TYPE(GSamplerCubeArray);
136 ADD_TYPE(GSamplerBuffer);
137 ADD_TYPE(GSampler2DMS);
138 ADD_TYPE(GSampler2DMSArray);
139
140 ADD_TYPE(Sampler1DShadow);
141 ADD_TYPE(Sampler2DShadow);
142 ADD_TYPE(SamplerCubeShadow);
143 ADD_TYPE(Sampler2DRectShadow);
144 ADD_TYPE(Sampler1DArrayShadow);
145 ADD_TYPE(Sampler2DArrayShadow);
146 ADD_TYPE(SamplerCubeArrayShadow);
147 ADD_TYPE(GSampler2DArrayShadow);
148 ADD_TYPE(GSamplerCubeArrayShadow);
149
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400150 String skCapsName("sk_Caps");
151 Variable* skCaps = new Variable(Position(), Modifiers(), skCapsName,
Ethan Nicholas3605ace2016-11-21 15:59:48 -0500152 *fContext.fSkCaps_Type, Variable::kGlobal_Storage);
153 fIRGenerator->fSymbolTable->add(skCapsName, std::unique_ptr<Symbol>(skCaps));
154
ethannicholas5961bc92016-10-12 06:39:56 -0700155 Modifiers::Flag ignored1;
156 std::vector<std::unique_ptr<ProgramElement>> ignored2;
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -0400157 fIRGenerator->convertProgram(String(SKSL_INCLUDE), *fTypes, &ignored1, &ignored2);
ethannicholasddb37d62016-10-20 09:54:00 -0700158 fIRGenerator->fSymbolTable->markAllFunctionsBuiltin();
ethannicholasb3058bd2016-07-01 08:22:01 -0700159 ASSERT(!fErrorCount);
160}
161
162Compiler::~Compiler() {
163 delete fIRGenerator;
164}
165
ethannicholas22f939e2016-10-13 13:25:34 -0700166// add the definition created by assigning to the lvalue to the definition set
Ethan Nicholas86a43402017-01-19 13:32:00 -0500167void Compiler::addDefinition(const Expression* lvalue, std::unique_ptr<Expression>* expr,
168 DefinitionMap* definitions) {
ethannicholas22f939e2016-10-13 13:25:34 -0700169 switch (lvalue->fKind) {
170 case Expression::kVariableReference_Kind: {
171 const Variable& var = ((VariableReference*) lvalue)->fVariable;
172 if (var.fStorage == Variable::kLocal_Storage) {
173 (*definitions)[&var] = expr;
174 }
175 break;
176 }
177 case Expression::kSwizzle_Kind:
178 // We consider the variable written to as long as at least some of its components have
179 // been written to. This will lead to some false negatives (we won't catch it if you
180 // write to foo.x and then read foo.y), but being stricter could lead to false positives
Mike Klein6ad99092016-10-26 10:35:22 -0400181 // (we write to foo.x, and then pass foo to a function which happens to only read foo.x,
182 // 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 -0700183 // more complicated whole-program analysis. This is probably good enough.
Mike Klein6ad99092016-10-26 10:35:22 -0400184 this->addDefinition(((Swizzle*) lvalue)->fBase.get(),
Ethan Nicholas86a43402017-01-19 13:32:00 -0500185 (std::unique_ptr<Expression>*) &fContext.fDefined_Expression,
ethannicholas22f939e2016-10-13 13:25:34 -0700186 definitions);
187 break;
188 case Expression::kIndex_Kind:
189 // see comments in Swizzle
Mike Klein6ad99092016-10-26 10:35:22 -0400190 this->addDefinition(((IndexExpression*) lvalue)->fBase.get(),
Ethan Nicholas86a43402017-01-19 13:32:00 -0500191 (std::unique_ptr<Expression>*) &fContext.fDefined_Expression,
ethannicholas22f939e2016-10-13 13:25:34 -0700192 definitions);
193 break;
194 case Expression::kFieldAccess_Kind:
195 // see comments in Swizzle
Mike Klein6ad99092016-10-26 10:35:22 -0400196 this->addDefinition(((FieldAccess*) lvalue)->fBase.get(),
Ethan Nicholas86a43402017-01-19 13:32:00 -0500197 (std::unique_ptr<Expression>*) &fContext.fDefined_Expression,
ethannicholas22f939e2016-10-13 13:25:34 -0700198 definitions);
199 break;
200 default:
201 // not an lvalue, can't happen
202 ASSERT(false);
203 }
204}
205
206// add local variables defined by this node to the set
Mike Klein6ad99092016-10-26 10:35:22 -0400207void Compiler::addDefinitions(const BasicBlock::Node& node,
Ethan Nicholas86a43402017-01-19 13:32:00 -0500208 DefinitionMap* definitions) {
ethannicholas22f939e2016-10-13 13:25:34 -0700209 switch (node.fKind) {
210 case BasicBlock::Node::kExpression_Kind: {
Ethan Nicholascb670962017-04-20 19:31:52 -0400211 ASSERT(node.expression());
212 const Expression* expr = (Expression*) node.expression()->get();
Ethan Nicholas86a43402017-01-19 13:32:00 -0500213 switch (expr->fKind) {
214 case Expression::kBinary_Kind: {
215 BinaryExpression* b = (BinaryExpression*) expr;
216 if (b->fOperator == Token::EQ) {
217 this->addDefinition(b->fLeft.get(), &b->fRight, definitions);
218 } else if (Token::IsAssignment(b->fOperator)) {
219 this->addDefinition(
220 b->fLeft.get(),
221 (std::unique_ptr<Expression>*) &fContext.fDefined_Expression,
222 definitions);
223
224 }
225 break;
ethannicholas22f939e2016-10-13 13:25:34 -0700226 }
Ethan Nicholas86a43402017-01-19 13:32:00 -0500227 case Expression::kPrefix_Kind: {
228 const PrefixExpression* p = (PrefixExpression*) expr;
229 if (p->fOperator == Token::MINUSMINUS || p->fOperator == Token::PLUSPLUS) {
230 this->addDefinition(
231 p->fOperand.get(),
232 (std::unique_ptr<Expression>*) &fContext.fDefined_Expression,
233 definitions);
234 }
235 break;
236 }
237 case Expression::kPostfix_Kind: {
238 const PostfixExpression* p = (PostfixExpression*) expr;
239 if (p->fOperator == Token::MINUSMINUS || p->fOperator == Token::PLUSPLUS) {
240 this->addDefinition(
241 p->fOperand.get(),
242 (std::unique_ptr<Expression>*) &fContext.fDefined_Expression,
243 definitions);
Ethan Nicholas86a43402017-01-19 13:32:00 -0500244 }
245 break;
246 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400247 case Expression::kVariableReference_Kind: {
248 const VariableReference* v = (VariableReference*) expr;
249 if (v->fRefKind != VariableReference::kRead_RefKind) {
250 this->addDefinition(
251 v,
252 (std::unique_ptr<Expression>*) &fContext.fDefined_Expression,
253 definitions);
254 }
255 }
Ethan Nicholas86a43402017-01-19 13:32:00 -0500256 default:
257 break;
ethannicholas22f939e2016-10-13 13:25:34 -0700258 }
259 break;
260 }
261 case BasicBlock::Node::kStatement_Kind: {
Ethan Nicholascb670962017-04-20 19:31:52 -0400262 const Statement* stmt = (Statement*) node.statement()->get();
Ethan Nicholasb4dc4192017-06-02 10:16:28 -0400263 if (stmt->fKind == Statement::kVarDeclaration_Kind) {
264 VarDeclaration& vd = (VarDeclaration&) *stmt;
265 if (vd.fValue) {
266 (*definitions)[vd.fVar] = &vd.fValue;
ethannicholas22f939e2016-10-13 13:25:34 -0700267 }
268 }
269 break;
270 }
271 }
272}
273
274void Compiler::scanCFG(CFG* cfg, BlockId blockId, std::set<BlockId>* workList) {
275 BasicBlock& block = cfg->fBlocks[blockId];
276
277 // compute definitions after this block
Ethan Nicholas86a43402017-01-19 13:32:00 -0500278 DefinitionMap after = block.fBefore;
ethannicholas22f939e2016-10-13 13:25:34 -0700279 for (const BasicBlock::Node& n : block.fNodes) {
280 this->addDefinitions(n, &after);
281 }
282
283 // propagate definitions to exits
284 for (BlockId exitId : block.fExits) {
285 BasicBlock& exit = cfg->fBlocks[exitId];
286 for (const auto& pair : after) {
Ethan Nicholas86a43402017-01-19 13:32:00 -0500287 std::unique_ptr<Expression>* e1 = pair.second;
288 auto found = exit.fBefore.find(pair.first);
289 if (found == exit.fBefore.end()) {
290 // exit has no definition for it, just copy it
291 workList->insert(exitId);
ethannicholas22f939e2016-10-13 13:25:34 -0700292 exit.fBefore[pair.first] = e1;
293 } else {
Ethan Nicholas86a43402017-01-19 13:32:00 -0500294 // exit has a (possibly different) value already defined
295 std::unique_ptr<Expression>* e2 = exit.fBefore[pair.first];
ethannicholas22f939e2016-10-13 13:25:34 -0700296 if (e1 != e2) {
297 // definition has changed, merge and add exit block to worklist
298 workList->insert(exitId);
Ethan Nicholasaf197692017-02-27 13:26:45 -0500299 if (e1 && e2) {
300 exit.fBefore[pair.first] =
Ethan Nicholas86a43402017-01-19 13:32:00 -0500301 (std::unique_ptr<Expression>*) &fContext.fDefined_Expression;
Ethan Nicholasaf197692017-02-27 13:26:45 -0500302 } else {
303 exit.fBefore[pair.first] = nullptr;
304 }
ethannicholas22f939e2016-10-13 13:25:34 -0700305 }
306 }
307 }
308 }
309}
310
311// returns a map which maps all local variables in the function to null, indicating that their value
312// is initially unknown
Ethan Nicholas86a43402017-01-19 13:32:00 -0500313static DefinitionMap compute_start_state(const CFG& cfg) {
314 DefinitionMap result;
Mike Klein6ad99092016-10-26 10:35:22 -0400315 for (const auto& block : cfg.fBlocks) {
316 for (const auto& node : block.fNodes) {
ethannicholas22f939e2016-10-13 13:25:34 -0700317 if (node.fKind == BasicBlock::Node::kStatement_Kind) {
Ethan Nicholascb670962017-04-20 19:31:52 -0400318 ASSERT(node.statement());
319 const Statement* s = node.statement()->get();
ethannicholas22f939e2016-10-13 13:25:34 -0700320 if (s->fKind == Statement::kVarDeclarations_Kind) {
321 const VarDeclarationsStatement* vd = (const VarDeclarationsStatement*) s;
Ethan Nicholascb670962017-04-20 19:31:52 -0400322 for (const auto& decl : vd->fDeclaration->fVars) {
Ethan Nicholas91a10532017-06-22 11:24:38 -0400323 if (decl->fKind == Statement::kVarDeclaration_Kind) {
324 result[((VarDeclaration&) *decl).fVar] = nullptr;
325 }
Mike Klein6ad99092016-10-26 10:35:22 -0400326 }
ethannicholas22f939e2016-10-13 13:25:34 -0700327 }
328 }
329 }
330 }
331 return result;
332}
333
Ethan Nicholascb670962017-04-20 19:31:52 -0400334/**
335 * Returns true if assigning to this lvalue has no effect.
336 */
337static bool is_dead(const Expression& lvalue) {
338 switch (lvalue.fKind) {
339 case Expression::kVariableReference_Kind:
340 return ((VariableReference&) lvalue).fVariable.dead();
341 case Expression::kSwizzle_Kind:
342 return is_dead(*((Swizzle&) lvalue).fBase);
343 case Expression::kFieldAccess_Kind:
344 return is_dead(*((FieldAccess&) lvalue).fBase);
345 case Expression::kIndex_Kind: {
346 const IndexExpression& idx = (IndexExpression&) lvalue;
347 return is_dead(*idx.fBase) && !idx.fIndex->hasSideEffects();
348 }
349 default:
350 ABORT("invalid lvalue: %s\n", lvalue.description().c_str());
351 }
352}
ethannicholas22f939e2016-10-13 13:25:34 -0700353
Ethan Nicholascb670962017-04-20 19:31:52 -0400354/**
355 * Returns true if this is an assignment which can be collapsed down to just the right hand side due
356 * to a dead target and lack of side effects on the left hand side.
357 */
358static bool dead_assignment(const BinaryExpression& b) {
359 if (!Token::IsAssignment(b.fOperator)) {
360 return false;
361 }
362 return is_dead(*b.fLeft);
363}
364
365void Compiler::computeDataFlow(CFG* cfg) {
366 cfg->fBlocks[cfg->fStart].fBefore = compute_start_state(*cfg);
ethannicholas22f939e2016-10-13 13:25:34 -0700367 std::set<BlockId> workList;
Ethan Nicholascb670962017-04-20 19:31:52 -0400368 for (BlockId i = 0; i < cfg->fBlocks.size(); i++) {
ethannicholas22f939e2016-10-13 13:25:34 -0700369 workList.insert(i);
370 }
371 while (workList.size()) {
372 BlockId next = *workList.begin();
373 workList.erase(workList.begin());
Ethan Nicholascb670962017-04-20 19:31:52 -0400374 this->scanCFG(cfg, next, &workList);
ethannicholas22f939e2016-10-13 13:25:34 -0700375 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400376}
377
378/**
379 * Attempts to replace the expression pointed to by iter with a new one (in both the CFG and the
380 * IR). If the expression can be cleanly removed, returns true and updates the iterator to point to
381 * the newly-inserted element. Otherwise updates only the IR and returns false (and the CFG will
382 * need to be regenerated).
383 */
384bool try_replace_expression(BasicBlock* b,
385 std::vector<BasicBlock::Node>::iterator* iter,
386 std::unique_ptr<Expression>* newExpression) {
387 std::unique_ptr<Expression>* target = (*iter)->expression();
388 if (!b->tryRemoveExpression(iter)) {
389 *target = std::move(*newExpression);
390 return false;
391 }
392 *target = std::move(*newExpression);
393 return b->tryInsertExpression(iter, target);
394}
395
396/**
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400397 * Returns true if the expression is a constant numeric literal with the specified value, or a
398 * constant vector with all elements equal to the specified value.
Ethan Nicholascb670962017-04-20 19:31:52 -0400399 */
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400400bool is_constant(const Expression& expr, double value) {
Ethan Nicholascb670962017-04-20 19:31:52 -0400401 switch (expr.fKind) {
402 case Expression::kIntLiteral_Kind:
403 return ((IntLiteral&) expr).fValue == value;
404 case Expression::kFloatLiteral_Kind:
405 return ((FloatLiteral&) expr).fValue == value;
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400406 case Expression::kConstructor_Kind: {
407 Constructor& c = (Constructor&) expr;
408 if (c.fType.kind() == Type::kVector_Kind && c.isConstant()) {
409 for (int i = 0; i < c.fType.columns(); ++i) {
410 if (!is_constant(c.getVecComponent(i), value)) {
411 return false;
412 }
413 }
414 return true;
415 }
416 return false;
417 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400418 default:
419 return false;
420 }
421}
422
423/**
424 * Collapses the binary expression pointed to by iter down to just the right side (in both the IR
425 * and CFG structures).
426 */
427void delete_left(BasicBlock* b,
428 std::vector<BasicBlock::Node>::iterator* iter,
429 bool* outUpdated,
430 bool* outNeedsRescan) {
431 *outUpdated = true;
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400432 std::unique_ptr<Expression>* target = (*iter)->expression();
433 ASSERT((*target)->fKind == Expression::kBinary_Kind);
434 BinaryExpression& bin = (BinaryExpression&) **target;
435 bool result;
436 if (bin.fOperator == Token::EQ) {
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400437 result = b->tryRemoveLValueBefore(iter, bin.fLeft.get());
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400438 } else {
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400439 result = b->tryRemoveExpressionBefore(iter, bin.fLeft.get());
Ethan Nicholascb670962017-04-20 19:31:52 -0400440 }
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400441 *target = std::move(bin.fRight);
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400442 if (!result) {
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400443 *outNeedsRescan = true;
444 return;
445 }
446 if (*iter == b->fNodes.begin()) {
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400447 *outNeedsRescan = true;
448 return;
449 }
450 --(*iter);
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400451 if ((*iter)->fKind != BasicBlock::Node::kExpression_Kind ||
452 (*iter)->expression() != &bin.fRight) {
453 *outNeedsRescan = true;
454 return;
455 }
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400456 *iter = b->fNodes.erase(*iter);
457 ASSERT((*iter)->expression() == target);
Ethan Nicholascb670962017-04-20 19:31:52 -0400458}
459
460/**
461 * Collapses the binary expression pointed to by iter down to just the left side (in both the IR and
462 * CFG structures).
463 */
464void delete_right(BasicBlock* b,
465 std::vector<BasicBlock::Node>::iterator* iter,
466 bool* outUpdated,
467 bool* outNeedsRescan) {
468 *outUpdated = true;
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400469 std::unique_ptr<Expression>* target = (*iter)->expression();
470 ASSERT((*target)->fKind == Expression::kBinary_Kind);
471 BinaryExpression& bin = (BinaryExpression&) **target;
472 if (!b->tryRemoveExpressionBefore(iter, bin.fRight.get())) {
473 *target = std::move(bin.fLeft);
Ethan Nicholascb670962017-04-20 19:31:52 -0400474 *outNeedsRescan = true;
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400475 return;
Ethan Nicholascb670962017-04-20 19:31:52 -0400476 }
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400477 *target = std::move(bin.fLeft);
478 if (*iter == b->fNodes.begin()) {
479 *outNeedsRescan = true;
480 return;
481 }
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400482 --(*iter);
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400483 if (((*iter)->fKind != BasicBlock::Node::kExpression_Kind ||
484 (*iter)->expression() != &bin.fLeft)) {
485 *outNeedsRescan = true;
486 return;
487 }
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400488 *iter = b->fNodes.erase(*iter);
489 ASSERT((*iter)->expression() == target);
Ethan Nicholascb670962017-04-20 19:31:52 -0400490}
491
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400492/**
493 * Constructs the specified type using a single argument.
494 */
495static std::unique_ptr<Expression> construct(const Type& type, std::unique_ptr<Expression> v) {
496 std::vector<std::unique_ptr<Expression>> args;
497 args.push_back(std::move(v));
498 auto result = std::unique_ptr<Expression>(new Constructor(Position(), type, std::move(args)));
499 return result;
500}
501
502/**
503 * Used in the implementations of vectorize_left and vectorize_right. Given a vector type and an
504 * expression x, deletes the expression pointed to by iter and replaces it with <type>(x).
505 */
506static void vectorize(BasicBlock* b,
507 std::vector<BasicBlock::Node>::iterator* iter,
508 const Type& type,
509 std::unique_ptr<Expression>* otherExpression,
510 bool* outUpdated,
511 bool* outNeedsRescan) {
512 ASSERT((*(*iter)->expression())->fKind == Expression::kBinary_Kind);
513 ASSERT(type.kind() == Type::kVector_Kind);
514 ASSERT((*otherExpression)->fType.kind() == Type::kScalar_Kind);
515 *outUpdated = true;
516 std::unique_ptr<Expression>* target = (*iter)->expression();
517 if (!b->tryRemoveExpression(iter)) {
518 *target = construct(type, std::move(*otherExpression));
519 *outNeedsRescan = true;
520 } else {
521 *target = construct(type, std::move(*otherExpression));
522 if (!b->tryInsertExpression(iter, target)) {
523 *outNeedsRescan = true;
524 }
525 }
526}
527
528/**
529 * Given a binary expression of the form x <op> vec<n>(y), deletes the right side and vectorizes the
530 * left to yield vec<n>(x).
531 */
532static void vectorize_left(BasicBlock* b,
533 std::vector<BasicBlock::Node>::iterator* iter,
534 bool* outUpdated,
535 bool* outNeedsRescan) {
536 BinaryExpression& bin = (BinaryExpression&) **(*iter)->expression();
537 vectorize(b, iter, bin.fRight->fType, &bin.fLeft, outUpdated, outNeedsRescan);
538}
539
540/**
541 * Given a binary expression of the form vec<n>(x) <op> y, deletes the left side and vectorizes the
542 * right to yield vec<n>(y).
543 */
544static void vectorize_right(BasicBlock* b,
545 std::vector<BasicBlock::Node>::iterator* iter,
546 bool* outUpdated,
547 bool* outNeedsRescan) {
548 BinaryExpression& bin = (BinaryExpression&) **(*iter)->expression();
549 vectorize(b, iter, bin.fLeft->fType, &bin.fRight, outUpdated, outNeedsRescan);
550}
551
552// Mark that an expression which we were writing to is no longer being written to
553void clear_write(const Expression& expr) {
554 switch (expr.fKind) {
555 case Expression::kVariableReference_Kind: {
556 ((VariableReference&) expr).setRefKind(VariableReference::kRead_RefKind);
557 break;
558 }
559 case Expression::kFieldAccess_Kind:
560 clear_write(*((FieldAccess&) expr).fBase);
561 break;
562 case Expression::kSwizzle_Kind:
563 clear_write(*((Swizzle&) expr).fBase);
564 break;
565 case Expression::kIndex_Kind:
566 clear_write(*((IndexExpression&) expr).fBase);
567 break;
568 default:
569 ABORT("shouldn't be writing to this kind of expression\n");
570 break;
571 }
572}
573
Ethan Nicholascb670962017-04-20 19:31:52 -0400574void Compiler::simplifyExpression(DefinitionMap& definitions,
575 BasicBlock& b,
576 std::vector<BasicBlock::Node>::iterator* iter,
577 std::unordered_set<const Variable*>* undefinedVariables,
578 bool* outUpdated,
579 bool* outNeedsRescan) {
580 Expression* expr = (*iter)->expression()->get();
581 ASSERT(expr);
582 if ((*iter)->fConstantPropagation) {
583 std::unique_ptr<Expression> optimized = expr->constantPropagate(*fIRGenerator, definitions);
584 if (optimized) {
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400585 *outUpdated = true;
Ethan Nicholascb670962017-04-20 19:31:52 -0400586 if (!try_replace_expression(&b, iter, &optimized)) {
587 *outNeedsRescan = true;
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400588 return;
Ethan Nicholascb670962017-04-20 19:31:52 -0400589 }
590 ASSERT((*iter)->fKind == BasicBlock::Node::kExpression_Kind);
591 expr = (*iter)->expression()->get();
Ethan Nicholascb670962017-04-20 19:31:52 -0400592 }
593 }
594 switch (expr->fKind) {
595 case Expression::kVariableReference_Kind: {
596 const Variable& var = ((VariableReference*) expr)->fVariable;
597 if (var.fStorage == Variable::kLocal_Storage && !definitions[&var] &&
598 (*undefinedVariables).find(&var) == (*undefinedVariables).end()) {
599 (*undefinedVariables).insert(&var);
600 this->error(expr->fPosition,
601 "'" + var.fName + "' has not been assigned");
602 }
603 break;
604 }
605 case Expression::kTernary_Kind: {
606 TernaryExpression* t = (TernaryExpression*) expr;
607 if (t->fTest->fKind == Expression::kBoolLiteral_Kind) {
608 // ternary has a constant test, replace it with either the true or
609 // false branch
610 if (((BoolLiteral&) *t->fTest).fValue) {
611 (*iter)->setExpression(std::move(t->fIfTrue));
612 } else {
613 (*iter)->setExpression(std::move(t->fIfFalse));
614 }
615 *outUpdated = true;
616 *outNeedsRescan = true;
617 }
618 break;
619 }
620 case Expression::kBinary_Kind: {
Ethan Nicholascb670962017-04-20 19:31:52 -0400621 BinaryExpression* bin = (BinaryExpression*) expr;
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400622 if (dead_assignment(*bin)) {
623 delete_left(&b, iter, outUpdated, outNeedsRescan);
624 break;
625 }
626 // collapse useless expressions like x * 1 or x + 0
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400627 if (((bin->fLeft->fType.kind() != Type::kScalar_Kind) &&
628 (bin->fLeft->fType.kind() != Type::kVector_Kind)) ||
629 ((bin->fRight->fType.kind() != Type::kScalar_Kind) &&
630 (bin->fRight->fType.kind() != Type::kVector_Kind))) {
631 break;
632 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400633 switch (bin->fOperator) {
634 case Token::STAR:
635 if (is_constant(*bin->fLeft, 1)) {
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400636 if (bin->fLeft->fType.kind() == Type::kVector_Kind &&
637 bin->fRight->fType.kind() == Type::kScalar_Kind) {
638 // vec4(1) * x -> vec4(x)
639 vectorize_right(&b, iter, outUpdated, outNeedsRescan);
640 } else {
641 // 1 * x -> x
642 // 1 * vec4(x) -> vec4(x)
643 // vec4(1) * vec4(x) -> vec4(x)
644 delete_left(&b, iter, outUpdated, outNeedsRescan);
645 }
646 }
647 else if (is_constant(*bin->fLeft, 0)) {
648 if (bin->fLeft->fType.kind() == Type::kScalar_Kind &&
649 bin->fRight->fType.kind() == Type::kVector_Kind) {
650 // 0 * vec4(x) -> vec4(0)
651 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
652 } else {
653 // 0 * x -> 0
654 // vec4(0) * x -> vec4(0)
655 // vec4(0) * vec4(x) -> vec4(0)
656 delete_right(&b, iter, outUpdated, outNeedsRescan);
657 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400658 }
659 else if (is_constant(*bin->fRight, 1)) {
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400660 if (bin->fLeft->fType.kind() == Type::kScalar_Kind &&
661 bin->fRight->fType.kind() == Type::kVector_Kind) {
662 // x * vec4(1) -> vec4(x)
663 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
664 } else {
665 // x * 1 -> x
666 // vec4(x) * 1 -> vec4(x)
667 // vec4(x) * vec4(1) -> vec4(x)
668 delete_right(&b, iter, outUpdated, outNeedsRescan);
669 }
670 }
671 else if (is_constant(*bin->fRight, 0)) {
672 if (bin->fLeft->fType.kind() == Type::kVector_Kind &&
673 bin->fRight->fType.kind() == Type::kScalar_Kind) {
674 // vec4(x) * 0 -> vec4(0)
675 vectorize_right(&b, iter, outUpdated, outNeedsRescan);
676 } else {
677 // x * 0 -> 0
678 // x * vec4(0) -> vec4(0)
679 // vec4(x) * vec4(0) -> vec4(0)
680 delete_left(&b, iter, outUpdated, outNeedsRescan);
681 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400682 }
683 break;
Ethan Nicholas56e42712017-04-21 10:23:37 -0400684 case Token::PLUS:
Ethan Nicholascb670962017-04-20 19:31:52 -0400685 if (is_constant(*bin->fLeft, 0)) {
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400686 if (bin->fLeft->fType.kind() == Type::kVector_Kind &&
687 bin->fRight->fType.kind() == Type::kScalar_Kind) {
688 // vec4(0) + x -> vec4(x)
689 vectorize_right(&b, iter, outUpdated, outNeedsRescan);
690 } else {
691 // 0 + x -> x
692 // 0 + vec4(x) -> vec4(x)
693 // vec4(0) + vec4(x) -> vec4(x)
694 delete_left(&b, iter, outUpdated, outNeedsRescan);
695 }
696 } else if (is_constant(*bin->fRight, 0)) {
697 if (bin->fLeft->fType.kind() == Type::kScalar_Kind &&
698 bin->fRight->fType.kind() == Type::kVector_Kind) {
699 // x + vec4(0) -> vec4(x)
700 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
701 } else {
702 // x + 0 -> x
703 // vec4(x) + 0 -> vec4(x)
704 // vec4(x) + vec4(0) -> vec4(x)
705 delete_right(&b, iter, outUpdated, outNeedsRescan);
706 }
Ethan Nicholas56e42712017-04-21 10:23:37 -0400707 }
708 break;
709 case Token::MINUS:
710 if (is_constant(*bin->fRight, 0)) {
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400711 if (bin->fLeft->fType.kind() == Type::kScalar_Kind &&
712 bin->fRight->fType.kind() == Type::kVector_Kind) {
713 // x - vec4(0) -> vec4(x)
714 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
715 } else {
716 // x - 0 -> x
717 // vec4(x) - 0 -> vec4(x)
718 // vec4(x) - vec4(0) -> vec4(x)
719 delete_right(&b, iter, outUpdated, outNeedsRescan);
720 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400721 }
722 break;
723 case Token::SLASH:
724 if (is_constant(*bin->fRight, 1)) {
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400725 if (bin->fLeft->fType.kind() == Type::kScalar_Kind &&
726 bin->fRight->fType.kind() == Type::kVector_Kind) {
727 // x / vec4(1) -> vec4(x)
728 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
729 } else {
730 // x / 1 -> x
731 // vec4(x) / 1 -> vec4(x)
732 // vec4(x) / vec4(1) -> vec4(x)
733 delete_right(&b, iter, outUpdated, outNeedsRescan);
734 }
735 } else if (is_constant(*bin->fLeft, 0)) {
736 if (bin->fLeft->fType.kind() == Type::kScalar_Kind &&
737 bin->fRight->fType.kind() == Type::kVector_Kind) {
738 // 0 / vec4(x) -> vec4(0)
739 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
740 } else {
741 // 0 / x -> 0
742 // vec4(0) / x -> vec4(0)
743 // vec4(0) / vec4(x) -> vec4(0)
744 delete_right(&b, iter, outUpdated, outNeedsRescan);
745 }
746 }
747 break;
748 case Token::PLUSEQ:
749 if (is_constant(*bin->fRight, 0)) {
750 clear_write(*bin->fLeft);
751 delete_right(&b, iter, outUpdated, outNeedsRescan);
752 }
753 break;
754 case Token::MINUSEQ:
755 if (is_constant(*bin->fRight, 0)) {
756 clear_write(*bin->fLeft);
757 delete_right(&b, iter, outUpdated, outNeedsRescan);
758 }
759 break;
760 case Token::STAREQ:
761 if (is_constant(*bin->fRight, 1)) {
762 clear_write(*bin->fLeft);
763 delete_right(&b, iter, outUpdated, outNeedsRescan);
764 }
765 break;
766 case Token::SLASHEQ:
767 if (is_constant(*bin->fRight, 1)) {
768 clear_write(*bin->fLeft);
Ethan Nicholascb670962017-04-20 19:31:52 -0400769 delete_right(&b, iter, outUpdated, outNeedsRescan);
770 }
771 break;
772 default:
773 break;
774 }
775 }
776 default:
777 break;
778 }
779}
780
Ethan Nicholas5ac13c22017-05-10 15:06:17 -0400781
782// returns true if this statement could potentially execute a break at the current level (we ignore
783// nested loops and switches, since any breaks inside of them will merely break the loop / switch)
784static bool contains_break(Statement& s) {
785 switch (s.fKind) {
786 case Statement::kBlock_Kind:
787 for (const auto& sub : ((Block&) s).fStatements) {
788 if (contains_break(*sub)) {
789 return true;
790 }
791 }
792 return false;
793 case Statement::kBreak_Kind:
794 return true;
795 case Statement::kIf_Kind: {
796 const IfStatement& i = (IfStatement&) s;
797 return contains_break(*i.fIfTrue) || (i.fIfFalse && contains_break(*i.fIfFalse));
798 }
799 default:
800 return false;
801 }
802}
803
804// Returns a block containing all of the statements that will be run if the given case matches
805// (which, owing to the statements being owned by unique_ptrs, means the switch itself will be
806// broken by this call and must then be discarded).
807// Returns null (and leaves the switch unmodified) if no such simple reduction is possible, such as
808// when break statements appear inside conditionals.
809static std::unique_ptr<Statement> block_for_case(SwitchStatement* s, SwitchCase* c) {
810 bool capturing = false;
811 std::vector<std::unique_ptr<Statement>*> statementPtrs;
812 for (const auto& current : s->fCases) {
813 if (current.get() == c) {
814 capturing = true;
815 }
816 if (capturing) {
817 for (auto& stmt : current->fStatements) {
818 if (stmt->fKind == Statement::kBreak_Kind) {
819 capturing = false;
820 break;
821 }
822 if (contains_break(*stmt)) {
823 return nullptr;
824 }
825 statementPtrs.push_back(&stmt);
826 }
827 if (!capturing) {
828 break;
829 }
830 }
831 }
832 std::vector<std::unique_ptr<Statement>> statements;
833 for (const auto& s : statementPtrs) {
834 statements.push_back(std::move(*s));
835 }
836 return std::unique_ptr<Statement>(new Block(Position(), std::move(statements)));
837}
838
Ethan Nicholascb670962017-04-20 19:31:52 -0400839void Compiler::simplifyStatement(DefinitionMap& definitions,
Ethan Nicholas5ac13c22017-05-10 15:06:17 -0400840 BasicBlock& b,
841 std::vector<BasicBlock::Node>::iterator* iter,
842 std::unordered_set<const Variable*>* undefinedVariables,
843 bool* outUpdated,
844 bool* outNeedsRescan) {
Ethan Nicholascb670962017-04-20 19:31:52 -0400845 Statement* stmt = (*iter)->statement()->get();
846 switch (stmt->fKind) {
Ethan Nicholasb4dc4192017-06-02 10:16:28 -0400847 case Statement::kVarDeclaration_Kind: {
848 const auto& varDecl = (VarDeclaration&) *stmt;
849 if (varDecl.fVar->dead() &&
850 (!varDecl.fValue ||
851 !varDecl.fValue->hasSideEffects())) {
852 if (varDecl.fValue) {
853 ASSERT((*iter)->statement()->get() == stmt);
854 if (!b.tryRemoveExpressionBefore(iter, varDecl.fValue.get())) {
855 *outNeedsRescan = true;
Ethan Nicholascb670962017-04-20 19:31:52 -0400856 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400857 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400858 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
Ethan Nicholasb4dc4192017-06-02 10:16:28 -0400859 *outUpdated = true;
Ethan Nicholascb670962017-04-20 19:31:52 -0400860 }
861 break;
862 }
863 case Statement::kIf_Kind: {
864 IfStatement& i = (IfStatement&) *stmt;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -0400865 if (i.fTest->fKind == Expression::kBoolLiteral_Kind) {
866 // constant if, collapse down to a single branch
867 if (((BoolLiteral&) *i.fTest).fValue) {
868 ASSERT(i.fIfTrue);
869 (*iter)->setStatement(std::move(i.fIfTrue));
870 } else {
871 if (i.fIfFalse) {
872 (*iter)->setStatement(std::move(i.fIfFalse));
873 } else {
874 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
875 }
876 }
877 *outUpdated = true;
878 *outNeedsRescan = true;
879 break;
880 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400881 if (i.fIfFalse && i.fIfFalse->isEmpty()) {
882 // else block doesn't do anything, remove it
883 i.fIfFalse.reset();
884 *outUpdated = true;
885 *outNeedsRescan = true;
886 }
887 if (!i.fIfFalse && i.fIfTrue->isEmpty()) {
888 // if block doesn't do anything, no else block
889 if (i.fTest->hasSideEffects()) {
890 // test has side effects, keep it
891 (*iter)->setStatement(std::unique_ptr<Statement>(
892 new ExpressionStatement(std::move(i.fTest))));
893 } else {
894 // no if, no else, no test side effects, kill the whole if
895 // statement
896 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
897 }
898 *outUpdated = true;
899 *outNeedsRescan = true;
900 }
901 break;
902 }
Ethan Nicholas5ac13c22017-05-10 15:06:17 -0400903 case Statement::kSwitch_Kind: {
904 SwitchStatement& s = (SwitchStatement&) *stmt;
905 if (s.fValue->isConstant()) {
906 // switch is constant, replace it with the case that matches
907 bool found = false;
908 SwitchCase* defaultCase = nullptr;
909 for (const auto& c : s.fCases) {
910 if (!c->fValue) {
911 defaultCase = c.get();
912 continue;
913 }
914 ASSERT(c->fValue->fKind == s.fValue->fKind);
915 found = c->fValue->compareConstant(fContext, *s.fValue);
916 if (found) {
917 std::unique_ptr<Statement> newBlock = block_for_case(&s, c.get());
918 if (newBlock) {
919 (*iter)->setStatement(std::move(newBlock));
920 break;
921 } else {
922 if (s.fIsStatic) {
923 this->error(s.fPosition,
924 "static switch contains non-static conditional break");
925 s.fIsStatic = false;
926 }
927 return; // can't simplify
928 }
929 }
930 }
931 if (!found) {
932 // no matching case. use default if it exists, or kill the whole thing
933 if (defaultCase) {
934 std::unique_ptr<Statement> newBlock = block_for_case(&s, defaultCase);
935 if (newBlock) {
936 (*iter)->setStatement(std::move(newBlock));
937 } else {
938 if (s.fIsStatic) {
939 this->error(s.fPosition,
940 "static switch contains non-static conditional break");
941 s.fIsStatic = false;
942 }
943 return; // can't simplify
944 }
945 } else {
946 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
947 }
948 }
949 *outUpdated = true;
950 *outNeedsRescan = true;
951 }
952 break;
953 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400954 case Statement::kExpression_Kind: {
955 ExpressionStatement& e = (ExpressionStatement&) *stmt;
956 ASSERT((*iter)->statement()->get() == &e);
Ethan Nicholascb670962017-04-20 19:31:52 -0400957 if (!e.fExpression->hasSideEffects()) {
958 // Expression statement with no side effects, kill it
959 if (!b.tryRemoveExpressionBefore(iter, e.fExpression.get())) {
960 *outNeedsRescan = true;
961 }
962 ASSERT((*iter)->statement()->get() == stmt);
963 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
964 *outUpdated = true;
965 }
966 break;
967 }
968 default:
969 break;
970 }
971}
972
973void Compiler::scanCFG(FunctionDefinition& f) {
974 CFG cfg = CFGGenerator().getCFG(f);
975 this->computeDataFlow(&cfg);
ethannicholas22f939e2016-10-13 13:25:34 -0700976
977 // check for unreachable code
978 for (size_t i = 0; i < cfg.fBlocks.size(); i++) {
Mike Klein6ad99092016-10-26 10:35:22 -0400979 if (i != cfg.fStart && !cfg.fBlocks[i].fEntrances.size() &&
ethannicholas22f939e2016-10-13 13:25:34 -0700980 cfg.fBlocks[i].fNodes.size()) {
Ethan Nicholas86a43402017-01-19 13:32:00 -0500981 Position p;
982 switch (cfg.fBlocks[i].fNodes[0].fKind) {
983 case BasicBlock::Node::kStatement_Kind:
Ethan Nicholascb670962017-04-20 19:31:52 -0400984 p = (*cfg.fBlocks[i].fNodes[0].statement())->fPosition;
Ethan Nicholas86a43402017-01-19 13:32:00 -0500985 break;
986 case BasicBlock::Node::kExpression_Kind:
Ethan Nicholascb670962017-04-20 19:31:52 -0400987 p = (*cfg.fBlocks[i].fNodes[0].expression())->fPosition;
Ethan Nicholas86a43402017-01-19 13:32:00 -0500988 break;
989 }
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400990 this->error(p, String("unreachable"));
ethannicholas22f939e2016-10-13 13:25:34 -0700991 }
992 }
993 if (fErrorCount) {
994 return;
995 }
996
Ethan Nicholascb670962017-04-20 19:31:52 -0400997 // check for dead code & undefined variables, perform constant propagation
998 std::unordered_set<const Variable*> undefinedVariables;
999 bool updated;
1000 bool needsRescan = false;
1001 do {
1002 if (needsRescan) {
1003 cfg = CFGGenerator().getCFG(f);
1004 this->computeDataFlow(&cfg);
1005 needsRescan = false;
Ethan Nicholas113628d2017-02-02 16:11:39 -05001006 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001007
1008 updated = false;
1009 for (BasicBlock& b : cfg.fBlocks) {
1010 DefinitionMap definitions = b.fBefore;
1011
1012 for (auto iter = b.fNodes.begin(); iter != b.fNodes.end() && !needsRescan; ++iter) {
1013 if (iter->fKind == BasicBlock::Node::kExpression_Kind) {
1014 this->simplifyExpression(definitions, b, &iter, &undefinedVariables, &updated,
1015 &needsRescan);
1016 } else {
1017 this->simplifyStatement(definitions, b, &iter, &undefinedVariables, &updated,
1018 &needsRescan);
1019 }
Ethan Nicholas4b330df2017-05-17 10:52:55 -04001020 if (needsRescan) {
1021 break;
1022 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001023 this->addDefinitions(*iter, &definitions);
1024 }
1025 }
1026 } while (updated);
1027 ASSERT(!needsRescan);
ethannicholas22f939e2016-10-13 13:25:34 -07001028
Ethan Nicholas91a10532017-06-22 11:24:38 -04001029 // verify static ifs & switches, clean up dead variable decls
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001030 for (BasicBlock& b : cfg.fBlocks) {
1031 DefinitionMap definitions = b.fBefore;
1032
Ethan Nicholas91a10532017-06-22 11:24:38 -04001033 for (auto iter = b.fNodes.begin(); iter != b.fNodes.end() && !needsRescan;) {
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001034 if (iter->fKind == BasicBlock::Node::kStatement_Kind) {
1035 const Statement& s = **iter->statement();
1036 switch (s.fKind) {
1037 case Statement::kIf_Kind:
1038 if (((const IfStatement&) s).fIsStatic) {
1039 this->error(s.fPosition, "static if has non-static test");
1040 }
Ethan Nicholas91a10532017-06-22 11:24:38 -04001041 ++iter;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001042 break;
1043 case Statement::kSwitch_Kind:
1044 if (((const SwitchStatement&) s).fIsStatic) {
1045 this->error(s.fPosition, "static switch has non-static test");
1046 }
Ethan Nicholas91a10532017-06-22 11:24:38 -04001047 ++iter;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001048 break;
Ethan Nicholas91a10532017-06-22 11:24:38 -04001049 case Statement::kVarDeclarations_Kind: {
1050 VarDeclarations& decls = *((VarDeclarationsStatement&) s).fDeclaration;
1051 for (auto varIter = decls.fVars.begin(); varIter != decls.fVars.end();) {
1052 if ((*varIter)->fKind == Statement::kNop_Kind) {
1053 varIter = decls.fVars.erase(varIter);
1054 } else {
1055 ++varIter;
1056 }
1057 }
1058 if (!decls.fVars.size()) {
1059 iter = b.fNodes.erase(iter);
1060 } else {
1061 ++iter;
1062 }
1063 break;
1064 }
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001065 default:
Ethan Nicholas91a10532017-06-22 11:24:38 -04001066 ++iter;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001067 break;
1068 }
Ethan Nicholas91a10532017-06-22 11:24:38 -04001069 } else {
1070 ++iter;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001071 }
1072 }
1073 }
1074
ethannicholas22f939e2016-10-13 13:25:34 -07001075 // check for missing return
1076 if (f.fDeclaration.fReturnType != *fContext.fVoid_Type) {
1077 if (cfg.fBlocks[cfg.fExit].fEntrances.size()) {
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001078 this->error(f.fPosition, String("function can exit without returning a value"));
ethannicholas22f939e2016-10-13 13:25:34 -07001079 }
1080 }
1081}
1082
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001083std::unique_ptr<Program> Compiler::convertProgram(Program::Kind kind, String text,
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001084 const Program::Settings& settings) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001085 fErrorText = "";
1086 fErrorCount = 0;
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001087 fIRGenerator->start(&settings);
ethannicholasd598f792016-07-25 10:08:54 -07001088 std::vector<std::unique_ptr<ProgramElement>> elements;
ethannicholas5961bc92016-10-12 06:39:56 -07001089 Modifiers::Flag ignored;
ethannicholasb3058bd2016-07-01 08:22:01 -07001090 switch (kind) {
1091 case Program::kVertex_Kind:
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -04001092 fIRGenerator->convertProgram(String(SKSL_VERT_INCLUDE), *fTypes, &ignored, &elements);
ethannicholasb3058bd2016-07-01 08:22:01 -07001093 break;
1094 case Program::kFragment_Kind:
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -04001095 fIRGenerator->convertProgram(String(SKSL_FRAG_INCLUDE), *fTypes, &ignored, &elements);
ethannicholasb3058bd2016-07-01 08:22:01 -07001096 break;
Ethan Nicholas52cad152017-02-16 16:37:32 -05001097 case Program::kGeometry_Kind:
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -04001098 fIRGenerator->convertProgram(String(SKSL_GEOM_INCLUDE), *fTypes, &ignored, &elements);
Ethan Nicholas52cad152017-02-16 16:37:32 -05001099 break;
ethannicholasb3058bd2016-07-01 08:22:01 -07001100 }
ethannicholasddb37d62016-10-20 09:54:00 -07001101 fIRGenerator->fSymbolTable->markAllFunctionsBuiltin();
ethannicholas5961bc92016-10-12 06:39:56 -07001102 Modifiers::Flag defaultPrecision;
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -04001103 fIRGenerator->convertProgram(text, *fTypes, &defaultPrecision, &elements);
1104 if (!fErrorCount) {
1105 for (auto& element : elements) {
1106 if (element->fKind == ProgramElement::kFunction_Kind) {
1107 this->scanCFG((FunctionDefinition&) *element);
1108 }
1109 }
1110 }
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001111 auto result = std::unique_ptr<Program>(new Program(kind, settings, defaultPrecision, &fContext,
1112 std::move(elements),
1113 fIRGenerator->fSymbolTable,
1114 fIRGenerator->fInputs));
Ethan Nicholas3605ace2016-11-21 15:59:48 -05001115 fIRGenerator->finish();
ethannicholasb3058bd2016-07-01 08:22:01 -07001116 this->writeErrorCount();
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001117 if (fErrorCount) {
1118 return nullptr;
1119 }
1120 return result;
1121}
1122
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001123bool Compiler::toSPIRV(const Program& program, OutputStream& out) {
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001124#ifdef SK_ENABLE_SPIRV_VALIDATION
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001125 StringStream buffer;
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001126 SPIRVCodeGenerator cg(&fContext, &program, this, &buffer);
1127 bool result = cg.generateCode();
1128 if (result) {
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001129 spvtools::SpirvTools tools(SPV_ENV_VULKAN_1_0);
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001130 ASSERT(0 == buffer.size() % 4);
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001131 auto dumpmsg = [](spv_message_level_t, const char*, const spv_position_t&, const char* m) {
1132 SkDebugf("SPIR-V validation error: %s\n", m);
1133 };
1134 tools.SetMessageConsumer(dumpmsg);
1135 // Verify that the SPIR-V we produced is valid. If this assert fails, check the logs prior
1136 // to the failure to see the validation errors.
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001137 ASSERT_RESULT(tools.Validate((const uint32_t*) buffer.data(), buffer.size() / 4));
1138 out.write(buffer.data(), buffer.size());
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001139 }
1140#else
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001141 SPIRVCodeGenerator cg(&fContext, &program, this, &out);
1142 bool result = cg.generateCode();
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001143#endif
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001144 this->writeErrorCount();
Ethan Nicholasce33f102016-12-09 17:22:59 -05001145 return result;
1146}
1147
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001148bool Compiler::toSPIRV(const Program& program, String* out) {
1149 StringStream buffer;
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001150 bool result = this->toSPIRV(program, buffer);
1151 if (result) {
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001152 *out = String(buffer.data(), buffer.size());
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001153 }
1154 return result;
1155}
1156
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001157bool Compiler::toGLSL(const Program& program, OutputStream& out) {
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001158 GLSLCodeGenerator cg(&fContext, &program, this, &out);
1159 bool result = cg.generateCode();
1160 this->writeErrorCount();
1161 return result;
1162}
1163
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001164bool Compiler::toGLSL(const Program& program, String* out) {
1165 StringStream buffer;
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001166 bool result = this->toGLSL(program, buffer);
1167 if (result) {
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001168 *out = String(buffer.data(), buffer.size());
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001169 }
1170 return result;
1171}
1172
1173
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001174void Compiler::error(Position position, String msg) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001175 fErrorCount++;
1176 fErrorText += "error: " + position.description() + ": " + msg.c_str() + "\n";
1177}
1178
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001179String Compiler::errorText() {
1180 String result = fErrorText;
ethannicholasb3058bd2016-07-01 08:22:01 -07001181 return result;
1182}
1183
1184void Compiler::writeErrorCount() {
1185 if (fErrorCount) {
1186 fErrorText += to_string(fErrorCount) + " error";
1187 if (fErrorCount > 1) {
1188 fErrorText += "s";
1189 }
1190 fErrorText += "\n";
1191 }
1192}
1193
ethannicholasb3058bd2016-07-01 08:22:01 -07001194} // namespace