blob: 1b04bb1dea391cab065881a1e52452909e9c1446 [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"
17#include "ir/SkSLExpression.h"
Ethan Nicholascb670962017-04-20 19:31:52 -040018#include "ir/SkSLExpressionStatement.h"
ethannicholasb3058bd2016-07-01 08:22:01 -070019#include "ir/SkSLIntLiteral.h"
ethannicholas5961bc92016-10-12 06:39:56 -070020#include "ir/SkSLModifiersDeclaration.h"
Ethan Nicholascb670962017-04-20 19:31:52 -040021#include "ir/SkSLNop.h"
ethannicholasb3058bd2016-07-01 08:22:01 -070022#include "ir/SkSLSymbolTable.h"
Ethan Nicholascb670962017-04-20 19:31:52 -040023#include "ir/SkSLTernaryExpression.h"
ethannicholasddb37d62016-10-20 09:54:00 -070024#include "ir/SkSLUnresolvedFunction.h"
ethannicholas22f939e2016-10-13 13:25:34 -070025#include "ir/SkSLVarDeclarations.h"
ethannicholasb3058bd2016-07-01 08:22:01 -070026
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -040027#ifdef SK_ENABLE_SPIRV_VALIDATION
28#include "spirv-tools/libspirv.hpp"
29#endif
30
ethannicholasb3058bd2016-07-01 08:22:01 -070031#define STRINGIFY(x) #x
32
33// include the built-in shader symbols as static strings
34
ethannicholas5961bc92016-10-12 06:39:56 -070035static const char* SKSL_INCLUDE =
ethannicholasb3058bd2016-07-01 08:22:01 -070036#include "sksl.include"
37;
38
ethannicholas5961bc92016-10-12 06:39:56 -070039static const char* SKSL_VERT_INCLUDE =
ethannicholasb3058bd2016-07-01 08:22:01 -070040#include "sksl_vert.include"
41;
42
ethannicholas5961bc92016-10-12 06:39:56 -070043static const char* SKSL_FRAG_INCLUDE =
ethannicholasb3058bd2016-07-01 08:22:01 -070044#include "sksl_frag.include"
45;
46
Ethan Nicholas52cad152017-02-16 16:37:32 -050047static const char* SKSL_GEOM_INCLUDE =
48#include "sksl_geom.include"
49;
50
Ethan Nicholas762466e2017-06-29 10:03:38 -040051static const char* SKSL_FP_INCLUDE =
52#include "sksl_fp.include"
53;
54
ethannicholasb3058bd2016-07-01 08:22:01 -070055namespace SkSL {
56
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -040057Compiler::Compiler(Flags flags)
58: fFlags(flags)
59, fErrorCount(0) {
Ethan Nicholas8feeff92017-03-30 14:11:58 -040060 auto types = std::shared_ptr<SymbolTable>(new SymbolTable(this));
61 auto symbols = std::shared_ptr<SymbolTable>(new SymbolTable(types, this));
ethannicholasd598f792016-07-25 10:08:54 -070062 fIRGenerator = new IRGenerator(&fContext, symbols, *this);
ethannicholasb3058bd2016-07-01 08:22:01 -070063 fTypes = types;
ethannicholasd598f792016-07-25 10:08:54 -070064 #define ADD_TYPE(t) types->addWithoutOwnership(fContext.f ## t ## _Type->fName, \
65 fContext.f ## t ## _Type.get())
ethannicholasb3058bd2016-07-01 08:22:01 -070066 ADD_TYPE(Void);
67 ADD_TYPE(Float);
Ethan Nicholas5af9ea32017-07-28 15:19:46 -040068 ADD_TYPE(Float2);
69 ADD_TYPE(Float3);
70 ADD_TYPE(Float4);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -040071 ADD_TYPE(Half);
72 ADD_TYPE(Half2);
73 ADD_TYPE(Half3);
74 ADD_TYPE(Half4);
ethannicholasb3058bd2016-07-01 08:22:01 -070075 ADD_TYPE(Double);
Ethan Nicholas5af9ea32017-07-28 15:19:46 -040076 ADD_TYPE(Double2);
77 ADD_TYPE(Double3);
78 ADD_TYPE(Double4);
ethannicholasb3058bd2016-07-01 08:22:01 -070079 ADD_TYPE(Int);
Ethan Nicholas5af9ea32017-07-28 15:19:46 -040080 ADD_TYPE(Int2);
81 ADD_TYPE(Int3);
82 ADD_TYPE(Int4);
ethannicholasb3058bd2016-07-01 08:22:01 -070083 ADD_TYPE(UInt);
Ethan Nicholas5af9ea32017-07-28 15:19:46 -040084 ADD_TYPE(UInt2);
85 ADD_TYPE(UInt3);
86 ADD_TYPE(UInt4);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -040087 ADD_TYPE(Short);
88 ADD_TYPE(Short2);
89 ADD_TYPE(Short3);
90 ADD_TYPE(Short4);
91 ADD_TYPE(UShort);
92 ADD_TYPE(UShort2);
93 ADD_TYPE(UShort3);
94 ADD_TYPE(UShort4);
ethannicholasb3058bd2016-07-01 08:22:01 -070095 ADD_TYPE(Bool);
Ethan Nicholas5af9ea32017-07-28 15:19:46 -040096 ADD_TYPE(Bool2);
97 ADD_TYPE(Bool3);
98 ADD_TYPE(Bool4);
99 ADD_TYPE(Float2x2);
100 ADD_TYPE(Float2x3);
101 ADD_TYPE(Float2x4);
102 ADD_TYPE(Float3x2);
103 ADD_TYPE(Float3x3);
104 ADD_TYPE(Float3x4);
105 ADD_TYPE(Float4x2);
106 ADD_TYPE(Float4x3);
107 ADD_TYPE(Float4x4);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -0400108 ADD_TYPE(Half2x2);
109 ADD_TYPE(Half2x3);
110 ADD_TYPE(Half2x4);
111 ADD_TYPE(Half3x2);
112 ADD_TYPE(Half3x3);
113 ADD_TYPE(Half3x4);
114 ADD_TYPE(Half4x2);
115 ADD_TYPE(Half4x3);
116 ADD_TYPE(Half4x4);
117 ADD_TYPE(Double2x2);
118 ADD_TYPE(Double2x3);
119 ADD_TYPE(Double2x4);
120 ADD_TYPE(Double3x2);
121 ADD_TYPE(Double3x3);
122 ADD_TYPE(Double3x4);
123 ADD_TYPE(Double4x2);
124 ADD_TYPE(Double4x3);
125 ADD_TYPE(Double4x4);
ethannicholasb3058bd2016-07-01 08:22:01 -0700126 ADD_TYPE(GenType);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -0400127 ADD_TYPE(GenHType);
ethannicholasb3058bd2016-07-01 08:22:01 -0700128 ADD_TYPE(GenDType);
129 ADD_TYPE(GenIType);
130 ADD_TYPE(GenUType);
131 ADD_TYPE(GenBType);
132 ADD_TYPE(Mat);
133 ADD_TYPE(Vec);
134 ADD_TYPE(GVec);
135 ADD_TYPE(GVec2);
136 ADD_TYPE(GVec3);
137 ADD_TYPE(GVec4);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -0400138 ADD_TYPE(HVec);
ethannicholasb3058bd2016-07-01 08:22:01 -0700139 ADD_TYPE(DVec);
140 ADD_TYPE(IVec);
141 ADD_TYPE(UVec);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -0400142 ADD_TYPE(SVec);
143 ADD_TYPE(USVec);
ethannicholasb3058bd2016-07-01 08:22:01 -0700144 ADD_TYPE(BVec);
145
146 ADD_TYPE(Sampler1D);
147 ADD_TYPE(Sampler2D);
148 ADD_TYPE(Sampler3D);
ethannicholas5961bc92016-10-12 06:39:56 -0700149 ADD_TYPE(SamplerExternalOES);
ethannicholasb3058bd2016-07-01 08:22:01 -0700150 ADD_TYPE(SamplerCube);
151 ADD_TYPE(Sampler2DRect);
152 ADD_TYPE(Sampler1DArray);
153 ADD_TYPE(Sampler2DArray);
154 ADD_TYPE(SamplerCubeArray);
155 ADD_TYPE(SamplerBuffer);
156 ADD_TYPE(Sampler2DMS);
157 ADD_TYPE(Sampler2DMSArray);
158
Brian Salomonbf7b6202016-11-11 16:08:03 -0500159 ADD_TYPE(ISampler2D);
160
Brian Salomon2a51de82016-11-16 12:06:01 -0500161 ADD_TYPE(Image2D);
162 ADD_TYPE(IImage2D);
163
Greg Daniel64773e62016-11-22 09:44:03 -0500164 ADD_TYPE(SubpassInput);
165 ADD_TYPE(SubpassInputMS);
166
ethannicholasb3058bd2016-07-01 08:22:01 -0700167 ADD_TYPE(GSampler1D);
168 ADD_TYPE(GSampler2D);
169 ADD_TYPE(GSampler3D);
170 ADD_TYPE(GSamplerCube);
171 ADD_TYPE(GSampler2DRect);
172 ADD_TYPE(GSampler1DArray);
173 ADD_TYPE(GSampler2DArray);
174 ADD_TYPE(GSamplerCubeArray);
175 ADD_TYPE(GSamplerBuffer);
176 ADD_TYPE(GSampler2DMS);
177 ADD_TYPE(GSampler2DMSArray);
178
179 ADD_TYPE(Sampler1DShadow);
180 ADD_TYPE(Sampler2DShadow);
181 ADD_TYPE(SamplerCubeShadow);
182 ADD_TYPE(Sampler2DRectShadow);
183 ADD_TYPE(Sampler1DArrayShadow);
184 ADD_TYPE(Sampler2DArrayShadow);
185 ADD_TYPE(SamplerCubeArrayShadow);
186 ADD_TYPE(GSampler2DArrayShadow);
187 ADD_TYPE(GSamplerCubeArrayShadow);
Ethan Nicholasc9472af2017-10-10 16:30:21 -0400188 ADD_TYPE(FragmentProcessor);
ethannicholasb3058bd2016-07-01 08:22:01 -0700189
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700190 StringFragment skCapsName("sk_Caps");
191 Variable* skCaps = new Variable(-1, Modifiers(), skCapsName,
Ethan Nicholas1ae353c2017-11-01 10:47:43 -0400192 *fContext.fSkCaps_Type, Variable::kGlobal_Storage, nullptr,
193 {});
Ethan Nicholas3605ace2016-11-21 15:59:48 -0500194 fIRGenerator->fSymbolTable->add(skCapsName, std::unique_ptr<Symbol>(skCaps));
195
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700196 StringFragment skArgsName("sk_Args");
197 Variable* skArgs = new Variable(-1, Modifiers(), skArgsName,
Ethan Nicholas1ae353c2017-11-01 10:47:43 -0400198 *fContext.fSkArgs_Type, Variable::kGlobal_Storage, nullptr,
199 {});
Ethan Nicholas762466e2017-06-29 10:03:38 -0400200 fIRGenerator->fSymbolTable->add(skArgsName, std::unique_ptr<Symbol>(skArgs));
201
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400202 std::vector<std::unique_ptr<ProgramElement>> ignored;
203 fIRGenerator->convertProgram(SKSL_INCLUDE, strlen(SKSL_INCLUDE), *fTypes, &ignored);
ethannicholasddb37d62016-10-20 09:54:00 -0700204 fIRGenerator->fSymbolTable->markAllFunctionsBuiltin();
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700205 if (fErrorCount) {
206 printf("Unexpected errors: %s\n", fErrorText.c_str());
207 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700208 ASSERT(!fErrorCount);
209}
210
211Compiler::~Compiler() {
212 delete fIRGenerator;
213}
214
ethannicholas22f939e2016-10-13 13:25:34 -0700215// add the definition created by assigning to the lvalue to the definition set
Ethan Nicholas86a43402017-01-19 13:32:00 -0500216void Compiler::addDefinition(const Expression* lvalue, std::unique_ptr<Expression>* expr,
217 DefinitionMap* definitions) {
ethannicholas22f939e2016-10-13 13:25:34 -0700218 switch (lvalue->fKind) {
219 case Expression::kVariableReference_Kind: {
220 const Variable& var = ((VariableReference*) lvalue)->fVariable;
221 if (var.fStorage == Variable::kLocal_Storage) {
222 (*definitions)[&var] = expr;
223 }
224 break;
225 }
226 case Expression::kSwizzle_Kind:
227 // We consider the variable written to as long as at least some of its components have
228 // been written to. This will lead to some false negatives (we won't catch it if you
229 // write to foo.x and then read foo.y), but being stricter could lead to false positives
Mike Klein6ad99092016-10-26 10:35:22 -0400230 // (we write to foo.x, and then pass foo to a function which happens to only read foo.x,
231 // 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 -0700232 // more complicated whole-program analysis. This is probably good enough.
Mike Klein6ad99092016-10-26 10:35:22 -0400233 this->addDefinition(((Swizzle*) lvalue)->fBase.get(),
Ethan Nicholas86a43402017-01-19 13:32:00 -0500234 (std::unique_ptr<Expression>*) &fContext.fDefined_Expression,
ethannicholas22f939e2016-10-13 13:25:34 -0700235 definitions);
236 break;
237 case Expression::kIndex_Kind:
238 // see comments in Swizzle
Mike Klein6ad99092016-10-26 10:35:22 -0400239 this->addDefinition(((IndexExpression*) lvalue)->fBase.get(),
Ethan Nicholas86a43402017-01-19 13:32:00 -0500240 (std::unique_ptr<Expression>*) &fContext.fDefined_Expression,
ethannicholas22f939e2016-10-13 13:25:34 -0700241 definitions);
242 break;
243 case Expression::kFieldAccess_Kind:
244 // see comments in Swizzle
Mike Klein6ad99092016-10-26 10:35:22 -0400245 this->addDefinition(((FieldAccess*) lvalue)->fBase.get(),
Ethan Nicholas86a43402017-01-19 13:32:00 -0500246 (std::unique_ptr<Expression>*) &fContext.fDefined_Expression,
ethannicholas22f939e2016-10-13 13:25:34 -0700247 definitions);
248 break;
249 default:
250 // not an lvalue, can't happen
251 ASSERT(false);
252 }
253}
254
255// add local variables defined by this node to the set
Mike Klein6ad99092016-10-26 10:35:22 -0400256void Compiler::addDefinitions(const BasicBlock::Node& node,
Ethan Nicholas86a43402017-01-19 13:32:00 -0500257 DefinitionMap* definitions) {
ethannicholas22f939e2016-10-13 13:25:34 -0700258 switch (node.fKind) {
259 case BasicBlock::Node::kExpression_Kind: {
Ethan Nicholascb670962017-04-20 19:31:52 -0400260 ASSERT(node.expression());
261 const Expression* expr = (Expression*) node.expression()->get();
Ethan Nicholas86a43402017-01-19 13:32:00 -0500262 switch (expr->fKind) {
263 case Expression::kBinary_Kind: {
264 BinaryExpression* b = (BinaryExpression*) expr;
265 if (b->fOperator == Token::EQ) {
266 this->addDefinition(b->fLeft.get(), &b->fRight, definitions);
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700267 } else if (Compiler::IsAssignment(b->fOperator)) {
Ethan Nicholas86a43402017-01-19 13:32:00 -0500268 this->addDefinition(
269 b->fLeft.get(),
270 (std::unique_ptr<Expression>*) &fContext.fDefined_Expression,
271 definitions);
272
273 }
274 break;
ethannicholas22f939e2016-10-13 13:25:34 -0700275 }
Ethan Nicholas86a43402017-01-19 13:32:00 -0500276 case Expression::kPrefix_Kind: {
277 const PrefixExpression* p = (PrefixExpression*) expr;
278 if (p->fOperator == Token::MINUSMINUS || p->fOperator == Token::PLUSPLUS) {
279 this->addDefinition(
280 p->fOperand.get(),
281 (std::unique_ptr<Expression>*) &fContext.fDefined_Expression,
282 definitions);
283 }
284 break;
285 }
286 case Expression::kPostfix_Kind: {
287 const PostfixExpression* p = (PostfixExpression*) expr;
288 if (p->fOperator == Token::MINUSMINUS || p->fOperator == Token::PLUSPLUS) {
289 this->addDefinition(
290 p->fOperand.get(),
291 (std::unique_ptr<Expression>*) &fContext.fDefined_Expression,
292 definitions);
Ethan Nicholas86a43402017-01-19 13:32:00 -0500293 }
294 break;
295 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400296 case Expression::kVariableReference_Kind: {
297 const VariableReference* v = (VariableReference*) expr;
298 if (v->fRefKind != VariableReference::kRead_RefKind) {
299 this->addDefinition(
300 v,
301 (std::unique_ptr<Expression>*) &fContext.fDefined_Expression,
302 definitions);
303 }
304 }
Ethan Nicholas86a43402017-01-19 13:32:00 -0500305 default:
306 break;
ethannicholas22f939e2016-10-13 13:25:34 -0700307 }
308 break;
309 }
310 case BasicBlock::Node::kStatement_Kind: {
Ethan Nicholascb670962017-04-20 19:31:52 -0400311 const Statement* stmt = (Statement*) node.statement()->get();
Ethan Nicholas1ae353c2017-11-01 10:47:43 -0400312 if (stmt->fKind == Statement::kVarDeclarations_Kind) {
313 for (Variable* var : ((VarDeclarationsStatement*) stmt)->fDeclaration->fVars) {
314 if (var->fInitialValue) {
315 (*definitions)[var] = &var->fInitialValue;
316 }
ethannicholas22f939e2016-10-13 13:25:34 -0700317 }
318 }
319 break;
320 }
321 }
322}
323
324void Compiler::scanCFG(CFG* cfg, BlockId blockId, std::set<BlockId>* workList) {
325 BasicBlock& block = cfg->fBlocks[blockId];
326
327 // compute definitions after this block
Ethan Nicholas86a43402017-01-19 13:32:00 -0500328 DefinitionMap after = block.fBefore;
ethannicholas22f939e2016-10-13 13:25:34 -0700329 for (const BasicBlock::Node& n : block.fNodes) {
330 this->addDefinitions(n, &after);
331 }
332
333 // propagate definitions to exits
334 for (BlockId exitId : block.fExits) {
335 BasicBlock& exit = cfg->fBlocks[exitId];
336 for (const auto& pair : after) {
Ethan Nicholas86a43402017-01-19 13:32:00 -0500337 std::unique_ptr<Expression>* e1 = pair.second;
338 auto found = exit.fBefore.find(pair.first);
339 if (found == exit.fBefore.end()) {
340 // exit has no definition for it, just copy it
341 workList->insert(exitId);
ethannicholas22f939e2016-10-13 13:25:34 -0700342 exit.fBefore[pair.first] = e1;
343 } else {
Ethan Nicholas86a43402017-01-19 13:32:00 -0500344 // exit has a (possibly different) value already defined
345 std::unique_ptr<Expression>* e2 = exit.fBefore[pair.first];
ethannicholas22f939e2016-10-13 13:25:34 -0700346 if (e1 != e2) {
347 // definition has changed, merge and add exit block to worklist
348 workList->insert(exitId);
Ethan Nicholasaf197692017-02-27 13:26:45 -0500349 if (e1 && e2) {
350 exit.fBefore[pair.first] =
Ethan Nicholas86a43402017-01-19 13:32:00 -0500351 (std::unique_ptr<Expression>*) &fContext.fDefined_Expression;
Ethan Nicholasaf197692017-02-27 13:26:45 -0500352 } else {
353 exit.fBefore[pair.first] = nullptr;
354 }
ethannicholas22f939e2016-10-13 13:25:34 -0700355 }
356 }
357 }
358 }
359}
360
361// returns a map which maps all local variables in the function to null, indicating that their value
362// is initially unknown
Ethan Nicholas86a43402017-01-19 13:32:00 -0500363static DefinitionMap compute_start_state(const CFG& cfg) {
364 DefinitionMap result;
Mike Klein6ad99092016-10-26 10:35:22 -0400365 for (const auto& block : cfg.fBlocks) {
366 for (const auto& node : block.fNodes) {
ethannicholas22f939e2016-10-13 13:25:34 -0700367 if (node.fKind == BasicBlock::Node::kStatement_Kind) {
Ethan Nicholascb670962017-04-20 19:31:52 -0400368 ASSERT(node.statement());
369 const Statement* s = node.statement()->get();
ethannicholas22f939e2016-10-13 13:25:34 -0700370 if (s->fKind == Statement::kVarDeclarations_Kind) {
371 const VarDeclarationsStatement* vd = (const VarDeclarationsStatement*) s;
Ethan Nicholas1ae353c2017-11-01 10:47:43 -0400372 for (const Variable* var : vd->fDeclaration->fVars) {
373 result[var] = nullptr;
Mike Klein6ad99092016-10-26 10:35:22 -0400374 }
ethannicholas22f939e2016-10-13 13:25:34 -0700375 }
376 }
377 }
378 }
379 return result;
380}
381
Ethan Nicholascb670962017-04-20 19:31:52 -0400382/**
383 * Returns true if assigning to this lvalue has no effect.
384 */
385static bool is_dead(const Expression& lvalue) {
386 switch (lvalue.fKind) {
387 case Expression::kVariableReference_Kind:
388 return ((VariableReference&) lvalue).fVariable.dead();
389 case Expression::kSwizzle_Kind:
390 return is_dead(*((Swizzle&) lvalue).fBase);
391 case Expression::kFieldAccess_Kind:
392 return is_dead(*((FieldAccess&) lvalue).fBase);
393 case Expression::kIndex_Kind: {
394 const IndexExpression& idx = (IndexExpression&) lvalue;
395 return is_dead(*idx.fBase) && !idx.fIndex->hasSideEffects();
396 }
397 default:
398 ABORT("invalid lvalue: %s\n", lvalue.description().c_str());
399 }
400}
ethannicholas22f939e2016-10-13 13:25:34 -0700401
Ethan Nicholascb670962017-04-20 19:31:52 -0400402/**
403 * Returns true if this is an assignment which can be collapsed down to just the right hand side due
404 * to a dead target and lack of side effects on the left hand side.
405 */
406static bool dead_assignment(const BinaryExpression& b) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700407 if (!Compiler::IsAssignment(b.fOperator)) {
Ethan Nicholascb670962017-04-20 19:31:52 -0400408 return false;
409 }
410 return is_dead(*b.fLeft);
411}
412
413void Compiler::computeDataFlow(CFG* cfg) {
414 cfg->fBlocks[cfg->fStart].fBefore = compute_start_state(*cfg);
ethannicholas22f939e2016-10-13 13:25:34 -0700415 std::set<BlockId> workList;
Ethan Nicholascb670962017-04-20 19:31:52 -0400416 for (BlockId i = 0; i < cfg->fBlocks.size(); i++) {
ethannicholas22f939e2016-10-13 13:25:34 -0700417 workList.insert(i);
418 }
419 while (workList.size()) {
420 BlockId next = *workList.begin();
421 workList.erase(workList.begin());
Ethan Nicholascb670962017-04-20 19:31:52 -0400422 this->scanCFG(cfg, next, &workList);
ethannicholas22f939e2016-10-13 13:25:34 -0700423 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400424}
425
426/**
427 * Attempts to replace the expression pointed to by iter with a new one (in both the CFG and the
428 * IR). If the expression can be cleanly removed, returns true and updates the iterator to point to
429 * the newly-inserted element. Otherwise updates only the IR and returns false (and the CFG will
430 * need to be regenerated).
431 */
432bool try_replace_expression(BasicBlock* b,
433 std::vector<BasicBlock::Node>::iterator* iter,
434 std::unique_ptr<Expression>* newExpression) {
435 std::unique_ptr<Expression>* target = (*iter)->expression();
436 if (!b->tryRemoveExpression(iter)) {
437 *target = std::move(*newExpression);
438 return false;
439 }
440 *target = std::move(*newExpression);
441 return b->tryInsertExpression(iter, target);
442}
443
444/**
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400445 * Returns true if the expression is a constant numeric literal with the specified value, or a
446 * constant vector with all elements equal to the specified value.
Ethan Nicholascb670962017-04-20 19:31:52 -0400447 */
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400448bool is_constant(const Expression& expr, double value) {
Ethan Nicholascb670962017-04-20 19:31:52 -0400449 switch (expr.fKind) {
450 case Expression::kIntLiteral_Kind:
451 return ((IntLiteral&) expr).fValue == value;
452 case Expression::kFloatLiteral_Kind:
453 return ((FloatLiteral&) expr).fValue == value;
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400454 case Expression::kConstructor_Kind: {
455 Constructor& c = (Constructor&) expr;
456 if (c.fType.kind() == Type::kVector_Kind && c.isConstant()) {
457 for (int i = 0; i < c.fType.columns(); ++i) {
458 if (!is_constant(c.getVecComponent(i), value)) {
459 return false;
460 }
461 }
462 return true;
463 }
464 return false;
465 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400466 default:
467 return false;
468 }
469}
470
471/**
472 * Collapses the binary expression pointed to by iter down to just the right side (in both the IR
473 * and CFG structures).
474 */
475void delete_left(BasicBlock* b,
476 std::vector<BasicBlock::Node>::iterator* iter,
477 bool* outUpdated,
478 bool* outNeedsRescan) {
479 *outUpdated = true;
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400480 std::unique_ptr<Expression>* target = (*iter)->expression();
481 ASSERT((*target)->fKind == Expression::kBinary_Kind);
482 BinaryExpression& bin = (BinaryExpression&) **target;
483 bool result;
484 if (bin.fOperator == Token::EQ) {
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400485 result = b->tryRemoveLValueBefore(iter, bin.fLeft.get());
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400486 } else {
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400487 result = b->tryRemoveExpressionBefore(iter, bin.fLeft.get());
Ethan Nicholascb670962017-04-20 19:31:52 -0400488 }
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400489 *target = std::move(bin.fRight);
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400490 if (!result) {
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400491 *outNeedsRescan = true;
492 return;
493 }
494 if (*iter == b->fNodes.begin()) {
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400495 *outNeedsRescan = true;
496 return;
497 }
498 --(*iter);
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400499 if ((*iter)->fKind != BasicBlock::Node::kExpression_Kind ||
500 (*iter)->expression() != &bin.fRight) {
501 *outNeedsRescan = true;
502 return;
503 }
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400504 *iter = b->fNodes.erase(*iter);
505 ASSERT((*iter)->expression() == target);
Ethan Nicholascb670962017-04-20 19:31:52 -0400506}
507
508/**
509 * Collapses the binary expression pointed to by iter down to just the left side (in both the IR and
510 * CFG structures).
511 */
512void delete_right(BasicBlock* b,
513 std::vector<BasicBlock::Node>::iterator* iter,
514 bool* outUpdated,
515 bool* outNeedsRescan) {
516 *outUpdated = true;
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400517 std::unique_ptr<Expression>* target = (*iter)->expression();
518 ASSERT((*target)->fKind == Expression::kBinary_Kind);
519 BinaryExpression& bin = (BinaryExpression&) **target;
520 if (!b->tryRemoveExpressionBefore(iter, bin.fRight.get())) {
521 *target = std::move(bin.fLeft);
Ethan Nicholascb670962017-04-20 19:31:52 -0400522 *outNeedsRescan = true;
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400523 return;
Ethan Nicholascb670962017-04-20 19:31:52 -0400524 }
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400525 *target = std::move(bin.fLeft);
526 if (*iter == b->fNodes.begin()) {
527 *outNeedsRescan = true;
528 return;
529 }
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400530 --(*iter);
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400531 if (((*iter)->fKind != BasicBlock::Node::kExpression_Kind ||
532 (*iter)->expression() != &bin.fLeft)) {
533 *outNeedsRescan = true;
534 return;
535 }
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400536 *iter = b->fNodes.erase(*iter);
537 ASSERT((*iter)->expression() == target);
Ethan Nicholascb670962017-04-20 19:31:52 -0400538}
539
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400540/**
541 * Constructs the specified type using a single argument.
542 */
543static std::unique_ptr<Expression> construct(const Type& type, std::unique_ptr<Expression> v) {
544 std::vector<std::unique_ptr<Expression>> args;
545 args.push_back(std::move(v));
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700546 auto result = std::unique_ptr<Expression>(new Constructor(-1, type, std::move(args)));
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400547 return result;
548}
549
550/**
551 * Used in the implementations of vectorize_left and vectorize_right. Given a vector type and an
552 * expression x, deletes the expression pointed to by iter and replaces it with <type>(x).
553 */
554static void vectorize(BasicBlock* b,
555 std::vector<BasicBlock::Node>::iterator* iter,
556 const Type& type,
557 std::unique_ptr<Expression>* otherExpression,
558 bool* outUpdated,
559 bool* outNeedsRescan) {
560 ASSERT((*(*iter)->expression())->fKind == Expression::kBinary_Kind);
561 ASSERT(type.kind() == Type::kVector_Kind);
562 ASSERT((*otherExpression)->fType.kind() == Type::kScalar_Kind);
563 *outUpdated = true;
564 std::unique_ptr<Expression>* target = (*iter)->expression();
565 if (!b->tryRemoveExpression(iter)) {
566 *target = construct(type, std::move(*otherExpression));
567 *outNeedsRescan = true;
568 } else {
569 *target = construct(type, std::move(*otherExpression));
570 if (!b->tryInsertExpression(iter, target)) {
571 *outNeedsRescan = true;
572 }
573 }
574}
575
576/**
577 * Given a binary expression of the form x <op> vec<n>(y), deletes the right side and vectorizes the
578 * left to yield vec<n>(x).
579 */
580static void vectorize_left(BasicBlock* b,
581 std::vector<BasicBlock::Node>::iterator* iter,
582 bool* outUpdated,
583 bool* outNeedsRescan) {
584 BinaryExpression& bin = (BinaryExpression&) **(*iter)->expression();
585 vectorize(b, iter, bin.fRight->fType, &bin.fLeft, outUpdated, outNeedsRescan);
586}
587
588/**
589 * Given a binary expression of the form vec<n>(x) <op> y, deletes the left side and vectorizes the
590 * right to yield vec<n>(y).
591 */
592static void vectorize_right(BasicBlock* b,
593 std::vector<BasicBlock::Node>::iterator* iter,
594 bool* outUpdated,
595 bool* outNeedsRescan) {
596 BinaryExpression& bin = (BinaryExpression&) **(*iter)->expression();
597 vectorize(b, iter, bin.fLeft->fType, &bin.fRight, outUpdated, outNeedsRescan);
598}
599
600// Mark that an expression which we were writing to is no longer being written to
601void clear_write(const Expression& expr) {
602 switch (expr.fKind) {
603 case Expression::kVariableReference_Kind: {
604 ((VariableReference&) expr).setRefKind(VariableReference::kRead_RefKind);
605 break;
606 }
607 case Expression::kFieldAccess_Kind:
608 clear_write(*((FieldAccess&) expr).fBase);
609 break;
610 case Expression::kSwizzle_Kind:
611 clear_write(*((Swizzle&) expr).fBase);
612 break;
613 case Expression::kIndex_Kind:
614 clear_write(*((IndexExpression&) expr).fBase);
615 break;
616 default:
617 ABORT("shouldn't be writing to this kind of expression\n");
618 break;
619 }
620}
621
Ethan Nicholascb670962017-04-20 19:31:52 -0400622void Compiler::simplifyExpression(DefinitionMap& definitions,
623 BasicBlock& b,
624 std::vector<BasicBlock::Node>::iterator* iter,
625 std::unordered_set<const Variable*>* undefinedVariables,
626 bool* outUpdated,
627 bool* outNeedsRescan) {
628 Expression* expr = (*iter)->expression()->get();
629 ASSERT(expr);
630 if ((*iter)->fConstantPropagation) {
631 std::unique_ptr<Expression> optimized = expr->constantPropagate(*fIRGenerator, definitions);
632 if (optimized) {
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400633 *outUpdated = true;
Ethan Nicholascb670962017-04-20 19:31:52 -0400634 if (!try_replace_expression(&b, iter, &optimized)) {
635 *outNeedsRescan = true;
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400636 return;
Ethan Nicholascb670962017-04-20 19:31:52 -0400637 }
638 ASSERT((*iter)->fKind == BasicBlock::Node::kExpression_Kind);
639 expr = (*iter)->expression()->get();
Ethan Nicholascb670962017-04-20 19:31:52 -0400640 }
641 }
642 switch (expr->fKind) {
643 case Expression::kVariableReference_Kind: {
644 const Variable& var = ((VariableReference*) expr)->fVariable;
645 if (var.fStorage == Variable::kLocal_Storage && !definitions[&var] &&
646 (*undefinedVariables).find(&var) == (*undefinedVariables).end()) {
647 (*undefinedVariables).insert(&var);
Ethan Nicholas1ae353c2017-11-01 10:47:43 -0400648 this->error(expr->fOffset, "'" + var.fName + "' has not been assigned");
Ethan Nicholascb670962017-04-20 19:31:52 -0400649 }
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 Nicholas1ae353c2017-11-01 10:47:43 -0400893 case Statement::kVarDeclarations_Kind: {
894 std::vector<Variable*>& vars = ((VarDeclarationsStatement*) stmt)->fDeclaration->fVars;
895 for (auto varIter = vars.begin(); varIter != vars.end();) {
896 Variable* var = *varIter;
897 if (var->dead() && (!var->fInitialValue || !var->fInitialValue->hasSideEffects())) {
898 if (var->fInitialValue) {
899 ASSERT((*iter)->statement()->get() == stmt);
900 if (!b.tryRemoveExpressionAfter(iter, var->fInitialValue.get())) {
901 *outNeedsRescan = true;
902 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400903 }
Ethan Nicholas1ae353c2017-11-01 10:47:43 -0400904 varIter = vars.erase(varIter);
905 *outUpdated = true;
906 } else {
907 ++varIter;
Ethan Nicholascb670962017-04-20 19:31:52 -0400908 }
Ethan Nicholas1ae353c2017-11-01 10:47:43 -0400909 }
910 if (!vars.size()) {
Ethan Nicholascb670962017-04-20 19:31:52 -0400911 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
912 }
913 break;
914 }
915 case Statement::kIf_Kind: {
916 IfStatement& i = (IfStatement&) *stmt;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -0400917 if (i.fTest->fKind == Expression::kBoolLiteral_Kind) {
918 // constant if, collapse down to a single branch
919 if (((BoolLiteral&) *i.fTest).fValue) {
920 ASSERT(i.fIfTrue);
921 (*iter)->setStatement(std::move(i.fIfTrue));
922 } else {
923 if (i.fIfFalse) {
924 (*iter)->setStatement(std::move(i.fIfFalse));
925 } else {
926 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
927 }
928 }
929 *outUpdated = true;
930 *outNeedsRescan = true;
931 break;
932 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400933 if (i.fIfFalse && i.fIfFalse->isEmpty()) {
934 // else block doesn't do anything, remove it
935 i.fIfFalse.reset();
936 *outUpdated = true;
937 *outNeedsRescan = true;
938 }
939 if (!i.fIfFalse && i.fIfTrue->isEmpty()) {
940 // if block doesn't do anything, no else block
941 if (i.fTest->hasSideEffects()) {
942 // test has side effects, keep it
943 (*iter)->setStatement(std::unique_ptr<Statement>(
944 new ExpressionStatement(std::move(i.fTest))));
945 } else {
946 // no if, no else, no test side effects, kill the whole if
947 // statement
948 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
949 }
950 *outUpdated = true;
951 *outNeedsRescan = true;
952 }
953 break;
954 }
Ethan Nicholas5ac13c22017-05-10 15:06:17 -0400955 case Statement::kSwitch_Kind: {
956 SwitchStatement& s = (SwitchStatement&) *stmt;
957 if (s.fValue->isConstant()) {
958 // switch is constant, replace it with the case that matches
959 bool found = false;
960 SwitchCase* defaultCase = nullptr;
961 for (const auto& c : s.fCases) {
962 if (!c->fValue) {
963 defaultCase = c.get();
964 continue;
965 }
966 ASSERT(c->fValue->fKind == s.fValue->fKind);
967 found = c->fValue->compareConstant(fContext, *s.fValue);
968 if (found) {
969 std::unique_ptr<Statement> newBlock = block_for_case(&s, c.get());
970 if (newBlock) {
971 (*iter)->setStatement(std::move(newBlock));
972 break;
973 } else {
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -0400974 if (s.fIsStatic && !(fFlags & kPermitInvalidStaticTests_Flag)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700975 this->error(s.fOffset,
Ethan Nicholas5ac13c22017-05-10 15:06:17 -0400976 "static switch contains non-static conditional break");
977 s.fIsStatic = false;
978 }
979 return; // can't simplify
980 }
981 }
982 }
983 if (!found) {
984 // no matching case. use default if it exists, or kill the whole thing
985 if (defaultCase) {
986 std::unique_ptr<Statement> newBlock = block_for_case(&s, defaultCase);
987 if (newBlock) {
988 (*iter)->setStatement(std::move(newBlock));
989 } else {
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -0400990 if (s.fIsStatic && !(fFlags & kPermitInvalidStaticTests_Flag)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700991 this->error(s.fOffset,
Ethan Nicholas5ac13c22017-05-10 15:06:17 -0400992 "static switch contains non-static conditional break");
993 s.fIsStatic = false;
994 }
995 return; // can't simplify
996 }
997 } else {
998 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
999 }
1000 }
1001 *outUpdated = true;
1002 *outNeedsRescan = true;
1003 }
1004 break;
1005 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001006 case Statement::kExpression_Kind: {
1007 ExpressionStatement& e = (ExpressionStatement&) *stmt;
1008 ASSERT((*iter)->statement()->get() == &e);
Ethan Nicholascb670962017-04-20 19:31:52 -04001009 if (!e.fExpression->hasSideEffects()) {
1010 // Expression statement with no side effects, kill it
1011 if (!b.tryRemoveExpressionBefore(iter, e.fExpression.get())) {
1012 *outNeedsRescan = true;
1013 }
1014 ASSERT((*iter)->statement()->get() == stmt);
1015 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
1016 *outUpdated = true;
1017 }
1018 break;
1019 }
1020 default:
1021 break;
1022 }
1023}
1024
1025void Compiler::scanCFG(FunctionDefinition& f) {
1026 CFG cfg = CFGGenerator().getCFG(f);
1027 this->computeDataFlow(&cfg);
ethannicholas22f939e2016-10-13 13:25:34 -07001028
1029 // check for unreachable code
1030 for (size_t i = 0; i < cfg.fBlocks.size(); i++) {
Mike Klein6ad99092016-10-26 10:35:22 -04001031 if (i != cfg.fStart && !cfg.fBlocks[i].fEntrances.size() &&
ethannicholas22f939e2016-10-13 13:25:34 -07001032 cfg.fBlocks[i].fNodes.size()) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001033 int offset;
Ethan Nicholas86a43402017-01-19 13:32:00 -05001034 switch (cfg.fBlocks[i].fNodes[0].fKind) {
1035 case BasicBlock::Node::kStatement_Kind:
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001036 offset = (*cfg.fBlocks[i].fNodes[0].statement())->fOffset;
Ethan Nicholas86a43402017-01-19 13:32:00 -05001037 break;
1038 case BasicBlock::Node::kExpression_Kind:
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001039 offset = (*cfg.fBlocks[i].fNodes[0].expression())->fOffset;
Ethan Nicholas86a43402017-01-19 13:32:00 -05001040 break;
1041 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001042 this->error(offset, String("unreachable"));
ethannicholas22f939e2016-10-13 13:25:34 -07001043 }
1044 }
1045 if (fErrorCount) {
1046 return;
1047 }
1048
Ethan Nicholascb670962017-04-20 19:31:52 -04001049 // check for dead code & undefined variables, perform constant propagation
1050 std::unordered_set<const Variable*> undefinedVariables;
1051 bool updated;
1052 bool needsRescan = false;
1053 do {
1054 if (needsRescan) {
1055 cfg = CFGGenerator().getCFG(f);
1056 this->computeDataFlow(&cfg);
1057 needsRescan = false;
Ethan Nicholas113628d2017-02-02 16:11:39 -05001058 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001059
1060 updated = false;
1061 for (BasicBlock& b : cfg.fBlocks) {
1062 DefinitionMap definitions = b.fBefore;
1063
1064 for (auto iter = b.fNodes.begin(); iter != b.fNodes.end() && !needsRescan; ++iter) {
1065 if (iter->fKind == BasicBlock::Node::kExpression_Kind) {
1066 this->simplifyExpression(definitions, b, &iter, &undefinedVariables, &updated,
1067 &needsRescan);
1068 } else {
1069 this->simplifyStatement(definitions, b, &iter, &undefinedVariables, &updated,
1070 &needsRescan);
1071 }
Ethan Nicholas4b330df2017-05-17 10:52:55 -04001072 if (needsRescan) {
1073 break;
1074 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001075 this->addDefinitions(*iter, &definitions);
1076 }
1077 }
1078 } while (updated);
1079 ASSERT(!needsRescan);
ethannicholas22f939e2016-10-13 13:25:34 -07001080
Ethan Nicholas91a10532017-06-22 11:24:38 -04001081 // verify static ifs & switches, clean up dead variable decls
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001082 for (BasicBlock& b : cfg.fBlocks) {
1083 DefinitionMap definitions = b.fBefore;
1084
Ethan Nicholas91a10532017-06-22 11:24:38 -04001085 for (auto iter = b.fNodes.begin(); iter != b.fNodes.end() && !needsRescan;) {
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001086 if (iter->fKind == BasicBlock::Node::kStatement_Kind) {
1087 const Statement& s = **iter->statement();
1088 switch (s.fKind) {
1089 case Statement::kIf_Kind:
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -04001090 if (((const IfStatement&) s).fIsStatic &&
1091 !(fFlags & kPermitInvalidStaticTests_Flag)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001092 this->error(s.fOffset, "static if has non-static test");
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001093 }
Ethan Nicholas91a10532017-06-22 11:24:38 -04001094 ++iter;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001095 break;
1096 case Statement::kSwitch_Kind:
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -04001097 if (((const SwitchStatement&) s).fIsStatic &&
1098 !(fFlags & kPermitInvalidStaticTests_Flag)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001099 this->error(s.fOffset, "static switch has non-static test");
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001100 }
Ethan Nicholas91a10532017-06-22 11:24:38 -04001101 ++iter;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001102 break;
1103 default:
Ethan Nicholas91a10532017-06-22 11:24:38 -04001104 ++iter;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001105 break;
1106 }
Ethan Nicholas91a10532017-06-22 11:24:38 -04001107 } else {
1108 ++iter;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001109 }
1110 }
1111 }
1112
ethannicholas22f939e2016-10-13 13:25:34 -07001113 // check for missing return
1114 if (f.fDeclaration.fReturnType != *fContext.fVoid_Type) {
1115 if (cfg.fBlocks[cfg.fExit].fEntrances.size()) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001116 this->error(f.fOffset, String("function can exit without returning a value"));
ethannicholas22f939e2016-10-13 13:25:34 -07001117 }
1118 }
1119}
1120
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001121std::unique_ptr<Program> Compiler::convertProgram(Program::Kind kind, String text,
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001122 const Program::Settings& settings) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001123 fErrorText = "";
1124 fErrorCount = 0;
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001125 fIRGenerator->start(&settings);
ethannicholasd598f792016-07-25 10:08:54 -07001126 std::vector<std::unique_ptr<ProgramElement>> elements;
ethannicholasb3058bd2016-07-01 08:22:01 -07001127 switch (kind) {
1128 case Program::kVertex_Kind:
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001129 fIRGenerator->convertProgram(SKSL_VERT_INCLUDE, strlen(SKSL_VERT_INCLUDE), *fTypes,
Ethan Nicholasf7b88202017-09-18 14:10:39 -04001130 &elements);
ethannicholasb3058bd2016-07-01 08:22:01 -07001131 break;
1132 case Program::kFragment_Kind:
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001133 fIRGenerator->convertProgram(SKSL_FRAG_INCLUDE, strlen(SKSL_FRAG_INCLUDE), *fTypes,
Ethan Nicholasf7b88202017-09-18 14:10:39 -04001134 &elements);
ethannicholasb3058bd2016-07-01 08:22:01 -07001135 break;
Ethan Nicholas52cad152017-02-16 16:37:32 -05001136 case Program::kGeometry_Kind:
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001137 fIRGenerator->convertProgram(SKSL_GEOM_INCLUDE, strlen(SKSL_GEOM_INCLUDE), *fTypes,
Ethan Nicholasf7b88202017-09-18 14:10:39 -04001138 &elements);
Ethan Nicholas52cad152017-02-16 16:37:32 -05001139 break;
Ethan Nicholas762466e2017-06-29 10:03:38 -04001140 case Program::kFragmentProcessor_Kind:
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001141 fIRGenerator->convertProgram(SKSL_FP_INCLUDE, strlen(SKSL_FP_INCLUDE), *fTypes,
Ethan Nicholasf7b88202017-09-18 14:10:39 -04001142 &elements);
Ethan Nicholas762466e2017-06-29 10:03:38 -04001143 break;
ethannicholasb3058bd2016-07-01 08:22:01 -07001144 }
ethannicholasddb37d62016-10-20 09:54:00 -07001145 fIRGenerator->fSymbolTable->markAllFunctionsBuiltin();
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001146 std::unique_ptr<String> textPtr(new String(std::move(text)));
1147 fSource = textPtr.get();
Ethan Nicholasf7b88202017-09-18 14:10:39 -04001148 fIRGenerator->convertProgram(textPtr->c_str(), textPtr->size(), *fTypes, &elements);
Ethan Nicholas7da6dfa2017-06-21 11:25:18 -04001149 if (!fErrorCount) {
1150 for (auto& element : elements) {
1151 if (element->fKind == ProgramElement::kFunction_Kind) {
1152 this->scanCFG((FunctionDefinition&) *element);
1153 }
1154 }
1155 }
Ethan Nicholasf7b88202017-09-18 14:10:39 -04001156 auto result = std::unique_ptr<Program>(new Program(kind,
1157 std::move(textPtr),
1158 settings,
1159 &fContext,
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001160 std::move(elements),
1161 fIRGenerator->fSymbolTable,
1162 fIRGenerator->fInputs));
Ethan Nicholas3605ace2016-11-21 15:59:48 -05001163 fIRGenerator->finish();
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001164 fSource = nullptr;
ethannicholasb3058bd2016-07-01 08:22:01 -07001165 this->writeErrorCount();
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001166 if (fErrorCount) {
1167 return nullptr;
1168 }
1169 return result;
1170}
1171
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001172bool Compiler::toSPIRV(const Program& program, OutputStream& out) {
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001173#ifdef SK_ENABLE_SPIRV_VALIDATION
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001174 StringStream buffer;
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001175 fSource = program.fSource.get();
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001176 SPIRVCodeGenerator cg(&fContext, &program, this, &buffer);
1177 bool result = cg.generateCode();
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001178 fSource = nullptr;
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001179 if (result) {
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001180 spvtools::SpirvTools tools(SPV_ENV_VULKAN_1_0);
Ethan Nicholas762466e2017-06-29 10:03:38 -04001181 const String& data = buffer.str();
1182 ASSERT(0 == data.size() % 4);
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001183 auto dumpmsg = [](spv_message_level_t, const char*, const spv_position_t&, const char* m) {
1184 SkDebugf("SPIR-V validation error: %s\n", m);
1185 };
1186 tools.SetMessageConsumer(dumpmsg);
1187 // Verify that the SPIR-V we produced is valid. If this assert fails, check the logs prior
1188 // to the failure to see the validation errors.
Ethan Nicholas762466e2017-06-29 10:03:38 -04001189 ASSERT_RESULT(tools.Validate((const uint32_t*) data.c_str(), data.size() / 4));
1190 out.write(data.c_str(), data.size());
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001191 }
1192#else
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001193 fSource = program.fSource.get();
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001194 SPIRVCodeGenerator cg(&fContext, &program, this, &out);
1195 bool result = cg.generateCode();
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001196 fSource = nullptr;
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001197#endif
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001198 this->writeErrorCount();
Ethan Nicholasce33f102016-12-09 17:22:59 -05001199 return result;
1200}
1201
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001202bool Compiler::toSPIRV(const Program& program, String* out) {
1203 StringStream buffer;
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001204 bool result = this->toSPIRV(program, buffer);
1205 if (result) {
Ethan Nicholas762466e2017-06-29 10:03:38 -04001206 *out = buffer.str();
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001207 }
1208 return result;
1209}
1210
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001211bool Compiler::toGLSL(const Program& program, OutputStream& out) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001212 fSource = program.fSource.get();
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001213 GLSLCodeGenerator cg(&fContext, &program, this, &out);
1214 bool result = cg.generateCode();
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001215 fSource = nullptr;
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001216 this->writeErrorCount();
1217 return result;
1218}
1219
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001220bool Compiler::toGLSL(const Program& program, String* out) {
1221 StringStream buffer;
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001222 bool result = this->toGLSL(program, buffer);
1223 if (result) {
Ethan Nicholas762466e2017-06-29 10:03:38 -04001224 *out = buffer.str();
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001225 }
1226 return result;
1227}
1228
Ethan Nicholascc305772017-10-13 16:17:45 -04001229bool Compiler::toMetal(const Program& program, OutputStream& out) {
1230 MetalCodeGenerator cg(&fContext, &program, this, &out);
1231 bool result = cg.generateCode();
1232 this->writeErrorCount();
1233 return result;
1234}
1235
Ethan Nicholas762466e2017-06-29 10:03:38 -04001236bool Compiler::toCPP(const Program& program, String name, OutputStream& out) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001237 fSource = program.fSource.get();
Ethan Nicholas762466e2017-06-29 10:03:38 -04001238 CPPCodeGenerator cg(&fContext, &program, this, name, &out);
1239 bool result = cg.generateCode();
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001240 fSource = nullptr;
Ethan Nicholas762466e2017-06-29 10:03:38 -04001241 this->writeErrorCount();
1242 return result;
1243}
1244
1245bool Compiler::toH(const Program& program, String name, OutputStream& out) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001246 fSource = program.fSource.get();
Ethan Nicholasc9472af2017-10-10 16:30:21 -04001247 HCodeGenerator cg(&fContext, &program, this, name, &out);
Ethan Nicholas762466e2017-06-29 10:03:38 -04001248 bool result = cg.generateCode();
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001249 fSource = nullptr;
Ethan Nicholas762466e2017-06-29 10:03:38 -04001250 this->writeErrorCount();
1251 return result;
1252}
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001253
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001254const char* Compiler::OperatorName(Token::Kind kind) {
1255 switch (kind) {
1256 case Token::PLUS: return "+";
1257 case Token::MINUS: return "-";
1258 case Token::STAR: return "*";
1259 case Token::SLASH: return "/";
1260 case Token::PERCENT: return "%";
1261 case Token::SHL: return "<<";
1262 case Token::SHR: return ">>";
1263 case Token::LOGICALNOT: return "!";
1264 case Token::LOGICALAND: return "&&";
1265 case Token::LOGICALOR: return "||";
1266 case Token::LOGICALXOR: return "^^";
1267 case Token::BITWISENOT: return "~";
1268 case Token::BITWISEAND: return "&";
1269 case Token::BITWISEOR: return "|";
1270 case Token::BITWISEXOR: return "^";
1271 case Token::EQ: return "=";
1272 case Token::EQEQ: return "==";
1273 case Token::NEQ: return "!=";
1274 case Token::LT: return "<";
1275 case Token::GT: return ">";
1276 case Token::LTEQ: return "<=";
1277 case Token::GTEQ: return ">=";
1278 case Token::PLUSEQ: return "+=";
1279 case Token::MINUSEQ: return "-=";
1280 case Token::STAREQ: return "*=";
1281 case Token::SLASHEQ: return "/=";
1282 case Token::PERCENTEQ: return "%=";
1283 case Token::SHLEQ: return "<<=";
1284 case Token::SHREQ: return ">>=";
1285 case Token::LOGICALANDEQ: return "&&=";
1286 case Token::LOGICALOREQ: return "||=";
1287 case Token::LOGICALXOREQ: return "^^=";
1288 case Token::BITWISEANDEQ: return "&=";
1289 case Token::BITWISEOREQ: return "|=";
1290 case Token::BITWISEXOREQ: return "^=";
1291 case Token::PLUSPLUS: return "++";
1292 case Token::MINUSMINUS: return "--";
1293 case Token::COMMA: return ",";
1294 default:
1295 ABORT("unsupported operator: %d\n", kind);
1296 }
1297}
1298
1299
1300bool Compiler::IsAssignment(Token::Kind op) {
1301 switch (op) {
1302 case Token::EQ: // fall through
1303 case Token::PLUSEQ: // fall through
1304 case Token::MINUSEQ: // fall through
1305 case Token::STAREQ: // fall through
1306 case Token::SLASHEQ: // fall through
1307 case Token::PERCENTEQ: // fall through
1308 case Token::SHLEQ: // fall through
1309 case Token::SHREQ: // fall through
1310 case Token::BITWISEOREQ: // fall through
1311 case Token::BITWISEXOREQ: // fall through
1312 case Token::BITWISEANDEQ: // fall through
1313 case Token::LOGICALOREQ: // fall through
1314 case Token::LOGICALXOREQ: // fall through
1315 case Token::LOGICALANDEQ:
1316 return true;
1317 default:
1318 return false;
1319 }
1320}
1321
1322Position Compiler::position(int offset) {
1323 ASSERT(fSource);
1324 int line = 1;
1325 int column = 1;
1326 for (int i = 0; i < offset; i++) {
1327 if ((*fSource)[i] == '\n') {
1328 ++line;
1329 column = 1;
1330 }
1331 else {
1332 ++column;
1333 }
1334 }
1335 return Position(line, column);
1336}
1337
1338void Compiler::error(int offset, String msg) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001339 fErrorCount++;
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001340 Position pos = this->position(offset);
1341 fErrorText += "error: " + to_string(pos.fLine) + ": " + msg.c_str() + "\n";
ethannicholasb3058bd2016-07-01 08:22:01 -07001342}
1343
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001344String Compiler::errorText() {
1345 String result = fErrorText;
ethannicholasb3058bd2016-07-01 08:22:01 -07001346 return result;
1347}
1348
1349void Compiler::writeErrorCount() {
1350 if (fErrorCount) {
1351 fErrorText += to_string(fErrorCount) + " error";
1352 if (fErrorCount > 1) {
1353 fErrorText += "s";
1354 }
1355 fErrorText += "\n";
1356 }
1357}
1358
ethannicholasb3058bd2016-07-01 08:22:01 -07001359} // namespace