blob: d96515cd882af7424f986da17ca3e2d3eab316bd [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"
ethannicholasb3058bd2016-07-01 08:22:01 -070015#include "SkSLSPIRVCodeGenerator.h"
16#include "ir/SkSLExpression.h"
Ethan Nicholascb670962017-04-20 19:31:52 -040017#include "ir/SkSLExpressionStatement.h"
ethannicholasb3058bd2016-07-01 08:22:01 -070018#include "ir/SkSLIntLiteral.h"
ethannicholas5961bc92016-10-12 06:39:56 -070019#include "ir/SkSLModifiersDeclaration.h"
Ethan Nicholascb670962017-04-20 19:31:52 -040020#include "ir/SkSLNop.h"
ethannicholasb3058bd2016-07-01 08:22:01 -070021#include "ir/SkSLSymbolTable.h"
Ethan Nicholascb670962017-04-20 19:31:52 -040022#include "ir/SkSLTernaryExpression.h"
ethannicholasddb37d62016-10-20 09:54:00 -070023#include "ir/SkSLUnresolvedFunction.h"
ethannicholas22f939e2016-10-13 13:25:34 -070024#include "ir/SkSLVarDeclarations.h"
ethannicholasb3058bd2016-07-01 08:22:01 -070025
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -040026#ifdef SK_ENABLE_SPIRV_VALIDATION
27#include "spirv-tools/libspirv.hpp"
28#endif
29
ethannicholasb3058bd2016-07-01 08:22:01 -070030#define STRINGIFY(x) #x
31
32// include the built-in shader symbols as static strings
33
ethannicholas5961bc92016-10-12 06:39:56 -070034static const char* SKSL_INCLUDE =
ethannicholasb3058bd2016-07-01 08:22:01 -070035#include "sksl.include"
36;
37
ethannicholas5961bc92016-10-12 06:39:56 -070038static const char* SKSL_VERT_INCLUDE =
ethannicholasb3058bd2016-07-01 08:22:01 -070039#include "sksl_vert.include"
40;
41
ethannicholas5961bc92016-10-12 06:39:56 -070042static const char* SKSL_FRAG_INCLUDE =
ethannicholasb3058bd2016-07-01 08:22:01 -070043#include "sksl_frag.include"
44;
45
Ethan Nicholas52cad152017-02-16 16:37:32 -050046static const char* SKSL_GEOM_INCLUDE =
47#include "sksl_geom.include"
48;
49
Ethan Nicholas762466e2017-06-29 10:03:38 -040050static const char* SKSL_FP_INCLUDE =
51#include "sksl_fp.include"
52;
53
54
ethannicholasb3058bd2016-07-01 08:22:01 -070055namespace SkSL {
56
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -040057Compiler::Compiler(Flags flags)
58: fFlags(flags)
59, fErrorCount(0) {
Ethan Nicholas8feeff92017-03-30 14:11:58 -040060 auto types = std::shared_ptr<SymbolTable>(new SymbolTable(this));
61 auto symbols = std::shared_ptr<SymbolTable>(new SymbolTable(types, this));
ethannicholasd598f792016-07-25 10:08:54 -070062 fIRGenerator = new IRGenerator(&fContext, symbols, *this);
ethannicholasb3058bd2016-07-01 08:22:01 -070063 fTypes = types;
ethannicholasd598f792016-07-25 10:08:54 -070064 #define ADD_TYPE(t) types->addWithoutOwnership(fContext.f ## t ## _Type->fName, \
65 fContext.f ## t ## _Type.get())
ethannicholasb3058bd2016-07-01 08:22:01 -070066 ADD_TYPE(Void);
67 ADD_TYPE(Float);
Ethan Nicholas5af9ea32017-07-28 15:19:46 -040068 ADD_TYPE(Float2);
69 ADD_TYPE(Float3);
70 ADD_TYPE(Float4);
ethannicholasb3058bd2016-07-01 08:22:01 -070071 ADD_TYPE(Double);
Ethan Nicholas5af9ea32017-07-28 15:19:46 -040072 ADD_TYPE(Double2);
73 ADD_TYPE(Double3);
74 ADD_TYPE(Double4);
ethannicholasb3058bd2016-07-01 08:22:01 -070075 ADD_TYPE(Int);
Ethan Nicholas5af9ea32017-07-28 15:19:46 -040076 ADD_TYPE(Int2);
77 ADD_TYPE(Int3);
78 ADD_TYPE(Int4);
ethannicholasb3058bd2016-07-01 08:22:01 -070079 ADD_TYPE(UInt);
Ethan Nicholas5af9ea32017-07-28 15:19:46 -040080 ADD_TYPE(UInt2);
81 ADD_TYPE(UInt3);
82 ADD_TYPE(UInt4);
ethannicholasb3058bd2016-07-01 08:22:01 -070083 ADD_TYPE(Bool);
Ethan Nicholas5af9ea32017-07-28 15:19:46 -040084 ADD_TYPE(Bool2);
85 ADD_TYPE(Bool3);
86 ADD_TYPE(Bool4);
87 ADD_TYPE(Float2x2);
88 ADD_TYPE(Float2x3);
89 ADD_TYPE(Float2x4);
90 ADD_TYPE(Float3x2);
91 ADD_TYPE(Float3x3);
92 ADD_TYPE(Float3x4);
93 ADD_TYPE(Float4x2);
94 ADD_TYPE(Float4x3);
95 ADD_TYPE(Float4x4);
ethannicholasb3058bd2016-07-01 08:22:01 -070096 ADD_TYPE(GenType);
97 ADD_TYPE(GenDType);
98 ADD_TYPE(GenIType);
99 ADD_TYPE(GenUType);
100 ADD_TYPE(GenBType);
101 ADD_TYPE(Mat);
102 ADD_TYPE(Vec);
103 ADD_TYPE(GVec);
104 ADD_TYPE(GVec2);
105 ADD_TYPE(GVec3);
106 ADD_TYPE(GVec4);
107 ADD_TYPE(DVec);
108 ADD_TYPE(IVec);
109 ADD_TYPE(UVec);
110 ADD_TYPE(BVec);
111
112 ADD_TYPE(Sampler1D);
113 ADD_TYPE(Sampler2D);
114 ADD_TYPE(Sampler3D);
ethannicholas5961bc92016-10-12 06:39:56 -0700115 ADD_TYPE(SamplerExternalOES);
ethannicholasb3058bd2016-07-01 08:22:01 -0700116 ADD_TYPE(SamplerCube);
117 ADD_TYPE(Sampler2DRect);
118 ADD_TYPE(Sampler1DArray);
119 ADD_TYPE(Sampler2DArray);
120 ADD_TYPE(SamplerCubeArray);
121 ADD_TYPE(SamplerBuffer);
122 ADD_TYPE(Sampler2DMS);
123 ADD_TYPE(Sampler2DMSArray);
124
Brian Salomonbf7b6202016-11-11 16:08:03 -0500125 ADD_TYPE(ISampler2D);
126
Brian Salomon2a51de82016-11-16 12:06:01 -0500127 ADD_TYPE(Image2D);
128 ADD_TYPE(IImage2D);
129
Greg Daniel64773e62016-11-22 09:44:03 -0500130 ADD_TYPE(SubpassInput);
131 ADD_TYPE(SubpassInputMS);
132
ethannicholasb3058bd2016-07-01 08:22:01 -0700133 ADD_TYPE(GSampler1D);
134 ADD_TYPE(GSampler2D);
135 ADD_TYPE(GSampler3D);
136 ADD_TYPE(GSamplerCube);
137 ADD_TYPE(GSampler2DRect);
138 ADD_TYPE(GSampler1DArray);
139 ADD_TYPE(GSampler2DArray);
140 ADD_TYPE(GSamplerCubeArray);
141 ADD_TYPE(GSamplerBuffer);
142 ADD_TYPE(GSampler2DMS);
143 ADD_TYPE(GSampler2DMSArray);
144
145 ADD_TYPE(Sampler1DShadow);
146 ADD_TYPE(Sampler2DShadow);
147 ADD_TYPE(SamplerCubeShadow);
148 ADD_TYPE(Sampler2DRectShadow);
149 ADD_TYPE(Sampler1DArrayShadow);
150 ADD_TYPE(Sampler2DArrayShadow);
151 ADD_TYPE(SamplerCubeArrayShadow);
152 ADD_TYPE(GSampler2DArrayShadow);
153 ADD_TYPE(GSamplerCubeArrayShadow);
Ethan Nicholas762466e2017-06-29 10:03:38 -0400154 ADD_TYPE(ColorSpaceXform);
ethannicholasb3058bd2016-07-01 08:22:01 -0700155
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400156 String skCapsName("sk_Caps");
157 Variable* skCaps = new Variable(Position(), Modifiers(), skCapsName,
Ethan Nicholas3605ace2016-11-21 15:59:48 -0500158 *fContext.fSkCaps_Type, Variable::kGlobal_Storage);
159 fIRGenerator->fSymbolTable->add(skCapsName, std::unique_ptr<Symbol>(skCaps));
160
Ethan Nicholas762466e2017-06-29 10:03:38 -0400161 String skArgsName("sk_Args");
162 Variable* skArgs = new Variable(Position(), Modifiers(), skArgsName,
163 *fContext.fSkArgs_Type, Variable::kGlobal_Storage);
164 fIRGenerator->fSymbolTable->add(skArgsName, std::unique_ptr<Symbol>(skArgs));
165
ethannicholas5961bc92016-10-12 06:39:56 -0700166 Modifiers::Flag ignored1;
167 std::vector<std::unique_ptr<ProgramElement>> ignored2;
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -0400168 fIRGenerator->convertProgram(String(SKSL_INCLUDE), *fTypes, &ignored1, &ignored2);
ethannicholasddb37d62016-10-20 09:54:00 -0700169 fIRGenerator->fSymbolTable->markAllFunctionsBuiltin();
ethannicholasb3058bd2016-07-01 08:22:01 -0700170 ASSERT(!fErrorCount);
171}
172
173Compiler::~Compiler() {
174 delete fIRGenerator;
175}
176
ethannicholas22f939e2016-10-13 13:25:34 -0700177// add the definition created by assigning to the lvalue to the definition set
Ethan Nicholas86a43402017-01-19 13:32:00 -0500178void Compiler::addDefinition(const Expression* lvalue, std::unique_ptr<Expression>* expr,
179 DefinitionMap* definitions) {
ethannicholas22f939e2016-10-13 13:25:34 -0700180 switch (lvalue->fKind) {
181 case Expression::kVariableReference_Kind: {
182 const Variable& var = ((VariableReference*) lvalue)->fVariable;
183 if (var.fStorage == Variable::kLocal_Storage) {
184 (*definitions)[&var] = expr;
185 }
186 break;
187 }
188 case Expression::kSwizzle_Kind:
189 // We consider the variable written to as long as at least some of its components have
190 // been written to. This will lead to some false negatives (we won't catch it if you
191 // write to foo.x and then read foo.y), but being stricter could lead to false positives
Mike Klein6ad99092016-10-26 10:35:22 -0400192 // (we write to foo.x, and then pass foo to a function which happens to only read foo.x,
193 // 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 -0700194 // more complicated whole-program analysis. This is probably good enough.
Mike Klein6ad99092016-10-26 10:35:22 -0400195 this->addDefinition(((Swizzle*) lvalue)->fBase.get(),
Ethan Nicholas86a43402017-01-19 13:32:00 -0500196 (std::unique_ptr<Expression>*) &fContext.fDefined_Expression,
ethannicholas22f939e2016-10-13 13:25:34 -0700197 definitions);
198 break;
199 case Expression::kIndex_Kind:
200 // see comments in Swizzle
Mike Klein6ad99092016-10-26 10:35:22 -0400201 this->addDefinition(((IndexExpression*) lvalue)->fBase.get(),
Ethan Nicholas86a43402017-01-19 13:32:00 -0500202 (std::unique_ptr<Expression>*) &fContext.fDefined_Expression,
ethannicholas22f939e2016-10-13 13:25:34 -0700203 definitions);
204 break;
205 case Expression::kFieldAccess_Kind:
206 // see comments in Swizzle
Mike Klein6ad99092016-10-26 10:35:22 -0400207 this->addDefinition(((FieldAccess*) lvalue)->fBase.get(),
Ethan Nicholas86a43402017-01-19 13:32:00 -0500208 (std::unique_ptr<Expression>*) &fContext.fDefined_Expression,
ethannicholas22f939e2016-10-13 13:25:34 -0700209 definitions);
210 break;
211 default:
212 // not an lvalue, can't happen
213 ASSERT(false);
214 }
215}
216
217// add local variables defined by this node to the set
Mike Klein6ad99092016-10-26 10:35:22 -0400218void Compiler::addDefinitions(const BasicBlock::Node& node,
Ethan Nicholas86a43402017-01-19 13:32:00 -0500219 DefinitionMap* definitions) {
ethannicholas22f939e2016-10-13 13:25:34 -0700220 switch (node.fKind) {
221 case BasicBlock::Node::kExpression_Kind: {
Ethan Nicholascb670962017-04-20 19:31:52 -0400222 ASSERT(node.expression());
223 const Expression* expr = (Expression*) node.expression()->get();
Ethan Nicholas86a43402017-01-19 13:32:00 -0500224 switch (expr->fKind) {
225 case Expression::kBinary_Kind: {
226 BinaryExpression* b = (BinaryExpression*) expr;
227 if (b->fOperator == Token::EQ) {
228 this->addDefinition(b->fLeft.get(), &b->fRight, definitions);
229 } else if (Token::IsAssignment(b->fOperator)) {
230 this->addDefinition(
231 b->fLeft.get(),
232 (std::unique_ptr<Expression>*) &fContext.fDefined_Expression,
233 definitions);
234
235 }
236 break;
ethannicholas22f939e2016-10-13 13:25:34 -0700237 }
Ethan Nicholas86a43402017-01-19 13:32:00 -0500238 case Expression::kPrefix_Kind: {
239 const PrefixExpression* p = (PrefixExpression*) expr;
240 if (p->fOperator == Token::MINUSMINUS || p->fOperator == Token::PLUSPLUS) {
241 this->addDefinition(
242 p->fOperand.get(),
243 (std::unique_ptr<Expression>*) &fContext.fDefined_Expression,
244 definitions);
245 }
246 break;
247 }
248 case Expression::kPostfix_Kind: {
249 const PostfixExpression* p = (PostfixExpression*) expr;
250 if (p->fOperator == Token::MINUSMINUS || p->fOperator == Token::PLUSPLUS) {
251 this->addDefinition(
252 p->fOperand.get(),
253 (std::unique_ptr<Expression>*) &fContext.fDefined_Expression,
254 definitions);
Ethan Nicholas86a43402017-01-19 13:32:00 -0500255 }
256 break;
257 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400258 case Expression::kVariableReference_Kind: {
259 const VariableReference* v = (VariableReference*) expr;
260 if (v->fRefKind != VariableReference::kRead_RefKind) {
261 this->addDefinition(
262 v,
263 (std::unique_ptr<Expression>*) &fContext.fDefined_Expression,
264 definitions);
265 }
266 }
Ethan Nicholas86a43402017-01-19 13:32:00 -0500267 default:
268 break;
ethannicholas22f939e2016-10-13 13:25:34 -0700269 }
270 break;
271 }
272 case BasicBlock::Node::kStatement_Kind: {
Ethan Nicholascb670962017-04-20 19:31:52 -0400273 const Statement* stmt = (Statement*) node.statement()->get();
Ethan Nicholasb4dc4192017-06-02 10:16:28 -0400274 if (stmt->fKind == Statement::kVarDeclaration_Kind) {
275 VarDeclaration& vd = (VarDeclaration&) *stmt;
276 if (vd.fValue) {
277 (*definitions)[vd.fVar] = &vd.fValue;
ethannicholas22f939e2016-10-13 13:25:34 -0700278 }
279 }
280 break;
281 }
282 }
283}
284
285void Compiler::scanCFG(CFG* cfg, BlockId blockId, std::set<BlockId>* workList) {
286 BasicBlock& block = cfg->fBlocks[blockId];
287
288 // compute definitions after this block
Ethan Nicholas86a43402017-01-19 13:32:00 -0500289 DefinitionMap after = block.fBefore;
ethannicholas22f939e2016-10-13 13:25:34 -0700290 for (const BasicBlock::Node& n : block.fNodes) {
291 this->addDefinitions(n, &after);
292 }
293
294 // propagate definitions to exits
295 for (BlockId exitId : block.fExits) {
296 BasicBlock& exit = cfg->fBlocks[exitId];
297 for (const auto& pair : after) {
Ethan Nicholas86a43402017-01-19 13:32:00 -0500298 std::unique_ptr<Expression>* e1 = pair.second;
299 auto found = exit.fBefore.find(pair.first);
300 if (found == exit.fBefore.end()) {
301 // exit has no definition for it, just copy it
302 workList->insert(exitId);
ethannicholas22f939e2016-10-13 13:25:34 -0700303 exit.fBefore[pair.first] = e1;
304 } else {
Ethan Nicholas86a43402017-01-19 13:32:00 -0500305 // exit has a (possibly different) value already defined
306 std::unique_ptr<Expression>* e2 = exit.fBefore[pair.first];
ethannicholas22f939e2016-10-13 13:25:34 -0700307 if (e1 != e2) {
308 // definition has changed, merge and add exit block to worklist
309 workList->insert(exitId);
Ethan Nicholasaf197692017-02-27 13:26:45 -0500310 if (e1 && e2) {
311 exit.fBefore[pair.first] =
Ethan Nicholas86a43402017-01-19 13:32:00 -0500312 (std::unique_ptr<Expression>*) &fContext.fDefined_Expression;
Ethan Nicholasaf197692017-02-27 13:26:45 -0500313 } else {
314 exit.fBefore[pair.first] = nullptr;
315 }
ethannicholas22f939e2016-10-13 13:25:34 -0700316 }
317 }
318 }
319 }
320}
321
322// returns a map which maps all local variables in the function to null, indicating that their value
323// is initially unknown
Ethan Nicholas86a43402017-01-19 13:32:00 -0500324static DefinitionMap compute_start_state(const CFG& cfg) {
325 DefinitionMap result;
Mike Klein6ad99092016-10-26 10:35:22 -0400326 for (const auto& block : cfg.fBlocks) {
327 for (const auto& node : block.fNodes) {
ethannicholas22f939e2016-10-13 13:25:34 -0700328 if (node.fKind == BasicBlock::Node::kStatement_Kind) {
Ethan Nicholascb670962017-04-20 19:31:52 -0400329 ASSERT(node.statement());
330 const Statement* s = node.statement()->get();
ethannicholas22f939e2016-10-13 13:25:34 -0700331 if (s->fKind == Statement::kVarDeclarations_Kind) {
332 const VarDeclarationsStatement* vd = (const VarDeclarationsStatement*) s;
Ethan Nicholascb670962017-04-20 19:31:52 -0400333 for (const auto& decl : vd->fDeclaration->fVars) {
Ethan Nicholas91a10532017-06-22 11:24:38 -0400334 if (decl->fKind == Statement::kVarDeclaration_Kind) {
335 result[((VarDeclaration&) *decl).fVar] = nullptr;
336 }
Mike Klein6ad99092016-10-26 10:35:22 -0400337 }
ethannicholas22f939e2016-10-13 13:25:34 -0700338 }
339 }
340 }
341 }
342 return result;
343}
344
Ethan Nicholascb670962017-04-20 19:31:52 -0400345/**
346 * Returns true if assigning to this lvalue has no effect.
347 */
348static bool is_dead(const Expression& lvalue) {
349 switch (lvalue.fKind) {
350 case Expression::kVariableReference_Kind:
351 return ((VariableReference&) lvalue).fVariable.dead();
352 case Expression::kSwizzle_Kind:
353 return is_dead(*((Swizzle&) lvalue).fBase);
354 case Expression::kFieldAccess_Kind:
355 return is_dead(*((FieldAccess&) lvalue).fBase);
356 case Expression::kIndex_Kind: {
357 const IndexExpression& idx = (IndexExpression&) lvalue;
358 return is_dead(*idx.fBase) && !idx.fIndex->hasSideEffects();
359 }
360 default:
361 ABORT("invalid lvalue: %s\n", lvalue.description().c_str());
362 }
363}
ethannicholas22f939e2016-10-13 13:25:34 -0700364
Ethan Nicholascb670962017-04-20 19:31:52 -0400365/**
366 * Returns true if this is an assignment which can be collapsed down to just the right hand side due
367 * to a dead target and lack of side effects on the left hand side.
368 */
369static bool dead_assignment(const BinaryExpression& b) {
370 if (!Token::IsAssignment(b.fOperator)) {
371 return false;
372 }
373 return is_dead(*b.fLeft);
374}
375
376void Compiler::computeDataFlow(CFG* cfg) {
377 cfg->fBlocks[cfg->fStart].fBefore = compute_start_state(*cfg);
ethannicholas22f939e2016-10-13 13:25:34 -0700378 std::set<BlockId> workList;
Ethan Nicholascb670962017-04-20 19:31:52 -0400379 for (BlockId i = 0; i < cfg->fBlocks.size(); i++) {
ethannicholas22f939e2016-10-13 13:25:34 -0700380 workList.insert(i);
381 }
382 while (workList.size()) {
383 BlockId next = *workList.begin();
384 workList.erase(workList.begin());
Ethan Nicholascb670962017-04-20 19:31:52 -0400385 this->scanCFG(cfg, next, &workList);
ethannicholas22f939e2016-10-13 13:25:34 -0700386 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400387}
388
389/**
390 * Attempts to replace the expression pointed to by iter with a new one (in both the CFG and the
391 * IR). If the expression can be cleanly removed, returns true and updates the iterator to point to
392 * the newly-inserted element. Otherwise updates only the IR and returns false (and the CFG will
393 * need to be regenerated).
394 */
395bool try_replace_expression(BasicBlock* b,
396 std::vector<BasicBlock::Node>::iterator* iter,
397 std::unique_ptr<Expression>* newExpression) {
398 std::unique_ptr<Expression>* target = (*iter)->expression();
399 if (!b->tryRemoveExpression(iter)) {
400 *target = std::move(*newExpression);
401 return false;
402 }
403 *target = std::move(*newExpression);
404 return b->tryInsertExpression(iter, target);
405}
406
407/**
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400408 * Returns true if the expression is a constant numeric literal with the specified value, or a
409 * constant vector with all elements equal to the specified value.
Ethan Nicholascb670962017-04-20 19:31:52 -0400410 */
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400411bool is_constant(const Expression& expr, double value) {
Ethan Nicholascb670962017-04-20 19:31:52 -0400412 switch (expr.fKind) {
413 case Expression::kIntLiteral_Kind:
414 return ((IntLiteral&) expr).fValue == value;
415 case Expression::kFloatLiteral_Kind:
416 return ((FloatLiteral&) expr).fValue == value;
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400417 case Expression::kConstructor_Kind: {
418 Constructor& c = (Constructor&) expr;
419 if (c.fType.kind() == Type::kVector_Kind && c.isConstant()) {
420 for (int i = 0; i < c.fType.columns(); ++i) {
421 if (!is_constant(c.getVecComponent(i), value)) {
422 return false;
423 }
424 }
425 return true;
426 }
427 return false;
428 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400429 default:
430 return false;
431 }
432}
433
434/**
435 * Collapses the binary expression pointed to by iter down to just the right side (in both the IR
436 * and CFG structures).
437 */
438void delete_left(BasicBlock* b,
439 std::vector<BasicBlock::Node>::iterator* iter,
440 bool* outUpdated,
441 bool* outNeedsRescan) {
442 *outUpdated = true;
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400443 std::unique_ptr<Expression>* target = (*iter)->expression();
444 ASSERT((*target)->fKind == Expression::kBinary_Kind);
445 BinaryExpression& bin = (BinaryExpression&) **target;
446 bool result;
447 if (bin.fOperator == Token::EQ) {
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400448 result = b->tryRemoveLValueBefore(iter, bin.fLeft.get());
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400449 } else {
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400450 result = b->tryRemoveExpressionBefore(iter, bin.fLeft.get());
Ethan Nicholascb670962017-04-20 19:31:52 -0400451 }
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400452 *target = std::move(bin.fRight);
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400453 if (!result) {
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400454 *outNeedsRescan = true;
455 return;
456 }
457 if (*iter == b->fNodes.begin()) {
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400458 *outNeedsRescan = true;
459 return;
460 }
461 --(*iter);
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400462 if ((*iter)->fKind != BasicBlock::Node::kExpression_Kind ||
463 (*iter)->expression() != &bin.fRight) {
464 *outNeedsRescan = true;
465 return;
466 }
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400467 *iter = b->fNodes.erase(*iter);
468 ASSERT((*iter)->expression() == target);
Ethan Nicholascb670962017-04-20 19:31:52 -0400469}
470
471/**
472 * Collapses the binary expression pointed to by iter down to just the left side (in both the IR and
473 * CFG structures).
474 */
475void delete_right(BasicBlock* b,
476 std::vector<BasicBlock::Node>::iterator* iter,
477 bool* outUpdated,
478 bool* outNeedsRescan) {
479 *outUpdated = true;
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400480 std::unique_ptr<Expression>* target = (*iter)->expression();
481 ASSERT((*target)->fKind == Expression::kBinary_Kind);
482 BinaryExpression& bin = (BinaryExpression&) **target;
483 if (!b->tryRemoveExpressionBefore(iter, bin.fRight.get())) {
484 *target = std::move(bin.fLeft);
Ethan Nicholascb670962017-04-20 19:31:52 -0400485 *outNeedsRescan = true;
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400486 return;
Ethan Nicholascb670962017-04-20 19:31:52 -0400487 }
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400488 *target = std::move(bin.fLeft);
489 if (*iter == b->fNodes.begin()) {
490 *outNeedsRescan = true;
491 return;
492 }
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400493 --(*iter);
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400494 if (((*iter)->fKind != BasicBlock::Node::kExpression_Kind ||
495 (*iter)->expression() != &bin.fLeft)) {
496 *outNeedsRescan = true;
497 return;
498 }
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400499 *iter = b->fNodes.erase(*iter);
500 ASSERT((*iter)->expression() == target);
Ethan Nicholascb670962017-04-20 19:31:52 -0400501}
502
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400503/**
504 * Constructs the specified type using a single argument.
505 */
506static std::unique_ptr<Expression> construct(const Type& type, std::unique_ptr<Expression> v) {
507 std::vector<std::unique_ptr<Expression>> args;
508 args.push_back(std::move(v));
509 auto result = std::unique_ptr<Expression>(new Constructor(Position(), type, std::move(args)));
510 return result;
511}
512
513/**
514 * Used in the implementations of vectorize_left and vectorize_right. Given a vector type and an
515 * expression x, deletes the expression pointed to by iter and replaces it with <type>(x).
516 */
517static void vectorize(BasicBlock* b,
518 std::vector<BasicBlock::Node>::iterator* iter,
519 const Type& type,
520 std::unique_ptr<Expression>* otherExpression,
521 bool* outUpdated,
522 bool* outNeedsRescan) {
523 ASSERT((*(*iter)->expression())->fKind == Expression::kBinary_Kind);
524 ASSERT(type.kind() == Type::kVector_Kind);
525 ASSERT((*otherExpression)->fType.kind() == Type::kScalar_Kind);
526 *outUpdated = true;
527 std::unique_ptr<Expression>* target = (*iter)->expression();
528 if (!b->tryRemoveExpression(iter)) {
529 *target = construct(type, std::move(*otherExpression));
530 *outNeedsRescan = true;
531 } else {
532 *target = construct(type, std::move(*otherExpression));
533 if (!b->tryInsertExpression(iter, target)) {
534 *outNeedsRescan = true;
535 }
536 }
537}
538
539/**
540 * Given a binary expression of the form x <op> vec<n>(y), deletes the right side and vectorizes the
541 * left to yield vec<n>(x).
542 */
543static void vectorize_left(BasicBlock* b,
544 std::vector<BasicBlock::Node>::iterator* iter,
545 bool* outUpdated,
546 bool* outNeedsRescan) {
547 BinaryExpression& bin = (BinaryExpression&) **(*iter)->expression();
548 vectorize(b, iter, bin.fRight->fType, &bin.fLeft, outUpdated, outNeedsRescan);
549}
550
551/**
552 * Given a binary expression of the form vec<n>(x) <op> y, deletes the left side and vectorizes the
553 * right to yield vec<n>(y).
554 */
555static void vectorize_right(BasicBlock* b,
556 std::vector<BasicBlock::Node>::iterator* iter,
557 bool* outUpdated,
558 bool* outNeedsRescan) {
559 BinaryExpression& bin = (BinaryExpression&) **(*iter)->expression();
560 vectorize(b, iter, bin.fLeft->fType, &bin.fRight, outUpdated, outNeedsRescan);
561}
562
563// Mark that an expression which we were writing to is no longer being written to
564void clear_write(const Expression& expr) {
565 switch (expr.fKind) {
566 case Expression::kVariableReference_Kind: {
567 ((VariableReference&) expr).setRefKind(VariableReference::kRead_RefKind);
568 break;
569 }
570 case Expression::kFieldAccess_Kind:
571 clear_write(*((FieldAccess&) expr).fBase);
572 break;
573 case Expression::kSwizzle_Kind:
574 clear_write(*((Swizzle&) expr).fBase);
575 break;
576 case Expression::kIndex_Kind:
577 clear_write(*((IndexExpression&) expr).fBase);
578 break;
579 default:
580 ABORT("shouldn't be writing to this kind of expression\n");
581 break;
582 }
583}
584
Ethan Nicholascb670962017-04-20 19:31:52 -0400585void Compiler::simplifyExpression(DefinitionMap& definitions,
586 BasicBlock& b,
587 std::vector<BasicBlock::Node>::iterator* iter,
588 std::unordered_set<const Variable*>* undefinedVariables,
589 bool* outUpdated,
590 bool* outNeedsRescan) {
591 Expression* expr = (*iter)->expression()->get();
592 ASSERT(expr);
593 if ((*iter)->fConstantPropagation) {
594 std::unique_ptr<Expression> optimized = expr->constantPropagate(*fIRGenerator, definitions);
595 if (optimized) {
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400596 *outUpdated = true;
Ethan Nicholascb670962017-04-20 19:31:52 -0400597 if (!try_replace_expression(&b, iter, &optimized)) {
598 *outNeedsRescan = true;
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400599 return;
Ethan Nicholascb670962017-04-20 19:31:52 -0400600 }
601 ASSERT((*iter)->fKind == BasicBlock::Node::kExpression_Kind);
602 expr = (*iter)->expression()->get();
Ethan Nicholascb670962017-04-20 19:31:52 -0400603 }
604 }
605 switch (expr->fKind) {
606 case Expression::kVariableReference_Kind: {
607 const Variable& var = ((VariableReference*) expr)->fVariable;
608 if (var.fStorage == Variable::kLocal_Storage && !definitions[&var] &&
609 (*undefinedVariables).find(&var) == (*undefinedVariables).end()) {
610 (*undefinedVariables).insert(&var);
611 this->error(expr->fPosition,
612 "'" + var.fName + "' has not been assigned");
613 }
614 break;
615 }
616 case Expression::kTernary_Kind: {
617 TernaryExpression* t = (TernaryExpression*) expr;
618 if (t->fTest->fKind == Expression::kBoolLiteral_Kind) {
619 // ternary has a constant test, replace it with either the true or
620 // false branch
621 if (((BoolLiteral&) *t->fTest).fValue) {
622 (*iter)->setExpression(std::move(t->fIfTrue));
623 } else {
624 (*iter)->setExpression(std::move(t->fIfFalse));
625 }
626 *outUpdated = true;
627 *outNeedsRescan = true;
628 }
629 break;
630 }
631 case Expression::kBinary_Kind: {
Ethan Nicholascb670962017-04-20 19:31:52 -0400632 BinaryExpression* bin = (BinaryExpression*) expr;
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400633 if (dead_assignment(*bin)) {
634 delete_left(&b, iter, outUpdated, outNeedsRescan);
635 break;
636 }
637 // collapse useless expressions like x * 1 or x + 0
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400638 if (((bin->fLeft->fType.kind() != Type::kScalar_Kind) &&
639 (bin->fLeft->fType.kind() != Type::kVector_Kind)) ||
640 ((bin->fRight->fType.kind() != Type::kScalar_Kind) &&
641 (bin->fRight->fType.kind() != Type::kVector_Kind))) {
642 break;
643 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400644 switch (bin->fOperator) {
645 case Token::STAR:
646 if (is_constant(*bin->fLeft, 1)) {
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400647 if (bin->fLeft->fType.kind() == Type::kVector_Kind &&
648 bin->fRight->fType.kind() == Type::kScalar_Kind) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400649 // float4(1) * x -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400650 vectorize_right(&b, iter, outUpdated, outNeedsRescan);
651 } else {
652 // 1 * x -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400653 // 1 * float4(x) -> float4(x)
654 // float4(1) * float4(x) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400655 delete_left(&b, iter, outUpdated, outNeedsRescan);
656 }
657 }
658 else if (is_constant(*bin->fLeft, 0)) {
659 if (bin->fLeft->fType.kind() == Type::kScalar_Kind &&
660 bin->fRight->fType.kind() == Type::kVector_Kind) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400661 // 0 * float4(x) -> float4(0)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400662 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
663 } else {
664 // 0 * x -> 0
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400665 // float4(0) * x -> float4(0)
666 // float4(0) * float4(x) -> float4(0)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400667 delete_right(&b, iter, outUpdated, outNeedsRescan);
668 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400669 }
670 else if (is_constant(*bin->fRight, 1)) {
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400671 if (bin->fLeft->fType.kind() == Type::kScalar_Kind &&
672 bin->fRight->fType.kind() == Type::kVector_Kind) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400673 // x * float4(1) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400674 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
675 } else {
676 // x * 1 -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400677 // float4(x) * 1 -> float4(x)
678 // float4(x) * float4(1) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400679 delete_right(&b, iter, outUpdated, outNeedsRescan);
680 }
681 }
682 else if (is_constant(*bin->fRight, 0)) {
683 if (bin->fLeft->fType.kind() == Type::kVector_Kind &&
684 bin->fRight->fType.kind() == Type::kScalar_Kind) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400685 // float4(x) * 0 -> float4(0)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400686 vectorize_right(&b, iter, outUpdated, outNeedsRescan);
687 } else {
688 // x * 0 -> 0
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400689 // x * float4(0) -> float4(0)
690 // float4(x) * float4(0) -> float4(0)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400691 delete_left(&b, iter, outUpdated, outNeedsRescan);
692 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400693 }
694 break;
Ethan Nicholas56e42712017-04-21 10:23:37 -0400695 case Token::PLUS:
Ethan Nicholascb670962017-04-20 19:31:52 -0400696 if (is_constant(*bin->fLeft, 0)) {
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400697 if (bin->fLeft->fType.kind() == Type::kVector_Kind &&
698 bin->fRight->fType.kind() == Type::kScalar_Kind) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400699 // float4(0) + x -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400700 vectorize_right(&b, iter, outUpdated, outNeedsRescan);
701 } else {
702 // 0 + x -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400703 // 0 + float4(x) -> float4(x)
704 // float4(0) + float4(x) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400705 delete_left(&b, iter, outUpdated, outNeedsRescan);
706 }
707 } else if (is_constant(*bin->fRight, 0)) {
708 if (bin->fLeft->fType.kind() == Type::kScalar_Kind &&
709 bin->fRight->fType.kind() == Type::kVector_Kind) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400710 // x + float4(0) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400711 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
712 } else {
713 // x + 0 -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400714 // float4(x) + 0 -> float4(x)
715 // float4(x) + float4(0) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400716 delete_right(&b, iter, outUpdated, outNeedsRescan);
717 }
Ethan Nicholas56e42712017-04-21 10:23:37 -0400718 }
719 break;
720 case Token::MINUS:
721 if (is_constant(*bin->fRight, 0)) {
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400722 if (bin->fLeft->fType.kind() == Type::kScalar_Kind &&
723 bin->fRight->fType.kind() == Type::kVector_Kind) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400724 // x - float4(0) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400725 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
726 } else {
727 // x - 0 -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400728 // float4(x) - 0 -> float4(x)
729 // float4(x) - float4(0) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400730 delete_right(&b, iter, outUpdated, outNeedsRescan);
731 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400732 }
733 break;
734 case Token::SLASH:
735 if (is_constant(*bin->fRight, 1)) {
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400736 if (bin->fLeft->fType.kind() == Type::kScalar_Kind &&
737 bin->fRight->fType.kind() == Type::kVector_Kind) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400738 // x / float4(1) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400739 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
740 } else {
741 // x / 1 -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400742 // float4(x) / 1 -> float4(x)
743 // float4(x) / float4(1) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400744 delete_right(&b, iter, outUpdated, outNeedsRescan);
745 }
746 } else if (is_constant(*bin->fLeft, 0)) {
747 if (bin->fLeft->fType.kind() == Type::kScalar_Kind &&
748 bin->fRight->fType.kind() == Type::kVector_Kind) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400749 // 0 / float4(x) -> float4(0)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400750 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
751 } else {
752 // 0 / x -> 0
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400753 // float4(0) / x -> float4(0)
754 // float4(0) / float4(x) -> float4(0)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400755 delete_right(&b, iter, outUpdated, outNeedsRescan);
756 }
757 }
758 break;
759 case Token::PLUSEQ:
760 if (is_constant(*bin->fRight, 0)) {
761 clear_write(*bin->fLeft);
762 delete_right(&b, iter, outUpdated, outNeedsRescan);
763 }
764 break;
765 case Token::MINUSEQ:
766 if (is_constant(*bin->fRight, 0)) {
767 clear_write(*bin->fLeft);
768 delete_right(&b, iter, outUpdated, outNeedsRescan);
769 }
770 break;
771 case Token::STAREQ:
772 if (is_constant(*bin->fRight, 1)) {
773 clear_write(*bin->fLeft);
774 delete_right(&b, iter, outUpdated, outNeedsRescan);
775 }
776 break;
777 case Token::SLASHEQ:
778 if (is_constant(*bin->fRight, 1)) {
779 clear_write(*bin->fLeft);
Ethan Nicholascb670962017-04-20 19:31:52 -0400780 delete_right(&b, iter, outUpdated, outNeedsRescan);
781 }
782 break;
783 default:
784 break;
785 }
786 }
787 default:
788 break;
789 }
790}
791
Ethan Nicholas5ac13c22017-05-10 15:06:17 -0400792// returns true if this statement could potentially execute a break at the current level (we ignore
793// nested loops and switches, since any breaks inside of them will merely break the loop / switch)
794static bool contains_break(Statement& s) {
795 switch (s.fKind) {
796 case Statement::kBlock_Kind:
797 for (const auto& sub : ((Block&) s).fStatements) {
798 if (contains_break(*sub)) {
799 return true;
800 }
801 }
802 return false;
803 case Statement::kBreak_Kind:
804 return true;
805 case Statement::kIf_Kind: {
806 const IfStatement& i = (IfStatement&) s;
807 return contains_break(*i.fIfTrue) || (i.fIfFalse && contains_break(*i.fIfFalse));
808 }
809 default:
810 return false;
811 }
812}
813
814// Returns a block containing all of the statements that will be run if the given case matches
815// (which, owing to the statements being owned by unique_ptrs, means the switch itself will be
816// broken by this call and must then be discarded).
817// Returns null (and leaves the switch unmodified) if no such simple reduction is possible, such as
818// when break statements appear inside conditionals.
819static std::unique_ptr<Statement> block_for_case(SwitchStatement* s, SwitchCase* c) {
820 bool capturing = false;
821 std::vector<std::unique_ptr<Statement>*> statementPtrs;
822 for (const auto& current : s->fCases) {
823 if (current.get() == c) {
824 capturing = true;
825 }
826 if (capturing) {
827 for (auto& stmt : current->fStatements) {
828 if (stmt->fKind == Statement::kBreak_Kind) {
829 capturing = false;
830 break;
831 }
832 if (contains_break(*stmt)) {
833 return nullptr;
834 }
835 statementPtrs.push_back(&stmt);
836 }
837 if (!capturing) {
838 break;
839 }
840 }
841 }
842 std::vector<std::unique_ptr<Statement>> statements;
843 for (const auto& s : statementPtrs) {
844 statements.push_back(std::move(*s));
845 }
Ethan Nicholasc432b0c2017-07-18 13:22:37 -0400846 return std::unique_ptr<Statement>(new Block(Position(), std::move(statements), s->fSymbols));
Ethan Nicholas5ac13c22017-05-10 15:06:17 -0400847}
848
Ethan Nicholascb670962017-04-20 19:31:52 -0400849void Compiler::simplifyStatement(DefinitionMap& definitions,
Ethan Nicholas5ac13c22017-05-10 15:06:17 -0400850 BasicBlock& b,
851 std::vector<BasicBlock::Node>::iterator* iter,
852 std::unordered_set<const Variable*>* undefinedVariables,
853 bool* outUpdated,
854 bool* outNeedsRescan) {
Ethan Nicholascb670962017-04-20 19:31:52 -0400855 Statement* stmt = (*iter)->statement()->get();
856 switch (stmt->fKind) {
Ethan Nicholasb4dc4192017-06-02 10:16:28 -0400857 case Statement::kVarDeclaration_Kind: {
858 const auto& varDecl = (VarDeclaration&) *stmt;
859 if (varDecl.fVar->dead() &&
860 (!varDecl.fValue ||
861 !varDecl.fValue->hasSideEffects())) {
862 if (varDecl.fValue) {
863 ASSERT((*iter)->statement()->get() == stmt);
864 if (!b.tryRemoveExpressionBefore(iter, varDecl.fValue.get())) {
865 *outNeedsRescan = true;
Ethan Nicholascb670962017-04-20 19:31:52 -0400866 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400867 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400868 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
Ethan Nicholasb4dc4192017-06-02 10:16:28 -0400869 *outUpdated = true;
Ethan Nicholascb670962017-04-20 19:31:52 -0400870 }
871 break;
872 }
873 case Statement::kIf_Kind: {
874 IfStatement& i = (IfStatement&) *stmt;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -0400875 if (i.fTest->fKind == Expression::kBoolLiteral_Kind) {
876 // constant if, collapse down to a single branch
877 if (((BoolLiteral&) *i.fTest).fValue) {
878 ASSERT(i.fIfTrue);
879 (*iter)->setStatement(std::move(i.fIfTrue));
880 } else {
881 if (i.fIfFalse) {
882 (*iter)->setStatement(std::move(i.fIfFalse));
883 } else {
884 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
885 }
886 }
887 *outUpdated = true;
888 *outNeedsRescan = true;
889 break;
890 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400891 if (i.fIfFalse && i.fIfFalse->isEmpty()) {
892 // else block doesn't do anything, remove it
893 i.fIfFalse.reset();
894 *outUpdated = true;
895 *outNeedsRescan = true;
896 }
897 if (!i.fIfFalse && i.fIfTrue->isEmpty()) {
898 // if block doesn't do anything, no else block
899 if (i.fTest->hasSideEffects()) {
900 // test has side effects, keep it
901 (*iter)->setStatement(std::unique_ptr<Statement>(
902 new ExpressionStatement(std::move(i.fTest))));
903 } else {
904 // no if, no else, no test side effects, kill the whole if
905 // statement
906 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
907 }
908 *outUpdated = true;
909 *outNeedsRescan = true;
910 }
911 break;
912 }
Ethan Nicholas5ac13c22017-05-10 15:06:17 -0400913 case Statement::kSwitch_Kind: {
914 SwitchStatement& s = (SwitchStatement&) *stmt;
915 if (s.fValue->isConstant()) {
916 // switch is constant, replace it with the case that matches
917 bool found = false;
918 SwitchCase* defaultCase = nullptr;
919 for (const auto& c : s.fCases) {
920 if (!c->fValue) {
921 defaultCase = c.get();
922 continue;
923 }
924 ASSERT(c->fValue->fKind == s.fValue->fKind);
925 found = c->fValue->compareConstant(fContext, *s.fValue);
926 if (found) {
927 std::unique_ptr<Statement> newBlock = block_for_case(&s, c.get());
928 if (newBlock) {
929 (*iter)->setStatement(std::move(newBlock));
930 break;
931 } else {
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -0400932 if (s.fIsStatic && !(fFlags & kPermitInvalidStaticTests_Flag)) {
Ethan Nicholas5ac13c22017-05-10 15:06:17 -0400933 this->error(s.fPosition,
934 "static switch contains non-static conditional break");
935 s.fIsStatic = false;
936 }
937 return; // can't simplify
938 }
939 }
940 }
941 if (!found) {
942 // no matching case. use default if it exists, or kill the whole thing
943 if (defaultCase) {
944 std::unique_ptr<Statement> newBlock = block_for_case(&s, defaultCase);
945 if (newBlock) {
946 (*iter)->setStatement(std::move(newBlock));
947 } else {
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -0400948 if (s.fIsStatic && !(fFlags & kPermitInvalidStaticTests_Flag)) {
Ethan Nicholas5ac13c22017-05-10 15:06:17 -0400949 this->error(s.fPosition,
950 "static switch contains non-static conditional break");
951 s.fIsStatic = false;
952 }
953 return; // can't simplify
954 }
955 } else {
956 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
957 }
958 }
959 *outUpdated = true;
960 *outNeedsRescan = true;
961 }
962 break;
963 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400964 case Statement::kExpression_Kind: {
965 ExpressionStatement& e = (ExpressionStatement&) *stmt;
966 ASSERT((*iter)->statement()->get() == &e);
Ethan Nicholascb670962017-04-20 19:31:52 -0400967 if (!e.fExpression->hasSideEffects()) {
968 // Expression statement with no side effects, kill it
969 if (!b.tryRemoveExpressionBefore(iter, e.fExpression.get())) {
970 *outNeedsRescan = true;
971 }
972 ASSERT((*iter)->statement()->get() == stmt);
973 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
974 *outUpdated = true;
975 }
976 break;
977 }
978 default:
979 break;
980 }
981}
982
983void Compiler::scanCFG(FunctionDefinition& f) {
984 CFG cfg = CFGGenerator().getCFG(f);
985 this->computeDataFlow(&cfg);
ethannicholas22f939e2016-10-13 13:25:34 -0700986
987 // check for unreachable code
988 for (size_t i = 0; i < cfg.fBlocks.size(); i++) {
Mike Klein6ad99092016-10-26 10:35:22 -0400989 if (i != cfg.fStart && !cfg.fBlocks[i].fEntrances.size() &&
ethannicholas22f939e2016-10-13 13:25:34 -0700990 cfg.fBlocks[i].fNodes.size()) {
Ethan Nicholas86a43402017-01-19 13:32:00 -0500991 Position p;
992 switch (cfg.fBlocks[i].fNodes[0].fKind) {
993 case BasicBlock::Node::kStatement_Kind:
Ethan Nicholascb670962017-04-20 19:31:52 -0400994 p = (*cfg.fBlocks[i].fNodes[0].statement())->fPosition;
Ethan Nicholas86a43402017-01-19 13:32:00 -0500995 break;
996 case BasicBlock::Node::kExpression_Kind:
Ethan Nicholascb670962017-04-20 19:31:52 -0400997 p = (*cfg.fBlocks[i].fNodes[0].expression())->fPosition;
Ethan Nicholas86a43402017-01-19 13:32:00 -0500998 break;
999 }
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001000 this->error(p, String("unreachable"));
ethannicholas22f939e2016-10-13 13:25:34 -07001001 }
1002 }
1003 if (fErrorCount) {
1004 return;
1005 }
1006
Ethan Nicholascb670962017-04-20 19:31:52 -04001007 // check for dead code & undefined variables, perform constant propagation
1008 std::unordered_set<const Variable*> undefinedVariables;
1009 bool updated;
1010 bool needsRescan = false;
1011 do {
1012 if (needsRescan) {
1013 cfg = CFGGenerator().getCFG(f);
1014 this->computeDataFlow(&cfg);
1015 needsRescan = false;
Ethan Nicholas113628d2017-02-02 16:11:39 -05001016 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001017
1018 updated = false;
1019 for (BasicBlock& b : cfg.fBlocks) {
1020 DefinitionMap definitions = b.fBefore;
1021
1022 for (auto iter = b.fNodes.begin(); iter != b.fNodes.end() && !needsRescan; ++iter) {
1023 if (iter->fKind == BasicBlock::Node::kExpression_Kind) {
1024 this->simplifyExpression(definitions, b, &iter, &undefinedVariables, &updated,
1025 &needsRescan);
1026 } else {
1027 this->simplifyStatement(definitions, b, &iter, &undefinedVariables, &updated,
1028 &needsRescan);
1029 }
Ethan Nicholas4b330df2017-05-17 10:52:55 -04001030 if (needsRescan) {
1031 break;
1032 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001033 this->addDefinitions(*iter, &definitions);
1034 }
1035 }
1036 } while (updated);
1037 ASSERT(!needsRescan);
ethannicholas22f939e2016-10-13 13:25:34 -07001038
Ethan Nicholas91a10532017-06-22 11:24:38 -04001039 // verify static ifs & switches, clean up dead variable decls
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001040 for (BasicBlock& b : cfg.fBlocks) {
1041 DefinitionMap definitions = b.fBefore;
1042
Ethan Nicholas91a10532017-06-22 11:24:38 -04001043 for (auto iter = b.fNodes.begin(); iter != b.fNodes.end() && !needsRescan;) {
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001044 if (iter->fKind == BasicBlock::Node::kStatement_Kind) {
1045 const Statement& s = **iter->statement();
1046 switch (s.fKind) {
1047 case Statement::kIf_Kind:
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -04001048 if (((const IfStatement&) s).fIsStatic &&
1049 !(fFlags & kPermitInvalidStaticTests_Flag)) {
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001050 this->error(s.fPosition, "static if has non-static test");
1051 }
Ethan Nicholas91a10532017-06-22 11:24:38 -04001052 ++iter;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001053 break;
1054 case Statement::kSwitch_Kind:
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -04001055 if (((const SwitchStatement&) s).fIsStatic &&
1056 !(fFlags & kPermitInvalidStaticTests_Flag)) {
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001057 this->error(s.fPosition, "static switch has non-static test");
1058 }
Ethan Nicholas91a10532017-06-22 11:24:38 -04001059 ++iter;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001060 break;
Ethan Nicholas91a10532017-06-22 11:24:38 -04001061 case Statement::kVarDeclarations_Kind: {
1062 VarDeclarations& decls = *((VarDeclarationsStatement&) s).fDeclaration;
1063 for (auto varIter = decls.fVars.begin(); varIter != decls.fVars.end();) {
1064 if ((*varIter)->fKind == Statement::kNop_Kind) {
1065 varIter = decls.fVars.erase(varIter);
1066 } else {
1067 ++varIter;
1068 }
1069 }
1070 if (!decls.fVars.size()) {
1071 iter = b.fNodes.erase(iter);
1072 } else {
1073 ++iter;
1074 }
1075 break;
1076 }
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001077 default:
Ethan Nicholas91a10532017-06-22 11:24:38 -04001078 ++iter;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001079 break;
1080 }
Ethan Nicholas91a10532017-06-22 11:24:38 -04001081 } else {
1082 ++iter;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001083 }
1084 }
1085 }
1086
ethannicholas22f939e2016-10-13 13:25:34 -07001087 // check for missing return
1088 if (f.fDeclaration.fReturnType != *fContext.fVoid_Type) {
1089 if (cfg.fBlocks[cfg.fExit].fEntrances.size()) {
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001090 this->error(f.fPosition, String("function can exit without returning a value"));
ethannicholas22f939e2016-10-13 13:25:34 -07001091 }
1092 }
1093}
1094
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001095std::unique_ptr<Program> Compiler::convertProgram(Program::Kind kind, String text,
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001096 const Program::Settings& settings) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001097 fErrorText = "";
1098 fErrorCount = 0;
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001099 fIRGenerator->start(&settings);
ethannicholasd598f792016-07-25 10:08:54 -07001100 std::vector<std::unique_ptr<ProgramElement>> elements;
ethannicholas5961bc92016-10-12 06:39:56 -07001101 Modifiers::Flag ignored;
ethannicholasb3058bd2016-07-01 08:22:01 -07001102 switch (kind) {
1103 case Program::kVertex_Kind:
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -04001104 fIRGenerator->convertProgram(String(SKSL_VERT_INCLUDE), *fTypes, &ignored, &elements);
ethannicholasb3058bd2016-07-01 08:22:01 -07001105 break;
1106 case Program::kFragment_Kind:
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -04001107 fIRGenerator->convertProgram(String(SKSL_FRAG_INCLUDE), *fTypes, &ignored, &elements);
ethannicholasb3058bd2016-07-01 08:22:01 -07001108 break;
Ethan Nicholas52cad152017-02-16 16:37:32 -05001109 case Program::kGeometry_Kind:
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -04001110 fIRGenerator->convertProgram(String(SKSL_GEOM_INCLUDE), *fTypes, &ignored, &elements);
Ethan Nicholas52cad152017-02-16 16:37:32 -05001111 break;
Ethan Nicholas762466e2017-06-29 10:03:38 -04001112 case Program::kFragmentProcessor_Kind:
1113 fIRGenerator->convertProgram(String(SKSL_FP_INCLUDE), *fTypes, &ignored, &elements);
1114 break;
ethannicholasb3058bd2016-07-01 08:22:01 -07001115 }
ethannicholasddb37d62016-10-20 09:54:00 -07001116 fIRGenerator->fSymbolTable->markAllFunctionsBuiltin();
ethannicholas5961bc92016-10-12 06:39:56 -07001117 Modifiers::Flag defaultPrecision;
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -04001118 fIRGenerator->convertProgram(text, *fTypes, &defaultPrecision, &elements);
1119 if (!fErrorCount) {
1120 for (auto& element : elements) {
1121 if (element->fKind == ProgramElement::kFunction_Kind) {
1122 this->scanCFG((FunctionDefinition&) *element);
1123 }
1124 }
1125 }
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001126 auto result = std::unique_ptr<Program>(new Program(kind, settings, defaultPrecision, &fContext,
1127 std::move(elements),
1128 fIRGenerator->fSymbolTable,
1129 fIRGenerator->fInputs));
Ethan Nicholas3605ace2016-11-21 15:59:48 -05001130 fIRGenerator->finish();
ethannicholasb3058bd2016-07-01 08:22:01 -07001131 this->writeErrorCount();
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001132 if (fErrorCount) {
1133 return nullptr;
1134 }
1135 return result;
1136}
1137
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001138bool Compiler::toSPIRV(const Program& program, OutputStream& out) {
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001139#ifdef SK_ENABLE_SPIRV_VALIDATION
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001140 StringStream buffer;
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001141 SPIRVCodeGenerator cg(&fContext, &program, this, &buffer);
1142 bool result = cg.generateCode();
1143 if (result) {
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001144 spvtools::SpirvTools tools(SPV_ENV_VULKAN_1_0);
Ethan Nicholas762466e2017-06-29 10:03:38 -04001145 const String& data = buffer.str();
1146 ASSERT(0 == data.size() % 4);
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001147 auto dumpmsg = [](spv_message_level_t, const char*, const spv_position_t&, const char* m) {
1148 SkDebugf("SPIR-V validation error: %s\n", m);
1149 };
1150 tools.SetMessageConsumer(dumpmsg);
1151 // Verify that the SPIR-V we produced is valid. If this assert fails, check the logs prior
1152 // to the failure to see the validation errors.
Ethan Nicholas762466e2017-06-29 10:03:38 -04001153 ASSERT_RESULT(tools.Validate((const uint32_t*) data.c_str(), data.size() / 4));
1154 out.write(data.c_str(), data.size());
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001155 }
1156#else
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001157 SPIRVCodeGenerator cg(&fContext, &program, this, &out);
1158 bool result = cg.generateCode();
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001159#endif
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001160 this->writeErrorCount();
Ethan Nicholasce33f102016-12-09 17:22:59 -05001161 return result;
1162}
1163
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001164bool Compiler::toSPIRV(const Program& program, String* out) {
1165 StringStream buffer;
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001166 bool result = this->toSPIRV(program, buffer);
1167 if (result) {
Ethan Nicholas762466e2017-06-29 10:03:38 -04001168 *out = buffer.str();
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001169 }
1170 return result;
1171}
1172
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001173bool Compiler::toGLSL(const Program& program, OutputStream& out) {
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001174 GLSLCodeGenerator cg(&fContext, &program, this, &out);
1175 bool result = cg.generateCode();
1176 this->writeErrorCount();
1177 return result;
1178}
1179
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001180bool Compiler::toGLSL(const Program& program, String* out) {
1181 StringStream buffer;
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001182 bool result = this->toGLSL(program, buffer);
1183 if (result) {
Ethan Nicholas762466e2017-06-29 10:03:38 -04001184 *out = buffer.str();
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001185 }
1186 return result;
1187}
1188
Ethan Nicholas762466e2017-06-29 10:03:38 -04001189bool Compiler::toCPP(const Program& program, String name, OutputStream& out) {
1190 CPPCodeGenerator cg(&fContext, &program, this, name, &out);
1191 bool result = cg.generateCode();
1192 this->writeErrorCount();
1193 return result;
1194}
1195
1196bool Compiler::toH(const Program& program, String name, OutputStream& out) {
1197 HCodeGenerator cg(&program, this, name, &out);
1198 bool result = cg.generateCode();
1199 this->writeErrorCount();
1200 return result;
1201}
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001202
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001203void Compiler::error(Position position, String msg) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001204 fErrorCount++;
1205 fErrorText += "error: " + position.description() + ": " + msg.c_str() + "\n";
1206}
1207
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001208String Compiler::errorText() {
1209 String result = fErrorText;
ethannicholasb3058bd2016-07-01 08:22:01 -07001210 return result;
1211}
1212
1213void Compiler::writeErrorCount() {
1214 if (fErrorCount) {
1215 fErrorText += to_string(fErrorCount) + " error";
1216 if (fErrorCount > 1) {
1217 fErrorText += "s";
1218 }
1219 fErrorText += "\n";
1220 }
1221}
1222
ethannicholasb3058bd2016-07-01 08:22:01 -07001223} // namespace