blob: 7db9440e7ff013d31fd45c106167166969ef0393 [file] [log] [blame]
ethannicholasb3058bd2016-07-01 08:22:01 -07001/*
2 * Copyright 2016 Google Inc.
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
Mike Klein6ad99092016-10-26 10:35:22 -04007
ethannicholasb3058bd2016-07-01 08:22:01 -07008#include "SkSLCompiler.h"
9
ethannicholas22f939e2016-10-13 13:25:34 -070010#include "SkSLCFGGenerator.h"
Ethan Nicholas762466e2017-06-29 10:03:38 -040011#include "SkSLCPPCodeGenerator.h"
Ethan Nicholas941e7e22016-12-12 15:33:30 -050012#include "SkSLGLSLCodeGenerator.h"
Ethan Nicholas762466e2017-06-29 10:03:38 -040013#include "SkSLHCodeGenerator.h"
ethannicholasb3058bd2016-07-01 08:22:01 -070014#include "SkSLIRGenerator.h"
Ethan Nicholascc305772017-10-13 16:17:45 -040015#include "SkSLMetalCodeGenerator.h"
ethannicholasb3058bd2016-07-01 08:22:01 -070016#include "SkSLSPIRVCodeGenerator.h"
Ethan Nicholasaae47c82017-11-10 15:34:03 -050017#include "ir/SkSLEnum.h"
ethannicholasb3058bd2016-07-01 08:22:01 -070018#include "ir/SkSLExpression.h"
Ethan Nicholascb670962017-04-20 19:31:52 -040019#include "ir/SkSLExpressionStatement.h"
Ethan Nicholasc6a19f12018-03-29 16:46:56 -040020#include "ir/SkSLFunctionCall.h"
ethannicholasb3058bd2016-07-01 08:22:01 -070021#include "ir/SkSLIntLiteral.h"
ethannicholas5961bc92016-10-12 06:39:56 -070022#include "ir/SkSLModifiersDeclaration.h"
Ethan Nicholascb670962017-04-20 19:31:52 -040023#include "ir/SkSLNop.h"
ethannicholasb3058bd2016-07-01 08:22:01 -070024#include "ir/SkSLSymbolTable.h"
Ethan Nicholascb670962017-04-20 19:31:52 -040025#include "ir/SkSLTernaryExpression.h"
ethannicholasddb37d62016-10-20 09:54:00 -070026#include "ir/SkSLUnresolvedFunction.h"
ethannicholas22f939e2016-10-13 13:25:34 -070027#include "ir/SkSLVarDeclarations.h"
ethannicholasb3058bd2016-07-01 08:22:01 -070028
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -040029#ifdef SK_ENABLE_SPIRV_VALIDATION
30#include "spirv-tools/libspirv.hpp"
31#endif
32
ethannicholasb3058bd2016-07-01 08:22:01 -070033// include the built-in shader symbols as static strings
34
Ethan Nicholas79707652017-11-16 11:20:11 -050035#define STRINGIFY(x) #x
36
ethannicholas5961bc92016-10-12 06:39:56 -070037static const char* SKSL_INCLUDE =
Ben Wagnera56c4d22018-01-24 17:32:17 -050038#include "sksl.inc"
ethannicholasb3058bd2016-07-01 08:22:01 -070039;
40
ethannicholas5961bc92016-10-12 06:39:56 -070041static const char* SKSL_VERT_INCLUDE =
Ben Wagnera56c4d22018-01-24 17:32:17 -050042#include "sksl_vert.inc"
ethannicholasb3058bd2016-07-01 08:22:01 -070043;
44
ethannicholas5961bc92016-10-12 06:39:56 -070045static const char* SKSL_FRAG_INCLUDE =
Ben Wagnera56c4d22018-01-24 17:32:17 -050046#include "sksl_frag.inc"
ethannicholasb3058bd2016-07-01 08:22:01 -070047;
48
Ethan Nicholas52cad152017-02-16 16:37:32 -050049static const char* SKSL_GEOM_INCLUDE =
Ben Wagnera56c4d22018-01-24 17:32:17 -050050#include "sksl_geom.inc"
Ethan Nicholas52cad152017-02-16 16:37:32 -050051;
52
Ethan Nicholas762466e2017-06-29 10:03:38 -040053static const char* SKSL_FP_INCLUDE =
Ben Wagnera56c4d22018-01-24 17:32:17 -050054#include "sksl_enums.inc"
55#include "sksl_fp.inc"
Ethan Nicholas762466e2017-06-29 10:03:38 -040056;
57
Ethan Nicholas26a9aad2018-03-27 14:10:52 -040058static const char* SKSL_CPU_INCLUDE =
59#include "sksl_cpu.inc"
60;
61
ethannicholasb3058bd2016-07-01 08:22:01 -070062namespace SkSL {
63
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -040064Compiler::Compiler(Flags flags)
65: fFlags(flags)
Ethan Nicholas26a9aad2018-03-27 14:10:52 -040066, fContext(new Context())
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -040067, fErrorCount(0) {
Ethan Nicholas8feeff92017-03-30 14:11:58 -040068 auto types = std::shared_ptr<SymbolTable>(new SymbolTable(this));
69 auto symbols = std::shared_ptr<SymbolTable>(new SymbolTable(types, this));
Ethan Nicholas26a9aad2018-03-27 14:10:52 -040070 fIRGenerator = new IRGenerator(fContext.get(), symbols, *this);
ethannicholasb3058bd2016-07-01 08:22:01 -070071 fTypes = types;
Ethan Nicholas26a9aad2018-03-27 14:10:52 -040072 #define ADD_TYPE(t) types->addWithoutOwnership(fContext->f ## t ## _Type->fName, \
73 fContext->f ## t ## _Type.get())
ethannicholasb3058bd2016-07-01 08:22:01 -070074 ADD_TYPE(Void);
75 ADD_TYPE(Float);
Ethan Nicholas5af9ea32017-07-28 15:19:46 -040076 ADD_TYPE(Float2);
77 ADD_TYPE(Float3);
78 ADD_TYPE(Float4);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -040079 ADD_TYPE(Half);
80 ADD_TYPE(Half2);
81 ADD_TYPE(Half3);
82 ADD_TYPE(Half4);
ethannicholasb3058bd2016-07-01 08:22:01 -070083 ADD_TYPE(Double);
Ethan Nicholas5af9ea32017-07-28 15:19:46 -040084 ADD_TYPE(Double2);
85 ADD_TYPE(Double3);
86 ADD_TYPE(Double4);
ethannicholasb3058bd2016-07-01 08:22:01 -070087 ADD_TYPE(Int);
Ethan Nicholas5af9ea32017-07-28 15:19:46 -040088 ADD_TYPE(Int2);
89 ADD_TYPE(Int3);
90 ADD_TYPE(Int4);
ethannicholasb3058bd2016-07-01 08:22:01 -070091 ADD_TYPE(UInt);
Ethan Nicholas5af9ea32017-07-28 15:19:46 -040092 ADD_TYPE(UInt2);
93 ADD_TYPE(UInt3);
94 ADD_TYPE(UInt4);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -040095 ADD_TYPE(Short);
96 ADD_TYPE(Short2);
97 ADD_TYPE(Short3);
98 ADD_TYPE(Short4);
99 ADD_TYPE(UShort);
100 ADD_TYPE(UShort2);
101 ADD_TYPE(UShort3);
102 ADD_TYPE(UShort4);
ethannicholasb3058bd2016-07-01 08:22:01 -0700103 ADD_TYPE(Bool);
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400104 ADD_TYPE(Bool2);
105 ADD_TYPE(Bool3);
106 ADD_TYPE(Bool4);
107 ADD_TYPE(Float2x2);
108 ADD_TYPE(Float2x3);
109 ADD_TYPE(Float2x4);
110 ADD_TYPE(Float3x2);
111 ADD_TYPE(Float3x3);
112 ADD_TYPE(Float3x4);
113 ADD_TYPE(Float4x2);
114 ADD_TYPE(Float4x3);
115 ADD_TYPE(Float4x4);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -0400116 ADD_TYPE(Half2x2);
117 ADD_TYPE(Half2x3);
118 ADD_TYPE(Half2x4);
119 ADD_TYPE(Half3x2);
120 ADD_TYPE(Half3x3);
121 ADD_TYPE(Half3x4);
122 ADD_TYPE(Half4x2);
123 ADD_TYPE(Half4x3);
124 ADD_TYPE(Half4x4);
125 ADD_TYPE(Double2x2);
126 ADD_TYPE(Double2x3);
127 ADD_TYPE(Double2x4);
128 ADD_TYPE(Double3x2);
129 ADD_TYPE(Double3x3);
130 ADD_TYPE(Double3x4);
131 ADD_TYPE(Double4x2);
132 ADD_TYPE(Double4x3);
133 ADD_TYPE(Double4x4);
ethannicholasb3058bd2016-07-01 08:22:01 -0700134 ADD_TYPE(GenType);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -0400135 ADD_TYPE(GenHType);
ethannicholasb3058bd2016-07-01 08:22:01 -0700136 ADD_TYPE(GenDType);
137 ADD_TYPE(GenIType);
138 ADD_TYPE(GenUType);
139 ADD_TYPE(GenBType);
140 ADD_TYPE(Mat);
141 ADD_TYPE(Vec);
142 ADD_TYPE(GVec);
143 ADD_TYPE(GVec2);
144 ADD_TYPE(GVec3);
145 ADD_TYPE(GVec4);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -0400146 ADD_TYPE(HVec);
ethannicholasb3058bd2016-07-01 08:22:01 -0700147 ADD_TYPE(DVec);
148 ADD_TYPE(IVec);
149 ADD_TYPE(UVec);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -0400150 ADD_TYPE(SVec);
151 ADD_TYPE(USVec);
ethannicholasb3058bd2016-07-01 08:22:01 -0700152 ADD_TYPE(BVec);
153
154 ADD_TYPE(Sampler1D);
155 ADD_TYPE(Sampler2D);
156 ADD_TYPE(Sampler3D);
ethannicholas5961bc92016-10-12 06:39:56 -0700157 ADD_TYPE(SamplerExternalOES);
ethannicholasb3058bd2016-07-01 08:22:01 -0700158 ADD_TYPE(SamplerCube);
159 ADD_TYPE(Sampler2DRect);
160 ADD_TYPE(Sampler1DArray);
161 ADD_TYPE(Sampler2DArray);
162 ADD_TYPE(SamplerCubeArray);
163 ADD_TYPE(SamplerBuffer);
164 ADD_TYPE(Sampler2DMS);
165 ADD_TYPE(Sampler2DMSArray);
166
Brian Salomonbf7b6202016-11-11 16:08:03 -0500167 ADD_TYPE(ISampler2D);
168
Brian Salomon2a51de82016-11-16 12:06:01 -0500169 ADD_TYPE(Image2D);
170 ADD_TYPE(IImage2D);
171
Greg Daniel64773e62016-11-22 09:44:03 -0500172 ADD_TYPE(SubpassInput);
173 ADD_TYPE(SubpassInputMS);
174
ethannicholasb3058bd2016-07-01 08:22:01 -0700175 ADD_TYPE(GSampler1D);
176 ADD_TYPE(GSampler2D);
177 ADD_TYPE(GSampler3D);
178 ADD_TYPE(GSamplerCube);
179 ADD_TYPE(GSampler2DRect);
180 ADD_TYPE(GSampler1DArray);
181 ADD_TYPE(GSampler2DArray);
182 ADD_TYPE(GSamplerCubeArray);
183 ADD_TYPE(GSamplerBuffer);
184 ADD_TYPE(GSampler2DMS);
185 ADD_TYPE(GSampler2DMSArray);
186
187 ADD_TYPE(Sampler1DShadow);
188 ADD_TYPE(Sampler2DShadow);
189 ADD_TYPE(SamplerCubeShadow);
190 ADD_TYPE(Sampler2DRectShadow);
191 ADD_TYPE(Sampler1DArrayShadow);
192 ADD_TYPE(Sampler2DArrayShadow);
193 ADD_TYPE(SamplerCubeArrayShadow);
194 ADD_TYPE(GSampler2DArrayShadow);
195 ADD_TYPE(GSamplerCubeArrayShadow);
Ethan Nicholasc9472af2017-10-10 16:30:21 -0400196 ADD_TYPE(FragmentProcessor);
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400197 ADD_TYPE(SkRasterPipeline);
ethannicholasb3058bd2016-07-01 08:22:01 -0700198
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700199 StringFragment skCapsName("sk_Caps");
200 Variable* skCaps = new Variable(-1, Modifiers(), skCapsName,
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400201 *fContext->fSkCaps_Type, Variable::kGlobal_Storage);
Ethan Nicholas3605ace2016-11-21 15:59:48 -0500202 fIRGenerator->fSymbolTable->add(skCapsName, std::unique_ptr<Symbol>(skCaps));
203
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700204 StringFragment skArgsName("sk_Args");
205 Variable* skArgs = new Variable(-1, Modifiers(), skArgsName,
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400206 *fContext->fSkArgs_Type, Variable::kGlobal_Storage);
Ethan Nicholas762466e2017-06-29 10:03:38 -0400207 fIRGenerator->fSymbolTable->add(skArgsName, std::unique_ptr<Symbol>(skArgs));
208
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400209 std::vector<std::unique_ptr<ProgramElement>> ignored;
Robert Phillipsfe8da172018-01-24 14:52:02 +0000210 fIRGenerator->convertProgram(Program::kFragment_Kind, SKSL_INCLUDE, strlen(SKSL_INCLUDE),
211 *fTypes, &ignored);
ethannicholasddb37d62016-10-20 09:54:00 -0700212 fIRGenerator->fSymbolTable->markAllFunctionsBuiltin();
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700213 if (fErrorCount) {
214 printf("Unexpected errors: %s\n", fErrorText.c_str());
215 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700216 ASSERT(!fErrorCount);
217}
218
219Compiler::~Compiler() {
220 delete fIRGenerator;
221}
222
ethannicholas22f939e2016-10-13 13:25:34 -0700223// add the definition created by assigning to the lvalue to the definition set
Ethan Nicholas86a43402017-01-19 13:32:00 -0500224void Compiler::addDefinition(const Expression* lvalue, std::unique_ptr<Expression>* expr,
225 DefinitionMap* definitions) {
ethannicholas22f939e2016-10-13 13:25:34 -0700226 switch (lvalue->fKind) {
227 case Expression::kVariableReference_Kind: {
228 const Variable& var = ((VariableReference*) lvalue)->fVariable;
229 if (var.fStorage == Variable::kLocal_Storage) {
230 (*definitions)[&var] = expr;
231 }
232 break;
233 }
234 case Expression::kSwizzle_Kind:
235 // We consider the variable written to as long as at least some of its components have
236 // been written to. This will lead to some false negatives (we won't catch it if you
237 // write to foo.x and then read foo.y), but being stricter could lead to false positives
Mike Klein6ad99092016-10-26 10:35:22 -0400238 // (we write to foo.x, and then pass foo to a function which happens to only read foo.x,
239 // 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 -0700240 // more complicated whole-program analysis. This is probably good enough.
Mike Klein6ad99092016-10-26 10:35:22 -0400241 this->addDefinition(((Swizzle*) lvalue)->fBase.get(),
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400242 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
ethannicholas22f939e2016-10-13 13:25:34 -0700243 definitions);
244 break;
245 case Expression::kIndex_Kind:
246 // see comments in Swizzle
Mike Klein6ad99092016-10-26 10:35:22 -0400247 this->addDefinition(((IndexExpression*) lvalue)->fBase.get(),
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400248 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
ethannicholas22f939e2016-10-13 13:25:34 -0700249 definitions);
250 break;
251 case Expression::kFieldAccess_Kind:
252 // see comments in Swizzle
Mike Klein6ad99092016-10-26 10:35:22 -0400253 this->addDefinition(((FieldAccess*) lvalue)->fBase.get(),
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400254 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
ethannicholas22f939e2016-10-13 13:25:34 -0700255 definitions);
256 break;
Ethan Nicholasa583b812018-01-18 13:32:11 -0500257 case Expression::kTernary_Kind:
258 // To simplify analysis, we just pretend that we write to both sides of the ternary.
259 // This allows for false positives (meaning we fail to detect that a variable might not
260 // have been assigned), but is preferable to false negatives.
261 this->addDefinition(((TernaryExpression*) lvalue)->fIfTrue.get(),
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400262 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
Ethan Nicholasa583b812018-01-18 13:32:11 -0500263 definitions);
264 this->addDefinition(((TernaryExpression*) lvalue)->fIfFalse.get(),
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400265 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
Ethan Nicholasa583b812018-01-18 13:32:11 -0500266 definitions);
267 break;
ethannicholas22f939e2016-10-13 13:25:34 -0700268 default:
269 // not an lvalue, can't happen
270 ASSERT(false);
271 }
272}
273
274// add local variables defined by this node to the set
Mike Klein6ad99092016-10-26 10:35:22 -0400275void Compiler::addDefinitions(const BasicBlock::Node& node,
Ethan Nicholas86a43402017-01-19 13:32:00 -0500276 DefinitionMap* definitions) {
ethannicholas22f939e2016-10-13 13:25:34 -0700277 switch (node.fKind) {
278 case BasicBlock::Node::kExpression_Kind: {
Ethan Nicholascb670962017-04-20 19:31:52 -0400279 ASSERT(node.expression());
280 const Expression* expr = (Expression*) node.expression()->get();
Ethan Nicholas86a43402017-01-19 13:32:00 -0500281 switch (expr->fKind) {
282 case Expression::kBinary_Kind: {
283 BinaryExpression* b = (BinaryExpression*) expr;
284 if (b->fOperator == Token::EQ) {
285 this->addDefinition(b->fLeft.get(), &b->fRight, definitions);
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700286 } else if (Compiler::IsAssignment(b->fOperator)) {
Ethan Nicholas86a43402017-01-19 13:32:00 -0500287 this->addDefinition(
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400288 b->fLeft.get(),
289 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
290 definitions);
Ethan Nicholas86a43402017-01-19 13:32:00 -0500291
292 }
293 break;
ethannicholas22f939e2016-10-13 13:25:34 -0700294 }
Ethan Nicholasc6a19f12018-03-29 16:46:56 -0400295 case Expression::kFunctionCall_Kind: {
296 const FunctionCall& c = (const FunctionCall&) *expr;
297 for (size_t i = 0; i < c.fFunction.fParameters.size(); ++i) {
298 if (c.fFunction.fParameters[i]->fModifiers.fFlags & Modifiers::kOut_Flag) {
299 this->addDefinition(
300 c.fArguments[i].get(),
301 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
302 definitions);
303 }
304 }
305 break;
306 }
Ethan Nicholas86a43402017-01-19 13:32:00 -0500307 case Expression::kPrefix_Kind: {
308 const PrefixExpression* p = (PrefixExpression*) expr;
309 if (p->fOperator == Token::MINUSMINUS || p->fOperator == Token::PLUSPLUS) {
310 this->addDefinition(
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400311 p->fOperand.get(),
312 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
313 definitions);
Ethan Nicholas86a43402017-01-19 13:32:00 -0500314 }
315 break;
316 }
317 case Expression::kPostfix_Kind: {
318 const PostfixExpression* p = (PostfixExpression*) expr;
319 if (p->fOperator == Token::MINUSMINUS || p->fOperator == Token::PLUSPLUS) {
320 this->addDefinition(
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400321 p->fOperand.get(),
322 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
323 definitions);
Ethan Nicholas86a43402017-01-19 13:32:00 -0500324 }
325 break;
326 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400327 case Expression::kVariableReference_Kind: {
328 const VariableReference* v = (VariableReference*) expr;
329 if (v->fRefKind != VariableReference::kRead_RefKind) {
330 this->addDefinition(
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400331 v,
332 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
333 definitions);
Ethan Nicholascb670962017-04-20 19:31:52 -0400334 }
335 }
Ethan Nicholas86a43402017-01-19 13:32:00 -0500336 default:
337 break;
ethannicholas22f939e2016-10-13 13:25:34 -0700338 }
339 break;
340 }
341 case BasicBlock::Node::kStatement_Kind: {
Ethan Nicholascb670962017-04-20 19:31:52 -0400342 const Statement* stmt = (Statement*) node.statement()->get();
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000343 if (stmt->fKind == Statement::kVarDeclaration_Kind) {
344 VarDeclaration& vd = (VarDeclaration&) *stmt;
345 if (vd.fValue) {
346 (*definitions)[vd.fVar] = &vd.fValue;
ethannicholas22f939e2016-10-13 13:25:34 -0700347 }
348 }
349 break;
350 }
351 }
352}
353
354void Compiler::scanCFG(CFG* cfg, BlockId blockId, std::set<BlockId>* workList) {
355 BasicBlock& block = cfg->fBlocks[blockId];
356
357 // compute definitions after this block
Ethan Nicholas86a43402017-01-19 13:32:00 -0500358 DefinitionMap after = block.fBefore;
ethannicholas22f939e2016-10-13 13:25:34 -0700359 for (const BasicBlock::Node& n : block.fNodes) {
360 this->addDefinitions(n, &after);
361 }
362
363 // propagate definitions to exits
364 for (BlockId exitId : block.fExits) {
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400365 if (exitId == blockId) {
366 continue;
367 }
ethannicholas22f939e2016-10-13 13:25:34 -0700368 BasicBlock& exit = cfg->fBlocks[exitId];
369 for (const auto& pair : after) {
Ethan Nicholas86a43402017-01-19 13:32:00 -0500370 std::unique_ptr<Expression>* e1 = pair.second;
371 auto found = exit.fBefore.find(pair.first);
372 if (found == exit.fBefore.end()) {
373 // exit has no definition for it, just copy it
374 workList->insert(exitId);
ethannicholas22f939e2016-10-13 13:25:34 -0700375 exit.fBefore[pair.first] = e1;
376 } else {
Ethan Nicholas86a43402017-01-19 13:32:00 -0500377 // exit has a (possibly different) value already defined
378 std::unique_ptr<Expression>* e2 = exit.fBefore[pair.first];
ethannicholas22f939e2016-10-13 13:25:34 -0700379 if (e1 != e2) {
380 // definition has changed, merge and add exit block to worklist
381 workList->insert(exitId);
Ethan Nicholasaf197692017-02-27 13:26:45 -0500382 if (e1 && e2) {
383 exit.fBefore[pair.first] =
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400384 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression;
Ethan Nicholasaf197692017-02-27 13:26:45 -0500385 } else {
386 exit.fBefore[pair.first] = nullptr;
387 }
ethannicholas22f939e2016-10-13 13:25:34 -0700388 }
389 }
390 }
391 }
392}
393
394// returns a map which maps all local variables in the function to null, indicating that their value
395// is initially unknown
Ethan Nicholas86a43402017-01-19 13:32:00 -0500396static DefinitionMap compute_start_state(const CFG& cfg) {
397 DefinitionMap result;
Mike Klein6ad99092016-10-26 10:35:22 -0400398 for (const auto& block : cfg.fBlocks) {
399 for (const auto& node : block.fNodes) {
ethannicholas22f939e2016-10-13 13:25:34 -0700400 if (node.fKind == BasicBlock::Node::kStatement_Kind) {
Ethan Nicholascb670962017-04-20 19:31:52 -0400401 ASSERT(node.statement());
402 const Statement* s = node.statement()->get();
ethannicholas22f939e2016-10-13 13:25:34 -0700403 if (s->fKind == Statement::kVarDeclarations_Kind) {
404 const VarDeclarationsStatement* vd = (const VarDeclarationsStatement*) s;
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000405 for (const auto& decl : vd->fDeclaration->fVars) {
406 if (decl->fKind == Statement::kVarDeclaration_Kind) {
407 result[((VarDeclaration&) *decl).fVar] = nullptr;
408 }
Mike Klein6ad99092016-10-26 10:35:22 -0400409 }
ethannicholas22f939e2016-10-13 13:25:34 -0700410 }
411 }
412 }
413 }
414 return result;
415}
416
Ethan Nicholascb670962017-04-20 19:31:52 -0400417/**
418 * Returns true if assigning to this lvalue has no effect.
419 */
420static bool is_dead(const Expression& lvalue) {
421 switch (lvalue.fKind) {
422 case Expression::kVariableReference_Kind:
423 return ((VariableReference&) lvalue).fVariable.dead();
424 case Expression::kSwizzle_Kind:
425 return is_dead(*((Swizzle&) lvalue).fBase);
426 case Expression::kFieldAccess_Kind:
427 return is_dead(*((FieldAccess&) lvalue).fBase);
428 case Expression::kIndex_Kind: {
429 const IndexExpression& idx = (IndexExpression&) lvalue;
430 return is_dead(*idx.fBase) && !idx.fIndex->hasSideEffects();
431 }
Ethan Nicholasa583b812018-01-18 13:32:11 -0500432 case Expression::kTernary_Kind: {
433 const TernaryExpression& t = (TernaryExpression&) lvalue;
434 return !t.fTest->hasSideEffects() && is_dead(*t.fIfTrue) && is_dead(*t.fIfFalse);
435 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400436 default:
437 ABORT("invalid lvalue: %s\n", lvalue.description().c_str());
438 }
439}
ethannicholas22f939e2016-10-13 13:25:34 -0700440
Ethan Nicholascb670962017-04-20 19:31:52 -0400441/**
442 * Returns true if this is an assignment which can be collapsed down to just the right hand side due
443 * to a dead target and lack of side effects on the left hand side.
444 */
445static bool dead_assignment(const BinaryExpression& b) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700446 if (!Compiler::IsAssignment(b.fOperator)) {
Ethan Nicholascb670962017-04-20 19:31:52 -0400447 return false;
448 }
449 return is_dead(*b.fLeft);
450}
451
452void Compiler::computeDataFlow(CFG* cfg) {
453 cfg->fBlocks[cfg->fStart].fBefore = compute_start_state(*cfg);
ethannicholas22f939e2016-10-13 13:25:34 -0700454 std::set<BlockId> workList;
Ethan Nicholascb670962017-04-20 19:31:52 -0400455 for (BlockId i = 0; i < cfg->fBlocks.size(); i++) {
ethannicholas22f939e2016-10-13 13:25:34 -0700456 workList.insert(i);
457 }
458 while (workList.size()) {
459 BlockId next = *workList.begin();
460 workList.erase(workList.begin());
Ethan Nicholascb670962017-04-20 19:31:52 -0400461 this->scanCFG(cfg, next, &workList);
ethannicholas22f939e2016-10-13 13:25:34 -0700462 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400463}
464
465/**
466 * Attempts to replace the expression pointed to by iter with a new one (in both the CFG and the
467 * IR). If the expression can be cleanly removed, returns true and updates the iterator to point to
468 * the newly-inserted element. Otherwise updates only the IR and returns false (and the CFG will
469 * need to be regenerated).
470 */
471bool try_replace_expression(BasicBlock* b,
472 std::vector<BasicBlock::Node>::iterator* iter,
473 std::unique_ptr<Expression>* newExpression) {
474 std::unique_ptr<Expression>* target = (*iter)->expression();
475 if (!b->tryRemoveExpression(iter)) {
476 *target = std::move(*newExpression);
477 return false;
478 }
479 *target = std::move(*newExpression);
480 return b->tryInsertExpression(iter, target);
481}
482
483/**
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400484 * Returns true if the expression is a constant numeric literal with the specified value, or a
485 * constant vector with all elements equal to the specified value.
Ethan Nicholascb670962017-04-20 19:31:52 -0400486 */
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400487bool is_constant(const Expression& expr, double value) {
Ethan Nicholascb670962017-04-20 19:31:52 -0400488 switch (expr.fKind) {
489 case Expression::kIntLiteral_Kind:
490 return ((IntLiteral&) expr).fValue == value;
491 case Expression::kFloatLiteral_Kind:
492 return ((FloatLiteral&) expr).fValue == value;
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400493 case Expression::kConstructor_Kind: {
494 Constructor& c = (Constructor&) expr;
495 if (c.fType.kind() == Type::kVector_Kind && c.isConstant()) {
496 for (int i = 0; i < c.fType.columns(); ++i) {
497 if (!is_constant(c.getVecComponent(i), value)) {
498 return false;
499 }
500 }
501 return true;
502 }
503 return false;
504 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400505 default:
506 return false;
507 }
508}
509
510/**
511 * Collapses the binary expression pointed to by iter down to just the right side (in both the IR
512 * and CFG structures).
513 */
514void delete_left(BasicBlock* b,
515 std::vector<BasicBlock::Node>::iterator* iter,
516 bool* outUpdated,
517 bool* outNeedsRescan) {
518 *outUpdated = true;
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400519 std::unique_ptr<Expression>* target = (*iter)->expression();
520 ASSERT((*target)->fKind == Expression::kBinary_Kind);
521 BinaryExpression& bin = (BinaryExpression&) **target;
Ethan Nicholas51493ee2017-12-11 12:34:33 -0500522 ASSERT(!bin.fLeft->hasSideEffects());
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400523 bool result;
524 if (bin.fOperator == Token::EQ) {
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400525 result = b->tryRemoveLValueBefore(iter, bin.fLeft.get());
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400526 } else {
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400527 result = b->tryRemoveExpressionBefore(iter, bin.fLeft.get());
Ethan Nicholascb670962017-04-20 19:31:52 -0400528 }
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400529 *target = std::move(bin.fRight);
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400530 if (!result) {
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400531 *outNeedsRescan = true;
532 return;
533 }
534 if (*iter == b->fNodes.begin()) {
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400535 *outNeedsRescan = true;
536 return;
537 }
538 --(*iter);
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400539 if ((*iter)->fKind != BasicBlock::Node::kExpression_Kind ||
540 (*iter)->expression() != &bin.fRight) {
541 *outNeedsRescan = true;
542 return;
543 }
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400544 *iter = b->fNodes.erase(*iter);
545 ASSERT((*iter)->expression() == target);
Ethan Nicholascb670962017-04-20 19:31:52 -0400546}
547
548/**
549 * Collapses the binary expression pointed to by iter down to just the left side (in both the IR and
550 * CFG structures).
551 */
552void delete_right(BasicBlock* b,
553 std::vector<BasicBlock::Node>::iterator* iter,
554 bool* outUpdated,
555 bool* outNeedsRescan) {
556 *outUpdated = true;
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400557 std::unique_ptr<Expression>* target = (*iter)->expression();
558 ASSERT((*target)->fKind == Expression::kBinary_Kind);
559 BinaryExpression& bin = (BinaryExpression&) **target;
Ethan Nicholas51493ee2017-12-11 12:34:33 -0500560 ASSERT(!bin.fRight->hasSideEffects());
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400561 if (!b->tryRemoveExpressionBefore(iter, bin.fRight.get())) {
562 *target = std::move(bin.fLeft);
Ethan Nicholascb670962017-04-20 19:31:52 -0400563 *outNeedsRescan = true;
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400564 return;
Ethan Nicholascb670962017-04-20 19:31:52 -0400565 }
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400566 *target = std::move(bin.fLeft);
567 if (*iter == b->fNodes.begin()) {
568 *outNeedsRescan = true;
569 return;
570 }
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400571 --(*iter);
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400572 if (((*iter)->fKind != BasicBlock::Node::kExpression_Kind ||
573 (*iter)->expression() != &bin.fLeft)) {
574 *outNeedsRescan = true;
575 return;
576 }
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400577 *iter = b->fNodes.erase(*iter);
578 ASSERT((*iter)->expression() == target);
Ethan Nicholascb670962017-04-20 19:31:52 -0400579}
580
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400581/**
582 * Constructs the specified type using a single argument.
583 */
584static std::unique_ptr<Expression> construct(const Type& type, std::unique_ptr<Expression> v) {
585 std::vector<std::unique_ptr<Expression>> args;
586 args.push_back(std::move(v));
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700587 auto result = std::unique_ptr<Expression>(new Constructor(-1, type, std::move(args)));
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400588 return result;
589}
590
591/**
592 * Used in the implementations of vectorize_left and vectorize_right. Given a vector type and an
593 * expression x, deletes the expression pointed to by iter and replaces it with <type>(x).
594 */
595static void vectorize(BasicBlock* b,
596 std::vector<BasicBlock::Node>::iterator* iter,
597 const Type& type,
598 std::unique_ptr<Expression>* otherExpression,
599 bool* outUpdated,
600 bool* outNeedsRescan) {
601 ASSERT((*(*iter)->expression())->fKind == Expression::kBinary_Kind);
602 ASSERT(type.kind() == Type::kVector_Kind);
603 ASSERT((*otherExpression)->fType.kind() == Type::kScalar_Kind);
604 *outUpdated = true;
605 std::unique_ptr<Expression>* target = (*iter)->expression();
606 if (!b->tryRemoveExpression(iter)) {
607 *target = construct(type, std::move(*otherExpression));
608 *outNeedsRescan = true;
609 } else {
610 *target = construct(type, std::move(*otherExpression));
611 if (!b->tryInsertExpression(iter, target)) {
612 *outNeedsRescan = true;
613 }
614 }
615}
616
617/**
618 * Given a binary expression of the form x <op> vec<n>(y), deletes the right side and vectorizes the
619 * left to yield vec<n>(x).
620 */
621static void vectorize_left(BasicBlock* b,
622 std::vector<BasicBlock::Node>::iterator* iter,
623 bool* outUpdated,
624 bool* outNeedsRescan) {
625 BinaryExpression& bin = (BinaryExpression&) **(*iter)->expression();
626 vectorize(b, iter, bin.fRight->fType, &bin.fLeft, outUpdated, outNeedsRescan);
627}
628
629/**
630 * Given a binary expression of the form vec<n>(x) <op> y, deletes the left side and vectorizes the
631 * right to yield vec<n>(y).
632 */
633static void vectorize_right(BasicBlock* b,
634 std::vector<BasicBlock::Node>::iterator* iter,
635 bool* outUpdated,
636 bool* outNeedsRescan) {
637 BinaryExpression& bin = (BinaryExpression&) **(*iter)->expression();
638 vectorize(b, iter, bin.fLeft->fType, &bin.fRight, outUpdated, outNeedsRescan);
639}
640
641// Mark that an expression which we were writing to is no longer being written to
642void clear_write(const Expression& expr) {
643 switch (expr.fKind) {
644 case Expression::kVariableReference_Kind: {
645 ((VariableReference&) expr).setRefKind(VariableReference::kRead_RefKind);
646 break;
647 }
648 case Expression::kFieldAccess_Kind:
649 clear_write(*((FieldAccess&) expr).fBase);
650 break;
651 case Expression::kSwizzle_Kind:
652 clear_write(*((Swizzle&) expr).fBase);
653 break;
654 case Expression::kIndex_Kind:
655 clear_write(*((IndexExpression&) expr).fBase);
656 break;
657 default:
658 ABORT("shouldn't be writing to this kind of expression\n");
659 break;
660 }
661}
662
Ethan Nicholascb670962017-04-20 19:31:52 -0400663void Compiler::simplifyExpression(DefinitionMap& definitions,
664 BasicBlock& b,
665 std::vector<BasicBlock::Node>::iterator* iter,
666 std::unordered_set<const Variable*>* undefinedVariables,
667 bool* outUpdated,
668 bool* outNeedsRescan) {
669 Expression* expr = (*iter)->expression()->get();
670 ASSERT(expr);
671 if ((*iter)->fConstantPropagation) {
672 std::unique_ptr<Expression> optimized = expr->constantPropagate(*fIRGenerator, definitions);
673 if (optimized) {
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400674 *outUpdated = true;
Ethan Nicholascb670962017-04-20 19:31:52 -0400675 if (!try_replace_expression(&b, iter, &optimized)) {
676 *outNeedsRescan = true;
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400677 return;
Ethan Nicholascb670962017-04-20 19:31:52 -0400678 }
679 ASSERT((*iter)->fKind == BasicBlock::Node::kExpression_Kind);
680 expr = (*iter)->expression()->get();
Ethan Nicholascb670962017-04-20 19:31:52 -0400681 }
682 }
683 switch (expr->fKind) {
684 case Expression::kVariableReference_Kind: {
Ethan Nicholas8f7e28f2018-03-26 14:24:27 -0400685 const VariableReference& ref = (VariableReference&) *expr;
686 const Variable& var = ref.fVariable;
687 if (ref.refKind() != VariableReference::kWrite_RefKind &&
688 ref.refKind() != VariableReference::kPointer_RefKind &&
689 var.fStorage == Variable::kLocal_Storage && !definitions[&var] &&
Ethan Nicholascb670962017-04-20 19:31:52 -0400690 (*undefinedVariables).find(&var) == (*undefinedVariables).end()) {
691 (*undefinedVariables).insert(&var);
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000692 this->error(expr->fOffset,
693 "'" + var.fName + "' has not been assigned");
Ethan Nicholascb670962017-04-20 19:31:52 -0400694 }
695 break;
696 }
697 case Expression::kTernary_Kind: {
698 TernaryExpression* t = (TernaryExpression*) expr;
699 if (t->fTest->fKind == Expression::kBoolLiteral_Kind) {
700 // ternary has a constant test, replace it with either the true or
701 // false branch
702 if (((BoolLiteral&) *t->fTest).fValue) {
703 (*iter)->setExpression(std::move(t->fIfTrue));
704 } else {
705 (*iter)->setExpression(std::move(t->fIfFalse));
706 }
707 *outUpdated = true;
708 *outNeedsRescan = true;
709 }
710 break;
711 }
712 case Expression::kBinary_Kind: {
Ethan Nicholascb670962017-04-20 19:31:52 -0400713 BinaryExpression* bin = (BinaryExpression*) expr;
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400714 if (dead_assignment(*bin)) {
715 delete_left(&b, iter, outUpdated, outNeedsRescan);
716 break;
717 }
718 // collapse useless expressions like x * 1 or x + 0
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400719 if (((bin->fLeft->fType.kind() != Type::kScalar_Kind) &&
720 (bin->fLeft->fType.kind() != Type::kVector_Kind)) ||
721 ((bin->fRight->fType.kind() != Type::kScalar_Kind) &&
722 (bin->fRight->fType.kind() != Type::kVector_Kind))) {
723 break;
724 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400725 switch (bin->fOperator) {
726 case Token::STAR:
727 if (is_constant(*bin->fLeft, 1)) {
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400728 if (bin->fLeft->fType.kind() == Type::kVector_Kind &&
729 bin->fRight->fType.kind() == Type::kScalar_Kind) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400730 // float4(1) * x -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400731 vectorize_right(&b, iter, outUpdated, outNeedsRescan);
732 } else {
733 // 1 * x -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400734 // 1 * float4(x) -> float4(x)
735 // float4(1) * float4(x) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400736 delete_left(&b, iter, outUpdated, outNeedsRescan);
737 }
738 }
739 else if (is_constant(*bin->fLeft, 0)) {
740 if (bin->fLeft->fType.kind() == Type::kScalar_Kind &&
Ethan Nicholas08dae922018-01-23 10:31:56 -0500741 bin->fRight->fType.kind() == Type::kVector_Kind &&
742 !bin->fRight->hasSideEffects()) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400743 // 0 * float4(x) -> float4(0)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400744 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
745 } else {
746 // 0 * x -> 0
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400747 // float4(0) * x -> float4(0)
748 // float4(0) * float4(x) -> float4(0)
Ethan Nicholas51493ee2017-12-11 12:34:33 -0500749 if (!bin->fRight->hasSideEffects()) {
750 delete_right(&b, iter, outUpdated, outNeedsRescan);
751 }
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400752 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400753 }
754 else if (is_constant(*bin->fRight, 1)) {
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400755 if (bin->fLeft->fType.kind() == Type::kScalar_Kind &&
756 bin->fRight->fType.kind() == Type::kVector_Kind) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400757 // x * float4(1) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400758 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
759 } else {
760 // x * 1 -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400761 // float4(x) * 1 -> float4(x)
762 // float4(x) * float4(1) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400763 delete_right(&b, iter, outUpdated, outNeedsRescan);
764 }
765 }
766 else if (is_constant(*bin->fRight, 0)) {
767 if (bin->fLeft->fType.kind() == Type::kVector_Kind &&
Ethan Nicholas08dae922018-01-23 10:31:56 -0500768 bin->fRight->fType.kind() == Type::kScalar_Kind &&
769 !bin->fLeft->hasSideEffects()) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400770 // float4(x) * 0 -> float4(0)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400771 vectorize_right(&b, iter, outUpdated, outNeedsRescan);
772 } else {
773 // x * 0 -> 0
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400774 // x * float4(0) -> float4(0)
775 // float4(x) * float4(0) -> float4(0)
Ethan Nicholas51493ee2017-12-11 12:34:33 -0500776 if (!bin->fLeft->hasSideEffects()) {
777 delete_left(&b, iter, outUpdated, outNeedsRescan);
778 }
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400779 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400780 }
781 break;
Ethan Nicholas56e42712017-04-21 10:23:37 -0400782 case Token::PLUS:
Ethan Nicholascb670962017-04-20 19:31:52 -0400783 if (is_constant(*bin->fLeft, 0)) {
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400784 if (bin->fLeft->fType.kind() == Type::kVector_Kind &&
785 bin->fRight->fType.kind() == Type::kScalar_Kind) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400786 // float4(0) + x -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400787 vectorize_right(&b, iter, outUpdated, outNeedsRescan);
788 } else {
789 // 0 + x -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400790 // 0 + float4(x) -> float4(x)
791 // float4(0) + float4(x) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400792 delete_left(&b, iter, outUpdated, outNeedsRescan);
793 }
794 } else if (is_constant(*bin->fRight, 0)) {
795 if (bin->fLeft->fType.kind() == Type::kScalar_Kind &&
796 bin->fRight->fType.kind() == Type::kVector_Kind) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400797 // x + float4(0) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400798 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
799 } else {
800 // x + 0 -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400801 // float4(x) + 0 -> float4(x)
802 // float4(x) + float4(0) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400803 delete_right(&b, iter, outUpdated, outNeedsRescan);
804 }
Ethan Nicholas56e42712017-04-21 10:23:37 -0400805 }
806 break;
807 case Token::MINUS:
808 if (is_constant(*bin->fRight, 0)) {
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400809 if (bin->fLeft->fType.kind() == Type::kScalar_Kind &&
810 bin->fRight->fType.kind() == Type::kVector_Kind) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400811 // x - float4(0) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400812 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
813 } else {
814 // x - 0 -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400815 // float4(x) - 0 -> float4(x)
816 // float4(x) - float4(0) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400817 delete_right(&b, iter, outUpdated, outNeedsRescan);
818 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400819 }
820 break;
821 case Token::SLASH:
822 if (is_constant(*bin->fRight, 1)) {
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400823 if (bin->fLeft->fType.kind() == Type::kScalar_Kind &&
824 bin->fRight->fType.kind() == Type::kVector_Kind) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400825 // x / float4(1) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400826 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
827 } else {
828 // x / 1 -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400829 // float4(x) / 1 -> float4(x)
830 // float4(x) / float4(1) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400831 delete_right(&b, iter, outUpdated, outNeedsRescan);
832 }
833 } else if (is_constant(*bin->fLeft, 0)) {
834 if (bin->fLeft->fType.kind() == Type::kScalar_Kind &&
Ethan Nicholas08dae922018-01-23 10:31:56 -0500835 bin->fRight->fType.kind() == Type::kVector_Kind &&
836 !bin->fRight->hasSideEffects()) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400837 // 0 / float4(x) -> float4(0)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400838 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
839 } else {
840 // 0 / x -> 0
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400841 // float4(0) / x -> float4(0)
842 // float4(0) / float4(x) -> float4(0)
Ethan Nicholas51493ee2017-12-11 12:34:33 -0500843 if (!bin->fRight->hasSideEffects()) {
844 delete_right(&b, iter, outUpdated, outNeedsRescan);
845 }
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400846 }
847 }
848 break;
849 case Token::PLUSEQ:
850 if (is_constant(*bin->fRight, 0)) {
851 clear_write(*bin->fLeft);
852 delete_right(&b, iter, outUpdated, outNeedsRescan);
853 }
854 break;
855 case Token::MINUSEQ:
856 if (is_constant(*bin->fRight, 0)) {
857 clear_write(*bin->fLeft);
858 delete_right(&b, iter, outUpdated, outNeedsRescan);
859 }
860 break;
861 case Token::STAREQ:
862 if (is_constant(*bin->fRight, 1)) {
863 clear_write(*bin->fLeft);
864 delete_right(&b, iter, outUpdated, outNeedsRescan);
865 }
866 break;
867 case Token::SLASHEQ:
868 if (is_constant(*bin->fRight, 1)) {
869 clear_write(*bin->fLeft);
Ethan Nicholascb670962017-04-20 19:31:52 -0400870 delete_right(&b, iter, outUpdated, outNeedsRescan);
871 }
872 break;
873 default:
874 break;
875 }
876 }
877 default:
878 break;
879 }
880}
881
Ethan Nicholas5ac13c22017-05-10 15:06:17 -0400882// returns true if this statement could potentially execute a break at the current level (we ignore
883// nested loops and switches, since any breaks inside of them will merely break the loop / switch)
884static bool contains_break(Statement& s) {
885 switch (s.fKind) {
886 case Statement::kBlock_Kind:
887 for (const auto& sub : ((Block&) s).fStatements) {
888 if (contains_break(*sub)) {
889 return true;
890 }
891 }
892 return false;
893 case Statement::kBreak_Kind:
894 return true;
895 case Statement::kIf_Kind: {
896 const IfStatement& i = (IfStatement&) s;
897 return contains_break(*i.fIfTrue) || (i.fIfFalse && contains_break(*i.fIfFalse));
898 }
899 default:
900 return false;
901 }
902}
903
904// Returns a block containing all of the statements that will be run if the given case matches
905// (which, owing to the statements being owned by unique_ptrs, means the switch itself will be
906// broken by this call and must then be discarded).
907// Returns null (and leaves the switch unmodified) if no such simple reduction is possible, such as
908// when break statements appear inside conditionals.
909static std::unique_ptr<Statement> block_for_case(SwitchStatement* s, SwitchCase* c) {
910 bool capturing = false;
911 std::vector<std::unique_ptr<Statement>*> statementPtrs;
912 for (const auto& current : s->fCases) {
913 if (current.get() == c) {
914 capturing = true;
915 }
916 if (capturing) {
917 for (auto& stmt : current->fStatements) {
918 if (stmt->fKind == Statement::kBreak_Kind) {
919 capturing = false;
920 break;
921 }
922 if (contains_break(*stmt)) {
923 return nullptr;
924 }
925 statementPtrs.push_back(&stmt);
926 }
927 if (!capturing) {
928 break;
929 }
930 }
931 }
932 std::vector<std::unique_ptr<Statement>> statements;
933 for (const auto& s : statementPtrs) {
934 statements.push_back(std::move(*s));
935 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700936 return std::unique_ptr<Statement>(new Block(-1, std::move(statements), s->fSymbols));
Ethan Nicholas5ac13c22017-05-10 15:06:17 -0400937}
938
Ethan Nicholascb670962017-04-20 19:31:52 -0400939void Compiler::simplifyStatement(DefinitionMap& definitions,
Ethan Nicholas5ac13c22017-05-10 15:06:17 -0400940 BasicBlock& b,
941 std::vector<BasicBlock::Node>::iterator* iter,
942 std::unordered_set<const Variable*>* undefinedVariables,
943 bool* outUpdated,
944 bool* outNeedsRescan) {
Ethan Nicholascb670962017-04-20 19:31:52 -0400945 Statement* stmt = (*iter)->statement()->get();
946 switch (stmt->fKind) {
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000947 case Statement::kVarDeclaration_Kind: {
948 const auto& varDecl = (VarDeclaration&) *stmt;
949 if (varDecl.fVar->dead() &&
950 (!varDecl.fValue ||
951 !varDecl.fValue->hasSideEffects())) {
952 if (varDecl.fValue) {
953 ASSERT((*iter)->statement()->get() == stmt);
954 if (!b.tryRemoveExpressionBefore(iter, varDecl.fValue.get())) {
955 *outNeedsRescan = true;
Ethan Nicholascb670962017-04-20 19:31:52 -0400956 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400957 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400958 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000959 *outUpdated = true;
Ethan Nicholascb670962017-04-20 19:31:52 -0400960 }
961 break;
962 }
963 case Statement::kIf_Kind: {
964 IfStatement& i = (IfStatement&) *stmt;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -0400965 if (i.fTest->fKind == Expression::kBoolLiteral_Kind) {
966 // constant if, collapse down to a single branch
967 if (((BoolLiteral&) *i.fTest).fValue) {
968 ASSERT(i.fIfTrue);
969 (*iter)->setStatement(std::move(i.fIfTrue));
970 } else {
971 if (i.fIfFalse) {
972 (*iter)->setStatement(std::move(i.fIfFalse));
973 } else {
974 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
975 }
976 }
977 *outUpdated = true;
978 *outNeedsRescan = true;
979 break;
980 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400981 if (i.fIfFalse && i.fIfFalse->isEmpty()) {
982 // else block doesn't do anything, remove it
983 i.fIfFalse.reset();
984 *outUpdated = true;
985 *outNeedsRescan = true;
986 }
987 if (!i.fIfFalse && i.fIfTrue->isEmpty()) {
988 // if block doesn't do anything, no else block
989 if (i.fTest->hasSideEffects()) {
990 // test has side effects, keep it
991 (*iter)->setStatement(std::unique_ptr<Statement>(
992 new ExpressionStatement(std::move(i.fTest))));
993 } else {
994 // no if, no else, no test side effects, kill the whole if
995 // statement
996 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
997 }
998 *outUpdated = true;
999 *outNeedsRescan = true;
1000 }
1001 break;
1002 }
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001003 case Statement::kSwitch_Kind: {
1004 SwitchStatement& s = (SwitchStatement&) *stmt;
1005 if (s.fValue->isConstant()) {
1006 // switch is constant, replace it with the case that matches
1007 bool found = false;
1008 SwitchCase* defaultCase = nullptr;
1009 for (const auto& c : s.fCases) {
1010 if (!c->fValue) {
1011 defaultCase = c.get();
1012 continue;
1013 }
1014 ASSERT(c->fValue->fKind == s.fValue->fKind);
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001015 found = c->fValue->compareConstant(*fContext, *s.fValue);
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001016 if (found) {
1017 std::unique_ptr<Statement> newBlock = block_for_case(&s, c.get());
1018 if (newBlock) {
1019 (*iter)->setStatement(std::move(newBlock));
1020 break;
1021 } else {
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -04001022 if (s.fIsStatic && !(fFlags & kPermitInvalidStaticTests_Flag)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001023 this->error(s.fOffset,
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001024 "static switch contains non-static conditional break");
1025 s.fIsStatic = false;
1026 }
1027 return; // can't simplify
1028 }
1029 }
1030 }
1031 if (!found) {
1032 // no matching case. use default if it exists, or kill the whole thing
1033 if (defaultCase) {
1034 std::unique_ptr<Statement> newBlock = block_for_case(&s, defaultCase);
1035 if (newBlock) {
1036 (*iter)->setStatement(std::move(newBlock));
1037 } else {
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -04001038 if (s.fIsStatic && !(fFlags & kPermitInvalidStaticTests_Flag)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001039 this->error(s.fOffset,
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001040 "static switch contains non-static conditional break");
1041 s.fIsStatic = false;
1042 }
1043 return; // can't simplify
1044 }
1045 } else {
1046 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
1047 }
1048 }
1049 *outUpdated = true;
1050 *outNeedsRescan = true;
1051 }
1052 break;
1053 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001054 case Statement::kExpression_Kind: {
1055 ExpressionStatement& e = (ExpressionStatement&) *stmt;
1056 ASSERT((*iter)->statement()->get() == &e);
Ethan Nicholascb670962017-04-20 19:31:52 -04001057 if (!e.fExpression->hasSideEffects()) {
1058 // Expression statement with no side effects, kill it
1059 if (!b.tryRemoveExpressionBefore(iter, e.fExpression.get())) {
1060 *outNeedsRescan = true;
1061 }
1062 ASSERT((*iter)->statement()->get() == stmt);
1063 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
1064 *outUpdated = true;
1065 }
1066 break;
1067 }
1068 default:
1069 break;
1070 }
1071}
1072
1073void Compiler::scanCFG(FunctionDefinition& f) {
1074 CFG cfg = CFGGenerator().getCFG(f);
1075 this->computeDataFlow(&cfg);
ethannicholas22f939e2016-10-13 13:25:34 -07001076
1077 // check for unreachable code
1078 for (size_t i = 0; i < cfg.fBlocks.size(); i++) {
Mike Klein6ad99092016-10-26 10:35:22 -04001079 if (i != cfg.fStart && !cfg.fBlocks[i].fEntrances.size() &&
ethannicholas22f939e2016-10-13 13:25:34 -07001080 cfg.fBlocks[i].fNodes.size()) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001081 int offset;
Ethan Nicholas86a43402017-01-19 13:32:00 -05001082 switch (cfg.fBlocks[i].fNodes[0].fKind) {
1083 case BasicBlock::Node::kStatement_Kind:
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001084 offset = (*cfg.fBlocks[i].fNodes[0].statement())->fOffset;
Ethan Nicholas86a43402017-01-19 13:32:00 -05001085 break;
1086 case BasicBlock::Node::kExpression_Kind:
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001087 offset = (*cfg.fBlocks[i].fNodes[0].expression())->fOffset;
Ethan Nicholas86a43402017-01-19 13:32:00 -05001088 break;
1089 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001090 this->error(offset, String("unreachable"));
ethannicholas22f939e2016-10-13 13:25:34 -07001091 }
1092 }
1093 if (fErrorCount) {
1094 return;
1095 }
1096
Ethan Nicholascb670962017-04-20 19:31:52 -04001097 // check for dead code & undefined variables, perform constant propagation
1098 std::unordered_set<const Variable*> undefinedVariables;
1099 bool updated;
1100 bool needsRescan = false;
1101 do {
1102 if (needsRescan) {
1103 cfg = CFGGenerator().getCFG(f);
1104 this->computeDataFlow(&cfg);
1105 needsRescan = false;
Ethan Nicholas113628d2017-02-02 16:11:39 -05001106 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001107
1108 updated = false;
1109 for (BasicBlock& b : cfg.fBlocks) {
1110 DefinitionMap definitions = b.fBefore;
1111
1112 for (auto iter = b.fNodes.begin(); iter != b.fNodes.end() && !needsRescan; ++iter) {
1113 if (iter->fKind == BasicBlock::Node::kExpression_Kind) {
1114 this->simplifyExpression(definitions, b, &iter, &undefinedVariables, &updated,
1115 &needsRescan);
1116 } else {
1117 this->simplifyStatement(definitions, b, &iter, &undefinedVariables, &updated,
1118 &needsRescan);
1119 }
Ethan Nicholas4b330df2017-05-17 10:52:55 -04001120 if (needsRescan) {
1121 break;
1122 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001123 this->addDefinitions(*iter, &definitions);
1124 }
1125 }
1126 } while (updated);
1127 ASSERT(!needsRescan);
ethannicholas22f939e2016-10-13 13:25:34 -07001128
Ethan Nicholas91a10532017-06-22 11:24:38 -04001129 // verify static ifs & switches, clean up dead variable decls
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001130 for (BasicBlock& b : cfg.fBlocks) {
1131 DefinitionMap definitions = b.fBefore;
1132
Ethan Nicholas91a10532017-06-22 11:24:38 -04001133 for (auto iter = b.fNodes.begin(); iter != b.fNodes.end() && !needsRescan;) {
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001134 if (iter->fKind == BasicBlock::Node::kStatement_Kind) {
1135 const Statement& s = **iter->statement();
1136 switch (s.fKind) {
1137 case Statement::kIf_Kind:
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -04001138 if (((const IfStatement&) s).fIsStatic &&
1139 !(fFlags & kPermitInvalidStaticTests_Flag)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001140 this->error(s.fOffset, "static if has non-static test");
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001141 }
Ethan Nicholas91a10532017-06-22 11:24:38 -04001142 ++iter;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001143 break;
1144 case Statement::kSwitch_Kind:
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -04001145 if (((const SwitchStatement&) s).fIsStatic &&
1146 !(fFlags & kPermitInvalidStaticTests_Flag)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001147 this->error(s.fOffset, "static switch has non-static test");
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001148 }
Ethan Nicholas91a10532017-06-22 11:24:38 -04001149 ++iter;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001150 break;
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001151 case Statement::kVarDeclarations_Kind: {
1152 VarDeclarations& decls = *((VarDeclarationsStatement&) s).fDeclaration;
1153 for (auto varIter = decls.fVars.begin(); varIter != decls.fVars.end();) {
1154 if ((*varIter)->fKind == Statement::kNop_Kind) {
1155 varIter = decls.fVars.erase(varIter);
1156 } else {
1157 ++varIter;
1158 }
1159 }
1160 if (!decls.fVars.size()) {
1161 iter = b.fNodes.erase(iter);
1162 } else {
1163 ++iter;
1164 }
1165 break;
1166 }
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001167 default:
Ethan Nicholas91a10532017-06-22 11:24:38 -04001168 ++iter;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001169 break;
1170 }
Ethan Nicholas91a10532017-06-22 11:24:38 -04001171 } else {
1172 ++iter;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001173 }
1174 }
1175 }
1176
ethannicholas22f939e2016-10-13 13:25:34 -07001177 // check for missing return
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001178 if (f.fDeclaration.fReturnType != *fContext->fVoid_Type) {
ethannicholas22f939e2016-10-13 13:25:34 -07001179 if (cfg.fBlocks[cfg.fExit].fEntrances.size()) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001180 this->error(f.fOffset, String("function can exit without returning a value"));
ethannicholas22f939e2016-10-13 13:25:34 -07001181 }
1182 }
1183}
1184
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001185std::unique_ptr<Program> Compiler::convertProgram(Program::Kind kind, String text,
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001186 const Program::Settings& settings) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001187 fErrorText = "";
1188 fErrorCount = 0;
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001189 fIRGenerator->start(&settings);
ethannicholasd598f792016-07-25 10:08:54 -07001190 std::vector<std::unique_ptr<ProgramElement>> elements;
ethannicholasb3058bd2016-07-01 08:22:01 -07001191 switch (kind) {
1192 case Program::kVertex_Kind:
Robert Phillipsfe8da172018-01-24 14:52:02 +00001193 fIRGenerator->convertProgram(kind, SKSL_VERT_INCLUDE, strlen(SKSL_VERT_INCLUDE),
1194 *fTypes, &elements);
ethannicholasb3058bd2016-07-01 08:22:01 -07001195 break;
1196 case Program::kFragment_Kind:
Robert Phillipsfe8da172018-01-24 14:52:02 +00001197 fIRGenerator->convertProgram(kind, SKSL_FRAG_INCLUDE, strlen(SKSL_FRAG_INCLUDE),
1198 *fTypes, &elements);
ethannicholasb3058bd2016-07-01 08:22:01 -07001199 break;
Ethan Nicholas52cad152017-02-16 16:37:32 -05001200 case Program::kGeometry_Kind:
Robert Phillipsfe8da172018-01-24 14:52:02 +00001201 fIRGenerator->convertProgram(kind, SKSL_GEOM_INCLUDE, strlen(SKSL_GEOM_INCLUDE),
1202 *fTypes, &elements);
Ethan Nicholas52cad152017-02-16 16:37:32 -05001203 break;
Ethan Nicholas762466e2017-06-29 10:03:38 -04001204 case Program::kFragmentProcessor_Kind:
Robert Phillipsfe8da172018-01-24 14:52:02 +00001205 fIRGenerator->convertProgram(kind, SKSL_FP_INCLUDE, strlen(SKSL_FP_INCLUDE), *fTypes,
Ethan Nicholasf7b88202017-09-18 14:10:39 -04001206 &elements);
Ethan Nicholas762466e2017-06-29 10:03:38 -04001207 break;
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001208 case Program::kCPU_Kind:
1209 fIRGenerator->convertProgram(kind, SKSL_CPU_INCLUDE, strlen(SKSL_CPU_INCLUDE),
1210 *fTypes, &elements);
1211 break;
ethannicholasb3058bd2016-07-01 08:22:01 -07001212 }
ethannicholasddb37d62016-10-20 09:54:00 -07001213 fIRGenerator->fSymbolTable->markAllFunctionsBuiltin();
Ethan Nicholasaae47c82017-11-10 15:34:03 -05001214 for (auto& element : elements) {
1215 if (element->fKind == ProgramElement::kEnum_Kind) {
1216 ((Enum&) *element).fBuiltin = true;
1217 }
1218 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001219 std::unique_ptr<String> textPtr(new String(std::move(text)));
1220 fSource = textPtr.get();
Robert Phillipsfe8da172018-01-24 14:52:02 +00001221 fIRGenerator->convertProgram(kind, textPtr->c_str(), textPtr->size(), *fTypes, &elements);
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -04001222 if (!fErrorCount) {
1223 for (auto& element : elements) {
1224 if (element->fKind == ProgramElement::kFunction_Kind) {
1225 this->scanCFG((FunctionDefinition&) *element);
1226 }
1227 }
1228 }
Ethan Nicholasf7b88202017-09-18 14:10:39 -04001229 auto result = std::unique_ptr<Program>(new Program(kind,
1230 std::move(textPtr),
1231 settings,
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001232 fContext,
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001233 std::move(elements),
1234 fIRGenerator->fSymbolTable,
1235 fIRGenerator->fInputs));
Ethan Nicholas3605ace2016-11-21 15:59:48 -05001236 fIRGenerator->finish();
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001237 fSource = nullptr;
ethannicholasb3058bd2016-07-01 08:22:01 -07001238 this->writeErrorCount();
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001239 if (fErrorCount) {
1240 return nullptr;
1241 }
1242 return result;
1243}
1244
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001245bool Compiler::toSPIRV(const Program& program, OutputStream& out) {
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001246#ifdef SK_ENABLE_SPIRV_VALIDATION
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001247 StringStream buffer;
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001248 fSource = program.fSource.get();
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001249 SPIRVCodeGenerator cg(fContext.get(), &program, this, &buffer);
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001250 bool result = cg.generateCode();
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001251 fSource = nullptr;
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001252 if (result) {
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001253 spvtools::SpirvTools tools(SPV_ENV_VULKAN_1_0);
Ethan Nicholas762466e2017-06-29 10:03:38 -04001254 const String& data = buffer.str();
1255 ASSERT(0 == data.size() % 4);
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001256 auto dumpmsg = [](spv_message_level_t, const char*, const spv_position_t&, const char* m) {
1257 SkDebugf("SPIR-V validation error: %s\n", m);
1258 };
1259 tools.SetMessageConsumer(dumpmsg);
1260 // Verify that the SPIR-V we produced is valid. If this assert fails, check the logs prior
1261 // to the failure to see the validation errors.
Ethan Nicholas762466e2017-06-29 10:03:38 -04001262 ASSERT_RESULT(tools.Validate((const uint32_t*) data.c_str(), data.size() / 4));
1263 out.write(data.c_str(), data.size());
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001264 }
1265#else
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001266 fSource = program.fSource.get();
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001267 SPIRVCodeGenerator cg(fContext.get(), &program, this, &out);
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001268 bool result = cg.generateCode();
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001269 fSource = nullptr;
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001270#endif
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001271 this->writeErrorCount();
Ethan Nicholasce33f102016-12-09 17:22:59 -05001272 return result;
1273}
1274
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001275bool Compiler::toSPIRV(const Program& program, String* out) {
1276 StringStream buffer;
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001277 bool result = this->toSPIRV(program, buffer);
1278 if (result) {
Ethan Nicholas762466e2017-06-29 10:03:38 -04001279 *out = buffer.str();
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001280 }
1281 return result;
1282}
1283
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001284bool Compiler::toGLSL(const Program& program, OutputStream& out) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001285 fSource = program.fSource.get();
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001286 GLSLCodeGenerator cg(fContext.get(), &program, this, &out);
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001287 bool result = cg.generateCode();
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001288 fSource = nullptr;
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001289 this->writeErrorCount();
1290 return result;
1291}
1292
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001293bool Compiler::toGLSL(const Program& program, String* out) {
1294 StringStream buffer;
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001295 bool result = this->toGLSL(program, buffer);
1296 if (result) {
Ethan Nicholas762466e2017-06-29 10:03:38 -04001297 *out = buffer.str();
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001298 }
1299 return result;
1300}
1301
Ethan Nicholascc305772017-10-13 16:17:45 -04001302bool Compiler::toMetal(const Program& program, OutputStream& out) {
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001303 MetalCodeGenerator cg(fContext.get(), &program, this, &out);
Ethan Nicholascc305772017-10-13 16:17:45 -04001304 bool result = cg.generateCode();
1305 this->writeErrorCount();
1306 return result;
1307}
1308
Ethan Nicholas762466e2017-06-29 10:03:38 -04001309bool Compiler::toCPP(const Program& program, String name, OutputStream& out) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001310 fSource = program.fSource.get();
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001311 CPPCodeGenerator cg(fContext.get(), &program, this, name, &out);
Ethan Nicholas762466e2017-06-29 10:03:38 -04001312 bool result = cg.generateCode();
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001313 fSource = nullptr;
Ethan Nicholas762466e2017-06-29 10:03:38 -04001314 this->writeErrorCount();
1315 return result;
1316}
1317
1318bool Compiler::toH(const Program& program, String name, OutputStream& out) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001319 fSource = program.fSource.get();
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001320 HCodeGenerator cg(fContext.get(), &program, this, name, &out);
Ethan Nicholas762466e2017-06-29 10:03:38 -04001321 bool result = cg.generateCode();
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001322 fSource = nullptr;
Ethan Nicholas762466e2017-06-29 10:03:38 -04001323 this->writeErrorCount();
1324 return result;
1325}
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001326
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001327const char* Compiler::OperatorName(Token::Kind kind) {
1328 switch (kind) {
1329 case Token::PLUS: return "+";
1330 case Token::MINUS: return "-";
1331 case Token::STAR: return "*";
1332 case Token::SLASH: return "/";
1333 case Token::PERCENT: return "%";
1334 case Token::SHL: return "<<";
1335 case Token::SHR: return ">>";
1336 case Token::LOGICALNOT: return "!";
1337 case Token::LOGICALAND: return "&&";
1338 case Token::LOGICALOR: return "||";
1339 case Token::LOGICALXOR: return "^^";
1340 case Token::BITWISENOT: return "~";
1341 case Token::BITWISEAND: return "&";
1342 case Token::BITWISEOR: return "|";
1343 case Token::BITWISEXOR: return "^";
1344 case Token::EQ: return "=";
1345 case Token::EQEQ: return "==";
1346 case Token::NEQ: return "!=";
1347 case Token::LT: return "<";
1348 case Token::GT: return ">";
1349 case Token::LTEQ: return "<=";
1350 case Token::GTEQ: return ">=";
1351 case Token::PLUSEQ: return "+=";
1352 case Token::MINUSEQ: return "-=";
1353 case Token::STAREQ: return "*=";
1354 case Token::SLASHEQ: return "/=";
1355 case Token::PERCENTEQ: return "%=";
1356 case Token::SHLEQ: return "<<=";
1357 case Token::SHREQ: return ">>=";
1358 case Token::LOGICALANDEQ: return "&&=";
1359 case Token::LOGICALOREQ: return "||=";
1360 case Token::LOGICALXOREQ: return "^^=";
1361 case Token::BITWISEANDEQ: return "&=";
1362 case Token::BITWISEOREQ: return "|=";
1363 case Token::BITWISEXOREQ: return "^=";
1364 case Token::PLUSPLUS: return "++";
1365 case Token::MINUSMINUS: return "--";
1366 case Token::COMMA: return ",";
1367 default:
1368 ABORT("unsupported operator: %d\n", kind);
1369 }
1370}
1371
1372
1373bool Compiler::IsAssignment(Token::Kind op) {
1374 switch (op) {
1375 case Token::EQ: // fall through
1376 case Token::PLUSEQ: // fall through
1377 case Token::MINUSEQ: // fall through
1378 case Token::STAREQ: // fall through
1379 case Token::SLASHEQ: // fall through
1380 case Token::PERCENTEQ: // fall through
1381 case Token::SHLEQ: // fall through
1382 case Token::SHREQ: // fall through
1383 case Token::BITWISEOREQ: // fall through
1384 case Token::BITWISEXOREQ: // fall through
1385 case Token::BITWISEANDEQ: // fall through
1386 case Token::LOGICALOREQ: // fall through
1387 case Token::LOGICALXOREQ: // fall through
1388 case Token::LOGICALANDEQ:
1389 return true;
1390 default:
1391 return false;
1392 }
1393}
1394
1395Position Compiler::position(int offset) {
1396 ASSERT(fSource);
1397 int line = 1;
1398 int column = 1;
1399 for (int i = 0; i < offset; i++) {
1400 if ((*fSource)[i] == '\n') {
1401 ++line;
1402 column = 1;
1403 }
1404 else {
1405 ++column;
1406 }
1407 }
1408 return Position(line, column);
1409}
1410
1411void Compiler::error(int offset, String msg) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001412 fErrorCount++;
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001413 Position pos = this->position(offset);
1414 fErrorText += "error: " + to_string(pos.fLine) + ": " + msg.c_str() + "\n";
ethannicholasb3058bd2016-07-01 08:22:01 -07001415}
1416
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001417String Compiler::errorText() {
1418 String result = fErrorText;
ethannicholasb3058bd2016-07-01 08:22:01 -07001419 return result;
1420}
1421
1422void Compiler::writeErrorCount() {
1423 if (fErrorCount) {
1424 fErrorText += to_string(fErrorCount) + " error";
1425 if (fErrorCount > 1) {
1426 fErrorText += "s";
1427 }
1428 fErrorText += "\n";
1429 }
1430}
1431
ethannicholasb3058bd2016-07-01 08:22:01 -07001432} // namespace