blob: 638e4d64bfd0d2bda52186e7379ee6a605ff5500 [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
ethannicholasb3058bd2016-07-01 08:22:01 -070054namespace SkSL {
55
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -040056Compiler::Compiler(Flags flags)
57: fFlags(flags)
58, fErrorCount(0) {
Ethan Nicholas8feeff92017-03-30 14:11:58 -040059 auto types = std::shared_ptr<SymbolTable>(new SymbolTable(this));
60 auto symbols = std::shared_ptr<SymbolTable>(new SymbolTable(types, this));
ethannicholasd598f792016-07-25 10:08:54 -070061 fIRGenerator = new IRGenerator(&fContext, symbols, *this);
ethannicholasb3058bd2016-07-01 08:22:01 -070062 fTypes = types;
ethannicholasd598f792016-07-25 10:08:54 -070063 #define ADD_TYPE(t) types->addWithoutOwnership(fContext.f ## t ## _Type->fName, \
64 fContext.f ## t ## _Type.get())
ethannicholasb3058bd2016-07-01 08:22:01 -070065 ADD_TYPE(Void);
66 ADD_TYPE(Float);
Ethan Nicholas5af9ea32017-07-28 15:19:46 -040067 ADD_TYPE(Float2);
68 ADD_TYPE(Float3);
69 ADD_TYPE(Float4);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -040070 ADD_TYPE(Half);
71 ADD_TYPE(Half2);
72 ADD_TYPE(Half3);
73 ADD_TYPE(Half4);
ethannicholasb3058bd2016-07-01 08:22:01 -070074 ADD_TYPE(Double);
Ethan Nicholas5af9ea32017-07-28 15:19:46 -040075 ADD_TYPE(Double2);
76 ADD_TYPE(Double3);
77 ADD_TYPE(Double4);
ethannicholasb3058bd2016-07-01 08:22:01 -070078 ADD_TYPE(Int);
Ethan Nicholas5af9ea32017-07-28 15:19:46 -040079 ADD_TYPE(Int2);
80 ADD_TYPE(Int3);
81 ADD_TYPE(Int4);
ethannicholasb3058bd2016-07-01 08:22:01 -070082 ADD_TYPE(UInt);
Ethan Nicholas5af9ea32017-07-28 15:19:46 -040083 ADD_TYPE(UInt2);
84 ADD_TYPE(UInt3);
85 ADD_TYPE(UInt4);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -040086 ADD_TYPE(Short);
87 ADD_TYPE(Short2);
88 ADD_TYPE(Short3);
89 ADD_TYPE(Short4);
90 ADD_TYPE(UShort);
91 ADD_TYPE(UShort2);
92 ADD_TYPE(UShort3);
93 ADD_TYPE(UShort4);
ethannicholasb3058bd2016-07-01 08:22:01 -070094 ADD_TYPE(Bool);
Ethan Nicholas5af9ea32017-07-28 15:19:46 -040095 ADD_TYPE(Bool2);
96 ADD_TYPE(Bool3);
97 ADD_TYPE(Bool4);
98 ADD_TYPE(Float2x2);
99 ADD_TYPE(Float2x3);
100 ADD_TYPE(Float2x4);
101 ADD_TYPE(Float3x2);
102 ADD_TYPE(Float3x3);
103 ADD_TYPE(Float3x4);
104 ADD_TYPE(Float4x2);
105 ADD_TYPE(Float4x3);
106 ADD_TYPE(Float4x4);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -0400107 ADD_TYPE(Half2x2);
108 ADD_TYPE(Half2x3);
109 ADD_TYPE(Half2x4);
110 ADD_TYPE(Half3x2);
111 ADD_TYPE(Half3x3);
112 ADD_TYPE(Half3x4);
113 ADD_TYPE(Half4x2);
114 ADD_TYPE(Half4x3);
115 ADD_TYPE(Half4x4);
116 ADD_TYPE(Double2x2);
117 ADD_TYPE(Double2x3);
118 ADD_TYPE(Double2x4);
119 ADD_TYPE(Double3x2);
120 ADD_TYPE(Double3x3);
121 ADD_TYPE(Double3x4);
122 ADD_TYPE(Double4x2);
123 ADD_TYPE(Double4x3);
124 ADD_TYPE(Double4x4);
ethannicholasb3058bd2016-07-01 08:22:01 -0700125 ADD_TYPE(GenType);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -0400126 ADD_TYPE(GenHType);
ethannicholasb3058bd2016-07-01 08:22:01 -0700127 ADD_TYPE(GenDType);
128 ADD_TYPE(GenIType);
129 ADD_TYPE(GenUType);
130 ADD_TYPE(GenBType);
131 ADD_TYPE(Mat);
132 ADD_TYPE(Vec);
133 ADD_TYPE(GVec);
134 ADD_TYPE(GVec2);
135 ADD_TYPE(GVec3);
136 ADD_TYPE(GVec4);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -0400137 ADD_TYPE(HVec);
ethannicholasb3058bd2016-07-01 08:22:01 -0700138 ADD_TYPE(DVec);
139 ADD_TYPE(IVec);
140 ADD_TYPE(UVec);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -0400141 ADD_TYPE(SVec);
142 ADD_TYPE(USVec);
ethannicholasb3058bd2016-07-01 08:22:01 -0700143 ADD_TYPE(BVec);
144
145 ADD_TYPE(Sampler1D);
146 ADD_TYPE(Sampler2D);
147 ADD_TYPE(Sampler3D);
ethannicholas5961bc92016-10-12 06:39:56 -0700148 ADD_TYPE(SamplerExternalOES);
ethannicholasb3058bd2016-07-01 08:22:01 -0700149 ADD_TYPE(SamplerCube);
150 ADD_TYPE(Sampler2DRect);
151 ADD_TYPE(Sampler1DArray);
152 ADD_TYPE(Sampler2DArray);
153 ADD_TYPE(SamplerCubeArray);
154 ADD_TYPE(SamplerBuffer);
155 ADD_TYPE(Sampler2DMS);
156 ADD_TYPE(Sampler2DMSArray);
157
Brian Salomonbf7b6202016-11-11 16:08:03 -0500158 ADD_TYPE(ISampler2D);
159
Brian Salomon2a51de82016-11-16 12:06:01 -0500160 ADD_TYPE(Image2D);
161 ADD_TYPE(IImage2D);
162
Greg Daniel64773e62016-11-22 09:44:03 -0500163 ADD_TYPE(SubpassInput);
164 ADD_TYPE(SubpassInputMS);
165
ethannicholasb3058bd2016-07-01 08:22:01 -0700166 ADD_TYPE(GSampler1D);
167 ADD_TYPE(GSampler2D);
168 ADD_TYPE(GSampler3D);
169 ADD_TYPE(GSamplerCube);
170 ADD_TYPE(GSampler2DRect);
171 ADD_TYPE(GSampler1DArray);
172 ADD_TYPE(GSampler2DArray);
173 ADD_TYPE(GSamplerCubeArray);
174 ADD_TYPE(GSamplerBuffer);
175 ADD_TYPE(GSampler2DMS);
176 ADD_TYPE(GSampler2DMSArray);
177
178 ADD_TYPE(Sampler1DShadow);
179 ADD_TYPE(Sampler2DShadow);
180 ADD_TYPE(SamplerCubeShadow);
181 ADD_TYPE(Sampler2DRectShadow);
182 ADD_TYPE(Sampler1DArrayShadow);
183 ADD_TYPE(Sampler2DArrayShadow);
184 ADD_TYPE(SamplerCubeArrayShadow);
185 ADD_TYPE(GSampler2DArrayShadow);
186 ADD_TYPE(GSamplerCubeArrayShadow);
Ethan Nicholas762466e2017-06-29 10:03:38 -0400187 ADD_TYPE(ColorSpaceXform);
ethannicholasb3058bd2016-07-01 08:22:01 -0700188
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700189 StringFragment skCapsName("sk_Caps");
190 Variable* skCaps = new Variable(-1, Modifiers(), skCapsName,
Ethan Nicholas3605ace2016-11-21 15:59:48 -0500191 *fContext.fSkCaps_Type, Variable::kGlobal_Storage);
192 fIRGenerator->fSymbolTable->add(skCapsName, std::unique_ptr<Symbol>(skCaps));
193
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700194 StringFragment skArgsName("sk_Args");
195 Variable* skArgs = new Variable(-1, Modifiers(), skArgsName,
Ethan Nicholas762466e2017-06-29 10:03:38 -0400196 *fContext.fSkArgs_Type, Variable::kGlobal_Storage);
197 fIRGenerator->fSymbolTable->add(skArgsName, std::unique_ptr<Symbol>(skArgs));
198
Ethan Nicholas27185a92017-09-18 02:41:08 +0000199 Modifiers::Flag ignored1;
200 std::vector<std::unique_ptr<ProgramElement>> ignored2;
201 fIRGenerator->convertProgram(SKSL_INCLUDE, strlen(SKSL_INCLUDE), *fTypes, &ignored1, &ignored2);
ethannicholasddb37d62016-10-20 09:54:00 -0700202 fIRGenerator->fSymbolTable->markAllFunctionsBuiltin();
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700203 if (fErrorCount) {
204 printf("Unexpected errors: %s\n", fErrorText.c_str());
205 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700206 ASSERT(!fErrorCount);
207}
208
209Compiler::~Compiler() {
210 delete fIRGenerator;
211}
212
ethannicholas22f939e2016-10-13 13:25:34 -0700213// add the definition created by assigning to the lvalue to the definition set
Ethan Nicholas86a43402017-01-19 13:32:00 -0500214void Compiler::addDefinition(const Expression* lvalue, std::unique_ptr<Expression>* expr,
215 DefinitionMap* definitions) {
ethannicholas22f939e2016-10-13 13:25:34 -0700216 switch (lvalue->fKind) {
217 case Expression::kVariableReference_Kind: {
218 const Variable& var = ((VariableReference*) lvalue)->fVariable;
219 if (var.fStorage == Variable::kLocal_Storage) {
220 (*definitions)[&var] = expr;
221 }
222 break;
223 }
224 case Expression::kSwizzle_Kind:
225 // We consider the variable written to as long as at least some of its components have
226 // been written to. This will lead to some false negatives (we won't catch it if you
227 // write to foo.x and then read foo.y), but being stricter could lead to false positives
Mike Klein6ad99092016-10-26 10:35:22 -0400228 // (we write to foo.x, and then pass foo to a function which happens to only read foo.x,
229 // 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 -0700230 // more complicated whole-program analysis. This is probably good enough.
Mike Klein6ad99092016-10-26 10:35:22 -0400231 this->addDefinition(((Swizzle*) lvalue)->fBase.get(),
Ethan Nicholas86a43402017-01-19 13:32:00 -0500232 (std::unique_ptr<Expression>*) &fContext.fDefined_Expression,
ethannicholas22f939e2016-10-13 13:25:34 -0700233 definitions);
234 break;
235 case Expression::kIndex_Kind:
236 // see comments in Swizzle
Mike Klein6ad99092016-10-26 10:35:22 -0400237 this->addDefinition(((IndexExpression*) lvalue)->fBase.get(),
Ethan Nicholas86a43402017-01-19 13:32:00 -0500238 (std::unique_ptr<Expression>*) &fContext.fDefined_Expression,
ethannicholas22f939e2016-10-13 13:25:34 -0700239 definitions);
240 break;
241 case Expression::kFieldAccess_Kind:
242 // see comments in Swizzle
Mike Klein6ad99092016-10-26 10:35:22 -0400243 this->addDefinition(((FieldAccess*) lvalue)->fBase.get(),
Ethan Nicholas86a43402017-01-19 13:32:00 -0500244 (std::unique_ptr<Expression>*) &fContext.fDefined_Expression,
ethannicholas22f939e2016-10-13 13:25:34 -0700245 definitions);
246 break;
247 default:
248 // not an lvalue, can't happen
249 ASSERT(false);
250 }
251}
252
253// add local variables defined by this node to the set
Mike Klein6ad99092016-10-26 10:35:22 -0400254void Compiler::addDefinitions(const BasicBlock::Node& node,
Ethan Nicholas86a43402017-01-19 13:32:00 -0500255 DefinitionMap* definitions) {
ethannicholas22f939e2016-10-13 13:25:34 -0700256 switch (node.fKind) {
257 case BasicBlock::Node::kExpression_Kind: {
Ethan Nicholascb670962017-04-20 19:31:52 -0400258 ASSERT(node.expression());
259 const Expression* expr = (Expression*) node.expression()->get();
Ethan Nicholas86a43402017-01-19 13:32:00 -0500260 switch (expr->fKind) {
261 case Expression::kBinary_Kind: {
262 BinaryExpression* b = (BinaryExpression*) expr;
263 if (b->fOperator == Token::EQ) {
264 this->addDefinition(b->fLeft.get(), &b->fRight, definitions);
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700265 } else if (Compiler::IsAssignment(b->fOperator)) {
Ethan Nicholas86a43402017-01-19 13:32:00 -0500266 this->addDefinition(
267 b->fLeft.get(),
268 (std::unique_ptr<Expression>*) &fContext.fDefined_Expression,
269 definitions);
270
271 }
272 break;
ethannicholas22f939e2016-10-13 13:25:34 -0700273 }
Ethan Nicholas86a43402017-01-19 13:32:00 -0500274 case Expression::kPrefix_Kind: {
275 const PrefixExpression* p = (PrefixExpression*) expr;
276 if (p->fOperator == Token::MINUSMINUS || p->fOperator == Token::PLUSPLUS) {
277 this->addDefinition(
278 p->fOperand.get(),
279 (std::unique_ptr<Expression>*) &fContext.fDefined_Expression,
280 definitions);
281 }
282 break;
283 }
284 case Expression::kPostfix_Kind: {
285 const PostfixExpression* p = (PostfixExpression*) expr;
286 if (p->fOperator == Token::MINUSMINUS || p->fOperator == Token::PLUSPLUS) {
287 this->addDefinition(
288 p->fOperand.get(),
289 (std::unique_ptr<Expression>*) &fContext.fDefined_Expression,
290 definitions);
Ethan Nicholas86a43402017-01-19 13:32:00 -0500291 }
292 break;
293 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400294 case Expression::kVariableReference_Kind: {
295 const VariableReference* v = (VariableReference*) expr;
296 if (v->fRefKind != VariableReference::kRead_RefKind) {
297 this->addDefinition(
298 v,
299 (std::unique_ptr<Expression>*) &fContext.fDefined_Expression,
300 definitions);
301 }
302 }
Ethan Nicholas86a43402017-01-19 13:32:00 -0500303 default:
304 break;
ethannicholas22f939e2016-10-13 13:25:34 -0700305 }
306 break;
307 }
308 case BasicBlock::Node::kStatement_Kind: {
Ethan Nicholascb670962017-04-20 19:31:52 -0400309 const Statement* stmt = (Statement*) node.statement()->get();
Ethan Nicholasb4dc4192017-06-02 10:16:28 -0400310 if (stmt->fKind == Statement::kVarDeclaration_Kind) {
311 VarDeclaration& vd = (VarDeclaration&) *stmt;
312 if (vd.fValue) {
313 (*definitions)[vd.fVar] = &vd.fValue;
ethannicholas22f939e2016-10-13 13:25:34 -0700314 }
315 }
316 break;
317 }
318 }
319}
320
321void Compiler::scanCFG(CFG* cfg, BlockId blockId, std::set<BlockId>* workList) {
322 BasicBlock& block = cfg->fBlocks[blockId];
323
324 // compute definitions after this block
Ethan Nicholas86a43402017-01-19 13:32:00 -0500325 DefinitionMap after = block.fBefore;
ethannicholas22f939e2016-10-13 13:25:34 -0700326 for (const BasicBlock::Node& n : block.fNodes) {
327 this->addDefinitions(n, &after);
328 }
329
330 // propagate definitions to exits
331 for (BlockId exitId : block.fExits) {
332 BasicBlock& exit = cfg->fBlocks[exitId];
333 for (const auto& pair : after) {
Ethan Nicholas86a43402017-01-19 13:32:00 -0500334 std::unique_ptr<Expression>* e1 = pair.second;
335 auto found = exit.fBefore.find(pair.first);
336 if (found == exit.fBefore.end()) {
337 // exit has no definition for it, just copy it
338 workList->insert(exitId);
ethannicholas22f939e2016-10-13 13:25:34 -0700339 exit.fBefore[pair.first] = e1;
340 } else {
Ethan Nicholas86a43402017-01-19 13:32:00 -0500341 // exit has a (possibly different) value already defined
342 std::unique_ptr<Expression>* e2 = exit.fBefore[pair.first];
ethannicholas22f939e2016-10-13 13:25:34 -0700343 if (e1 != e2) {
344 // definition has changed, merge and add exit block to worklist
345 workList->insert(exitId);
Ethan Nicholasaf197692017-02-27 13:26:45 -0500346 if (e1 && e2) {
347 exit.fBefore[pair.first] =
Ethan Nicholas86a43402017-01-19 13:32:00 -0500348 (std::unique_ptr<Expression>*) &fContext.fDefined_Expression;
Ethan Nicholasaf197692017-02-27 13:26:45 -0500349 } else {
350 exit.fBefore[pair.first] = nullptr;
351 }
ethannicholas22f939e2016-10-13 13:25:34 -0700352 }
353 }
354 }
355 }
356}
357
358// returns a map which maps all local variables in the function to null, indicating that their value
359// is initially unknown
Ethan Nicholas86a43402017-01-19 13:32:00 -0500360static DefinitionMap compute_start_state(const CFG& cfg) {
361 DefinitionMap result;
Mike Klein6ad99092016-10-26 10:35:22 -0400362 for (const auto& block : cfg.fBlocks) {
363 for (const auto& node : block.fNodes) {
ethannicholas22f939e2016-10-13 13:25:34 -0700364 if (node.fKind == BasicBlock::Node::kStatement_Kind) {
Ethan Nicholascb670962017-04-20 19:31:52 -0400365 ASSERT(node.statement());
366 const Statement* s = node.statement()->get();
ethannicholas22f939e2016-10-13 13:25:34 -0700367 if (s->fKind == Statement::kVarDeclarations_Kind) {
368 const VarDeclarationsStatement* vd = (const VarDeclarationsStatement*) s;
Ethan Nicholascb670962017-04-20 19:31:52 -0400369 for (const auto& decl : vd->fDeclaration->fVars) {
Ethan Nicholas91a10532017-06-22 11:24:38 -0400370 if (decl->fKind == Statement::kVarDeclaration_Kind) {
371 result[((VarDeclaration&) *decl).fVar] = nullptr;
372 }
Mike Klein6ad99092016-10-26 10:35:22 -0400373 }
ethannicholas22f939e2016-10-13 13:25:34 -0700374 }
375 }
376 }
377 }
378 return result;
379}
380
Ethan Nicholascb670962017-04-20 19:31:52 -0400381/**
382 * Returns true if assigning to this lvalue has no effect.
383 */
384static bool is_dead(const Expression& lvalue) {
385 switch (lvalue.fKind) {
386 case Expression::kVariableReference_Kind:
387 return ((VariableReference&) lvalue).fVariable.dead();
388 case Expression::kSwizzle_Kind:
389 return is_dead(*((Swizzle&) lvalue).fBase);
390 case Expression::kFieldAccess_Kind:
391 return is_dead(*((FieldAccess&) lvalue).fBase);
392 case Expression::kIndex_Kind: {
393 const IndexExpression& idx = (IndexExpression&) lvalue;
394 return is_dead(*idx.fBase) && !idx.fIndex->hasSideEffects();
395 }
396 default:
397 ABORT("invalid lvalue: %s\n", lvalue.description().c_str());
398 }
399}
ethannicholas22f939e2016-10-13 13:25:34 -0700400
Ethan Nicholascb670962017-04-20 19:31:52 -0400401/**
402 * Returns true if this is an assignment which can be collapsed down to just the right hand side due
403 * to a dead target and lack of side effects on the left hand side.
404 */
405static bool dead_assignment(const BinaryExpression& b) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700406 if (!Compiler::IsAssignment(b.fOperator)) {
Ethan Nicholascb670962017-04-20 19:31:52 -0400407 return false;
408 }
409 return is_dead(*b.fLeft);
410}
411
412void Compiler::computeDataFlow(CFG* cfg) {
413 cfg->fBlocks[cfg->fStart].fBefore = compute_start_state(*cfg);
ethannicholas22f939e2016-10-13 13:25:34 -0700414 std::set<BlockId> workList;
Ethan Nicholascb670962017-04-20 19:31:52 -0400415 for (BlockId i = 0; i < cfg->fBlocks.size(); i++) {
ethannicholas22f939e2016-10-13 13:25:34 -0700416 workList.insert(i);
417 }
418 while (workList.size()) {
419 BlockId next = *workList.begin();
420 workList.erase(workList.begin());
Ethan Nicholascb670962017-04-20 19:31:52 -0400421 this->scanCFG(cfg, next, &workList);
ethannicholas22f939e2016-10-13 13:25:34 -0700422 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400423}
424
425/**
426 * Attempts to replace the expression pointed to by iter with a new one (in both the CFG and the
427 * IR). If the expression can be cleanly removed, returns true and updates the iterator to point to
428 * the newly-inserted element. Otherwise updates only the IR and returns false (and the CFG will
429 * need to be regenerated).
430 */
431bool try_replace_expression(BasicBlock* b,
432 std::vector<BasicBlock::Node>::iterator* iter,
433 std::unique_ptr<Expression>* newExpression) {
434 std::unique_ptr<Expression>* target = (*iter)->expression();
435 if (!b->tryRemoveExpression(iter)) {
436 *target = std::move(*newExpression);
437 return false;
438 }
439 *target = std::move(*newExpression);
440 return b->tryInsertExpression(iter, target);
441}
442
443/**
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400444 * Returns true if the expression is a constant numeric literal with the specified value, or a
445 * constant vector with all elements equal to the specified value.
Ethan Nicholascb670962017-04-20 19:31:52 -0400446 */
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400447bool is_constant(const Expression& expr, double value) {
Ethan Nicholascb670962017-04-20 19:31:52 -0400448 switch (expr.fKind) {
449 case Expression::kIntLiteral_Kind:
450 return ((IntLiteral&) expr).fValue == value;
451 case Expression::kFloatLiteral_Kind:
452 return ((FloatLiteral&) expr).fValue == value;
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400453 case Expression::kConstructor_Kind: {
454 Constructor& c = (Constructor&) expr;
455 if (c.fType.kind() == Type::kVector_Kind && c.isConstant()) {
456 for (int i = 0; i < c.fType.columns(); ++i) {
457 if (!is_constant(c.getVecComponent(i), value)) {
458 return false;
459 }
460 }
461 return true;
462 }
463 return false;
464 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400465 default:
466 return false;
467 }
468}
469
470/**
471 * Collapses the binary expression pointed to by iter down to just the right side (in both the IR
472 * and CFG structures).
473 */
474void delete_left(BasicBlock* b,
475 std::vector<BasicBlock::Node>::iterator* iter,
476 bool* outUpdated,
477 bool* outNeedsRescan) {
478 *outUpdated = true;
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400479 std::unique_ptr<Expression>* target = (*iter)->expression();
480 ASSERT((*target)->fKind == Expression::kBinary_Kind);
481 BinaryExpression& bin = (BinaryExpression&) **target;
482 bool result;
483 if (bin.fOperator == Token::EQ) {
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400484 result = b->tryRemoveLValueBefore(iter, bin.fLeft.get());
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400485 } else {
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400486 result = b->tryRemoveExpressionBefore(iter, bin.fLeft.get());
Ethan Nicholascb670962017-04-20 19:31:52 -0400487 }
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400488 *target = std::move(bin.fRight);
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400489 if (!result) {
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400490 *outNeedsRescan = true;
491 return;
492 }
493 if (*iter == b->fNodes.begin()) {
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400494 *outNeedsRescan = true;
495 return;
496 }
497 --(*iter);
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400498 if ((*iter)->fKind != BasicBlock::Node::kExpression_Kind ||
499 (*iter)->expression() != &bin.fRight) {
500 *outNeedsRescan = true;
501 return;
502 }
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400503 *iter = b->fNodes.erase(*iter);
504 ASSERT((*iter)->expression() == target);
Ethan Nicholascb670962017-04-20 19:31:52 -0400505}
506
507/**
508 * Collapses the binary expression pointed to by iter down to just the left side (in both the IR and
509 * CFG structures).
510 */
511void delete_right(BasicBlock* b,
512 std::vector<BasicBlock::Node>::iterator* iter,
513 bool* outUpdated,
514 bool* outNeedsRescan) {
515 *outUpdated = true;
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400516 std::unique_ptr<Expression>* target = (*iter)->expression();
517 ASSERT((*target)->fKind == Expression::kBinary_Kind);
518 BinaryExpression& bin = (BinaryExpression&) **target;
519 if (!b->tryRemoveExpressionBefore(iter, bin.fRight.get())) {
520 *target = std::move(bin.fLeft);
Ethan Nicholascb670962017-04-20 19:31:52 -0400521 *outNeedsRescan = true;
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400522 return;
Ethan Nicholascb670962017-04-20 19:31:52 -0400523 }
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400524 *target = std::move(bin.fLeft);
525 if (*iter == b->fNodes.begin()) {
526 *outNeedsRescan = true;
527 return;
528 }
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400529 --(*iter);
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400530 if (((*iter)->fKind != BasicBlock::Node::kExpression_Kind ||
531 (*iter)->expression() != &bin.fLeft)) {
532 *outNeedsRescan = true;
533 return;
534 }
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400535 *iter = b->fNodes.erase(*iter);
536 ASSERT((*iter)->expression() == target);
Ethan Nicholascb670962017-04-20 19:31:52 -0400537}
538
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400539/**
540 * Constructs the specified type using a single argument.
541 */
542static std::unique_ptr<Expression> construct(const Type& type, std::unique_ptr<Expression> v) {
543 std::vector<std::unique_ptr<Expression>> args;
544 args.push_back(std::move(v));
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700545 auto result = std::unique_ptr<Expression>(new Constructor(-1, type, std::move(args)));
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400546 return result;
547}
548
549/**
550 * Used in the implementations of vectorize_left and vectorize_right. Given a vector type and an
551 * expression x, deletes the expression pointed to by iter and replaces it with <type>(x).
552 */
553static void vectorize(BasicBlock* b,
554 std::vector<BasicBlock::Node>::iterator* iter,
555 const Type& type,
556 std::unique_ptr<Expression>* otherExpression,
557 bool* outUpdated,
558 bool* outNeedsRescan) {
559 ASSERT((*(*iter)->expression())->fKind == Expression::kBinary_Kind);
560 ASSERT(type.kind() == Type::kVector_Kind);
561 ASSERT((*otherExpression)->fType.kind() == Type::kScalar_Kind);
562 *outUpdated = true;
563 std::unique_ptr<Expression>* target = (*iter)->expression();
564 if (!b->tryRemoveExpression(iter)) {
565 *target = construct(type, std::move(*otherExpression));
566 *outNeedsRescan = true;
567 } else {
568 *target = construct(type, std::move(*otherExpression));
569 if (!b->tryInsertExpression(iter, target)) {
570 *outNeedsRescan = true;
571 }
572 }
573}
574
575/**
576 * Given a binary expression of the form x <op> vec<n>(y), deletes the right side and vectorizes the
577 * left to yield vec<n>(x).
578 */
579static void vectorize_left(BasicBlock* b,
580 std::vector<BasicBlock::Node>::iterator* iter,
581 bool* outUpdated,
582 bool* outNeedsRescan) {
583 BinaryExpression& bin = (BinaryExpression&) **(*iter)->expression();
584 vectorize(b, iter, bin.fRight->fType, &bin.fLeft, outUpdated, outNeedsRescan);
585}
586
587/**
588 * Given a binary expression of the form vec<n>(x) <op> y, deletes the left side and vectorizes the
589 * right to yield vec<n>(y).
590 */
591static void vectorize_right(BasicBlock* b,
592 std::vector<BasicBlock::Node>::iterator* iter,
593 bool* outUpdated,
594 bool* outNeedsRescan) {
595 BinaryExpression& bin = (BinaryExpression&) **(*iter)->expression();
596 vectorize(b, iter, bin.fLeft->fType, &bin.fRight, outUpdated, outNeedsRescan);
597}
598
599// Mark that an expression which we were writing to is no longer being written to
600void clear_write(const Expression& expr) {
601 switch (expr.fKind) {
602 case Expression::kVariableReference_Kind: {
603 ((VariableReference&) expr).setRefKind(VariableReference::kRead_RefKind);
604 break;
605 }
606 case Expression::kFieldAccess_Kind:
607 clear_write(*((FieldAccess&) expr).fBase);
608 break;
609 case Expression::kSwizzle_Kind:
610 clear_write(*((Swizzle&) expr).fBase);
611 break;
612 case Expression::kIndex_Kind:
613 clear_write(*((IndexExpression&) expr).fBase);
614 break;
615 default:
616 ABORT("shouldn't be writing to this kind of expression\n");
617 break;
618 }
619}
620
Ethan Nicholascb670962017-04-20 19:31:52 -0400621void Compiler::simplifyExpression(DefinitionMap& definitions,
622 BasicBlock& b,
623 std::vector<BasicBlock::Node>::iterator* iter,
624 std::unordered_set<const Variable*>* undefinedVariables,
625 bool* outUpdated,
626 bool* outNeedsRescan) {
627 Expression* expr = (*iter)->expression()->get();
628 ASSERT(expr);
629 if ((*iter)->fConstantPropagation) {
630 std::unique_ptr<Expression> optimized = expr->constantPropagate(*fIRGenerator, definitions);
631 if (optimized) {
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400632 *outUpdated = true;
Ethan Nicholascb670962017-04-20 19:31:52 -0400633 if (!try_replace_expression(&b, iter, &optimized)) {
634 *outNeedsRescan = true;
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400635 return;
Ethan Nicholascb670962017-04-20 19:31:52 -0400636 }
637 ASSERT((*iter)->fKind == BasicBlock::Node::kExpression_Kind);
638 expr = (*iter)->expression()->get();
Ethan Nicholascb670962017-04-20 19:31:52 -0400639 }
640 }
641 switch (expr->fKind) {
642 case Expression::kVariableReference_Kind: {
643 const Variable& var = ((VariableReference*) expr)->fVariable;
644 if (var.fStorage == Variable::kLocal_Storage && !definitions[&var] &&
645 (*undefinedVariables).find(&var) == (*undefinedVariables).end()) {
646 (*undefinedVariables).insert(&var);
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700647 this->error(expr->fOffset,
Ethan Nicholascb670962017-04-20 19:31:52 -0400648 "'" + var.fName + "' has not been assigned");
649 }
650 break;
651 }
652 case Expression::kTernary_Kind: {
653 TernaryExpression* t = (TernaryExpression*) expr;
654 if (t->fTest->fKind == Expression::kBoolLiteral_Kind) {
655 // ternary has a constant test, replace it with either the true or
656 // false branch
657 if (((BoolLiteral&) *t->fTest).fValue) {
658 (*iter)->setExpression(std::move(t->fIfTrue));
659 } else {
660 (*iter)->setExpression(std::move(t->fIfFalse));
661 }
662 *outUpdated = true;
663 *outNeedsRescan = true;
664 }
665 break;
666 }
667 case Expression::kBinary_Kind: {
Ethan Nicholascb670962017-04-20 19:31:52 -0400668 BinaryExpression* bin = (BinaryExpression*) expr;
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400669 if (dead_assignment(*bin)) {
670 delete_left(&b, iter, outUpdated, outNeedsRescan);
671 break;
672 }
673 // collapse useless expressions like x * 1 or x + 0
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400674 if (((bin->fLeft->fType.kind() != Type::kScalar_Kind) &&
675 (bin->fLeft->fType.kind() != Type::kVector_Kind)) ||
676 ((bin->fRight->fType.kind() != Type::kScalar_Kind) &&
677 (bin->fRight->fType.kind() != Type::kVector_Kind))) {
678 break;
679 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400680 switch (bin->fOperator) {
681 case Token::STAR:
682 if (is_constant(*bin->fLeft, 1)) {
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400683 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(1) * x -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400686 vectorize_right(&b, iter, outUpdated, outNeedsRescan);
687 } else {
688 // 1 * x -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400689 // 1 * float4(x) -> float4(x)
690 // float4(1) * float4(x) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400691 delete_left(&b, iter, outUpdated, outNeedsRescan);
692 }
693 }
694 else if (is_constant(*bin->fLeft, 0)) {
695 if (bin->fLeft->fType.kind() == Type::kScalar_Kind &&
696 bin->fRight->fType.kind() == Type::kVector_Kind) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400697 // 0 * float4(x) -> float4(0)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400698 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
699 } else {
700 // 0 * x -> 0
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400701 // float4(0) * x -> float4(0)
702 // float4(0) * float4(x) -> float4(0)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400703 delete_right(&b, iter, outUpdated, outNeedsRescan);
704 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400705 }
706 else if (is_constant(*bin->fRight, 1)) {
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400707 if (bin->fLeft->fType.kind() == Type::kScalar_Kind &&
708 bin->fRight->fType.kind() == Type::kVector_Kind) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400709 // x * float4(1) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400710 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
711 } else {
712 // x * 1 -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400713 // float4(x) * 1 -> float4(x)
714 // float4(x) * float4(1) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400715 delete_right(&b, iter, outUpdated, outNeedsRescan);
716 }
717 }
718 else if (is_constant(*bin->fRight, 0)) {
719 if (bin->fLeft->fType.kind() == Type::kVector_Kind &&
720 bin->fRight->fType.kind() == Type::kScalar_Kind) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400721 // float4(x) * 0 -> float4(0)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400722 vectorize_right(&b, iter, outUpdated, outNeedsRescan);
723 } else {
724 // x * 0 -> 0
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400725 // x * float4(0) -> float4(0)
726 // float4(x) * float4(0) -> float4(0)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400727 delete_left(&b, iter, outUpdated, outNeedsRescan);
728 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400729 }
730 break;
Ethan Nicholas56e42712017-04-21 10:23:37 -0400731 case Token::PLUS:
Ethan Nicholascb670962017-04-20 19:31:52 -0400732 if (is_constant(*bin->fLeft, 0)) {
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400733 if (bin->fLeft->fType.kind() == Type::kVector_Kind &&
734 bin->fRight->fType.kind() == Type::kScalar_Kind) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400735 // float4(0) + x -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400736 vectorize_right(&b, iter, outUpdated, outNeedsRescan);
737 } else {
738 // 0 + x -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400739 // 0 + float4(x) -> float4(x)
740 // float4(0) + float4(x) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400741 delete_left(&b, iter, outUpdated, outNeedsRescan);
742 }
743 } else if (is_constant(*bin->fRight, 0)) {
744 if (bin->fLeft->fType.kind() == Type::kScalar_Kind &&
745 bin->fRight->fType.kind() == Type::kVector_Kind) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400746 // x + float4(0) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400747 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
748 } else {
749 // x + 0 -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400750 // float4(x) + 0 -> float4(x)
751 // float4(x) + float4(0) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400752 delete_right(&b, iter, outUpdated, outNeedsRescan);
753 }
Ethan Nicholas56e42712017-04-21 10:23:37 -0400754 }
755 break;
756 case Token::MINUS:
757 if (is_constant(*bin->fRight, 0)) {
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400758 if (bin->fLeft->fType.kind() == Type::kScalar_Kind &&
759 bin->fRight->fType.kind() == Type::kVector_Kind) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400760 // x - float4(0) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400761 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
762 } else {
763 // x - 0 -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400764 // float4(x) - 0 -> float4(x)
765 // float4(x) - float4(0) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400766 delete_right(&b, iter, outUpdated, outNeedsRescan);
767 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400768 }
769 break;
770 case Token::SLASH:
771 if (is_constant(*bin->fRight, 1)) {
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400772 if (bin->fLeft->fType.kind() == Type::kScalar_Kind &&
773 bin->fRight->fType.kind() == Type::kVector_Kind) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400774 // x / float4(1) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400775 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
776 } else {
777 // x / 1 -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400778 // float4(x) / 1 -> float4(x)
779 // float4(x) / float4(1) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400780 delete_right(&b, iter, outUpdated, outNeedsRescan);
781 }
782 } else if (is_constant(*bin->fLeft, 0)) {
783 if (bin->fLeft->fType.kind() == Type::kScalar_Kind &&
784 bin->fRight->fType.kind() == Type::kVector_Kind) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400785 // 0 / float4(x) -> float4(0)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400786 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
787 } else {
788 // 0 / x -> 0
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400789 // float4(0) / x -> float4(0)
790 // float4(0) / float4(x) -> float4(0)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400791 delete_right(&b, iter, outUpdated, outNeedsRescan);
792 }
793 }
794 break;
795 case Token::PLUSEQ:
796 if (is_constant(*bin->fRight, 0)) {
797 clear_write(*bin->fLeft);
798 delete_right(&b, iter, outUpdated, outNeedsRescan);
799 }
800 break;
801 case Token::MINUSEQ:
802 if (is_constant(*bin->fRight, 0)) {
803 clear_write(*bin->fLeft);
804 delete_right(&b, iter, outUpdated, outNeedsRescan);
805 }
806 break;
807 case Token::STAREQ:
808 if (is_constant(*bin->fRight, 1)) {
809 clear_write(*bin->fLeft);
810 delete_right(&b, iter, outUpdated, outNeedsRescan);
811 }
812 break;
813 case Token::SLASHEQ:
814 if (is_constant(*bin->fRight, 1)) {
815 clear_write(*bin->fLeft);
Ethan Nicholascb670962017-04-20 19:31:52 -0400816 delete_right(&b, iter, outUpdated, outNeedsRescan);
817 }
818 break;
819 default:
820 break;
821 }
822 }
823 default:
824 break;
825 }
826}
827
Ethan Nicholas5ac13c22017-05-10 15:06:17 -0400828// returns true if this statement could potentially execute a break at the current level (we ignore
829// nested loops and switches, since any breaks inside of them will merely break the loop / switch)
830static bool contains_break(Statement& s) {
831 switch (s.fKind) {
832 case Statement::kBlock_Kind:
833 for (const auto& sub : ((Block&) s).fStatements) {
834 if (contains_break(*sub)) {
835 return true;
836 }
837 }
838 return false;
839 case Statement::kBreak_Kind:
840 return true;
841 case Statement::kIf_Kind: {
842 const IfStatement& i = (IfStatement&) s;
843 return contains_break(*i.fIfTrue) || (i.fIfFalse && contains_break(*i.fIfFalse));
844 }
845 default:
846 return false;
847 }
848}
849
850// Returns a block containing all of the statements that will be run if the given case matches
851// (which, owing to the statements being owned by unique_ptrs, means the switch itself will be
852// broken by this call and must then be discarded).
853// Returns null (and leaves the switch unmodified) if no such simple reduction is possible, such as
854// when break statements appear inside conditionals.
855static std::unique_ptr<Statement> block_for_case(SwitchStatement* s, SwitchCase* c) {
856 bool capturing = false;
857 std::vector<std::unique_ptr<Statement>*> statementPtrs;
858 for (const auto& current : s->fCases) {
859 if (current.get() == c) {
860 capturing = true;
861 }
862 if (capturing) {
863 for (auto& stmt : current->fStatements) {
864 if (stmt->fKind == Statement::kBreak_Kind) {
865 capturing = false;
866 break;
867 }
868 if (contains_break(*stmt)) {
869 return nullptr;
870 }
871 statementPtrs.push_back(&stmt);
872 }
873 if (!capturing) {
874 break;
875 }
876 }
877 }
878 std::vector<std::unique_ptr<Statement>> statements;
879 for (const auto& s : statementPtrs) {
880 statements.push_back(std::move(*s));
881 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700882 return std::unique_ptr<Statement>(new Block(-1, std::move(statements), s->fSymbols));
Ethan Nicholas5ac13c22017-05-10 15:06:17 -0400883}
884
Ethan Nicholascb670962017-04-20 19:31:52 -0400885void Compiler::simplifyStatement(DefinitionMap& definitions,
Ethan Nicholas5ac13c22017-05-10 15:06:17 -0400886 BasicBlock& b,
887 std::vector<BasicBlock::Node>::iterator* iter,
888 std::unordered_set<const Variable*>* undefinedVariables,
889 bool* outUpdated,
890 bool* outNeedsRescan) {
Ethan Nicholascb670962017-04-20 19:31:52 -0400891 Statement* stmt = (*iter)->statement()->get();
892 switch (stmt->fKind) {
Ethan Nicholasb4dc4192017-06-02 10:16:28 -0400893 case Statement::kVarDeclaration_Kind: {
894 const auto& varDecl = (VarDeclaration&) *stmt;
895 if (varDecl.fVar->dead() &&
896 (!varDecl.fValue ||
897 !varDecl.fValue->hasSideEffects())) {
898 if (varDecl.fValue) {
899 ASSERT((*iter)->statement()->get() == stmt);
900 if (!b.tryRemoveExpressionBefore(iter, varDecl.fValue.get())) {
901 *outNeedsRescan = true;
Ethan Nicholascb670962017-04-20 19:31:52 -0400902 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400903 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400904 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
Ethan Nicholasb4dc4192017-06-02 10:16:28 -0400905 *outUpdated = true;
Ethan Nicholascb670962017-04-20 19:31:52 -0400906 }
907 break;
908 }
909 case Statement::kIf_Kind: {
910 IfStatement& i = (IfStatement&) *stmt;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -0400911 if (i.fTest->fKind == Expression::kBoolLiteral_Kind) {
912 // constant if, collapse down to a single branch
913 if (((BoolLiteral&) *i.fTest).fValue) {
914 ASSERT(i.fIfTrue);
915 (*iter)->setStatement(std::move(i.fIfTrue));
916 } else {
917 if (i.fIfFalse) {
918 (*iter)->setStatement(std::move(i.fIfFalse));
919 } else {
920 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
921 }
922 }
923 *outUpdated = true;
924 *outNeedsRescan = true;
925 break;
926 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400927 if (i.fIfFalse && i.fIfFalse->isEmpty()) {
928 // else block doesn't do anything, remove it
929 i.fIfFalse.reset();
930 *outUpdated = true;
931 *outNeedsRescan = true;
932 }
933 if (!i.fIfFalse && i.fIfTrue->isEmpty()) {
934 // if block doesn't do anything, no else block
935 if (i.fTest->hasSideEffects()) {
936 // test has side effects, keep it
937 (*iter)->setStatement(std::unique_ptr<Statement>(
938 new ExpressionStatement(std::move(i.fTest))));
939 } else {
940 // no if, no else, no test side effects, kill the whole if
941 // statement
942 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
943 }
944 *outUpdated = true;
945 *outNeedsRescan = true;
946 }
947 break;
948 }
Ethan Nicholas5ac13c22017-05-10 15:06:17 -0400949 case Statement::kSwitch_Kind: {
950 SwitchStatement& s = (SwitchStatement&) *stmt;
951 if (s.fValue->isConstant()) {
952 // switch is constant, replace it with the case that matches
953 bool found = false;
954 SwitchCase* defaultCase = nullptr;
955 for (const auto& c : s.fCases) {
956 if (!c->fValue) {
957 defaultCase = c.get();
958 continue;
959 }
960 ASSERT(c->fValue->fKind == s.fValue->fKind);
961 found = c->fValue->compareConstant(fContext, *s.fValue);
962 if (found) {
963 std::unique_ptr<Statement> newBlock = block_for_case(&s, c.get());
964 if (newBlock) {
965 (*iter)->setStatement(std::move(newBlock));
966 break;
967 } else {
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -0400968 if (s.fIsStatic && !(fFlags & kPermitInvalidStaticTests_Flag)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700969 this->error(s.fOffset,
Ethan Nicholas5ac13c22017-05-10 15:06:17 -0400970 "static switch contains non-static conditional break");
971 s.fIsStatic = false;
972 }
973 return; // can't simplify
974 }
975 }
976 }
977 if (!found) {
978 // no matching case. use default if it exists, or kill the whole thing
979 if (defaultCase) {
980 std::unique_ptr<Statement> newBlock = block_for_case(&s, defaultCase);
981 if (newBlock) {
982 (*iter)->setStatement(std::move(newBlock));
983 } else {
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -0400984 if (s.fIsStatic && !(fFlags & kPermitInvalidStaticTests_Flag)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700985 this->error(s.fOffset,
Ethan Nicholas5ac13c22017-05-10 15:06:17 -0400986 "static switch contains non-static conditional break");
987 s.fIsStatic = false;
988 }
989 return; // can't simplify
990 }
991 } else {
992 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
993 }
994 }
995 *outUpdated = true;
996 *outNeedsRescan = true;
997 }
998 break;
999 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001000 case Statement::kExpression_Kind: {
1001 ExpressionStatement& e = (ExpressionStatement&) *stmt;
1002 ASSERT((*iter)->statement()->get() == &e);
Ethan Nicholascb670962017-04-20 19:31:52 -04001003 if (!e.fExpression->hasSideEffects()) {
1004 // Expression statement with no side effects, kill it
1005 if (!b.tryRemoveExpressionBefore(iter, e.fExpression.get())) {
1006 *outNeedsRescan = true;
1007 }
1008 ASSERT((*iter)->statement()->get() == stmt);
1009 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
1010 *outUpdated = true;
1011 }
1012 break;
1013 }
1014 default:
1015 break;
1016 }
1017}
1018
1019void Compiler::scanCFG(FunctionDefinition& f) {
1020 CFG cfg = CFGGenerator().getCFG(f);
1021 this->computeDataFlow(&cfg);
ethannicholas22f939e2016-10-13 13:25:34 -07001022
1023 // check for unreachable code
1024 for (size_t i = 0; i < cfg.fBlocks.size(); i++) {
Mike Klein6ad99092016-10-26 10:35:22 -04001025 if (i != cfg.fStart && !cfg.fBlocks[i].fEntrances.size() &&
ethannicholas22f939e2016-10-13 13:25:34 -07001026 cfg.fBlocks[i].fNodes.size()) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001027 int offset;
Ethan Nicholas86a43402017-01-19 13:32:00 -05001028 switch (cfg.fBlocks[i].fNodes[0].fKind) {
1029 case BasicBlock::Node::kStatement_Kind:
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001030 offset = (*cfg.fBlocks[i].fNodes[0].statement())->fOffset;
Ethan Nicholas86a43402017-01-19 13:32:00 -05001031 break;
1032 case BasicBlock::Node::kExpression_Kind:
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001033 offset = (*cfg.fBlocks[i].fNodes[0].expression())->fOffset;
Ethan Nicholas86a43402017-01-19 13:32:00 -05001034 break;
1035 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001036 this->error(offset, String("unreachable"));
ethannicholas22f939e2016-10-13 13:25:34 -07001037 }
1038 }
1039 if (fErrorCount) {
1040 return;
1041 }
1042
Ethan Nicholascb670962017-04-20 19:31:52 -04001043 // check for dead code & undefined variables, perform constant propagation
1044 std::unordered_set<const Variable*> undefinedVariables;
1045 bool updated;
1046 bool needsRescan = false;
1047 do {
1048 if (needsRescan) {
1049 cfg = CFGGenerator().getCFG(f);
1050 this->computeDataFlow(&cfg);
1051 needsRescan = false;
Ethan Nicholas113628d2017-02-02 16:11:39 -05001052 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001053
1054 updated = false;
1055 for (BasicBlock& b : cfg.fBlocks) {
1056 DefinitionMap definitions = b.fBefore;
1057
1058 for (auto iter = b.fNodes.begin(); iter != b.fNodes.end() && !needsRescan; ++iter) {
1059 if (iter->fKind == BasicBlock::Node::kExpression_Kind) {
1060 this->simplifyExpression(definitions, b, &iter, &undefinedVariables, &updated,
1061 &needsRescan);
1062 } else {
1063 this->simplifyStatement(definitions, b, &iter, &undefinedVariables, &updated,
1064 &needsRescan);
1065 }
Ethan Nicholas4b330df2017-05-17 10:52:55 -04001066 if (needsRescan) {
1067 break;
1068 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001069 this->addDefinitions(*iter, &definitions);
1070 }
1071 }
1072 } while (updated);
1073 ASSERT(!needsRescan);
ethannicholas22f939e2016-10-13 13:25:34 -07001074
Ethan Nicholas91a10532017-06-22 11:24:38 -04001075 // verify static ifs & switches, clean up dead variable decls
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001076 for (BasicBlock& b : cfg.fBlocks) {
1077 DefinitionMap definitions = b.fBefore;
1078
Ethan Nicholas91a10532017-06-22 11:24:38 -04001079 for (auto iter = b.fNodes.begin(); iter != b.fNodes.end() && !needsRescan;) {
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001080 if (iter->fKind == BasicBlock::Node::kStatement_Kind) {
1081 const Statement& s = **iter->statement();
1082 switch (s.fKind) {
1083 case Statement::kIf_Kind:
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -04001084 if (((const IfStatement&) s).fIsStatic &&
1085 !(fFlags & kPermitInvalidStaticTests_Flag)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001086 this->error(s.fOffset, "static if has non-static test");
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001087 }
Ethan Nicholas91a10532017-06-22 11:24:38 -04001088 ++iter;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001089 break;
1090 case Statement::kSwitch_Kind:
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -04001091 if (((const SwitchStatement&) s).fIsStatic &&
1092 !(fFlags & kPermitInvalidStaticTests_Flag)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001093 this->error(s.fOffset, "static switch has non-static test");
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001094 }
Ethan Nicholas91a10532017-06-22 11:24:38 -04001095 ++iter;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001096 break;
Ethan Nicholas91a10532017-06-22 11:24:38 -04001097 case Statement::kVarDeclarations_Kind: {
1098 VarDeclarations& decls = *((VarDeclarationsStatement&) s).fDeclaration;
1099 for (auto varIter = decls.fVars.begin(); varIter != decls.fVars.end();) {
1100 if ((*varIter)->fKind == Statement::kNop_Kind) {
1101 varIter = decls.fVars.erase(varIter);
1102 } else {
1103 ++varIter;
1104 }
1105 }
1106 if (!decls.fVars.size()) {
1107 iter = b.fNodes.erase(iter);
1108 } else {
1109 ++iter;
1110 }
1111 break;
1112 }
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001113 default:
Ethan Nicholas91a10532017-06-22 11:24:38 -04001114 ++iter;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001115 break;
1116 }
Ethan Nicholas91a10532017-06-22 11:24:38 -04001117 } else {
1118 ++iter;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001119 }
1120 }
1121 }
1122
ethannicholas22f939e2016-10-13 13:25:34 -07001123 // check for missing return
1124 if (f.fDeclaration.fReturnType != *fContext.fVoid_Type) {
1125 if (cfg.fBlocks[cfg.fExit].fEntrances.size()) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001126 this->error(f.fOffset, String("function can exit without returning a value"));
ethannicholas22f939e2016-10-13 13:25:34 -07001127 }
1128 }
1129}
1130
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001131std::unique_ptr<Program> Compiler::convertProgram(Program::Kind kind, String text,
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001132 const Program::Settings& settings) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001133 fErrorText = "";
1134 fErrorCount = 0;
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001135 fIRGenerator->start(&settings);
ethannicholasd598f792016-07-25 10:08:54 -07001136 std::vector<std::unique_ptr<ProgramElement>> elements;
Ethan Nicholas27185a92017-09-18 02:41:08 +00001137 Modifiers::Flag ignored;
ethannicholasb3058bd2016-07-01 08:22:01 -07001138 switch (kind) {
1139 case Program::kVertex_Kind:
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001140 fIRGenerator->convertProgram(SKSL_VERT_INCLUDE, strlen(SKSL_VERT_INCLUDE), *fTypes,
Ethan Nicholas27185a92017-09-18 02:41:08 +00001141 &ignored, &elements);
ethannicholasb3058bd2016-07-01 08:22:01 -07001142 break;
1143 case Program::kFragment_Kind:
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001144 fIRGenerator->convertProgram(SKSL_FRAG_INCLUDE, strlen(SKSL_FRAG_INCLUDE), *fTypes,
Ethan Nicholas27185a92017-09-18 02:41:08 +00001145 &ignored, &elements);
ethannicholasb3058bd2016-07-01 08:22:01 -07001146 break;
Ethan Nicholas52cad152017-02-16 16:37:32 -05001147 case Program::kGeometry_Kind:
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001148 fIRGenerator->convertProgram(SKSL_GEOM_INCLUDE, strlen(SKSL_GEOM_INCLUDE), *fTypes,
Ethan Nicholas27185a92017-09-18 02:41:08 +00001149 &ignored, &elements);
Ethan Nicholas52cad152017-02-16 16:37:32 -05001150 break;
Ethan Nicholas762466e2017-06-29 10:03:38 -04001151 case Program::kFragmentProcessor_Kind:
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001152 fIRGenerator->convertProgram(SKSL_FP_INCLUDE, strlen(SKSL_FP_INCLUDE), *fTypes,
Ethan Nicholas27185a92017-09-18 02:41:08 +00001153 &ignored, &elements);
Ethan Nicholas762466e2017-06-29 10:03:38 -04001154 break;
ethannicholasb3058bd2016-07-01 08:22:01 -07001155 }
ethannicholasddb37d62016-10-20 09:54:00 -07001156 fIRGenerator->fSymbolTable->markAllFunctionsBuiltin();
Ethan Nicholas27185a92017-09-18 02:41:08 +00001157 Modifiers::Flag defaultPrecision;
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001158 std::unique_ptr<String> textPtr(new String(std::move(text)));
1159 fSource = textPtr.get();
Ethan Nicholas27185a92017-09-18 02:41:08 +00001160 fIRGenerator->convertProgram(textPtr->c_str(), textPtr->size(), *fTypes, &defaultPrecision,
1161 &elements);
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -04001162 if (!fErrorCount) {
1163 for (auto& element : elements) {
1164 if (element->fKind == ProgramElement::kFunction_Kind) {
1165 this->scanCFG((FunctionDefinition&) *element);
1166 }
1167 }
1168 }
Ethan Nicholas27185a92017-09-18 02:41:08 +00001169 auto result = std::unique_ptr<Program>(new Program(kind, std::move(textPtr), settings,
1170 defaultPrecision, &fContext,
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001171 std::move(elements),
1172 fIRGenerator->fSymbolTable,
1173 fIRGenerator->fInputs));
Ethan Nicholas3605ace2016-11-21 15:59:48 -05001174 fIRGenerator->finish();
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001175 fSource = nullptr;
ethannicholasb3058bd2016-07-01 08:22:01 -07001176 this->writeErrorCount();
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001177 if (fErrorCount) {
1178 return nullptr;
1179 }
1180 return result;
1181}
1182
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001183bool Compiler::toSPIRV(const Program& program, OutputStream& out) {
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001184#ifdef SK_ENABLE_SPIRV_VALIDATION
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001185 StringStream buffer;
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001186 fSource = program.fSource.get();
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001187 SPIRVCodeGenerator cg(&fContext, &program, this, &buffer);
1188 bool result = cg.generateCode();
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001189 fSource = nullptr;
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001190 if (result) {
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001191 spvtools::SpirvTools tools(SPV_ENV_VULKAN_1_0);
Ethan Nicholas762466e2017-06-29 10:03:38 -04001192 const String& data = buffer.str();
1193 ASSERT(0 == data.size() % 4);
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001194 auto dumpmsg = [](spv_message_level_t, const char*, const spv_position_t&, const char* m) {
1195 SkDebugf("SPIR-V validation error: %s\n", m);
1196 };
1197 tools.SetMessageConsumer(dumpmsg);
1198 // Verify that the SPIR-V we produced is valid. If this assert fails, check the logs prior
1199 // to the failure to see the validation errors.
Ethan Nicholas762466e2017-06-29 10:03:38 -04001200 ASSERT_RESULT(tools.Validate((const uint32_t*) data.c_str(), data.size() / 4));
1201 out.write(data.c_str(), data.size());
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001202 }
1203#else
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001204 fSource = program.fSource.get();
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001205 SPIRVCodeGenerator cg(&fContext, &program, this, &out);
1206 bool result = cg.generateCode();
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001207 fSource = nullptr;
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001208#endif
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001209 this->writeErrorCount();
Ethan Nicholasce33f102016-12-09 17:22:59 -05001210 return result;
1211}
1212
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001213bool Compiler::toSPIRV(const Program& program, String* out) {
1214 StringStream buffer;
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001215 bool result = this->toSPIRV(program, buffer);
1216 if (result) {
Ethan Nicholas762466e2017-06-29 10:03:38 -04001217 *out = buffer.str();
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001218 }
1219 return result;
1220}
1221
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001222bool Compiler::toGLSL(const Program& program, OutputStream& out) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001223 fSource = program.fSource.get();
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001224 GLSLCodeGenerator cg(&fContext, &program, this, &out);
1225 bool result = cg.generateCode();
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001226 fSource = nullptr;
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001227 this->writeErrorCount();
1228 return result;
1229}
1230
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001231bool Compiler::toGLSL(const Program& program, String* out) {
1232 StringStream buffer;
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001233 bool result = this->toGLSL(program, buffer);
1234 if (result) {
Ethan Nicholas762466e2017-06-29 10:03:38 -04001235 *out = buffer.str();
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001236 }
1237 return result;
1238}
1239
Ethan Nicholas762466e2017-06-29 10:03:38 -04001240bool Compiler::toCPP(const Program& program, String name, OutputStream& out) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001241 fSource = program.fSource.get();
Ethan Nicholas762466e2017-06-29 10:03:38 -04001242 CPPCodeGenerator cg(&fContext, &program, this, name, &out);
1243 bool result = cg.generateCode();
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001244 fSource = nullptr;
Ethan Nicholas762466e2017-06-29 10:03:38 -04001245 this->writeErrorCount();
1246 return result;
1247}
1248
1249bool Compiler::toH(const Program& program, String name, OutputStream& out) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001250 fSource = program.fSource.get();
Ethan Nicholas762466e2017-06-29 10:03:38 -04001251 HCodeGenerator cg(&program, this, name, &out);
1252 bool result = cg.generateCode();
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001253 fSource = nullptr;
Ethan Nicholas762466e2017-06-29 10:03:38 -04001254 this->writeErrorCount();
1255 return result;
1256}
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001257
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001258const char* Compiler::OperatorName(Token::Kind kind) {
1259 switch (kind) {
1260 case Token::PLUS: return "+";
1261 case Token::MINUS: return "-";
1262 case Token::STAR: return "*";
1263 case Token::SLASH: return "/";
1264 case Token::PERCENT: return "%";
1265 case Token::SHL: return "<<";
1266 case Token::SHR: return ">>";
1267 case Token::LOGICALNOT: return "!";
1268 case Token::LOGICALAND: return "&&";
1269 case Token::LOGICALOR: return "||";
1270 case Token::LOGICALXOR: return "^^";
1271 case Token::BITWISENOT: return "~";
1272 case Token::BITWISEAND: return "&";
1273 case Token::BITWISEOR: return "|";
1274 case Token::BITWISEXOR: return "^";
1275 case Token::EQ: return "=";
1276 case Token::EQEQ: return "==";
1277 case Token::NEQ: return "!=";
1278 case Token::LT: return "<";
1279 case Token::GT: return ">";
1280 case Token::LTEQ: return "<=";
1281 case Token::GTEQ: return ">=";
1282 case Token::PLUSEQ: return "+=";
1283 case Token::MINUSEQ: return "-=";
1284 case Token::STAREQ: return "*=";
1285 case Token::SLASHEQ: return "/=";
1286 case Token::PERCENTEQ: return "%=";
1287 case Token::SHLEQ: return "<<=";
1288 case Token::SHREQ: return ">>=";
1289 case Token::LOGICALANDEQ: return "&&=";
1290 case Token::LOGICALOREQ: return "||=";
1291 case Token::LOGICALXOREQ: return "^^=";
1292 case Token::BITWISEANDEQ: return "&=";
1293 case Token::BITWISEOREQ: return "|=";
1294 case Token::BITWISEXOREQ: return "^=";
1295 case Token::PLUSPLUS: return "++";
1296 case Token::MINUSMINUS: return "--";
1297 case Token::COMMA: return ",";
1298 default:
1299 ABORT("unsupported operator: %d\n", kind);
1300 }
1301}
1302
1303
1304bool Compiler::IsAssignment(Token::Kind op) {
1305 switch (op) {
1306 case Token::EQ: // fall through
1307 case Token::PLUSEQ: // fall through
1308 case Token::MINUSEQ: // fall through
1309 case Token::STAREQ: // fall through
1310 case Token::SLASHEQ: // fall through
1311 case Token::PERCENTEQ: // fall through
1312 case Token::SHLEQ: // fall through
1313 case Token::SHREQ: // fall through
1314 case Token::BITWISEOREQ: // fall through
1315 case Token::BITWISEXOREQ: // fall through
1316 case Token::BITWISEANDEQ: // fall through
1317 case Token::LOGICALOREQ: // fall through
1318 case Token::LOGICALXOREQ: // fall through
1319 case Token::LOGICALANDEQ:
1320 return true;
1321 default:
1322 return false;
1323 }
1324}
1325
1326Position Compiler::position(int offset) {
1327 ASSERT(fSource);
1328 int line = 1;
1329 int column = 1;
1330 for (int i = 0; i < offset; i++) {
1331 if ((*fSource)[i] == '\n') {
1332 ++line;
1333 column = 1;
1334 }
1335 else {
1336 ++column;
1337 }
1338 }
1339 return Position(line, column);
1340}
1341
1342void Compiler::error(int offset, String msg) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001343 fErrorCount++;
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001344 Position pos = this->position(offset);
1345 fErrorText += "error: " + to_string(pos.fLine) + ": " + msg.c_str() + "\n";
ethannicholasb3058bd2016-07-01 08:22:01 -07001346}
1347
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001348String Compiler::errorText() {
1349 String result = fErrorText;
ethannicholasb3058bd2016-07-01 08:22:01 -07001350 return result;
1351}
1352
1353void Compiler::writeErrorCount() {
1354 if (fErrorCount) {
1355 fErrorText += to_string(fErrorCount) + " error";
1356 if (fErrorCount > 1) {
1357 fErrorText += "s";
1358 }
1359 fErrorText += "\n";
1360 }
1361}
1362
ethannicholasb3058bd2016-07-01 08:22:01 -07001363} // namespace