blob: 9795a1ecb631665cf22048b385d72d4b83e630be [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
Mike Kleinc0bd9f92019-04-23 12:05:21 -05008#include "src/sksl/SkSLCompiler.h"
ethannicholasb3058bd2016-07-01 08:22:01 -07009
John Stilesfbd050b2020-08-03 13:21:46 -040010#include <memory>
John Stilesb8e010c2020-08-11 18:05:39 -040011#include <unordered_set>
John Stilesfbd050b2020-08-03 13:21:46 -040012
Mike Kleinc0bd9f92019-04-23 12:05:21 -050013#include "src/sksl/SkSLByteCodeGenerator.h"
14#include "src/sksl/SkSLCFGGenerator.h"
15#include "src/sksl/SkSLCPPCodeGenerator.h"
16#include "src/sksl/SkSLGLSLCodeGenerator.h"
17#include "src/sksl/SkSLHCodeGenerator.h"
18#include "src/sksl/SkSLIRGenerator.h"
19#include "src/sksl/SkSLMetalCodeGenerator.h"
20#include "src/sksl/SkSLPipelineStageCodeGenerator.h"
Ethan Nicholasc18bb512020-07-28 14:46:53 -040021#include "src/sksl/SkSLRehydrator.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050022#include "src/sksl/SkSLSPIRVCodeGenerator.h"
Brian Osmanc0243912020-02-19 15:35:26 -050023#include "src/sksl/SkSLSPIRVtoHLSL.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050024#include "src/sksl/ir/SkSLEnum.h"
25#include "src/sksl/ir/SkSLExpression.h"
26#include "src/sksl/ir/SkSLExpressionStatement.h"
27#include "src/sksl/ir/SkSLFunctionCall.h"
28#include "src/sksl/ir/SkSLIntLiteral.h"
29#include "src/sksl/ir/SkSLModifiersDeclaration.h"
30#include "src/sksl/ir/SkSLNop.h"
31#include "src/sksl/ir/SkSLSymbolTable.h"
32#include "src/sksl/ir/SkSLTernaryExpression.h"
33#include "src/sksl/ir/SkSLUnresolvedFunction.h"
34#include "src/sksl/ir/SkSLVarDeclarations.h"
ethannicholasb3058bd2016-07-01 08:22:01 -070035
Ethan Nicholasb33fa3f2020-08-06 13:00:19 -040036#include <fstream>
37
Ethan Nicholasa11035b2019-11-26 16:27:47 -050038#if !defined(SKSL_STANDALONE) & SK_SUPPORT_GPU
39#include "include/gpu/GrContextOptions.h"
40#include "src/gpu/GrShaderCaps.h"
41#endif
42
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -040043#ifdef SK_ENABLE_SPIRV_VALIDATION
44#include "spirv-tools/libspirv.hpp"
45#endif
46
Brian Osmandd496172020-08-08 08:17:18 -040047#if !SKSL_STANDALONE
Ethan Nicholasc18bb512020-07-28 14:46:53 -040048
49#include "src/sksl/generated/sksl_fp.dehydrated.sksl"
50#include "src/sksl/generated/sksl_frag.dehydrated.sksl"
51#include "src/sksl/generated/sksl_geom.dehydrated.sksl"
52#include "src/sksl/generated/sksl_gpu.dehydrated.sksl"
53#include "src/sksl/generated/sksl_interp.dehydrated.sksl"
54#include "src/sksl/generated/sksl_pipeline.dehydrated.sksl"
55#include "src/sksl/generated/sksl_vert.dehydrated.sksl"
56
57#else
58
Brian Osmandd496172020-08-08 08:17:18 -040059// GN generates or copies all of these files to the skslc executable directory
60static const char SKSL_GPU_INCLUDE[] = "sksl_gpu.sksl";
61static const char SKSL_INTERP_INCLUDE[] = "sksl_interp.sksl";
62static const char SKSL_VERT_INCLUDE[] = "sksl_vert.sksl";
63static const char SKSL_FRAG_INCLUDE[] = "sksl_frag.sksl";
64static const char SKSL_GEOM_INCLUDE[] = "sksl_geom.sksl";
65static const char SKSL_FP_INCLUDE[] = "sksl_fp.sksl";
66static const char SKSL_PIPELINE_INCLUDE[] = "sksl_pipeline.sksl";
Ethan Nicholasc18bb512020-07-28 14:46:53 -040067
68#endif
Ethan Nicholas0d997662019-04-08 09:46:01 -040069
ethannicholasb3058bd2016-07-01 08:22:01 -070070namespace SkSL {
71
Ethan Nicholasdb80f692019-11-22 14:06:12 -050072static void grab_intrinsics(std::vector<std::unique_ptr<ProgramElement>>* src,
Brian Osman08f986d2020-05-13 17:06:46 -040073 std::map<String, std::pair<std::unique_ptr<ProgramElement>, bool>>* target) {
74 for (auto iter = src->begin(); iter != src->end(); ) {
75 std::unique_ptr<ProgramElement>& element = *iter;
Ethan Nicholasdb80f692019-11-22 14:06:12 -050076 switch (element->fKind) {
77 case ProgramElement::kFunction_Kind: {
John Stiles3dc0da62020-08-19 17:48:31 -040078 FunctionDefinition& f = element->as<FunctionDefinition>();
Brian Osman08f986d2020-05-13 17:06:46 -040079 SkASSERT(f.fDeclaration.fBuiltin);
Ethan Nicholasc18bb512020-07-28 14:46:53 -040080 String key = f.fDeclaration.description();
Brian Osman08f986d2020-05-13 17:06:46 -040081 SkASSERT(target->find(key) == target->end());
82 (*target)[key] = std::make_pair(std::move(element), false);
83 iter = src->erase(iter);
Ethan Nicholasdb80f692019-11-22 14:06:12 -050084 break;
85 }
86 case ProgramElement::kEnum_Kind: {
John Stiles3dc0da62020-08-19 17:48:31 -040087 Enum& e = element->as<Enum>();
Ethan Nicholasdb80f692019-11-22 14:06:12 -050088 StringFragment name = e.fTypeName;
89 SkASSERT(target->find(name) == target->end());
90 (*target)[name] = std::make_pair(std::move(element), false);
Brian Osman08f986d2020-05-13 17:06:46 -040091 iter = src->erase(iter);
Ethan Nicholasdb80f692019-11-22 14:06:12 -050092 break;
93 }
94 default:
95 printf("unsupported include file element\n");
96 SkASSERT(false);
97 }
98 }
99}
100
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -0400101Compiler::Compiler(Flags flags)
102: fFlags(flags)
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400103, fContext(new Context())
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -0400104, fErrorCount(0) {
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400105 auto symbols = std::shared_ptr<SymbolTable>(new SymbolTable(this));
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400106 fIRGenerator = new IRGenerator(fContext.get(), symbols, *this);
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400107 #define ADD_TYPE(t) symbols->addWithoutOwnership(fContext->f ## t ## _Type->fName, \
108 fContext->f ## t ## _Type.get())
ethannicholasb3058bd2016-07-01 08:22:01 -0700109 ADD_TYPE(Void);
110 ADD_TYPE(Float);
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400111 ADD_TYPE(Float2);
112 ADD_TYPE(Float3);
113 ADD_TYPE(Float4);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -0400114 ADD_TYPE(Half);
115 ADD_TYPE(Half2);
116 ADD_TYPE(Half3);
117 ADD_TYPE(Half4);
ethannicholasb3058bd2016-07-01 08:22:01 -0700118 ADD_TYPE(Int);
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400119 ADD_TYPE(Int2);
120 ADD_TYPE(Int3);
121 ADD_TYPE(Int4);
ethannicholasb3058bd2016-07-01 08:22:01 -0700122 ADD_TYPE(UInt);
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400123 ADD_TYPE(UInt2);
124 ADD_TYPE(UInt3);
125 ADD_TYPE(UInt4);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -0400126 ADD_TYPE(Short);
127 ADD_TYPE(Short2);
128 ADD_TYPE(Short3);
129 ADD_TYPE(Short4);
130 ADD_TYPE(UShort);
131 ADD_TYPE(UShort2);
132 ADD_TYPE(UShort3);
133 ADD_TYPE(UShort4);
Ruiqi Maob609e6d2018-07-17 10:19:38 -0400134 ADD_TYPE(Byte);
135 ADD_TYPE(Byte2);
136 ADD_TYPE(Byte3);
137 ADD_TYPE(Byte4);
138 ADD_TYPE(UByte);
139 ADD_TYPE(UByte2);
140 ADD_TYPE(UByte3);
141 ADD_TYPE(UByte4);
ethannicholasb3058bd2016-07-01 08:22:01 -0700142 ADD_TYPE(Bool);
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400143 ADD_TYPE(Bool2);
144 ADD_TYPE(Bool3);
145 ADD_TYPE(Bool4);
146 ADD_TYPE(Float2x2);
147 ADD_TYPE(Float2x3);
148 ADD_TYPE(Float2x4);
149 ADD_TYPE(Float3x2);
150 ADD_TYPE(Float3x3);
151 ADD_TYPE(Float3x4);
152 ADD_TYPE(Float4x2);
153 ADD_TYPE(Float4x3);
154 ADD_TYPE(Float4x4);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -0400155 ADD_TYPE(Half2x2);
156 ADD_TYPE(Half2x3);
157 ADD_TYPE(Half2x4);
158 ADD_TYPE(Half3x2);
159 ADD_TYPE(Half3x3);
160 ADD_TYPE(Half3x4);
161 ADD_TYPE(Half4x2);
162 ADD_TYPE(Half4x3);
163 ADD_TYPE(Half4x4);
ethannicholasb3058bd2016-07-01 08:22:01 -0700164 ADD_TYPE(GenType);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -0400165 ADD_TYPE(GenHType);
ethannicholasb3058bd2016-07-01 08:22:01 -0700166 ADD_TYPE(GenIType);
167 ADD_TYPE(GenUType);
168 ADD_TYPE(GenBType);
169 ADD_TYPE(Mat);
170 ADD_TYPE(Vec);
171 ADD_TYPE(GVec);
172 ADD_TYPE(GVec2);
173 ADD_TYPE(GVec3);
174 ADD_TYPE(GVec4);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -0400175 ADD_TYPE(HVec);
ethannicholasb3058bd2016-07-01 08:22:01 -0700176 ADD_TYPE(IVec);
177 ADD_TYPE(UVec);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -0400178 ADD_TYPE(SVec);
179 ADD_TYPE(USVec);
Ruiqi Maob609e6d2018-07-17 10:19:38 -0400180 ADD_TYPE(ByteVec);
181 ADD_TYPE(UByteVec);
ethannicholasb3058bd2016-07-01 08:22:01 -0700182 ADD_TYPE(BVec);
183
184 ADD_TYPE(Sampler1D);
185 ADD_TYPE(Sampler2D);
186 ADD_TYPE(Sampler3D);
ethannicholas5961bc92016-10-12 06:39:56 -0700187 ADD_TYPE(SamplerExternalOES);
ethannicholasb3058bd2016-07-01 08:22:01 -0700188 ADD_TYPE(SamplerCube);
189 ADD_TYPE(Sampler2DRect);
190 ADD_TYPE(Sampler1DArray);
191 ADD_TYPE(Sampler2DArray);
192 ADD_TYPE(SamplerCubeArray);
193 ADD_TYPE(SamplerBuffer);
194 ADD_TYPE(Sampler2DMS);
195 ADD_TYPE(Sampler2DMSArray);
196
Brian Salomonbf7b6202016-11-11 16:08:03 -0500197 ADD_TYPE(ISampler2D);
198
Brian Salomon2a51de82016-11-16 12:06:01 -0500199 ADD_TYPE(Image2D);
200 ADD_TYPE(IImage2D);
201
Greg Daniel64773e62016-11-22 09:44:03 -0500202 ADD_TYPE(SubpassInput);
203 ADD_TYPE(SubpassInputMS);
204
ethannicholasb3058bd2016-07-01 08:22:01 -0700205 ADD_TYPE(GSampler1D);
206 ADD_TYPE(GSampler2D);
207 ADD_TYPE(GSampler3D);
208 ADD_TYPE(GSamplerCube);
209 ADD_TYPE(GSampler2DRect);
210 ADD_TYPE(GSampler1DArray);
211 ADD_TYPE(GSampler2DArray);
212 ADD_TYPE(GSamplerCubeArray);
213 ADD_TYPE(GSamplerBuffer);
214 ADD_TYPE(GSampler2DMS);
215 ADD_TYPE(GSampler2DMSArray);
216
217 ADD_TYPE(Sampler1DShadow);
218 ADD_TYPE(Sampler2DShadow);
219 ADD_TYPE(SamplerCubeShadow);
220 ADD_TYPE(Sampler2DRectShadow);
221 ADD_TYPE(Sampler1DArrayShadow);
222 ADD_TYPE(Sampler2DArrayShadow);
223 ADD_TYPE(SamplerCubeArrayShadow);
224 ADD_TYPE(GSampler2DArrayShadow);
225 ADD_TYPE(GSamplerCubeArrayShadow);
Ethan Nicholasc9472af2017-10-10 16:30:21 -0400226 ADD_TYPE(FragmentProcessor);
Stephen Whiteff5d7a22019-07-26 17:42:06 -0400227 ADD_TYPE(Sampler);
228 ADD_TYPE(Texture2D);
ethannicholasb3058bd2016-07-01 08:22:01 -0700229
Brian Osman28590d52020-03-23 16:59:08 -0400230 StringFragment fpAliasName("shader");
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400231 symbols->addWithoutOwnership(fpAliasName, fContext->fFragmentProcessor_Type.get());
Brian Osman28590d52020-03-23 16:59:08 -0400232
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700233 StringFragment skCapsName("sk_Caps");
John Stiles311dd9d2020-08-13 17:09:29 -0400234 fIRGenerator->fSymbolTable->add(
235 skCapsName,
236 std::make_unique<Variable>(/*offset=*/-1, Modifiers(), skCapsName,
237 *fContext->fSkCaps_Type, Variable::kGlobal_Storage));
Ethan Nicholas3605ace2016-11-21 15:59:48 -0500238
Ethan Nicholasdb80f692019-11-22 14:06:12 -0500239 fIRGenerator->fIntrinsics = &fGPUIntrinsics;
240 std::vector<std::unique_ptr<ProgramElement>> gpuIntrinsics;
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400241 std::vector<std::unique_ptr<ProgramElement>> interpIntrinsics;
Brian Osmandd496172020-08-08 08:17:18 -0400242#if SKSL_STANDALONE
Ethan Nicholasb33fa3f2020-08-06 13:00:19 -0400243 this->processIncludeFile(Program::kFragment_Kind, SKSL_GPU_INCLUDE, symbols, &gpuIntrinsics,
244 &fGpuSymbolTable);
245 this->processIncludeFile(Program::kVertex_Kind, SKSL_VERT_INCLUDE, fGpuSymbolTable,
246 &fVertexInclude, &fVertexSymbolTable);
247 this->processIncludeFile(Program::kFragment_Kind, SKSL_FRAG_INCLUDE, fGpuSymbolTable,
248 &fFragmentInclude, &fFragmentSymbolTable);
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400249#else
250 {
251 Rehydrator rehydrator(fContext.get(), symbols, this, SKSL_INCLUDE_sksl_gpu,
252 SKSL_INCLUDE_sksl_gpu_LENGTH);
253 fGpuSymbolTable = rehydrator.symbolTable();
254 gpuIntrinsics = rehydrator.elements();
255 }
256 {
257 Rehydrator rehydrator(fContext.get(), fGpuSymbolTable, this, SKSL_INCLUDE_sksl_vert,
258 SKSL_INCLUDE_sksl_vert_LENGTH);
259 fVertexSymbolTable = rehydrator.symbolTable();
260 fVertexInclude = rehydrator.elements();
261 }
262 {
263 Rehydrator rehydrator(fContext.get(), fGpuSymbolTable, this, SKSL_INCLUDE_sksl_frag,
264 SKSL_INCLUDE_sksl_frag_LENGTH);
265 fFragmentSymbolTable = rehydrator.symbolTable();
266 fFragmentInclude = rehydrator.elements();
267 }
268#endif
269 grab_intrinsics(&gpuIntrinsics, &fGPUIntrinsics);
Brian Osmanb08cc022020-04-02 11:38:40 -0400270 grab_intrinsics(&interpIntrinsics, &fInterpreterIntrinsics);
ethannicholasb3058bd2016-07-01 08:22:01 -0700271}
272
273Compiler::~Compiler() {
274 delete fIRGenerator;
275}
276
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400277void Compiler::loadGeometryIntrinsics() {
278 if (fGeometrySymbolTable) {
279 return;
280 }
Brian Osmandd496172020-08-08 08:17:18 -0400281 #if !SKSL_STANDALONE
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400282 {
283 Rehydrator rehydrator(fContext.get(), fGpuSymbolTable, this, SKSL_INCLUDE_sksl_geom,
284 SKSL_INCLUDE_sksl_geom_LENGTH);
285 fGeometrySymbolTable = rehydrator.symbolTable();
286 fGeometryInclude = rehydrator.elements();
287 }
288 #else
Ethan Nicholasb33fa3f2020-08-06 13:00:19 -0400289 this->processIncludeFile(Program::kGeometry_Kind, SKSL_GEOM_INCLUDE, fGpuSymbolTable,
290 &fGeometryInclude, &fGeometrySymbolTable);
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400291 #endif
292}
293
294void Compiler::loadPipelineIntrinsics() {
295 if (fPipelineSymbolTable) {
296 return;
297 }
Brian Osmandd496172020-08-08 08:17:18 -0400298 #if !SKSL_STANDALONE
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400299 {
300 Rehydrator rehydrator(fContext.get(), fGpuSymbolTable, this,
301 SKSL_INCLUDE_sksl_pipeline,
302 SKSL_INCLUDE_sksl_pipeline_LENGTH);
303 fPipelineSymbolTable = rehydrator.symbolTable();
304 fPipelineInclude = rehydrator.elements();
305 }
306 #else
307 this->processIncludeFile(Program::kPipelineStage_Kind, SKSL_PIPELINE_INCLUDE,
Ethan Nicholasb33fa3f2020-08-06 13:00:19 -0400308 fGpuSymbolTable, &fPipelineInclude, &fPipelineSymbolTable);
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400309 #endif
310}
311
312void Compiler::loadInterpreterIntrinsics() {
313 if (fInterpreterSymbolTable) {
314 return;
315 }
316 this->loadPipelineIntrinsics();
Brian Osmandd496172020-08-08 08:17:18 -0400317 #if !SKSL_STANDALONE
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400318 {
319 Rehydrator rehydrator(fContext.get(), fPipelineSymbolTable, this,
320 SKSL_INCLUDE_sksl_interp,
321 SKSL_INCLUDE_sksl_interp_LENGTH);
322 fInterpreterSymbolTable = rehydrator.symbolTable();
323 fInterpreterInclude = rehydrator.elements();
324 }
325 #else
326 this->processIncludeFile(Program::kGeneric_Kind, SKSL_INTERP_INCLUDE,
Ethan Nicholasb33fa3f2020-08-06 13:00:19 -0400327 fIRGenerator->fSymbolTable, &fInterpreterInclude,
328 &fInterpreterSymbolTable);
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400329 #endif
330}
331
Ethan Nicholasb33fa3f2020-08-06 13:00:19 -0400332void Compiler::processIncludeFile(Program::Kind kind, const char* path,
Ethan Nicholas8da1e652019-05-24 11:01:59 -0400333 std::shared_ptr<SymbolTable> base,
334 std::vector<std::unique_ptr<ProgramElement>>* outElements,
335 std::shared_ptr<SymbolTable>* outSymbolTable) {
Ethan Nicholasb33fa3f2020-08-06 13:00:19 -0400336 std::ifstream in(path);
337 std::string stdText{std::istreambuf_iterator<char>(in),
338 std::istreambuf_iterator<char>()};
339 if (in.rdstate()) {
340 printf("error reading %s\n", path);
341 abort();
342 }
343 if (!base) {
344 base = fIRGenerator->fSymbolTable;
345 }
346 SkASSERT(base);
347 const String* source = base->takeOwnershipOfString(std::make_unique<String>(stdText.c_str()));
348 fSource = source;
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400349 std::shared_ptr<SymbolTable> old = fIRGenerator->fSymbolTable;
350 if (base) {
351 fIRGenerator->fSymbolTable = std::move(base);
352 }
Ethan Nicholas8da1e652019-05-24 11:01:59 -0400353 Program::Settings settings;
Ethan Nicholasa11035b2019-11-26 16:27:47 -0500354#if !defined(SKSL_STANDALONE) & SK_SUPPORT_GPU
355 GrContextOptions opts;
356 GrShaderCaps caps(opts);
357 settings.fCaps = &caps;
358#endif
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400359 SkASSERT(fIRGenerator->fCanInline);
360 fIRGenerator->fCanInline = false;
361 fIRGenerator->start(&settings, nullptr, true);
Ethan Nicholasb33fa3f2020-08-06 13:00:19 -0400362 fIRGenerator->convertProgram(kind, source->c_str(), source->length(), outElements);
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400363 fIRGenerator->fCanInline = true;
Ethan Nicholas8da1e652019-05-24 11:01:59 -0400364 if (this->fErrorCount) {
365 printf("Unexpected errors: %s\n", this->fErrorText.c_str());
366 }
367 SkASSERT(!fErrorCount);
Ethan Nicholas8da1e652019-05-24 11:01:59 -0400368 *outSymbolTable = fIRGenerator->fSymbolTable;
Ethan Nicholasa11035b2019-11-26 16:27:47 -0500369#ifdef SK_DEBUG
370 fSource = nullptr;
371#endif
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400372 fIRGenerator->fSymbolTable = std::move(old);
Ethan Nicholas8da1e652019-05-24 11:01:59 -0400373}
374
ethannicholas22f939e2016-10-13 13:25:34 -0700375// add the definition created by assigning to the lvalue to the definition set
Ethan Nicholas86a43402017-01-19 13:32:00 -0500376void Compiler::addDefinition(const Expression* lvalue, std::unique_ptr<Expression>* expr,
377 DefinitionMap* definitions) {
ethannicholas22f939e2016-10-13 13:25:34 -0700378 switch (lvalue->fKind) {
379 case Expression::kVariableReference_Kind: {
John Stilesa5a97b42020-08-18 11:19:07 -0400380 const Variable& var = lvalue->as<VariableReference>().fVariable;
ethannicholas22f939e2016-10-13 13:25:34 -0700381 if (var.fStorage == Variable::kLocal_Storage) {
382 (*definitions)[&var] = expr;
383 }
384 break;
385 }
386 case Expression::kSwizzle_Kind:
387 // We consider the variable written to as long as at least some of its components have
388 // been written to. This will lead to some false negatives (we won't catch it if you
389 // write to foo.x and then read foo.y), but being stricter could lead to false positives
Mike Klein6ad99092016-10-26 10:35:22 -0400390 // (we write to foo.x, and then pass foo to a function which happens to only read foo.x,
391 // 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 -0700392 // more complicated whole-program analysis. This is probably good enough.
John Stilesa5a97b42020-08-18 11:19:07 -0400393 this->addDefinition(lvalue->as<Swizzle>().fBase.get(),
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400394 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
ethannicholas22f939e2016-10-13 13:25:34 -0700395 definitions);
396 break;
397 case Expression::kIndex_Kind:
398 // see comments in Swizzle
John Stilesa5a97b42020-08-18 11:19:07 -0400399 this->addDefinition(lvalue->as<IndexExpression>().fBase.get(),
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400400 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
ethannicholas22f939e2016-10-13 13:25:34 -0700401 definitions);
402 break;
403 case Expression::kFieldAccess_Kind:
404 // see comments in Swizzle
John Stilesa5a97b42020-08-18 11:19:07 -0400405 this->addDefinition(lvalue->as<FieldAccess>().fBase.get(),
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400406 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
ethannicholas22f939e2016-10-13 13:25:34 -0700407 definitions);
408 break;
Ethan Nicholasa583b812018-01-18 13:32:11 -0500409 case Expression::kTernary_Kind:
410 // To simplify analysis, we just pretend that we write to both sides of the ternary.
411 // This allows for false positives (meaning we fail to detect that a variable might not
412 // have been assigned), but is preferable to false negatives.
John Stilesa5a97b42020-08-18 11:19:07 -0400413 this->addDefinition(lvalue->as<TernaryExpression>().fIfTrue.get(),
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400414 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
Ethan Nicholasa583b812018-01-18 13:32:11 -0500415 definitions);
John Stilesa5a97b42020-08-18 11:19:07 -0400416 this->addDefinition(lvalue->as<TernaryExpression>().fIfFalse.get(),
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400417 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
Ethan Nicholasa583b812018-01-18 13:32:11 -0500418 definitions);
419 break;
Ethan Nicholas91164d12019-05-15 15:29:54 -0400420 case Expression::kExternalValue_Kind:
421 break;
ethannicholas22f939e2016-10-13 13:25:34 -0700422 default:
423 // not an lvalue, can't happen
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400424 SkASSERT(false);
ethannicholas22f939e2016-10-13 13:25:34 -0700425 }
426}
427
428// add local variables defined by this node to the set
Mike Klein6ad99092016-10-26 10:35:22 -0400429void Compiler::addDefinitions(const BasicBlock::Node& node,
Ethan Nicholas86a43402017-01-19 13:32:00 -0500430 DefinitionMap* definitions) {
ethannicholas22f939e2016-10-13 13:25:34 -0700431 switch (node.fKind) {
432 case BasicBlock::Node::kExpression_Kind: {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400433 SkASSERT(node.expression());
John Stilesa5a97b42020-08-18 11:19:07 -0400434 Expression* expr = node.expression()->get();
Ethan Nicholas86a43402017-01-19 13:32:00 -0500435 switch (expr->fKind) {
436 case Expression::kBinary_Kind: {
John Stilesa5a97b42020-08-18 11:19:07 -0400437 BinaryExpression* b = &expr->as<BinaryExpression>();
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400438 if (b->fOperator == Token::Kind::TK_EQ) {
Ethan Nicholas86a43402017-01-19 13:32:00 -0500439 this->addDefinition(b->fLeft.get(), &b->fRight, definitions);
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700440 } else if (Compiler::IsAssignment(b->fOperator)) {
Ethan Nicholas86a43402017-01-19 13:32:00 -0500441 this->addDefinition(
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400442 b->fLeft.get(),
443 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
444 definitions);
Ethan Nicholas86a43402017-01-19 13:32:00 -0500445
446 }
447 break;
ethannicholas22f939e2016-10-13 13:25:34 -0700448 }
Ethan Nicholasc6a19f12018-03-29 16:46:56 -0400449 case Expression::kFunctionCall_Kind: {
John Stilesa5a97b42020-08-18 11:19:07 -0400450 const FunctionCall& c = expr->as<FunctionCall>();
Ethan Nicholasc6a19f12018-03-29 16:46:56 -0400451 for (size_t i = 0; i < c.fFunction.fParameters.size(); ++i) {
452 if (c.fFunction.fParameters[i]->fModifiers.fFlags & Modifiers::kOut_Flag) {
453 this->addDefinition(
454 c.fArguments[i].get(),
455 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
456 definitions);
457 }
458 }
459 break;
460 }
Ethan Nicholas86a43402017-01-19 13:32:00 -0500461 case Expression::kPrefix_Kind: {
John Stilesa5a97b42020-08-18 11:19:07 -0400462 const PrefixExpression* p = &expr->as<PrefixExpression>();
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400463 if (p->fOperator == Token::Kind::TK_MINUSMINUS ||
464 p->fOperator == Token::Kind::TK_PLUSPLUS) {
Ethan Nicholas86a43402017-01-19 13:32:00 -0500465 this->addDefinition(
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400466 p->fOperand.get(),
467 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
468 definitions);
Ethan Nicholas86a43402017-01-19 13:32:00 -0500469 }
470 break;
471 }
472 case Expression::kPostfix_Kind: {
John Stilesa5a97b42020-08-18 11:19:07 -0400473 const PostfixExpression* p = &expr->as<PostfixExpression>();
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400474 if (p->fOperator == Token::Kind::TK_MINUSMINUS ||
475 p->fOperator == Token::Kind::TK_PLUSPLUS) {
Ethan Nicholas86a43402017-01-19 13:32:00 -0500476 this->addDefinition(
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400477 p->fOperand.get(),
478 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
479 definitions);
Ethan Nicholas86a43402017-01-19 13:32:00 -0500480 }
481 break;
482 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400483 case Expression::kVariableReference_Kind: {
John Stilesa5a97b42020-08-18 11:19:07 -0400484 const VariableReference* v = &expr->as<VariableReference>();
Ethan Nicholascb670962017-04-20 19:31:52 -0400485 if (v->fRefKind != VariableReference::kRead_RefKind) {
486 this->addDefinition(
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400487 v,
488 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
489 definitions);
Ethan Nicholascb670962017-04-20 19:31:52 -0400490 }
John Stiles30212b72020-06-11 17:55:07 -0400491 break;
Ethan Nicholascb670962017-04-20 19:31:52 -0400492 }
Ethan Nicholas86a43402017-01-19 13:32:00 -0500493 default:
494 break;
ethannicholas22f939e2016-10-13 13:25:34 -0700495 }
496 break;
497 }
498 case BasicBlock::Node::kStatement_Kind: {
John Stilesa5a97b42020-08-18 11:19:07 -0400499 Statement* stmt = node.statement()->get();
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000500 if (stmt->fKind == Statement::kVarDeclaration_Kind) {
John Stilesa5a97b42020-08-18 11:19:07 -0400501 VarDeclaration& vd = stmt->as<VarDeclaration>();
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000502 if (vd.fValue) {
503 (*definitions)[vd.fVar] = &vd.fValue;
ethannicholas22f939e2016-10-13 13:25:34 -0700504 }
505 }
506 break;
507 }
508 }
509}
510
511void Compiler::scanCFG(CFG* cfg, BlockId blockId, std::set<BlockId>* workList) {
512 BasicBlock& block = cfg->fBlocks[blockId];
513
514 // compute definitions after this block
Ethan Nicholas86a43402017-01-19 13:32:00 -0500515 DefinitionMap after = block.fBefore;
ethannicholas22f939e2016-10-13 13:25:34 -0700516 for (const BasicBlock::Node& n : block.fNodes) {
517 this->addDefinitions(n, &after);
518 }
519
520 // propagate definitions to exits
521 for (BlockId exitId : block.fExits) {
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400522 if (exitId == blockId) {
523 continue;
524 }
ethannicholas22f939e2016-10-13 13:25:34 -0700525 BasicBlock& exit = cfg->fBlocks[exitId];
526 for (const auto& pair : after) {
Ethan Nicholas86a43402017-01-19 13:32:00 -0500527 std::unique_ptr<Expression>* e1 = pair.second;
528 auto found = exit.fBefore.find(pair.first);
529 if (found == exit.fBefore.end()) {
530 // exit has no definition for it, just copy it
531 workList->insert(exitId);
ethannicholas22f939e2016-10-13 13:25:34 -0700532 exit.fBefore[pair.first] = e1;
533 } else {
Ethan Nicholas86a43402017-01-19 13:32:00 -0500534 // exit has a (possibly different) value already defined
535 std::unique_ptr<Expression>* e2 = exit.fBefore[pair.first];
ethannicholas22f939e2016-10-13 13:25:34 -0700536 if (e1 != e2) {
537 // definition has changed, merge and add exit block to worklist
538 workList->insert(exitId);
Ethan Nicholasaf197692017-02-27 13:26:45 -0500539 if (e1 && e2) {
540 exit.fBefore[pair.first] =
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400541 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression;
Ethan Nicholasaf197692017-02-27 13:26:45 -0500542 } else {
543 exit.fBefore[pair.first] = nullptr;
544 }
ethannicholas22f939e2016-10-13 13:25:34 -0700545 }
546 }
547 }
548 }
549}
550
551// returns a map which maps all local variables in the function to null, indicating that their value
552// is initially unknown
Ethan Nicholas86a43402017-01-19 13:32:00 -0500553static DefinitionMap compute_start_state(const CFG& cfg) {
554 DefinitionMap result;
Mike Klein6ad99092016-10-26 10:35:22 -0400555 for (const auto& block : cfg.fBlocks) {
556 for (const auto& node : block.fNodes) {
ethannicholas22f939e2016-10-13 13:25:34 -0700557 if (node.fKind == BasicBlock::Node::kStatement_Kind) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400558 SkASSERT(node.statement());
Ethan Nicholascb670962017-04-20 19:31:52 -0400559 const Statement* s = node.statement()->get();
ethannicholas22f939e2016-10-13 13:25:34 -0700560 if (s->fKind == Statement::kVarDeclarations_Kind) {
John Stilesa5a97b42020-08-18 11:19:07 -0400561 const VarDeclarationsStatement* vd = &s->as<VarDeclarationsStatement>();
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000562 for (const auto& decl : vd->fDeclaration->fVars) {
563 if (decl->fKind == Statement::kVarDeclaration_Kind) {
John Stilesa5a97b42020-08-18 11:19:07 -0400564 result[decl->as<VarDeclaration>().fVar] = nullptr;
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000565 }
Mike Klein6ad99092016-10-26 10:35:22 -0400566 }
ethannicholas22f939e2016-10-13 13:25:34 -0700567 }
568 }
569 }
570 }
571 return result;
572}
573
Ethan Nicholascb670962017-04-20 19:31:52 -0400574/**
575 * Returns true if assigning to this lvalue has no effect.
576 */
577static bool is_dead(const Expression& lvalue) {
578 switch (lvalue.fKind) {
579 case Expression::kVariableReference_Kind:
John Stilesa5a97b42020-08-18 11:19:07 -0400580 return lvalue.as<VariableReference>().fVariable.dead();
Ethan Nicholascb670962017-04-20 19:31:52 -0400581 case Expression::kSwizzle_Kind:
John Stilesa5a97b42020-08-18 11:19:07 -0400582 return is_dead(*lvalue.as<Swizzle>().fBase);
Ethan Nicholascb670962017-04-20 19:31:52 -0400583 case Expression::kFieldAccess_Kind:
John Stilesa5a97b42020-08-18 11:19:07 -0400584 return is_dead(*lvalue.as<FieldAccess>().fBase);
Ethan Nicholascb670962017-04-20 19:31:52 -0400585 case Expression::kIndex_Kind: {
John Stilesa5a97b42020-08-18 11:19:07 -0400586 const IndexExpression& idx = lvalue.as<IndexExpression>();
Ethan Nicholas2a099da2020-01-02 14:40:54 -0500587 return is_dead(*idx.fBase) &&
588 !idx.fIndex->hasProperty(Expression::Property::kSideEffects);
Ethan Nicholascb670962017-04-20 19:31:52 -0400589 }
Ethan Nicholasa583b812018-01-18 13:32:11 -0500590 case Expression::kTernary_Kind: {
John Stilesa5a97b42020-08-18 11:19:07 -0400591 const TernaryExpression& t = lvalue.as<TernaryExpression>();
Ethan Nicholasa583b812018-01-18 13:32:11 -0500592 return !t.fTest->hasSideEffects() && is_dead(*t.fIfTrue) && is_dead(*t.fIfFalse);
593 }
Ethan Nicholas91164d12019-05-15 15:29:54 -0400594 case Expression::kExternalValue_Kind:
595 return false;
Ethan Nicholascb670962017-04-20 19:31:52 -0400596 default:
Ethan Nicholas2a099da2020-01-02 14:40:54 -0500597#ifdef SK_DEBUG
Ethan Nicholascb670962017-04-20 19:31:52 -0400598 ABORT("invalid lvalue: %s\n", lvalue.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -0500599#endif
600 return false;
Ethan Nicholascb670962017-04-20 19:31:52 -0400601 }
602}
ethannicholas22f939e2016-10-13 13:25:34 -0700603
Ethan Nicholascb670962017-04-20 19:31:52 -0400604/**
605 * Returns true if this is an assignment which can be collapsed down to just the right hand side due
606 * to a dead target and lack of side effects on the left hand side.
607 */
608static bool dead_assignment(const BinaryExpression& b) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700609 if (!Compiler::IsAssignment(b.fOperator)) {
Ethan Nicholascb670962017-04-20 19:31:52 -0400610 return false;
611 }
612 return is_dead(*b.fLeft);
613}
614
615void Compiler::computeDataFlow(CFG* cfg) {
616 cfg->fBlocks[cfg->fStart].fBefore = compute_start_state(*cfg);
ethannicholas22f939e2016-10-13 13:25:34 -0700617 std::set<BlockId> workList;
Ethan Nicholascb670962017-04-20 19:31:52 -0400618 for (BlockId i = 0; i < cfg->fBlocks.size(); i++) {
ethannicholas22f939e2016-10-13 13:25:34 -0700619 workList.insert(i);
620 }
621 while (workList.size()) {
622 BlockId next = *workList.begin();
623 workList.erase(workList.begin());
Ethan Nicholascb670962017-04-20 19:31:52 -0400624 this->scanCFG(cfg, next, &workList);
ethannicholas22f939e2016-10-13 13:25:34 -0700625 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400626}
627
628/**
629 * Attempts to replace the expression pointed to by iter with a new one (in both the CFG and the
630 * IR). If the expression can be cleanly removed, returns true and updates the iterator to point to
631 * the newly-inserted element. Otherwise updates only the IR and returns false (and the CFG will
632 * need to be regenerated).
633 */
John Stilesafbf8992020-08-18 10:08:21 -0400634static bool try_replace_expression(BasicBlock* b,
635 std::vector<BasicBlock::Node>::iterator* iter,
636 std::unique_ptr<Expression>* newExpression) {
Ethan Nicholascb670962017-04-20 19:31:52 -0400637 std::unique_ptr<Expression>* target = (*iter)->expression();
638 if (!b->tryRemoveExpression(iter)) {
639 *target = std::move(*newExpression);
640 return false;
641 }
642 *target = std::move(*newExpression);
643 return b->tryInsertExpression(iter, target);
644}
645
646/**
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400647 * Returns true if the expression is a constant numeric literal with the specified value, or a
648 * constant vector with all elements equal to the specified value.
Ethan Nicholascb670962017-04-20 19:31:52 -0400649 */
John Stiles9d944232020-08-19 09:56:49 -0400650template <typename T = double>
651static bool is_constant(const Expression& expr, T value) {
Ethan Nicholascb670962017-04-20 19:31:52 -0400652 switch (expr.fKind) {
653 case Expression::kIntLiteral_Kind:
John Stiles81365af2020-08-18 09:24:00 -0400654 return expr.as<IntLiteral>().fValue == value;
John Stiles9d944232020-08-19 09:56:49 -0400655
Ethan Nicholascb670962017-04-20 19:31:52 -0400656 case Expression::kFloatLiteral_Kind:
John Stiles81365af2020-08-18 09:24:00 -0400657 return expr.as<FloatLiteral>().fValue == value;
John Stiles9d944232020-08-19 09:56:49 -0400658
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400659 case Expression::kConstructor_Kind: {
John Stiles9d944232020-08-19 09:56:49 -0400660 const Constructor& constructor = expr.as<Constructor>();
661 if (constructor.isCompileTimeConstant()) {
662 bool isFloat = constructor.fType.columns() > 1
663 ? constructor.fType.componentType().isFloat()
664 : constructor.fType.isFloat();
665 switch (constructor.fType.kind()) {
666 case Type::kVector_Kind:
667 for (int i = 0; i < constructor.fType.columns(); ++i) {
668 if (isFloat) {
669 if (constructor.getFVecComponent(i) != value) {
670 return false;
671 }
672 } else {
673 if (constructor.getIVecComponent(i) != value) {
674 return false;
675 }
676 }
Ethan Nicholasd188c182019-06-10 15:55:38 -0400677 }
John Stiles9d944232020-08-19 09:56:49 -0400678 return true;
679
680 case Type::kScalar_Kind:
681 SkASSERT(constructor.fArguments.size() == 1);
682 return is_constant<T>(*constructor.fArguments[0], value);
683
684 default:
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400685 return false;
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400686 }
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400687 }
688 return false;
689 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400690 default:
691 return false;
692 }
693}
694
695/**
696 * Collapses the binary expression pointed to by iter down to just the right side (in both the IR
697 * and CFG structures).
698 */
John Stilesafbf8992020-08-18 10:08:21 -0400699static void delete_left(BasicBlock* b,
700 std::vector<BasicBlock::Node>::iterator* iter,
701 bool* outUpdated,
702 bool* outNeedsRescan) {
Ethan Nicholascb670962017-04-20 19:31:52 -0400703 *outUpdated = true;
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400704 std::unique_ptr<Expression>* target = (*iter)->expression();
John Stilesa5a97b42020-08-18 11:19:07 -0400705 BinaryExpression& bin = (*target)->as<BinaryExpression>();
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400706 SkASSERT(!bin.fLeft->hasSideEffects());
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400707 bool result;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400708 if (bin.fOperator == Token::Kind::TK_EQ) {
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400709 result = b->tryRemoveLValueBefore(iter, bin.fLeft.get());
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400710 } else {
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400711 result = b->tryRemoveExpressionBefore(iter, bin.fLeft.get());
Ethan Nicholascb670962017-04-20 19:31:52 -0400712 }
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400713 *target = std::move(bin.fRight);
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400714 if (!result) {
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400715 *outNeedsRescan = true;
716 return;
717 }
718 if (*iter == b->fNodes.begin()) {
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400719 *outNeedsRescan = true;
720 return;
721 }
722 --(*iter);
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400723 if ((*iter)->fKind != BasicBlock::Node::kExpression_Kind ||
724 (*iter)->expression() != &bin.fRight) {
725 *outNeedsRescan = true;
726 return;
727 }
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400728 *iter = b->fNodes.erase(*iter);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400729 SkASSERT((*iter)->expression() == target);
Ethan Nicholascb670962017-04-20 19:31:52 -0400730}
731
732/**
733 * Collapses the binary expression pointed to by iter down to just the left side (in both the IR and
734 * CFG structures).
735 */
John Stilesafbf8992020-08-18 10:08:21 -0400736static void delete_right(BasicBlock* b,
737 std::vector<BasicBlock::Node>::iterator* iter,
738 bool* outUpdated,
739 bool* outNeedsRescan) {
Ethan Nicholascb670962017-04-20 19:31:52 -0400740 *outUpdated = true;
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400741 std::unique_ptr<Expression>* target = (*iter)->expression();
John Stilesa5a97b42020-08-18 11:19:07 -0400742 BinaryExpression& bin = (*target)->as<BinaryExpression>();
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400743 SkASSERT(!bin.fRight->hasSideEffects());
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400744 if (!b->tryRemoveExpressionBefore(iter, bin.fRight.get())) {
745 *target = std::move(bin.fLeft);
Ethan Nicholascb670962017-04-20 19:31:52 -0400746 *outNeedsRescan = true;
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400747 return;
Ethan Nicholascb670962017-04-20 19:31:52 -0400748 }
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400749 *target = std::move(bin.fLeft);
750 if (*iter == b->fNodes.begin()) {
751 *outNeedsRescan = true;
752 return;
753 }
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400754 --(*iter);
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400755 if (((*iter)->fKind != BasicBlock::Node::kExpression_Kind ||
756 (*iter)->expression() != &bin.fLeft)) {
757 *outNeedsRescan = true;
758 return;
759 }
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400760 *iter = b->fNodes.erase(*iter);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400761 SkASSERT((*iter)->expression() == target);
Ethan Nicholascb670962017-04-20 19:31:52 -0400762}
763
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400764/**
765 * Constructs the specified type using a single argument.
766 */
767static std::unique_ptr<Expression> construct(const Type& type, std::unique_ptr<Expression> v) {
768 std::vector<std::unique_ptr<Expression>> args;
769 args.push_back(std::move(v));
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700770 auto result = std::unique_ptr<Expression>(new Constructor(-1, type, std::move(args)));
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400771 return result;
772}
773
774/**
775 * Used in the implementations of vectorize_left and vectorize_right. Given a vector type and an
776 * expression x, deletes the expression pointed to by iter and replaces it with <type>(x).
777 */
778static void vectorize(BasicBlock* b,
779 std::vector<BasicBlock::Node>::iterator* iter,
780 const Type& type,
781 std::unique_ptr<Expression>* otherExpression,
782 bool* outUpdated,
783 bool* outNeedsRescan) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400784 SkASSERT((*(*iter)->expression())->fKind == Expression::kBinary_Kind);
785 SkASSERT(type.kind() == Type::kVector_Kind);
786 SkASSERT((*otherExpression)->fType.kind() == Type::kScalar_Kind);
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400787 *outUpdated = true;
788 std::unique_ptr<Expression>* target = (*iter)->expression();
789 if (!b->tryRemoveExpression(iter)) {
790 *target = construct(type, std::move(*otherExpression));
791 *outNeedsRescan = true;
792 } else {
793 *target = construct(type, std::move(*otherExpression));
794 if (!b->tryInsertExpression(iter, target)) {
795 *outNeedsRescan = true;
796 }
797 }
798}
799
800/**
801 * Given a binary expression of the form x <op> vec<n>(y), deletes the right side and vectorizes the
802 * left to yield vec<n>(x).
803 */
804static void vectorize_left(BasicBlock* b,
805 std::vector<BasicBlock::Node>::iterator* iter,
806 bool* outUpdated,
807 bool* outNeedsRescan) {
John Stilesa5a97b42020-08-18 11:19:07 -0400808 BinaryExpression& bin = (*(*iter)->expression())->as<BinaryExpression>();
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400809 vectorize(b, iter, bin.fRight->fType, &bin.fLeft, outUpdated, outNeedsRescan);
810}
811
812/**
813 * Given a binary expression of the form vec<n>(x) <op> y, deletes the left side and vectorizes the
814 * right to yield vec<n>(y).
815 */
816static void vectorize_right(BasicBlock* b,
817 std::vector<BasicBlock::Node>::iterator* iter,
818 bool* outUpdated,
819 bool* outNeedsRescan) {
John Stilesa5a97b42020-08-18 11:19:07 -0400820 BinaryExpression& bin = (*(*iter)->expression())->as<BinaryExpression>();
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400821 vectorize(b, iter, bin.fLeft->fType, &bin.fRight, outUpdated, outNeedsRescan);
822}
823
824// Mark that an expression which we were writing to is no longer being written to
John Stilesa5a97b42020-08-18 11:19:07 -0400825static void clear_write(Expression& expr) {
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400826 switch (expr.fKind) {
827 case Expression::kVariableReference_Kind: {
John Stilesa5a97b42020-08-18 11:19:07 -0400828 expr.as<VariableReference>().setRefKind(VariableReference::kRead_RefKind);
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400829 break;
830 }
831 case Expression::kFieldAccess_Kind:
John Stilesa5a97b42020-08-18 11:19:07 -0400832 clear_write(*expr.as<FieldAccess>().fBase);
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400833 break;
834 case Expression::kSwizzle_Kind:
John Stilesa5a97b42020-08-18 11:19:07 -0400835 clear_write(*expr.as<Swizzle>().fBase);
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400836 break;
837 case Expression::kIndex_Kind:
John Stilesa5a97b42020-08-18 11:19:07 -0400838 clear_write(*expr.as<IndexExpression>().fBase);
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400839 break;
840 default:
841 ABORT("shouldn't be writing to this kind of expression\n");
842 break;
843 }
844}
845
Ethan Nicholascb670962017-04-20 19:31:52 -0400846void Compiler::simplifyExpression(DefinitionMap& definitions,
847 BasicBlock& b,
848 std::vector<BasicBlock::Node>::iterator* iter,
849 std::unordered_set<const Variable*>* undefinedVariables,
850 bool* outUpdated,
851 bool* outNeedsRescan) {
852 Expression* expr = (*iter)->expression()->get();
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400853 SkASSERT(expr);
Ethan Nicholascb670962017-04-20 19:31:52 -0400854 if ((*iter)->fConstantPropagation) {
855 std::unique_ptr<Expression> optimized = expr->constantPropagate(*fIRGenerator, definitions);
856 if (optimized) {
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400857 *outUpdated = true;
Ethan Nicholascb670962017-04-20 19:31:52 -0400858 if (!try_replace_expression(&b, iter, &optimized)) {
859 *outNeedsRescan = true;
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400860 return;
Ethan Nicholascb670962017-04-20 19:31:52 -0400861 }
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400862 SkASSERT((*iter)->fKind == BasicBlock::Node::kExpression_Kind);
Ethan Nicholascb670962017-04-20 19:31:52 -0400863 expr = (*iter)->expression()->get();
Ethan Nicholascb670962017-04-20 19:31:52 -0400864 }
865 }
866 switch (expr->fKind) {
867 case Expression::kVariableReference_Kind: {
John Stilesa5a97b42020-08-18 11:19:07 -0400868 const VariableReference& ref = expr->as<VariableReference>();
Ethan Nicholas8f7e28f2018-03-26 14:24:27 -0400869 const Variable& var = ref.fVariable;
870 if (ref.refKind() != VariableReference::kWrite_RefKind &&
871 ref.refKind() != VariableReference::kPointer_RefKind &&
872 var.fStorage == Variable::kLocal_Storage && !definitions[&var] &&
Ethan Nicholascb670962017-04-20 19:31:52 -0400873 (*undefinedVariables).find(&var) == (*undefinedVariables).end()) {
874 (*undefinedVariables).insert(&var);
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000875 this->error(expr->fOffset,
876 "'" + var.fName + "' has not been assigned");
Ethan Nicholascb670962017-04-20 19:31:52 -0400877 }
878 break;
879 }
880 case Expression::kTernary_Kind: {
John Stiles403a3632020-08-20 12:11:48 -0400881 TernaryExpression* t = &expr->as<TernaryExpression>();
Ethan Nicholascb670962017-04-20 19:31:52 -0400882 if (t->fTest->fKind == Expression::kBoolLiteral_Kind) {
883 // ternary has a constant test, replace it with either the true or
884 // false branch
John Stiles403a3632020-08-20 12:11:48 -0400885 if (t->fTest->as<BoolLiteral>().fValue) {
Ethan Nicholascb670962017-04-20 19:31:52 -0400886 (*iter)->setExpression(std::move(t->fIfTrue));
887 } else {
888 (*iter)->setExpression(std::move(t->fIfFalse));
889 }
890 *outUpdated = true;
891 *outNeedsRescan = true;
892 }
893 break;
894 }
895 case Expression::kBinary_Kind: {
John Stiles403a3632020-08-20 12:11:48 -0400896 BinaryExpression* bin = &expr->as<BinaryExpression>();
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400897 if (dead_assignment(*bin)) {
898 delete_left(&b, iter, outUpdated, outNeedsRescan);
899 break;
900 }
901 // collapse useless expressions like x * 1 or x + 0
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400902 if (((bin->fLeft->fType.kind() != Type::kScalar_Kind) &&
903 (bin->fLeft->fType.kind() != Type::kVector_Kind)) ||
904 ((bin->fRight->fType.kind() != Type::kScalar_Kind) &&
905 (bin->fRight->fType.kind() != Type::kVector_Kind))) {
906 break;
907 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400908 switch (bin->fOperator) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400909 case Token::Kind::TK_STAR:
Ethan Nicholascb670962017-04-20 19:31:52 -0400910 if (is_constant(*bin->fLeft, 1)) {
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400911 if (bin->fLeft->fType.kind() == Type::kVector_Kind &&
912 bin->fRight->fType.kind() == Type::kScalar_Kind) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400913 // float4(1) * x -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400914 vectorize_right(&b, iter, outUpdated, outNeedsRescan);
915 } else {
916 // 1 * x -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400917 // 1 * float4(x) -> float4(x)
918 // float4(1) * float4(x) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400919 delete_left(&b, iter, outUpdated, outNeedsRescan);
920 }
921 }
922 else if (is_constant(*bin->fLeft, 0)) {
923 if (bin->fLeft->fType.kind() == Type::kScalar_Kind &&
Ethan Nicholas08dae922018-01-23 10:31:56 -0500924 bin->fRight->fType.kind() == Type::kVector_Kind &&
925 !bin->fRight->hasSideEffects()) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400926 // 0 * float4(x) -> float4(0)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400927 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
928 } else {
929 // 0 * x -> 0
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400930 // float4(0) * x -> float4(0)
931 // float4(0) * float4(x) -> float4(0)
Ethan Nicholas51493ee2017-12-11 12:34:33 -0500932 if (!bin->fRight->hasSideEffects()) {
933 delete_right(&b, iter, outUpdated, outNeedsRescan);
934 }
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400935 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400936 }
937 else if (is_constant(*bin->fRight, 1)) {
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400938 if (bin->fLeft->fType.kind() == Type::kScalar_Kind &&
939 bin->fRight->fType.kind() == Type::kVector_Kind) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400940 // x * float4(1) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400941 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
942 } else {
943 // x * 1 -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400944 // float4(x) * 1 -> float4(x)
945 // float4(x) * float4(1) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400946 delete_right(&b, iter, outUpdated, outNeedsRescan);
947 }
948 }
949 else if (is_constant(*bin->fRight, 0)) {
950 if (bin->fLeft->fType.kind() == Type::kVector_Kind &&
Ethan Nicholas08dae922018-01-23 10:31:56 -0500951 bin->fRight->fType.kind() == Type::kScalar_Kind &&
952 !bin->fLeft->hasSideEffects()) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400953 // float4(x) * 0 -> float4(0)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400954 vectorize_right(&b, iter, outUpdated, outNeedsRescan);
955 } else {
956 // x * 0 -> 0
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400957 // x * float4(0) -> float4(0)
958 // float4(x) * float4(0) -> float4(0)
Ethan Nicholas51493ee2017-12-11 12:34:33 -0500959 if (!bin->fLeft->hasSideEffects()) {
960 delete_left(&b, iter, outUpdated, outNeedsRescan);
961 }
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400962 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400963 }
964 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400965 case Token::Kind::TK_PLUS:
Ethan Nicholascb670962017-04-20 19:31:52 -0400966 if (is_constant(*bin->fLeft, 0)) {
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400967 if (bin->fLeft->fType.kind() == Type::kVector_Kind &&
968 bin->fRight->fType.kind() == Type::kScalar_Kind) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400969 // float4(0) + x -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400970 vectorize_right(&b, iter, outUpdated, outNeedsRescan);
971 } else {
972 // 0 + x -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400973 // 0 + float4(x) -> float4(x)
974 // float4(0) + float4(x) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400975 delete_left(&b, iter, outUpdated, outNeedsRescan);
976 }
977 } else if (is_constant(*bin->fRight, 0)) {
978 if (bin->fLeft->fType.kind() == Type::kScalar_Kind &&
979 bin->fRight->fType.kind() == Type::kVector_Kind) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400980 // x + float4(0) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400981 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
982 } else {
983 // x + 0 -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400984 // float4(x) + 0 -> float4(x)
985 // float4(x) + float4(0) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400986 delete_right(&b, iter, outUpdated, outNeedsRescan);
987 }
Ethan Nicholas56e42712017-04-21 10:23:37 -0400988 }
989 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400990 case Token::Kind::TK_MINUS:
Ethan Nicholas56e42712017-04-21 10:23:37 -0400991 if (is_constant(*bin->fRight, 0)) {
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400992 if (bin->fLeft->fType.kind() == Type::kScalar_Kind &&
993 bin->fRight->fType.kind() == Type::kVector_Kind) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400994 // x - float4(0) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400995 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
996 } else {
997 // x - 0 -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400998 // float4(x) - 0 -> float4(x)
999 // float4(x) - float4(0) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -04001000 delete_right(&b, iter, outUpdated, outNeedsRescan);
1001 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001002 }
1003 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001004 case Token::Kind::TK_SLASH:
Ethan Nicholascb670962017-04-20 19:31:52 -04001005 if (is_constant(*bin->fRight, 1)) {
Ethan Nicholasfe53e582017-04-27 16:24:51 -04001006 if (bin->fLeft->fType.kind() == Type::kScalar_Kind &&
1007 bin->fRight->fType.kind() == Type::kVector_Kind) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -04001008 // x / float4(1) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -04001009 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
1010 } else {
1011 // x / 1 -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -04001012 // float4(x) / 1 -> float4(x)
1013 // float4(x) / float4(1) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -04001014 delete_right(&b, iter, outUpdated, outNeedsRescan);
1015 }
1016 } else if (is_constant(*bin->fLeft, 0)) {
1017 if (bin->fLeft->fType.kind() == Type::kScalar_Kind &&
Ethan Nicholas08dae922018-01-23 10:31:56 -05001018 bin->fRight->fType.kind() == Type::kVector_Kind &&
1019 !bin->fRight->hasSideEffects()) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -04001020 // 0 / float4(x) -> float4(0)
Ethan Nicholasfe53e582017-04-27 16:24:51 -04001021 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
1022 } else {
1023 // 0 / x -> 0
Ethan Nicholas5af9ea32017-07-28 15:19:46 -04001024 // float4(0) / x -> float4(0)
1025 // float4(0) / float4(x) -> float4(0)
Ethan Nicholas51493ee2017-12-11 12:34:33 -05001026 if (!bin->fRight->hasSideEffects()) {
1027 delete_right(&b, iter, outUpdated, outNeedsRescan);
1028 }
Ethan Nicholasfe53e582017-04-27 16:24:51 -04001029 }
1030 }
1031 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001032 case Token::Kind::TK_PLUSEQ:
Ethan Nicholasfe53e582017-04-27 16:24:51 -04001033 if (is_constant(*bin->fRight, 0)) {
1034 clear_write(*bin->fLeft);
1035 delete_right(&b, iter, outUpdated, outNeedsRescan);
1036 }
1037 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001038 case Token::Kind::TK_MINUSEQ:
Ethan Nicholasfe53e582017-04-27 16:24:51 -04001039 if (is_constant(*bin->fRight, 0)) {
1040 clear_write(*bin->fLeft);
1041 delete_right(&b, iter, outUpdated, outNeedsRescan);
1042 }
1043 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001044 case Token::Kind::TK_STAREQ:
Ethan Nicholasfe53e582017-04-27 16:24:51 -04001045 if (is_constant(*bin->fRight, 1)) {
1046 clear_write(*bin->fLeft);
1047 delete_right(&b, iter, outUpdated, outNeedsRescan);
1048 }
1049 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001050 case Token::Kind::TK_SLASHEQ:
Ethan Nicholasfe53e582017-04-27 16:24:51 -04001051 if (is_constant(*bin->fRight, 1)) {
1052 clear_write(*bin->fLeft);
Ethan Nicholascb670962017-04-20 19:31:52 -04001053 delete_right(&b, iter, outUpdated, outNeedsRescan);
1054 }
1055 break;
1056 default:
1057 break;
1058 }
Ethan Nicholas409f6f02019-09-17 12:34:39 -04001059 break;
1060 }
1061 case Expression::kSwizzle_Kind: {
John Stiles403a3632020-08-20 12:11:48 -04001062 Swizzle& s = expr->as<Swizzle>();
Ethan Nicholas409f6f02019-09-17 12:34:39 -04001063 // detect identity swizzles like foo.rgba
1064 if ((int) s.fComponents.size() == s.fBase->fType.columns()) {
1065 bool identity = true;
1066 for (int i = 0; i < (int) s.fComponents.size(); ++i) {
1067 if (s.fComponents[i] != i) {
1068 identity = false;
1069 break;
1070 }
1071 }
1072 if (identity) {
1073 *outUpdated = true;
1074 if (!try_replace_expression(&b, iter, &s.fBase)) {
1075 *outNeedsRescan = true;
1076 return;
1077 }
1078 SkASSERT((*iter)->fKind == BasicBlock::Node::kExpression_Kind);
1079 break;
1080 }
1081 }
1082 // detect swizzles of swizzles, e.g. replace foo.argb.r000 with foo.a000
1083 if (s.fBase->fKind == Expression::kSwizzle_Kind) {
John Stilesa5a97b42020-08-18 11:19:07 -04001084 Swizzle& base = s.fBase->as<Swizzle>();
Ethan Nicholas409f6f02019-09-17 12:34:39 -04001085 std::vector<int> final;
1086 for (int c : s.fComponents) {
1087 if (c == SKSL_SWIZZLE_0 || c == SKSL_SWIZZLE_1) {
1088 final.push_back(c);
1089 } else {
1090 final.push_back(base.fComponents[c]);
1091 }
1092 }
1093 *outUpdated = true;
1094 std::unique_ptr<Expression> replacement(new Swizzle(*fContext, base.fBase->clone(),
1095 std::move(final)));
1096 if (!try_replace_expression(&b, iter, &replacement)) {
1097 *outNeedsRescan = true;
1098 return;
1099 }
1100 SkASSERT((*iter)->fKind == BasicBlock::Node::kExpression_Kind);
Ethan Nicholas409f6f02019-09-17 12:34:39 -04001101 }
John Stiles30212b72020-06-11 17:55:07 -04001102 break;
Ethan Nicholascb670962017-04-20 19:31:52 -04001103 }
1104 default:
1105 break;
1106 }
1107}
1108
John Stiles92219b42020-06-15 12:32:24 -04001109// Implementation-detail recursive helper function for `contains_conditional_break`.
1110static bool contains_conditional_break_impl(Statement& s, bool inConditional) {
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001111 switch (s.fKind) {
1112 case Statement::kBlock_Kind:
John Stilesa5a97b42020-08-18 11:19:07 -04001113 for (const std::unique_ptr<Statement>& sub : s.as<Block>().fStatements) {
John Stiles92219b42020-06-15 12:32:24 -04001114 if (contains_conditional_break_impl(*sub, inConditional)) {
Ethan Nicholas5005a222018-08-24 13:06:27 -04001115 return true;
1116 }
1117 }
1118 return false;
John Stiles92219b42020-06-15 12:32:24 -04001119
Ethan Nicholas5005a222018-08-24 13:06:27 -04001120 case Statement::kBreak_Kind:
1121 return inConditional;
John Stiles92219b42020-06-15 12:32:24 -04001122
Ethan Nicholas5005a222018-08-24 13:06:27 -04001123 case Statement::kIf_Kind: {
John Stilesa5a97b42020-08-18 11:19:07 -04001124 const IfStatement& i = s.as<IfStatement>();
John Stiles92219b42020-06-15 12:32:24 -04001125 return contains_conditional_break_impl(*i.fIfTrue, /*inConditional=*/true) ||
1126 (i.fIfFalse &&
1127 contains_conditional_break_impl(*i.fIfFalse, /*inConditional=*/true));
Ethan Nicholas5005a222018-08-24 13:06:27 -04001128 }
John Stiles92219b42020-06-15 12:32:24 -04001129
Ethan Nicholas5005a222018-08-24 13:06:27 -04001130 default:
1131 return false;
1132 }
1133}
1134
John Stiles92219b42020-06-15 12:32:24 -04001135// Returns true if this statement could potentially execute a break at the current level. We ignore
1136// nested loops and switches, since any breaks inside of them will merely break the loop / switch.
1137static bool contains_conditional_break(Statement& s) {
1138 return contains_conditional_break_impl(s, /*inConditional=*/false);
1139}
1140
Ethan Nicholas5005a222018-08-24 13:06:27 -04001141// returns true if this statement definitely executes a break at the current level (we ignore
1142// nested loops and switches, since any breaks inside of them will merely break the loop / switch)
1143static bool contains_unconditional_break(Statement& s) {
1144 switch (s.fKind) {
1145 case Statement::kBlock_Kind:
John Stiles92219b42020-06-15 12:32:24 -04001146 for (const std::unique_ptr<Statement>& sub : static_cast<Block&>(s).fStatements) {
Ethan Nicholas5005a222018-08-24 13:06:27 -04001147 if (contains_unconditional_break(*sub)) {
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001148 return true;
1149 }
1150 }
1151 return false;
John Stiles92219b42020-06-15 12:32:24 -04001152
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001153 case Statement::kBreak_Kind:
1154 return true;
John Stiles92219b42020-06-15 12:32:24 -04001155
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001156 default:
1157 return false;
1158 }
1159}
1160
John Stiles92219b42020-06-15 12:32:24 -04001161static void move_all_but_break(std::unique_ptr<Statement>& stmt,
1162 std::vector<std::unique_ptr<Statement>>* target) {
Ethan Nicholas739e1ca2020-06-11 12:16:14 -04001163 switch (stmt->fKind) {
John Stiles92219b42020-06-15 12:32:24 -04001164 case Statement::kBlock_Kind: {
1165 // Recurse into the block.
1166 Block& block = static_cast<Block&>(*stmt);
1167
1168 std::vector<std::unique_ptr<Statement>> blockStmts;
1169 blockStmts.reserve(block.fStatements.size());
1170 for (std::unique_ptr<Statement>& statementInBlock : block.fStatements) {
1171 move_all_but_break(statementInBlock, &blockStmts);
Ethan Nicholas739e1ca2020-06-11 12:16:14 -04001172 }
John Stiles92219b42020-06-15 12:32:24 -04001173
1174 target->push_back(std::make_unique<Block>(block.fOffset, std::move(blockStmts),
1175 block.fSymbols, block.fIsScope));
Ethan Nicholas739e1ca2020-06-11 12:16:14 -04001176 break;
John Stiles92219b42020-06-15 12:32:24 -04001177 }
1178
Ethan Nicholas739e1ca2020-06-11 12:16:14 -04001179 case Statement::kBreak_Kind:
John Stiles92219b42020-06-15 12:32:24 -04001180 // Do not append a break to the target.
1181 break;
1182
Ethan Nicholas739e1ca2020-06-11 12:16:14 -04001183 default:
John Stiles92219b42020-06-15 12:32:24 -04001184 // Append normal statements to the target.
1185 target->push_back(std::move(stmt));
1186 break;
Ethan Nicholas739e1ca2020-06-11 12:16:14 -04001187 }
1188}
1189
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001190// Returns a block containing all of the statements that will be run if the given case matches
1191// (which, owing to the statements being owned by unique_ptrs, means the switch itself will be
1192// broken by this call and must then be discarded).
1193// Returns null (and leaves the switch unmodified) if no such simple reduction is possible, such as
1194// when break statements appear inside conditionals.
John Stiles92219b42020-06-15 12:32:24 -04001195static std::unique_ptr<Statement> block_for_case(SwitchStatement* switchStatement,
1196 SwitchCase* caseToCapture) {
1197 // We have to be careful to not move any of the pointers until after we're sure we're going to
1198 // succeed, so before we make any changes at all, we check the switch-cases to decide on a plan
1199 // of action. First, find the switch-case we are interested in.
1200 auto iter = switchStatement->fCases.begin();
1201 for (; iter != switchStatement->fCases.end(); ++iter) {
1202 if (iter->get() == caseToCapture) {
1203 break;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001204 }
John Stiles92219b42020-06-15 12:32:24 -04001205 }
1206
1207 // Next, walk forward through the rest of the switch. If we find a conditional break, we're
1208 // stuck and can't simplify at all. If we find an unconditional break, we have a range of
1209 // statements that we can use for simplification.
1210 auto startIter = iter;
1211 Statement* unconditionalBreakStmt = nullptr;
1212 for (; iter != switchStatement->fCases.end(); ++iter) {
1213 for (std::unique_ptr<Statement>& stmt : (*iter)->fStatements) {
1214 if (contains_conditional_break(*stmt)) {
1215 // We can't reduce switch-cases to a block when they have conditional breaks.
1216 return nullptr;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001217 }
John Stiles92219b42020-06-15 12:32:24 -04001218
1219 if (contains_unconditional_break(*stmt)) {
1220 // We found an unconditional break. We can use this block, but we need to strip
1221 // out the break statement.
1222 unconditionalBreakStmt = stmt.get();
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001223 break;
1224 }
1225 }
John Stiles92219b42020-06-15 12:32:24 -04001226
1227 if (unconditionalBreakStmt != nullptr) {
1228 break;
1229 }
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001230 }
John Stiles92219b42020-06-15 12:32:24 -04001231
1232 // We fell off the bottom of the switch or encountered a break. We know the range of statements
1233 // that we need to move over, and we know it's safe to do so.
1234 std::vector<std::unique_ptr<Statement>> caseStmts;
1235
1236 // We can move over most of the statements as-is.
1237 while (startIter != iter) {
1238 for (std::unique_ptr<Statement>& stmt : (*startIter)->fStatements) {
1239 caseStmts.push_back(std::move(stmt));
1240 }
1241 ++startIter;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001242 }
John Stiles92219b42020-06-15 12:32:24 -04001243
1244 // If we found an unconditional break at the end, we need to move what we can while avoiding
1245 // that break.
1246 if (unconditionalBreakStmt != nullptr) {
1247 for (std::unique_ptr<Statement>& stmt : (*startIter)->fStatements) {
1248 if (stmt.get() == unconditionalBreakStmt) {
1249 move_all_but_break(stmt, &caseStmts);
1250 unconditionalBreakStmt = nullptr;
1251 break;
1252 }
1253
1254 caseStmts.push_back(std::move(stmt));
1255 }
1256 }
1257
1258 SkASSERT(unconditionalBreakStmt == nullptr); // Verify that we fixed the unconditional break.
1259
1260 // Return our newly-synthesized block.
1261 return std::make_unique<Block>(/*offset=*/-1, std::move(caseStmts), switchStatement->fSymbols);
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001262}
1263
Ethan Nicholascb670962017-04-20 19:31:52 -04001264void Compiler::simplifyStatement(DefinitionMap& definitions,
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001265 BasicBlock& b,
1266 std::vector<BasicBlock::Node>::iterator* iter,
1267 std::unordered_set<const Variable*>* undefinedVariables,
1268 bool* outUpdated,
1269 bool* outNeedsRescan) {
Ethan Nicholascb670962017-04-20 19:31:52 -04001270 Statement* stmt = (*iter)->statement()->get();
1271 switch (stmt->fKind) {
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001272 case Statement::kVarDeclaration_Kind: {
John Stilesa5a97b42020-08-18 11:19:07 -04001273 const auto& varDecl = stmt->as<VarDeclaration>();
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001274 if (varDecl.fVar->dead() &&
1275 (!varDecl.fValue ||
1276 !varDecl.fValue->hasSideEffects())) {
1277 if (varDecl.fValue) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001278 SkASSERT((*iter)->statement()->get() == stmt);
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001279 if (!b.tryRemoveExpressionBefore(iter, varDecl.fValue.get())) {
1280 *outNeedsRescan = true;
Ethan Nicholascb670962017-04-20 19:31:52 -04001281 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001282 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001283 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001284 *outUpdated = true;
Ethan Nicholascb670962017-04-20 19:31:52 -04001285 }
1286 break;
1287 }
1288 case Statement::kIf_Kind: {
John Stilesa5a97b42020-08-18 11:19:07 -04001289 IfStatement& i = stmt->as<IfStatement>();
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001290 if (i.fTest->fKind == Expression::kBoolLiteral_Kind) {
1291 // constant if, collapse down to a single branch
John Stilesa5a97b42020-08-18 11:19:07 -04001292 if (i.fTest->as<BoolLiteral>().fValue) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001293 SkASSERT(i.fIfTrue);
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001294 (*iter)->setStatement(std::move(i.fIfTrue));
1295 } else {
1296 if (i.fIfFalse) {
1297 (*iter)->setStatement(std::move(i.fIfFalse));
1298 } else {
1299 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
1300 }
1301 }
1302 *outUpdated = true;
1303 *outNeedsRescan = true;
1304 break;
1305 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001306 if (i.fIfFalse && i.fIfFalse->isEmpty()) {
1307 // else block doesn't do anything, remove it
1308 i.fIfFalse.reset();
1309 *outUpdated = true;
1310 *outNeedsRescan = true;
1311 }
1312 if (!i.fIfFalse && i.fIfTrue->isEmpty()) {
1313 // if block doesn't do anything, no else block
1314 if (i.fTest->hasSideEffects()) {
1315 // test has side effects, keep it
1316 (*iter)->setStatement(std::unique_ptr<Statement>(
1317 new ExpressionStatement(std::move(i.fTest))));
1318 } else {
1319 // no if, no else, no test side effects, kill the whole if
1320 // statement
1321 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
1322 }
1323 *outUpdated = true;
1324 *outNeedsRescan = true;
1325 }
1326 break;
1327 }
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001328 case Statement::kSwitch_Kind: {
John Stilesa5a97b42020-08-18 11:19:07 -04001329 SwitchStatement& s = stmt->as<SwitchStatement>();
Brian Osmanb6b95732020-06-30 11:44:27 -04001330 if (s.fValue->isCompileTimeConstant()) {
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001331 // switch is constant, replace it with the case that matches
1332 bool found = false;
1333 SwitchCase* defaultCase = nullptr;
John Stiles9d944232020-08-19 09:56:49 -04001334 for (const std::unique_ptr<SwitchCase>& c : s.fCases) {
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001335 if (!c->fValue) {
1336 defaultCase = c.get();
1337 continue;
1338 }
John Stiles9d944232020-08-19 09:56:49 -04001339 if (is_constant<int64_t>(*s.fValue, c->fValue->getConstantInt())) {
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001340 std::unique_ptr<Statement> newBlock = block_for_case(&s, c.get());
1341 if (newBlock) {
1342 (*iter)->setStatement(std::move(newBlock));
John Stiles9d944232020-08-19 09:56:49 -04001343 found = true;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001344 break;
1345 } else {
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -04001346 if (s.fIsStatic && !(fFlags & kPermitInvalidStaticTests_Flag)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001347 this->error(s.fOffset,
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001348 "static switch contains non-static conditional break");
1349 s.fIsStatic = false;
1350 }
1351 return; // can't simplify
1352 }
1353 }
1354 }
1355 if (!found) {
1356 // no matching case. use default if it exists, or kill the whole thing
1357 if (defaultCase) {
1358 std::unique_ptr<Statement> newBlock = block_for_case(&s, defaultCase);
1359 if (newBlock) {
1360 (*iter)->setStatement(std::move(newBlock));
1361 } else {
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -04001362 if (s.fIsStatic && !(fFlags & kPermitInvalidStaticTests_Flag)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001363 this->error(s.fOffset,
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001364 "static switch contains non-static conditional break");
1365 s.fIsStatic = false;
1366 }
1367 return; // can't simplify
1368 }
1369 } else {
1370 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
1371 }
1372 }
1373 *outUpdated = true;
1374 *outNeedsRescan = true;
1375 }
1376 break;
1377 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001378 case Statement::kExpression_Kind: {
John Stilesa5a97b42020-08-18 11:19:07 -04001379 ExpressionStatement& e = stmt->as<ExpressionStatement>();
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001380 SkASSERT((*iter)->statement()->get() == &e);
Ethan Nicholascb670962017-04-20 19:31:52 -04001381 if (!e.fExpression->hasSideEffects()) {
1382 // Expression statement with no side effects, kill it
1383 if (!b.tryRemoveExpressionBefore(iter, e.fExpression.get())) {
1384 *outNeedsRescan = true;
1385 }
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001386 SkASSERT((*iter)->statement()->get() == stmt);
Ethan Nicholascb670962017-04-20 19:31:52 -04001387 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
1388 *outUpdated = true;
1389 }
1390 break;
1391 }
1392 default:
1393 break;
1394 }
1395}
1396
1397void Compiler::scanCFG(FunctionDefinition& f) {
1398 CFG cfg = CFGGenerator().getCFG(f);
1399 this->computeDataFlow(&cfg);
ethannicholas22f939e2016-10-13 13:25:34 -07001400
1401 // check for unreachable code
1402 for (size_t i = 0; i < cfg.fBlocks.size(); i++) {
Mike Klein6ad99092016-10-26 10:35:22 -04001403 if (i != cfg.fStart && !cfg.fBlocks[i].fEntrances.size() &&
ethannicholas22f939e2016-10-13 13:25:34 -07001404 cfg.fBlocks[i].fNodes.size()) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001405 int offset;
Ethan Nicholas86a43402017-01-19 13:32:00 -05001406 switch (cfg.fBlocks[i].fNodes[0].fKind) {
1407 case BasicBlock::Node::kStatement_Kind:
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001408 offset = (*cfg.fBlocks[i].fNodes[0].statement())->fOffset;
Ethan Nicholas86a43402017-01-19 13:32:00 -05001409 break;
1410 case BasicBlock::Node::kExpression_Kind:
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001411 offset = (*cfg.fBlocks[i].fNodes[0].expression())->fOffset;
Ethan Nicholas70728ef2020-05-28 07:09:00 -04001412 if ((*cfg.fBlocks[i].fNodes[0].expression())->fKind ==
1413 Expression::kBoolLiteral_Kind) {
1414 // Function inlining can generate do { ... } while(false) loops which always
1415 // break, so the boolean condition is considered unreachable. Since not
1416 // being able to reach a literal is a non-issue in the first place, we
1417 // don't report an error in this case.
1418 continue;
1419 }
Ethan Nicholas86a43402017-01-19 13:32:00 -05001420 break;
1421 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001422 this->error(offset, String("unreachable"));
ethannicholas22f939e2016-10-13 13:25:34 -07001423 }
1424 }
1425 if (fErrorCount) {
1426 return;
1427 }
1428
Ethan Nicholascb670962017-04-20 19:31:52 -04001429 // check for dead code & undefined variables, perform constant propagation
1430 std::unordered_set<const Variable*> undefinedVariables;
1431 bool updated;
1432 bool needsRescan = false;
1433 do {
1434 if (needsRescan) {
1435 cfg = CFGGenerator().getCFG(f);
1436 this->computeDataFlow(&cfg);
1437 needsRescan = false;
Ethan Nicholas113628d2017-02-02 16:11:39 -05001438 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001439
1440 updated = false;
Ethan Nicholas1de14812020-06-19 15:32:49 -04001441 bool first = true;
Ethan Nicholascb670962017-04-20 19:31:52 -04001442 for (BasicBlock& b : cfg.fBlocks) {
Ethan Nicholas1de14812020-06-19 15:32:49 -04001443 if (!first && b.fEntrances.empty()) {
1444 // Block was reachable before optimization, but has since become unreachable. In
1445 // addition to being dead code, it's broken - since control flow can't reach it, no
1446 // prior variable definitions can reach it, and therefore variables might look to
1447 // have not been properly assigned. Kill it.
1448 for (BasicBlock::Node& node : b.fNodes) {
1449 if (node.fKind == BasicBlock::Node::kStatement_Kind &&
1450 (*node.statement())->fKind != Statement::kNop_Kind) {
1451 node.setStatement(std::unique_ptr<Statement>(new Nop()));
1452 }
1453 }
1454 continue;
1455 }
1456 first = false;
Ethan Nicholascb670962017-04-20 19:31:52 -04001457 DefinitionMap definitions = b.fBefore;
1458
1459 for (auto iter = b.fNodes.begin(); iter != b.fNodes.end() && !needsRescan; ++iter) {
1460 if (iter->fKind == BasicBlock::Node::kExpression_Kind) {
1461 this->simplifyExpression(definitions, b, &iter, &undefinedVariables, &updated,
1462 &needsRescan);
1463 } else {
1464 this->simplifyStatement(definitions, b, &iter, &undefinedVariables, &updated,
1465 &needsRescan);
1466 }
Ethan Nicholas4b330df2017-05-17 10:52:55 -04001467 if (needsRescan) {
1468 break;
1469 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001470 this->addDefinitions(*iter, &definitions);
1471 }
1472 }
1473 } while (updated);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001474 SkASSERT(!needsRescan);
ethannicholas22f939e2016-10-13 13:25:34 -07001475
Ethan Nicholas91a10532017-06-22 11:24:38 -04001476 // verify static ifs & switches, clean up dead variable decls
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001477 for (BasicBlock& b : cfg.fBlocks) {
1478 DefinitionMap definitions = b.fBefore;
1479
Ethan Nicholas91a10532017-06-22 11:24:38 -04001480 for (auto iter = b.fNodes.begin(); iter != b.fNodes.end() && !needsRescan;) {
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001481 if (iter->fKind == BasicBlock::Node::kStatement_Kind) {
1482 const Statement& s = **iter->statement();
1483 switch (s.fKind) {
1484 case Statement::kIf_Kind:
John Stilesa5a97b42020-08-18 11:19:07 -04001485 if (s.as<IfStatement>().fIsStatic &&
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -04001486 !(fFlags & kPermitInvalidStaticTests_Flag)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001487 this->error(s.fOffset, "static if has non-static test");
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001488 }
Ethan Nicholas91a10532017-06-22 11:24:38 -04001489 ++iter;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001490 break;
1491 case Statement::kSwitch_Kind:
John Stilesa5a97b42020-08-18 11:19:07 -04001492 if (s.as<SwitchStatement>().fIsStatic &&
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -04001493 !(fFlags & kPermitInvalidStaticTests_Flag)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001494 this->error(s.fOffset, "static switch has non-static test");
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001495 }
Ethan Nicholas91a10532017-06-22 11:24:38 -04001496 ++iter;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001497 break;
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001498 case Statement::kVarDeclarations_Kind: {
John Stilesa5a97b42020-08-18 11:19:07 -04001499 VarDeclarations& decls = *s.as<VarDeclarationsStatement>().fDeclaration;
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001500 for (auto varIter = decls.fVars.begin(); varIter != decls.fVars.end();) {
1501 if ((*varIter)->fKind == Statement::kNop_Kind) {
1502 varIter = decls.fVars.erase(varIter);
1503 } else {
1504 ++varIter;
1505 }
1506 }
1507 if (!decls.fVars.size()) {
1508 iter = b.fNodes.erase(iter);
1509 } else {
1510 ++iter;
1511 }
1512 break;
1513 }
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001514 default:
Ethan Nicholas91a10532017-06-22 11:24:38 -04001515 ++iter;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001516 break;
1517 }
Ethan Nicholas91a10532017-06-22 11:24:38 -04001518 } else {
1519 ++iter;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001520 }
1521 }
1522 }
1523
ethannicholas22f939e2016-10-13 13:25:34 -07001524 // check for missing return
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001525 if (f.fDeclaration.fReturnType != *fContext->fVoid_Type) {
ethannicholas22f939e2016-10-13 13:25:34 -07001526 if (cfg.fBlocks[cfg.fExit].fEntrances.size()) {
Ethan Nicholasdb80f692019-11-22 14:06:12 -05001527 this->error(f.fOffset, String("function '" + String(f.fDeclaration.fName) +
1528 "' can exit without returning a value"));
ethannicholas22f939e2016-10-13 13:25:34 -07001529 }
1530 }
1531}
1532
Ethan Nicholas91164d12019-05-15 15:29:54 -04001533void Compiler::registerExternalValue(ExternalValue* value) {
1534 fIRGenerator->fRootSymbolTable->addWithoutOwnership(value->fName, value);
1535}
1536
Ethan Nicholasc18bb512020-07-28 14:46:53 -04001537const Symbol* Compiler::takeOwnership(std::unique_ptr<const Symbol> symbol) {
John Stiles3ae071e2020-08-05 15:29:29 -04001538 return fIRGenerator->fRootSymbolTable->takeOwnershipOfSymbol(std::move(symbol));
Ethan Nicholas91164d12019-05-15 15:29:54 -04001539}
1540
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001541std::unique_ptr<Program> Compiler::convertProgram(Program::Kind kind, String text,
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001542 const Program::Settings& settings) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001543 fErrorText = "";
1544 fErrorCount = 0;
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001545 std::vector<std::unique_ptr<ProgramElement>>* inherited;
ethannicholasd598f792016-07-25 10:08:54 -07001546 std::vector<std::unique_ptr<ProgramElement>> elements;
ethannicholasb3058bd2016-07-01 08:22:01 -07001547 switch (kind) {
1548 case Program::kVertex_Kind:
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001549 inherited = &fVertexInclude;
1550 fIRGenerator->fSymbolTable = fVertexSymbolTable;
Ethan Nicholasdb80f692019-11-22 14:06:12 -05001551 fIRGenerator->fIntrinsics = &fGPUIntrinsics;
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001552 fIRGenerator->start(&settings, inherited);
ethannicholasb3058bd2016-07-01 08:22:01 -07001553 break;
1554 case Program::kFragment_Kind:
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001555 inherited = &fFragmentInclude;
1556 fIRGenerator->fSymbolTable = fFragmentSymbolTable;
Ethan Nicholasdb80f692019-11-22 14:06:12 -05001557 fIRGenerator->fIntrinsics = &fGPUIntrinsics;
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001558 fIRGenerator->start(&settings, inherited);
ethannicholasb3058bd2016-07-01 08:22:01 -07001559 break;
Ethan Nicholas52cad152017-02-16 16:37:32 -05001560 case Program::kGeometry_Kind:
Ethan Nicholasc18bb512020-07-28 14:46:53 -04001561 this->loadGeometryIntrinsics();
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001562 inherited = &fGeometryInclude;
1563 fIRGenerator->fSymbolTable = fGeometrySymbolTable;
Ethan Nicholasdb80f692019-11-22 14:06:12 -05001564 fIRGenerator->fIntrinsics = &fGPUIntrinsics;
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001565 fIRGenerator->start(&settings, inherited);
Ethan Nicholas52cad152017-02-16 16:37:32 -05001566 break;
Ethan Nicholasb33fa3f2020-08-06 13:00:19 -04001567 case Program::kFragmentProcessor_Kind: {
Brian Osmandd496172020-08-08 08:17:18 -04001568#if !SKSL_STANDALONE
Ethan Nicholasc18bb512020-07-28 14:46:53 -04001569 {
1570 Rehydrator rehydrator(fContext.get(), fGpuSymbolTable, this,
1571 SKSL_INCLUDE_sksl_fp,
1572 SKSL_INCLUDE_sksl_fp_LENGTH);
1573 fFPSymbolTable = rehydrator.symbolTable();
1574 fFPInclude = rehydrator.elements();
1575 }
1576 inherited = &fFPInclude;
1577 fIRGenerator->fSymbolTable = fFPSymbolTable;
1578 fIRGenerator->fIntrinsics = &fGPUIntrinsics;
1579 fIRGenerator->start(&settings, inherited);
1580 break;
1581#else
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001582 inherited = nullptr;
Ethan Nicholas8da1e652019-05-24 11:01:59 -04001583 fIRGenerator->fSymbolTable = fGpuSymbolTable;
Ethan Nicholasb33fa3f2020-08-06 13:00:19 -04001584 fIRGenerator->start(&settings, /*inherited=*/nullptr, /*builtin=*/true);
Ethan Nicholasdb80f692019-11-22 14:06:12 -05001585 fIRGenerator->fIntrinsics = &fGPUIntrinsics;
Ethan Nicholasb33fa3f2020-08-06 13:00:19 -04001586 std::ifstream in(SKSL_FP_INCLUDE);
1587 std::string stdText{std::istreambuf_iterator<char>(in),
1588 std::istreambuf_iterator<char>()};
1589 if (in.rdstate()) {
1590 printf("error reading %s\n", SKSL_FP_INCLUDE);
1591 abort();
1592 }
1593 const String* source = fGpuSymbolTable->takeOwnershipOfString(
1594 std::make_unique<String>(stdText.c_str()));
1595 fIRGenerator->convertProgram(kind, source->c_str(), source->length(), &elements);
Ethan Nicholasc18bb512020-07-28 14:46:53 -04001596 fIRGenerator->fIsBuiltinCode = false;
Ethan Nicholas762466e2017-06-29 10:03:38 -04001597 break;
Ethan Nicholasc18bb512020-07-28 14:46:53 -04001598#endif
Ethan Nicholasb33fa3f2020-08-06 13:00:19 -04001599 }
Ethan Nicholas8da1e652019-05-24 11:01:59 -04001600 case Program::kPipelineStage_Kind:
Ethan Nicholasc18bb512020-07-28 14:46:53 -04001601 this->loadPipelineIntrinsics();
Ethan Nicholas8da1e652019-05-24 11:01:59 -04001602 inherited = &fPipelineInclude;
1603 fIRGenerator->fSymbolTable = fPipelineSymbolTable;
Ethan Nicholasdb80f692019-11-22 14:06:12 -05001604 fIRGenerator->fIntrinsics = &fGPUIntrinsics;
Ethan Nicholas8da1e652019-05-24 11:01:59 -04001605 fIRGenerator->start(&settings, inherited);
1606 break;
Ethan Nicholas746035a2019-04-23 13:31:09 -04001607 case Program::kGeneric_Kind:
Ethan Nicholasc18bb512020-07-28 14:46:53 -04001608 this->loadInterpreterIntrinsics();
Ethan Nicholas8da1e652019-05-24 11:01:59 -04001609 inherited = &fInterpreterInclude;
1610 fIRGenerator->fSymbolTable = fInterpreterSymbolTable;
Ethan Nicholasdb80f692019-11-22 14:06:12 -05001611 fIRGenerator->fIntrinsics = &fInterpreterIntrinsics;
Ethan Nicholas8da1e652019-05-24 11:01:59 -04001612 fIRGenerator->start(&settings, inherited);
Ethan Nicholas0d997662019-04-08 09:46:01 -04001613 break;
ethannicholasb3058bd2016-07-01 08:22:01 -07001614 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001615 std::unique_ptr<String> textPtr(new String(std::move(text)));
1616 fSource = textPtr.get();
Ethan Nicholasc18bb512020-07-28 14:46:53 -04001617 fIRGenerator->convertProgram(kind, textPtr->c_str(), textPtr->size(), &elements);
John Stilesfbd050b2020-08-03 13:21:46 -04001618 auto result = std::make_unique<Program>(kind,
1619 std::move(textPtr),
1620 settings,
1621 fContext,
1622 inherited,
1623 std::move(elements),
1624 fIRGenerator->fSymbolTable,
1625 fIRGenerator->fInputs);
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001626 if (fErrorCount) {
1627 return nullptr;
1628 }
1629 return result;
1630}
1631
Ethan Nicholas00543112018-07-31 09:44:36 -04001632bool Compiler::optimize(Program& program) {
1633 SkASSERT(!fErrorCount);
1634 if (!program.fIsOptimized) {
1635 program.fIsOptimized = true;
1636 fIRGenerator->fKind = program.fKind;
1637 fIRGenerator->fSettings = &program.fSettings;
1638 for (auto& element : program) {
1639 if (element.fKind == ProgramElement::kFunction_Kind) {
John Stiles3dc0da62020-08-19 17:48:31 -04001640 this->scanCFG(element.as<FunctionDefinition>());
Ethan Nicholas00543112018-07-31 09:44:36 -04001641 }
1642 }
Ethan Nicholase8ad02c2020-06-03 16:58:20 -04001643 // we wait until after analysis to remove dead functions so that we still report errors
1644 // even in unused code
1645 if (program.fSettings.fRemoveDeadFunctions) {
1646 for (auto iter = program.fElements.begin(); iter != program.fElements.end(); ) {
1647 if ((*iter)->fKind == ProgramElement::kFunction_Kind) {
John Stiles3dc0da62020-08-19 17:48:31 -04001648 const FunctionDefinition& f = (*iter)->as<FunctionDefinition>();
Ethan Nicholase8ad02c2020-06-03 16:58:20 -04001649 if (!f.fDeclaration.fCallCount && f.fDeclaration.fName != "main") {
1650 iter = program.fElements.erase(iter);
1651 continue;
1652 }
1653 }
1654 ++iter;
1655 }
1656 }
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001657 if (program.fKind != Program::kFragmentProcessor_Kind) {
1658 for (auto iter = program.fElements.begin(); iter != program.fElements.end();) {
1659 if ((*iter)->fKind == ProgramElement::kVar_Kind) {
John Stiles3dc0da62020-08-19 17:48:31 -04001660 VarDeclarations& vars = (*iter)->as<VarDeclarations>();
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001661 for (auto varIter = vars.fVars.begin(); varIter != vars.fVars.end();) {
John Stiles403a3632020-08-20 12:11:48 -04001662 const Variable& var = *(*varIter)->as<VarDeclaration>().fVar;
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001663 if (var.dead()) {
1664 varIter = vars.fVars.erase(varIter);
1665 } else {
1666 ++varIter;
1667 }
1668 }
1669 if (vars.fVars.size() == 0) {
1670 iter = program.fElements.erase(iter);
1671 continue;
1672 }
1673 }
1674 ++iter;
1675 }
1676 }
Ethan Nicholas00543112018-07-31 09:44:36 -04001677 }
1678 return fErrorCount == 0;
1679}
1680
Brian Osmanfb32ddf2019-06-18 10:14:20 -04001681#if defined(SKSL_STANDALONE) || SK_SUPPORT_GPU
1682
Ethan Nicholas00543112018-07-31 09:44:36 -04001683bool Compiler::toSPIRV(Program& program, OutputStream& out) {
1684 if (!this->optimize(program)) {
1685 return false;
1686 }
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001687#ifdef SK_ENABLE_SPIRV_VALIDATION
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001688 StringStream buffer;
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001689 fSource = program.fSource.get();
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001690 SPIRVCodeGenerator cg(fContext.get(), &program, this, &buffer);
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001691 bool result = cg.generateCode();
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001692 fSource = nullptr;
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001693 if (result) {
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001694 spvtools::SpirvTools tools(SPV_ENV_VULKAN_1_0);
Ethan Nicholas762466e2017-06-29 10:03:38 -04001695 const String& data = buffer.str();
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001696 SkASSERT(0 == data.size() % 4);
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001697 auto dumpmsg = [](spv_message_level_t, const char*, const spv_position_t&, const char* m) {
1698 SkDebugf("SPIR-V validation error: %s\n", m);
1699 };
1700 tools.SetMessageConsumer(dumpmsg);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001701 // Verify that the SPIR-V we produced is valid. If this SkASSERT fails, check the logs prior
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001702 // to the failure to see the validation errors.
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001703 SkAssertResult(tools.Validate((const uint32_t*) data.c_str(), data.size() / 4));
Ethan Nicholas762466e2017-06-29 10:03:38 -04001704 out.write(data.c_str(), data.size());
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001705 }
1706#else
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001707 fSource = program.fSource.get();
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001708 SPIRVCodeGenerator cg(fContext.get(), &program, this, &out);
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001709 bool result = cg.generateCode();
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001710 fSource = nullptr;
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001711#endif
Ethan Nicholasce33f102016-12-09 17:22:59 -05001712 return result;
1713}
1714
Ethan Nicholas00543112018-07-31 09:44:36 -04001715bool Compiler::toSPIRV(Program& program, String* out) {
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001716 StringStream buffer;
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001717 bool result = this->toSPIRV(program, buffer);
1718 if (result) {
Ethan Nicholas762466e2017-06-29 10:03:38 -04001719 *out = buffer.str();
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001720 }
1721 return result;
1722}
1723
Ethan Nicholas00543112018-07-31 09:44:36 -04001724bool Compiler::toGLSL(Program& program, OutputStream& out) {
1725 if (!this->optimize(program)) {
1726 return false;
1727 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001728 fSource = program.fSource.get();
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001729 GLSLCodeGenerator cg(fContext.get(), &program, this, &out);
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001730 bool result = cg.generateCode();
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001731 fSource = nullptr;
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001732 return result;
1733}
1734
Ethan Nicholas00543112018-07-31 09:44:36 -04001735bool Compiler::toGLSL(Program& program, String* out) {
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001736 StringStream buffer;
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001737 bool result = this->toGLSL(program, buffer);
1738 if (result) {
Ethan Nicholas762466e2017-06-29 10:03:38 -04001739 *out = buffer.str();
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001740 }
1741 return result;
1742}
1743
Brian Osmanc0243912020-02-19 15:35:26 -05001744bool Compiler::toHLSL(Program& program, String* out) {
1745 String spirv;
1746 if (!this->toSPIRV(program, &spirv)) {
1747 return false;
1748 }
1749
1750 return SPIRVtoHLSL(spirv, out);
1751}
1752
Ethan Nicholas00543112018-07-31 09:44:36 -04001753bool Compiler::toMetal(Program& program, OutputStream& out) {
1754 if (!this->optimize(program)) {
1755 return false;
1756 }
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001757 MetalCodeGenerator cg(fContext.get(), &program, this, &out);
Ethan Nicholascc305772017-10-13 16:17:45 -04001758 bool result = cg.generateCode();
Ethan Nicholascc305772017-10-13 16:17:45 -04001759 return result;
1760}
1761
Ethan Nicholas00543112018-07-31 09:44:36 -04001762bool Compiler::toMetal(Program& program, String* out) {
1763 if (!this->optimize(program)) {
1764 return false;
1765 }
Timothy Liangb8eeb802018-07-23 16:46:16 -04001766 StringStream buffer;
1767 bool result = this->toMetal(program, buffer);
1768 if (result) {
1769 *out = buffer.str();
1770 }
1771 return result;
1772}
1773
Ethan Nicholas2a479a52020-08-18 16:29:45 -04001774#if defined(SKSL_STANDALONE) || defined(GR_TEST_UTILS)
Ethan Nicholas00543112018-07-31 09:44:36 -04001775bool Compiler::toCPP(Program& program, String name, OutputStream& out) {
1776 if (!this->optimize(program)) {
1777 return false;
1778 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001779 fSource = program.fSource.get();
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001780 CPPCodeGenerator cg(fContext.get(), &program, this, name, &out);
Ethan Nicholas762466e2017-06-29 10:03:38 -04001781 bool result = cg.generateCode();
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001782 fSource = nullptr;
Ethan Nicholas762466e2017-06-29 10:03:38 -04001783 return result;
1784}
1785
Ethan Nicholas00543112018-07-31 09:44:36 -04001786bool Compiler::toH(Program& program, String name, OutputStream& out) {
1787 if (!this->optimize(program)) {
1788 return false;
1789 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001790 fSource = program.fSource.get();
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001791 HCodeGenerator cg(fContext.get(), &program, this, name, &out);
Ethan Nicholas762466e2017-06-29 10:03:38 -04001792 bool result = cg.generateCode();
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001793 fSource = nullptr;
Ethan Nicholas00543112018-07-31 09:44:36 -04001794 return result;
1795}
Ethan Nicholas2a479a52020-08-18 16:29:45 -04001796#endif // defined(SKSL_STANDALONE) || defined(GR_TEST_UTILS)
Ethan Nicholas00543112018-07-31 09:44:36 -04001797
Ethan Nicholas2a479a52020-08-18 16:29:45 -04001798#endif // defined(SKSL_STANDALONE) || SK_SUPPORT_GPU
Brian Osman2e29ab52019-09-20 12:19:11 -04001799
1800#if !defined(SKSL_STANDALONE) && SK_SUPPORT_GPU
Brian Osmana4b91692020-08-10 14:26:16 -04001801bool Compiler::toPipelineStage(Program& program, PipelineStageArgs* outArgs) {
1802 if (!this->optimize(program)) {
1803 return false;
1804 }
Ethan Nicholas00543112018-07-31 09:44:36 -04001805 fSource = program.fSource.get();
1806 StringStream buffer;
Brian Osman300fe1d2020-01-23 15:42:43 -05001807 PipelineStageCodeGenerator cg(fContext.get(), &program, this, &buffer, outArgs);
Ethan Nicholas00543112018-07-31 09:44:36 -04001808 bool result = cg.generateCode();
1809 fSource = nullptr;
1810 if (result) {
Brian Osman107c6662019-12-30 15:02:30 -05001811 outArgs->fCode = buffer.str();
Ethan Nicholas00543112018-07-31 09:44:36 -04001812 }
Ethan Nicholas762466e2017-06-29 10:03:38 -04001813 return result;
1814}
Brian Osmanfb32ddf2019-06-18 10:14:20 -04001815#endif
1816
Ethan Nicholas0e9401d2019-03-21 11:05:37 -04001817std::unique_ptr<ByteCode> Compiler::toByteCode(Program& program) {
Mike Klein853d4ed2020-08-20 00:41:00 +00001818#if defined(SK_ENABLE_SKSL_INTERPRETER)
Ethan Nicholas0e9401d2019-03-21 11:05:37 -04001819 if (!this->optimize(program)) {
1820 return nullptr;
1821 }
Brian Osman808f0212020-01-21 15:36:47 -05001822 fSource = program.fSource.get();
Ethan Nicholas0e9401d2019-03-21 11:05:37 -04001823 std::unique_ptr<ByteCode> result(new ByteCode());
Brian Osmanb08cc022020-04-02 11:38:40 -04001824 ByteCodeGenerator cg(fContext.get(), &program, this, result.get());
1825 bool success = cg.generateCode();
1826 fSource = nullptr;
1827 if (success) {
Ethan Nicholas0e9401d2019-03-21 11:05:37 -04001828 return result;
1829 }
Mike Klein853d4ed2020-08-20 00:41:00 +00001830#else
1831 ABORT("ByteCode interpreter not enabled");
1832#endif
Ethan Nicholas0e9401d2019-03-21 11:05:37 -04001833 return nullptr;
1834}
1835
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001836const char* Compiler::OperatorName(Token::Kind kind) {
1837 switch (kind) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001838 case Token::Kind::TK_PLUS: return "+";
1839 case Token::Kind::TK_MINUS: return "-";
1840 case Token::Kind::TK_STAR: return "*";
1841 case Token::Kind::TK_SLASH: return "/";
1842 case Token::Kind::TK_PERCENT: return "%";
1843 case Token::Kind::TK_SHL: return "<<";
1844 case Token::Kind::TK_SHR: return ">>";
1845 case Token::Kind::TK_LOGICALNOT: return "!";
1846 case Token::Kind::TK_LOGICALAND: return "&&";
1847 case Token::Kind::TK_LOGICALOR: return "||";
1848 case Token::Kind::TK_LOGICALXOR: return "^^";
1849 case Token::Kind::TK_BITWISENOT: return "~";
1850 case Token::Kind::TK_BITWISEAND: return "&";
1851 case Token::Kind::TK_BITWISEOR: return "|";
1852 case Token::Kind::TK_BITWISEXOR: return "^";
1853 case Token::Kind::TK_EQ: return "=";
1854 case Token::Kind::TK_EQEQ: return "==";
1855 case Token::Kind::TK_NEQ: return "!=";
1856 case Token::Kind::TK_LT: return "<";
1857 case Token::Kind::TK_GT: return ">";
1858 case Token::Kind::TK_LTEQ: return "<=";
1859 case Token::Kind::TK_GTEQ: return ">=";
1860 case Token::Kind::TK_PLUSEQ: return "+=";
1861 case Token::Kind::TK_MINUSEQ: return "-=";
1862 case Token::Kind::TK_STAREQ: return "*=";
1863 case Token::Kind::TK_SLASHEQ: return "/=";
1864 case Token::Kind::TK_PERCENTEQ: return "%=";
1865 case Token::Kind::TK_SHLEQ: return "<<=";
1866 case Token::Kind::TK_SHREQ: return ">>=";
1867 case Token::Kind::TK_LOGICALANDEQ: return "&&=";
1868 case Token::Kind::TK_LOGICALOREQ: return "||=";
1869 case Token::Kind::TK_LOGICALXOREQ: return "^^=";
1870 case Token::Kind::TK_BITWISEANDEQ: return "&=";
1871 case Token::Kind::TK_BITWISEOREQ: return "|=";
1872 case Token::Kind::TK_BITWISEXOREQ: return "^=";
1873 case Token::Kind::TK_PLUSPLUS: return "++";
1874 case Token::Kind::TK_MINUSMINUS: return "--";
1875 case Token::Kind::TK_COMMA: return ",";
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001876 default:
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001877 ABORT("unsupported operator: %d\n", (int) kind);
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001878 }
1879}
1880
1881
1882bool Compiler::IsAssignment(Token::Kind op) {
1883 switch (op) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001884 case Token::Kind::TK_EQ: // fall through
1885 case Token::Kind::TK_PLUSEQ: // fall through
1886 case Token::Kind::TK_MINUSEQ: // fall through
1887 case Token::Kind::TK_STAREQ: // fall through
1888 case Token::Kind::TK_SLASHEQ: // fall through
1889 case Token::Kind::TK_PERCENTEQ: // fall through
1890 case Token::Kind::TK_SHLEQ: // fall through
1891 case Token::Kind::TK_SHREQ: // fall through
1892 case Token::Kind::TK_BITWISEOREQ: // fall through
1893 case Token::Kind::TK_BITWISEXOREQ: // fall through
1894 case Token::Kind::TK_BITWISEANDEQ: // fall through
1895 case Token::Kind::TK_LOGICALOREQ: // fall through
1896 case Token::Kind::TK_LOGICALXOREQ: // fall through
1897 case Token::Kind::TK_LOGICALANDEQ:
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001898 return true;
1899 default:
1900 return false;
1901 }
1902}
1903
1904Position Compiler::position(int offset) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001905 SkASSERT(fSource);
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001906 int line = 1;
1907 int column = 1;
1908 for (int i = 0; i < offset; i++) {
1909 if ((*fSource)[i] == '\n') {
1910 ++line;
1911 column = 1;
1912 }
1913 else {
1914 ++column;
1915 }
1916 }
1917 return Position(line, column);
1918}
1919
1920void Compiler::error(int offset, String msg) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001921 fErrorCount++;
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001922 Position pos = this->position(offset);
1923 fErrorText += "error: " + to_string(pos.fLine) + ": " + msg.c_str() + "\n";
ethannicholasb3058bd2016-07-01 08:22:01 -07001924}
1925
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001926String Compiler::errorText() {
Ethan Nicholas00543112018-07-31 09:44:36 -04001927 this->writeErrorCount();
1928 fErrorCount = 0;
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001929 String result = fErrorText;
ethannicholasb3058bd2016-07-01 08:22:01 -07001930 return result;
1931}
1932
1933void Compiler::writeErrorCount() {
1934 if (fErrorCount) {
1935 fErrorText += to_string(fErrorCount) + " error";
1936 if (fErrorCount > 1) {
1937 fErrorText += "s";
1938 }
1939 fErrorText += "\n";
1940 }
1941}
1942
John Stilesa6841be2020-08-06 14:11:56 -04001943} // namespace SkSL