blob: 85f4bb6d7fb2a98e262bc1b4a05b0a34e9787613 [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
Mike Kleinc0bd9f92019-04-23 12:05:21 -050010#include "src/sksl/SkSLByteCodeGenerator.h"
11#include "src/sksl/SkSLCFGGenerator.h"
12#include "src/sksl/SkSLCPPCodeGenerator.h"
13#include "src/sksl/SkSLGLSLCodeGenerator.h"
14#include "src/sksl/SkSLHCodeGenerator.h"
15#include "src/sksl/SkSLIRGenerator.h"
16#include "src/sksl/SkSLMetalCodeGenerator.h"
17#include "src/sksl/SkSLPipelineStageCodeGenerator.h"
18#include "src/sksl/SkSLSPIRVCodeGenerator.h"
Brian Osmanc0243912020-02-19 15:35:26 -050019#include "src/sksl/SkSLSPIRVtoHLSL.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050020#include "src/sksl/ir/SkSLEnum.h"
21#include "src/sksl/ir/SkSLExpression.h"
22#include "src/sksl/ir/SkSLExpressionStatement.h"
23#include "src/sksl/ir/SkSLFunctionCall.h"
24#include "src/sksl/ir/SkSLIntLiteral.h"
25#include "src/sksl/ir/SkSLModifiersDeclaration.h"
26#include "src/sksl/ir/SkSLNop.h"
27#include "src/sksl/ir/SkSLSymbolTable.h"
28#include "src/sksl/ir/SkSLTernaryExpression.h"
29#include "src/sksl/ir/SkSLUnresolvedFunction.h"
30#include "src/sksl/ir/SkSLVarDeclarations.h"
ethannicholasb3058bd2016-07-01 08:22:01 -070031
Ethan Nicholasa11035b2019-11-26 16:27:47 -050032#if !defined(SKSL_STANDALONE) & SK_SUPPORT_GPU
33#include "include/gpu/GrContextOptions.h"
34#include "src/gpu/GrShaderCaps.h"
35#endif
36
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -040037#ifdef SK_ENABLE_SPIRV_VALIDATION
38#include "spirv-tools/libspirv.hpp"
39#endif
40
ethannicholasb3058bd2016-07-01 08:22:01 -070041// include the built-in shader symbols as static strings
42
Ethan Nicholas79707652017-11-16 11:20:11 -050043#define STRINGIFY(x) #x
44
Ethan Nicholas8da1e652019-05-24 11:01:59 -040045static const char* SKSL_GPU_INCLUDE =
46#include "sksl_gpu.inc"
47;
48
Brian Salomonf8c187c2019-12-19 14:41:57 -050049static const char* SKSL_BLEND_INCLUDE =
50#include "sksl_blend.inc"
51;
52
Ethan Nicholas8da1e652019-05-24 11:01:59 -040053static const char* SKSL_INTERP_INCLUDE =
54#include "sksl_interp.inc"
ethannicholasb3058bd2016-07-01 08:22:01 -070055;
56
ethannicholas5961bc92016-10-12 06:39:56 -070057static const char* SKSL_VERT_INCLUDE =
Ben Wagnera56c4d22018-01-24 17:32:17 -050058#include "sksl_vert.inc"
ethannicholasb3058bd2016-07-01 08:22:01 -070059;
60
ethannicholas5961bc92016-10-12 06:39:56 -070061static const char* SKSL_FRAG_INCLUDE =
Ben Wagnera56c4d22018-01-24 17:32:17 -050062#include "sksl_frag.inc"
ethannicholasb3058bd2016-07-01 08:22:01 -070063;
64
Ethan Nicholas52cad152017-02-16 16:37:32 -050065static const char* SKSL_GEOM_INCLUDE =
Ben Wagnera56c4d22018-01-24 17:32:17 -050066#include "sksl_geom.inc"
Ethan Nicholas52cad152017-02-16 16:37:32 -050067;
68
Ethan Nicholas762466e2017-06-29 10:03:38 -040069static const char* SKSL_FP_INCLUDE =
Ben Wagnera56c4d22018-01-24 17:32:17 -050070#include "sksl_enums.inc"
71#include "sksl_fp.inc"
Ethan Nicholas762466e2017-06-29 10:03:38 -040072;
73
Ethan Nicholas8da1e652019-05-24 11:01:59 -040074static const char* SKSL_PIPELINE_INCLUDE =
75#include "sksl_pipeline.inc"
Ethan Nicholas0d997662019-04-08 09:46:01 -040076;
77
ethannicholasb3058bd2016-07-01 08:22:01 -070078namespace SkSL {
79
Ethan Nicholasdb80f692019-11-22 14:06:12 -050080static void grab_intrinsics(std::vector<std::unique_ptr<ProgramElement>>* src,
Brian Osman08f986d2020-05-13 17:06:46 -040081 std::map<String, std::pair<std::unique_ptr<ProgramElement>, bool>>* target) {
82 for (auto iter = src->begin(); iter != src->end(); ) {
83 std::unique_ptr<ProgramElement>& element = *iter;
Ethan Nicholasdb80f692019-11-22 14:06:12 -050084 switch (element->fKind) {
85 case ProgramElement::kFunction_Kind: {
86 FunctionDefinition& f = (FunctionDefinition&) *element;
Brian Osman08f986d2020-05-13 17:06:46 -040087 SkASSERT(f.fDeclaration.fBuiltin);
88 String key = f.fDeclaration.declaration();
89 SkASSERT(target->find(key) == target->end());
90 (*target)[key] = std::make_pair(std::move(element), false);
91 iter = src->erase(iter);
Ethan Nicholasdb80f692019-11-22 14:06:12 -050092 break;
93 }
94 case ProgramElement::kEnum_Kind: {
95 Enum& e = (Enum&) *element;
96 StringFragment name = e.fTypeName;
97 SkASSERT(target->find(name) == target->end());
98 (*target)[name] = std::make_pair(std::move(element), false);
Brian Osman08f986d2020-05-13 17:06:46 -040099 iter = src->erase(iter);
Ethan Nicholasdb80f692019-11-22 14:06:12 -0500100 break;
101 }
102 default:
103 printf("unsupported include file element\n");
104 SkASSERT(false);
105 }
106 }
107}
108
109
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -0400110Compiler::Compiler(Flags flags)
111: fFlags(flags)
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400112, fContext(new Context())
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -0400113, fErrorCount(0) {
Ethan Nicholas8feeff92017-03-30 14:11:58 -0400114 auto types = std::shared_ptr<SymbolTable>(new SymbolTable(this));
115 auto symbols = std::shared_ptr<SymbolTable>(new SymbolTable(types, this));
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400116 fIRGenerator = new IRGenerator(fContext.get(), symbols, *this);
ethannicholasb3058bd2016-07-01 08:22:01 -0700117 fTypes = types;
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400118 #define ADD_TYPE(t) types->addWithoutOwnership(fContext->f ## t ## _Type->fName, \
119 fContext->f ## t ## _Type.get())
ethannicholasb3058bd2016-07-01 08:22:01 -0700120 ADD_TYPE(Void);
121 ADD_TYPE(Float);
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400122 ADD_TYPE(Float2);
123 ADD_TYPE(Float3);
124 ADD_TYPE(Float4);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -0400125 ADD_TYPE(Half);
126 ADD_TYPE(Half2);
127 ADD_TYPE(Half3);
128 ADD_TYPE(Half4);
ethannicholasb3058bd2016-07-01 08:22:01 -0700129 ADD_TYPE(Double);
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400130 ADD_TYPE(Double2);
131 ADD_TYPE(Double3);
132 ADD_TYPE(Double4);
ethannicholasb3058bd2016-07-01 08:22:01 -0700133 ADD_TYPE(Int);
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400134 ADD_TYPE(Int2);
135 ADD_TYPE(Int3);
136 ADD_TYPE(Int4);
ethannicholasb3058bd2016-07-01 08:22:01 -0700137 ADD_TYPE(UInt);
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400138 ADD_TYPE(UInt2);
139 ADD_TYPE(UInt3);
140 ADD_TYPE(UInt4);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -0400141 ADD_TYPE(Short);
142 ADD_TYPE(Short2);
143 ADD_TYPE(Short3);
144 ADD_TYPE(Short4);
145 ADD_TYPE(UShort);
146 ADD_TYPE(UShort2);
147 ADD_TYPE(UShort3);
148 ADD_TYPE(UShort4);
Ruiqi Maob609e6d2018-07-17 10:19:38 -0400149 ADD_TYPE(Byte);
150 ADD_TYPE(Byte2);
151 ADD_TYPE(Byte3);
152 ADD_TYPE(Byte4);
153 ADD_TYPE(UByte);
154 ADD_TYPE(UByte2);
155 ADD_TYPE(UByte3);
156 ADD_TYPE(UByte4);
ethannicholasb3058bd2016-07-01 08:22:01 -0700157 ADD_TYPE(Bool);
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400158 ADD_TYPE(Bool2);
159 ADD_TYPE(Bool3);
160 ADD_TYPE(Bool4);
161 ADD_TYPE(Float2x2);
162 ADD_TYPE(Float2x3);
163 ADD_TYPE(Float2x4);
164 ADD_TYPE(Float3x2);
165 ADD_TYPE(Float3x3);
166 ADD_TYPE(Float3x4);
167 ADD_TYPE(Float4x2);
168 ADD_TYPE(Float4x3);
169 ADD_TYPE(Float4x4);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -0400170 ADD_TYPE(Half2x2);
171 ADD_TYPE(Half2x3);
172 ADD_TYPE(Half2x4);
173 ADD_TYPE(Half3x2);
174 ADD_TYPE(Half3x3);
175 ADD_TYPE(Half3x4);
176 ADD_TYPE(Half4x2);
177 ADD_TYPE(Half4x3);
178 ADD_TYPE(Half4x4);
179 ADD_TYPE(Double2x2);
180 ADD_TYPE(Double2x3);
181 ADD_TYPE(Double2x4);
182 ADD_TYPE(Double3x2);
183 ADD_TYPE(Double3x3);
184 ADD_TYPE(Double3x4);
185 ADD_TYPE(Double4x2);
186 ADD_TYPE(Double4x3);
187 ADD_TYPE(Double4x4);
ethannicholasb3058bd2016-07-01 08:22:01 -0700188 ADD_TYPE(GenType);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -0400189 ADD_TYPE(GenHType);
ethannicholasb3058bd2016-07-01 08:22:01 -0700190 ADD_TYPE(GenDType);
191 ADD_TYPE(GenIType);
192 ADD_TYPE(GenUType);
193 ADD_TYPE(GenBType);
194 ADD_TYPE(Mat);
195 ADD_TYPE(Vec);
196 ADD_TYPE(GVec);
197 ADD_TYPE(GVec2);
198 ADD_TYPE(GVec3);
199 ADD_TYPE(GVec4);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -0400200 ADD_TYPE(HVec);
ethannicholasb3058bd2016-07-01 08:22:01 -0700201 ADD_TYPE(DVec);
202 ADD_TYPE(IVec);
203 ADD_TYPE(UVec);
Ethan Nicholasdcba08e2017-08-02 10:52:54 -0400204 ADD_TYPE(SVec);
205 ADD_TYPE(USVec);
Ruiqi Maob609e6d2018-07-17 10:19:38 -0400206 ADD_TYPE(ByteVec);
207 ADD_TYPE(UByteVec);
ethannicholasb3058bd2016-07-01 08:22:01 -0700208 ADD_TYPE(BVec);
209
210 ADD_TYPE(Sampler1D);
211 ADD_TYPE(Sampler2D);
212 ADD_TYPE(Sampler3D);
ethannicholas5961bc92016-10-12 06:39:56 -0700213 ADD_TYPE(SamplerExternalOES);
ethannicholasb3058bd2016-07-01 08:22:01 -0700214 ADD_TYPE(SamplerCube);
215 ADD_TYPE(Sampler2DRect);
216 ADD_TYPE(Sampler1DArray);
217 ADD_TYPE(Sampler2DArray);
218 ADD_TYPE(SamplerCubeArray);
219 ADD_TYPE(SamplerBuffer);
220 ADD_TYPE(Sampler2DMS);
221 ADD_TYPE(Sampler2DMSArray);
222
Brian Salomonbf7b6202016-11-11 16:08:03 -0500223 ADD_TYPE(ISampler2D);
224
Brian Salomon2a51de82016-11-16 12:06:01 -0500225 ADD_TYPE(Image2D);
226 ADD_TYPE(IImage2D);
227
Greg Daniel64773e62016-11-22 09:44:03 -0500228 ADD_TYPE(SubpassInput);
229 ADD_TYPE(SubpassInputMS);
230
ethannicholasb3058bd2016-07-01 08:22:01 -0700231 ADD_TYPE(GSampler1D);
232 ADD_TYPE(GSampler2D);
233 ADD_TYPE(GSampler3D);
234 ADD_TYPE(GSamplerCube);
235 ADD_TYPE(GSampler2DRect);
236 ADD_TYPE(GSampler1DArray);
237 ADD_TYPE(GSampler2DArray);
238 ADD_TYPE(GSamplerCubeArray);
239 ADD_TYPE(GSamplerBuffer);
240 ADD_TYPE(GSampler2DMS);
241 ADD_TYPE(GSampler2DMSArray);
242
243 ADD_TYPE(Sampler1DShadow);
244 ADD_TYPE(Sampler2DShadow);
245 ADD_TYPE(SamplerCubeShadow);
246 ADD_TYPE(Sampler2DRectShadow);
247 ADD_TYPE(Sampler1DArrayShadow);
248 ADD_TYPE(Sampler2DArrayShadow);
249 ADD_TYPE(SamplerCubeArrayShadow);
250 ADD_TYPE(GSampler2DArrayShadow);
251 ADD_TYPE(GSamplerCubeArrayShadow);
Ethan Nicholasc9472af2017-10-10 16:30:21 -0400252 ADD_TYPE(FragmentProcessor);
Stephen Whiteff5d7a22019-07-26 17:42:06 -0400253 ADD_TYPE(Sampler);
254 ADD_TYPE(Texture2D);
ethannicholasb3058bd2016-07-01 08:22:01 -0700255
Brian Osman28590d52020-03-23 16:59:08 -0400256 StringFragment fpAliasName("shader");
257 fTypes->addWithoutOwnership(fpAliasName, fContext->fFragmentProcessor_Type.get());
258
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700259 StringFragment skCapsName("sk_Caps");
260 Variable* skCaps = new Variable(-1, Modifiers(), skCapsName,
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400261 *fContext->fSkCaps_Type, Variable::kGlobal_Storage);
Ethan Nicholas3605ace2016-11-21 15:59:48 -0500262 fIRGenerator->fSymbolTable->add(skCapsName, std::unique_ptr<Symbol>(skCaps));
263
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700264 StringFragment skArgsName("sk_Args");
265 Variable* skArgs = new Variable(-1, Modifiers(), skArgsName,
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400266 *fContext->fSkArgs_Type, Variable::kGlobal_Storage);
Ethan Nicholas762466e2017-06-29 10:03:38 -0400267 fIRGenerator->fSymbolTable->add(skArgsName, std::unique_ptr<Symbol>(skArgs));
268
Ethan Nicholasdb80f692019-11-22 14:06:12 -0500269 fIRGenerator->fIntrinsics = &fGPUIntrinsics;
270 std::vector<std::unique_ptr<ProgramElement>> gpuIntrinsics;
Ethan Nicholas8da1e652019-05-24 11:01:59 -0400271 this->processIncludeFile(Program::kFragment_Kind, SKSL_GPU_INCLUDE, strlen(SKSL_GPU_INCLUDE),
Ethan Nicholasdb80f692019-11-22 14:06:12 -0500272 symbols, &gpuIntrinsics, &fGpuSymbolTable);
Brian Salomonf8c187c2019-12-19 14:41:57 -0500273 this->processIncludeFile(Program::kFragment_Kind, SKSL_BLEND_INCLUDE,
274 strlen(SKSL_BLEND_INCLUDE), std::move(fGpuSymbolTable), &gpuIntrinsics,
275 &fGpuSymbolTable);
Ethan Nicholasdb80f692019-11-22 14:06:12 -0500276 grab_intrinsics(&gpuIntrinsics, &fGPUIntrinsics);
277 // need to hang on to the source so that FunctionDefinition.fSource pointers in this file
278 // remain valid
279 fGpuIncludeSource = std::move(fIRGenerator->fFile);
Ethan Nicholas8da1e652019-05-24 11:01:59 -0400280 this->processIncludeFile(Program::kVertex_Kind, SKSL_VERT_INCLUDE, strlen(SKSL_VERT_INCLUDE),
281 fGpuSymbolTable, &fVertexInclude, &fVertexSymbolTable);
282 this->processIncludeFile(Program::kFragment_Kind, SKSL_FRAG_INCLUDE, strlen(SKSL_FRAG_INCLUDE),
283 fGpuSymbolTable, &fFragmentInclude, &fFragmentSymbolTable);
284 this->processIncludeFile(Program::kGeometry_Kind, SKSL_GEOM_INCLUDE, strlen(SKSL_GEOM_INCLUDE),
285 fGpuSymbolTable, &fGeometryInclude, &fGeometrySymbolTable);
286 this->processIncludeFile(Program::kPipelineStage_Kind, SKSL_PIPELINE_INCLUDE,
287 strlen(SKSL_PIPELINE_INCLUDE), fGpuSymbolTable, &fPipelineInclude,
288 &fPipelineSymbolTable);
Brian Osmanb08cc022020-04-02 11:38:40 -0400289 std::vector<std::unique_ptr<ProgramElement>> interpIntrinsics;
Ethan Nicholas8da1e652019-05-24 11:01:59 -0400290 this->processIncludeFile(Program::kGeneric_Kind, SKSL_INTERP_INCLUDE,
291 strlen(SKSL_INTERP_INCLUDE), symbols, &fInterpreterInclude,
292 &fInterpreterSymbolTable);
Brian Osmanb08cc022020-04-02 11:38:40 -0400293 grab_intrinsics(&interpIntrinsics, &fInterpreterIntrinsics);
ethannicholasb3058bd2016-07-01 08:22:01 -0700294}
295
296Compiler::~Compiler() {
297 delete fIRGenerator;
298}
299
Ethan Nicholas8da1e652019-05-24 11:01:59 -0400300void Compiler::processIncludeFile(Program::Kind kind, const char* src, size_t length,
301 std::shared_ptr<SymbolTable> base,
302 std::vector<std::unique_ptr<ProgramElement>>* outElements,
303 std::shared_ptr<SymbolTable>* outSymbolTable) {
Ethan Nicholasa11035b2019-11-26 16:27:47 -0500304#ifdef SK_DEBUG
305 String source(src, length);
306 fSource = &source;
307#endif
Ethan Nicholas8da1e652019-05-24 11:01:59 -0400308 fIRGenerator->fSymbolTable = std::move(base);
309 Program::Settings settings;
Ethan Nicholasa11035b2019-11-26 16:27:47 -0500310#if !defined(SKSL_STANDALONE) & SK_SUPPORT_GPU
311 GrContextOptions opts;
312 GrShaderCaps caps(opts);
313 settings.fCaps = &caps;
314#endif
Ethan Nicholas8da1e652019-05-24 11:01:59 -0400315 fIRGenerator->start(&settings, nullptr);
316 fIRGenerator->convertProgram(kind, src, length, *fTypes, outElements);
317 if (this->fErrorCount) {
318 printf("Unexpected errors: %s\n", this->fErrorText.c_str());
319 }
320 SkASSERT(!fErrorCount);
321 fIRGenerator->fSymbolTable->markAllFunctionsBuiltin();
322 *outSymbolTable = fIRGenerator->fSymbolTable;
Ethan Nicholasa11035b2019-11-26 16:27:47 -0500323#ifdef SK_DEBUG
324 fSource = nullptr;
325#endif
Ethan Nicholas8da1e652019-05-24 11:01:59 -0400326}
327
ethannicholas22f939e2016-10-13 13:25:34 -0700328// add the definition created by assigning to the lvalue to the definition set
Ethan Nicholas86a43402017-01-19 13:32:00 -0500329void Compiler::addDefinition(const Expression* lvalue, std::unique_ptr<Expression>* expr,
330 DefinitionMap* definitions) {
ethannicholas22f939e2016-10-13 13:25:34 -0700331 switch (lvalue->fKind) {
332 case Expression::kVariableReference_Kind: {
333 const Variable& var = ((VariableReference*) lvalue)->fVariable;
334 if (var.fStorage == Variable::kLocal_Storage) {
335 (*definitions)[&var] = expr;
336 }
337 break;
338 }
339 case Expression::kSwizzle_Kind:
340 // We consider the variable written to as long as at least some of its components have
341 // been written to. This will lead to some false negatives (we won't catch it if you
342 // write to foo.x and then read foo.y), but being stricter could lead to false positives
Mike Klein6ad99092016-10-26 10:35:22 -0400343 // (we write to foo.x, and then pass foo to a function which happens to only read foo.x,
344 // 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 -0700345 // more complicated whole-program analysis. This is probably good enough.
Mike Klein6ad99092016-10-26 10:35:22 -0400346 this->addDefinition(((Swizzle*) lvalue)->fBase.get(),
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400347 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
ethannicholas22f939e2016-10-13 13:25:34 -0700348 definitions);
349 break;
350 case Expression::kIndex_Kind:
351 // see comments in Swizzle
Mike Klein6ad99092016-10-26 10:35:22 -0400352 this->addDefinition(((IndexExpression*) lvalue)->fBase.get(),
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400353 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
ethannicholas22f939e2016-10-13 13:25:34 -0700354 definitions);
355 break;
356 case Expression::kFieldAccess_Kind:
357 // see comments in Swizzle
Mike Klein6ad99092016-10-26 10:35:22 -0400358 this->addDefinition(((FieldAccess*) lvalue)->fBase.get(),
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400359 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
ethannicholas22f939e2016-10-13 13:25:34 -0700360 definitions);
361 break;
Ethan Nicholasa583b812018-01-18 13:32:11 -0500362 case Expression::kTernary_Kind:
363 // To simplify analysis, we just pretend that we write to both sides of the ternary.
364 // This allows for false positives (meaning we fail to detect that a variable might not
365 // have been assigned), but is preferable to false negatives.
366 this->addDefinition(((TernaryExpression*) lvalue)->fIfTrue.get(),
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400367 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
Ethan Nicholasa583b812018-01-18 13:32:11 -0500368 definitions);
369 this->addDefinition(((TernaryExpression*) lvalue)->fIfFalse.get(),
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400370 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
Ethan Nicholasa583b812018-01-18 13:32:11 -0500371 definitions);
372 break;
Ethan Nicholas91164d12019-05-15 15:29:54 -0400373 case Expression::kExternalValue_Kind:
374 break;
ethannicholas22f939e2016-10-13 13:25:34 -0700375 default:
376 // not an lvalue, can't happen
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400377 SkASSERT(false);
ethannicholas22f939e2016-10-13 13:25:34 -0700378 }
379}
380
381// add local variables defined by this node to the set
Mike Klein6ad99092016-10-26 10:35:22 -0400382void Compiler::addDefinitions(const BasicBlock::Node& node,
Ethan Nicholas86a43402017-01-19 13:32:00 -0500383 DefinitionMap* definitions) {
ethannicholas22f939e2016-10-13 13:25:34 -0700384 switch (node.fKind) {
385 case BasicBlock::Node::kExpression_Kind: {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400386 SkASSERT(node.expression());
Ethan Nicholascb670962017-04-20 19:31:52 -0400387 const Expression* expr = (Expression*) node.expression()->get();
Ethan Nicholas86a43402017-01-19 13:32:00 -0500388 switch (expr->fKind) {
389 case Expression::kBinary_Kind: {
390 BinaryExpression* b = (BinaryExpression*) expr;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400391 if (b->fOperator == Token::Kind::TK_EQ) {
Ethan Nicholas86a43402017-01-19 13:32:00 -0500392 this->addDefinition(b->fLeft.get(), &b->fRight, definitions);
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700393 } else if (Compiler::IsAssignment(b->fOperator)) {
Ethan Nicholas86a43402017-01-19 13:32:00 -0500394 this->addDefinition(
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400395 b->fLeft.get(),
396 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
397 definitions);
Ethan Nicholas86a43402017-01-19 13:32:00 -0500398
399 }
400 break;
ethannicholas22f939e2016-10-13 13:25:34 -0700401 }
Ethan Nicholasc6a19f12018-03-29 16:46:56 -0400402 case Expression::kFunctionCall_Kind: {
403 const FunctionCall& c = (const FunctionCall&) *expr;
404 for (size_t i = 0; i < c.fFunction.fParameters.size(); ++i) {
405 if (c.fFunction.fParameters[i]->fModifiers.fFlags & Modifiers::kOut_Flag) {
406 this->addDefinition(
407 c.fArguments[i].get(),
408 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
409 definitions);
410 }
411 }
412 break;
413 }
Ethan Nicholas86a43402017-01-19 13:32:00 -0500414 case Expression::kPrefix_Kind: {
415 const PrefixExpression* p = (PrefixExpression*) expr;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400416 if (p->fOperator == Token::Kind::TK_MINUSMINUS ||
417 p->fOperator == Token::Kind::TK_PLUSPLUS) {
Ethan Nicholas86a43402017-01-19 13:32:00 -0500418 this->addDefinition(
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400419 p->fOperand.get(),
420 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
421 definitions);
Ethan Nicholas86a43402017-01-19 13:32:00 -0500422 }
423 break;
424 }
425 case Expression::kPostfix_Kind: {
426 const PostfixExpression* p = (PostfixExpression*) expr;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400427 if (p->fOperator == Token::Kind::TK_MINUSMINUS ||
428 p->fOperator == Token::Kind::TK_PLUSPLUS) {
Ethan Nicholas86a43402017-01-19 13:32:00 -0500429 this->addDefinition(
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400430 p->fOperand.get(),
431 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
432 definitions);
Ethan Nicholas86a43402017-01-19 13:32:00 -0500433 }
434 break;
435 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400436 case Expression::kVariableReference_Kind: {
437 const VariableReference* v = (VariableReference*) expr;
438 if (v->fRefKind != VariableReference::kRead_RefKind) {
439 this->addDefinition(
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400440 v,
441 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
442 definitions);
Ethan Nicholascb670962017-04-20 19:31:52 -0400443 }
444 }
Ethan Nicholas86a43402017-01-19 13:32:00 -0500445 default:
446 break;
ethannicholas22f939e2016-10-13 13:25:34 -0700447 }
448 break;
449 }
450 case BasicBlock::Node::kStatement_Kind: {
Ethan Nicholascb670962017-04-20 19:31:52 -0400451 const Statement* stmt = (Statement*) node.statement()->get();
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000452 if (stmt->fKind == Statement::kVarDeclaration_Kind) {
453 VarDeclaration& vd = (VarDeclaration&) *stmt;
454 if (vd.fValue) {
455 (*definitions)[vd.fVar] = &vd.fValue;
ethannicholas22f939e2016-10-13 13:25:34 -0700456 }
457 }
458 break;
459 }
460 }
461}
462
463void Compiler::scanCFG(CFG* cfg, BlockId blockId, std::set<BlockId>* workList) {
464 BasicBlock& block = cfg->fBlocks[blockId];
465
466 // compute definitions after this block
Ethan Nicholas86a43402017-01-19 13:32:00 -0500467 DefinitionMap after = block.fBefore;
ethannicholas22f939e2016-10-13 13:25:34 -0700468 for (const BasicBlock::Node& n : block.fNodes) {
469 this->addDefinitions(n, &after);
470 }
471
472 // propagate definitions to exits
473 for (BlockId exitId : block.fExits) {
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400474 if (exitId == blockId) {
475 continue;
476 }
ethannicholas22f939e2016-10-13 13:25:34 -0700477 BasicBlock& exit = cfg->fBlocks[exitId];
478 for (const auto& pair : after) {
Ethan Nicholas86a43402017-01-19 13:32:00 -0500479 std::unique_ptr<Expression>* e1 = pair.second;
480 auto found = exit.fBefore.find(pair.first);
481 if (found == exit.fBefore.end()) {
482 // exit has no definition for it, just copy it
483 workList->insert(exitId);
ethannicholas22f939e2016-10-13 13:25:34 -0700484 exit.fBefore[pair.first] = e1;
485 } else {
Ethan Nicholas86a43402017-01-19 13:32:00 -0500486 // exit has a (possibly different) value already defined
487 std::unique_ptr<Expression>* e2 = exit.fBefore[pair.first];
ethannicholas22f939e2016-10-13 13:25:34 -0700488 if (e1 != e2) {
489 // definition has changed, merge and add exit block to worklist
490 workList->insert(exitId);
Ethan Nicholasaf197692017-02-27 13:26:45 -0500491 if (e1 && e2) {
492 exit.fBefore[pair.first] =
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400493 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression;
Ethan Nicholasaf197692017-02-27 13:26:45 -0500494 } else {
495 exit.fBefore[pair.first] = nullptr;
496 }
ethannicholas22f939e2016-10-13 13:25:34 -0700497 }
498 }
499 }
500 }
501}
502
503// returns a map which maps all local variables in the function to null, indicating that their value
504// is initially unknown
Ethan Nicholas86a43402017-01-19 13:32:00 -0500505static DefinitionMap compute_start_state(const CFG& cfg) {
506 DefinitionMap result;
Mike Klein6ad99092016-10-26 10:35:22 -0400507 for (const auto& block : cfg.fBlocks) {
508 for (const auto& node : block.fNodes) {
ethannicholas22f939e2016-10-13 13:25:34 -0700509 if (node.fKind == BasicBlock::Node::kStatement_Kind) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400510 SkASSERT(node.statement());
Ethan Nicholascb670962017-04-20 19:31:52 -0400511 const Statement* s = node.statement()->get();
ethannicholas22f939e2016-10-13 13:25:34 -0700512 if (s->fKind == Statement::kVarDeclarations_Kind) {
513 const VarDeclarationsStatement* vd = (const VarDeclarationsStatement*) s;
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000514 for (const auto& decl : vd->fDeclaration->fVars) {
515 if (decl->fKind == Statement::kVarDeclaration_Kind) {
516 result[((VarDeclaration&) *decl).fVar] = nullptr;
517 }
Mike Klein6ad99092016-10-26 10:35:22 -0400518 }
ethannicholas22f939e2016-10-13 13:25:34 -0700519 }
520 }
521 }
522 }
523 return result;
524}
525
Ethan Nicholascb670962017-04-20 19:31:52 -0400526/**
527 * Returns true if assigning to this lvalue has no effect.
528 */
529static bool is_dead(const Expression& lvalue) {
530 switch (lvalue.fKind) {
531 case Expression::kVariableReference_Kind:
532 return ((VariableReference&) lvalue).fVariable.dead();
533 case Expression::kSwizzle_Kind:
534 return is_dead(*((Swizzle&) lvalue).fBase);
535 case Expression::kFieldAccess_Kind:
536 return is_dead(*((FieldAccess&) lvalue).fBase);
537 case Expression::kIndex_Kind: {
538 const IndexExpression& idx = (IndexExpression&) lvalue;
Ethan Nicholas2a099da2020-01-02 14:40:54 -0500539 return is_dead(*idx.fBase) &&
540 !idx.fIndex->hasProperty(Expression::Property::kSideEffects);
Ethan Nicholascb670962017-04-20 19:31:52 -0400541 }
Ethan Nicholasa583b812018-01-18 13:32:11 -0500542 case Expression::kTernary_Kind: {
543 const TernaryExpression& t = (TernaryExpression&) lvalue;
544 return !t.fTest->hasSideEffects() && is_dead(*t.fIfTrue) && is_dead(*t.fIfFalse);
545 }
Ethan Nicholas91164d12019-05-15 15:29:54 -0400546 case Expression::kExternalValue_Kind:
547 return false;
Ethan Nicholascb670962017-04-20 19:31:52 -0400548 default:
Ethan Nicholas2a099da2020-01-02 14:40:54 -0500549#ifdef SK_DEBUG
Ethan Nicholascb670962017-04-20 19:31:52 -0400550 ABORT("invalid lvalue: %s\n", lvalue.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -0500551#endif
552 return false;
Ethan Nicholascb670962017-04-20 19:31:52 -0400553 }
554}
ethannicholas22f939e2016-10-13 13:25:34 -0700555
Ethan Nicholascb670962017-04-20 19:31:52 -0400556/**
557 * Returns true if this is an assignment which can be collapsed down to just the right hand side due
558 * to a dead target and lack of side effects on the left hand side.
559 */
560static bool dead_assignment(const BinaryExpression& b) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700561 if (!Compiler::IsAssignment(b.fOperator)) {
Ethan Nicholascb670962017-04-20 19:31:52 -0400562 return false;
563 }
564 return is_dead(*b.fLeft);
565}
566
567void Compiler::computeDataFlow(CFG* cfg) {
568 cfg->fBlocks[cfg->fStart].fBefore = compute_start_state(*cfg);
ethannicholas22f939e2016-10-13 13:25:34 -0700569 std::set<BlockId> workList;
Ethan Nicholascb670962017-04-20 19:31:52 -0400570 for (BlockId i = 0; i < cfg->fBlocks.size(); i++) {
ethannicholas22f939e2016-10-13 13:25:34 -0700571 workList.insert(i);
572 }
573 while (workList.size()) {
574 BlockId next = *workList.begin();
575 workList.erase(workList.begin());
Ethan Nicholascb670962017-04-20 19:31:52 -0400576 this->scanCFG(cfg, next, &workList);
ethannicholas22f939e2016-10-13 13:25:34 -0700577 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400578}
579
580/**
581 * Attempts to replace the expression pointed to by iter with a new one (in both the CFG and the
582 * IR). If the expression can be cleanly removed, returns true and updates the iterator to point to
583 * the newly-inserted element. Otherwise updates only the IR and returns false (and the CFG will
584 * need to be regenerated).
585 */
586bool try_replace_expression(BasicBlock* b,
587 std::vector<BasicBlock::Node>::iterator* iter,
588 std::unique_ptr<Expression>* newExpression) {
589 std::unique_ptr<Expression>* target = (*iter)->expression();
590 if (!b->tryRemoveExpression(iter)) {
591 *target = std::move(*newExpression);
592 return false;
593 }
594 *target = std::move(*newExpression);
595 return b->tryInsertExpression(iter, target);
596}
597
598/**
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400599 * Returns true if the expression is a constant numeric literal with the specified value, or a
600 * constant vector with all elements equal to the specified value.
Ethan Nicholascb670962017-04-20 19:31:52 -0400601 */
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400602bool is_constant(const Expression& expr, double value) {
Ethan Nicholascb670962017-04-20 19:31:52 -0400603 switch (expr.fKind) {
604 case Expression::kIntLiteral_Kind:
605 return ((IntLiteral&) expr).fValue == value;
606 case Expression::kFloatLiteral_Kind:
607 return ((FloatLiteral&) expr).fValue == value;
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400608 case Expression::kConstructor_Kind: {
609 Constructor& c = (Constructor&) expr;
Ethan Nicholasd188c182019-06-10 15:55:38 -0400610 bool isFloat = c.fType.columns() > 1 ? c.fType.componentType().isFloat()
611 : c.fType.isFloat();
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400612 if (c.fType.kind() == Type::kVector_Kind && c.isConstant()) {
613 for (int i = 0; i < c.fType.columns(); ++i) {
Ethan Nicholasd188c182019-06-10 15:55:38 -0400614 if (isFloat) {
615 if (c.getFVecComponent(i) != value) {
616 return false;
617 }
618 } else if (c.getIVecComponent(i) != value) {
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400619 return false;
620 }
621 }
622 return true;
623 }
624 return false;
625 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400626 default:
627 return false;
628 }
629}
630
631/**
632 * Collapses the binary expression pointed to by iter down to just the right side (in both the IR
633 * and CFG structures).
634 */
635void delete_left(BasicBlock* b,
636 std::vector<BasicBlock::Node>::iterator* iter,
637 bool* outUpdated,
638 bool* outNeedsRescan) {
639 *outUpdated = true;
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400640 std::unique_ptr<Expression>* target = (*iter)->expression();
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400641 SkASSERT((*target)->fKind == Expression::kBinary_Kind);
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400642 BinaryExpression& bin = (BinaryExpression&) **target;
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400643 SkASSERT(!bin.fLeft->hasSideEffects());
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400644 bool result;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400645 if (bin.fOperator == Token::Kind::TK_EQ) {
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400646 result = b->tryRemoveLValueBefore(iter, bin.fLeft.get());
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400647 } else {
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400648 result = b->tryRemoveExpressionBefore(iter, bin.fLeft.get());
Ethan Nicholascb670962017-04-20 19:31:52 -0400649 }
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400650 *target = std::move(bin.fRight);
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400651 if (!result) {
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400652 *outNeedsRescan = true;
653 return;
654 }
655 if (*iter == b->fNodes.begin()) {
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400656 *outNeedsRescan = true;
657 return;
658 }
659 --(*iter);
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400660 if ((*iter)->fKind != BasicBlock::Node::kExpression_Kind ||
661 (*iter)->expression() != &bin.fRight) {
662 *outNeedsRescan = true;
663 return;
664 }
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400665 *iter = b->fNodes.erase(*iter);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400666 SkASSERT((*iter)->expression() == target);
Ethan Nicholascb670962017-04-20 19:31:52 -0400667}
668
669/**
670 * Collapses the binary expression pointed to by iter down to just the left side (in both the IR and
671 * CFG structures).
672 */
673void delete_right(BasicBlock* b,
674 std::vector<BasicBlock::Node>::iterator* iter,
675 bool* outUpdated,
676 bool* outNeedsRescan) {
677 *outUpdated = true;
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400678 std::unique_ptr<Expression>* target = (*iter)->expression();
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400679 SkASSERT((*target)->fKind == Expression::kBinary_Kind);
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400680 BinaryExpression& bin = (BinaryExpression&) **target;
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400681 SkASSERT(!bin.fRight->hasSideEffects());
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400682 if (!b->tryRemoveExpressionBefore(iter, bin.fRight.get())) {
683 *target = std::move(bin.fLeft);
Ethan Nicholascb670962017-04-20 19:31:52 -0400684 *outNeedsRescan = true;
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400685 return;
Ethan Nicholascb670962017-04-20 19:31:52 -0400686 }
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400687 *target = std::move(bin.fLeft);
688 if (*iter == b->fNodes.begin()) {
689 *outNeedsRescan = true;
690 return;
691 }
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400692 --(*iter);
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400693 if (((*iter)->fKind != BasicBlock::Node::kExpression_Kind ||
694 (*iter)->expression() != &bin.fLeft)) {
695 *outNeedsRescan = true;
696 return;
697 }
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400698 *iter = b->fNodes.erase(*iter);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400699 SkASSERT((*iter)->expression() == target);
Ethan Nicholascb670962017-04-20 19:31:52 -0400700}
701
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400702/**
703 * Constructs the specified type using a single argument.
704 */
705static std::unique_ptr<Expression> construct(const Type& type, std::unique_ptr<Expression> v) {
706 std::vector<std::unique_ptr<Expression>> args;
707 args.push_back(std::move(v));
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700708 auto result = std::unique_ptr<Expression>(new Constructor(-1, type, std::move(args)));
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400709 return result;
710}
711
712/**
713 * Used in the implementations of vectorize_left and vectorize_right. Given a vector type and an
714 * expression x, deletes the expression pointed to by iter and replaces it with <type>(x).
715 */
716static void vectorize(BasicBlock* b,
717 std::vector<BasicBlock::Node>::iterator* iter,
718 const Type& type,
719 std::unique_ptr<Expression>* otherExpression,
720 bool* outUpdated,
721 bool* outNeedsRescan) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400722 SkASSERT((*(*iter)->expression())->fKind == Expression::kBinary_Kind);
723 SkASSERT(type.kind() == Type::kVector_Kind);
724 SkASSERT((*otherExpression)->fType.kind() == Type::kScalar_Kind);
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400725 *outUpdated = true;
726 std::unique_ptr<Expression>* target = (*iter)->expression();
727 if (!b->tryRemoveExpression(iter)) {
728 *target = construct(type, std::move(*otherExpression));
729 *outNeedsRescan = true;
730 } else {
731 *target = construct(type, std::move(*otherExpression));
732 if (!b->tryInsertExpression(iter, target)) {
733 *outNeedsRescan = true;
734 }
735 }
736}
737
738/**
739 * Given a binary expression of the form x <op> vec<n>(y), deletes the right side and vectorizes the
740 * left to yield vec<n>(x).
741 */
742static void vectorize_left(BasicBlock* b,
743 std::vector<BasicBlock::Node>::iterator* iter,
744 bool* outUpdated,
745 bool* outNeedsRescan) {
746 BinaryExpression& bin = (BinaryExpression&) **(*iter)->expression();
747 vectorize(b, iter, bin.fRight->fType, &bin.fLeft, outUpdated, outNeedsRescan);
748}
749
750/**
751 * Given a binary expression of the form vec<n>(x) <op> y, deletes the left side and vectorizes the
752 * right to yield vec<n>(y).
753 */
754static void vectorize_right(BasicBlock* b,
755 std::vector<BasicBlock::Node>::iterator* iter,
756 bool* outUpdated,
757 bool* outNeedsRescan) {
758 BinaryExpression& bin = (BinaryExpression&) **(*iter)->expression();
759 vectorize(b, iter, bin.fLeft->fType, &bin.fRight, outUpdated, outNeedsRescan);
760}
761
762// Mark that an expression which we were writing to is no longer being written to
763void clear_write(const Expression& expr) {
764 switch (expr.fKind) {
765 case Expression::kVariableReference_Kind: {
766 ((VariableReference&) expr).setRefKind(VariableReference::kRead_RefKind);
767 break;
768 }
769 case Expression::kFieldAccess_Kind:
770 clear_write(*((FieldAccess&) expr).fBase);
771 break;
772 case Expression::kSwizzle_Kind:
773 clear_write(*((Swizzle&) expr).fBase);
774 break;
775 case Expression::kIndex_Kind:
776 clear_write(*((IndexExpression&) expr).fBase);
777 break;
778 default:
779 ABORT("shouldn't be writing to this kind of expression\n");
780 break;
781 }
782}
783
Ethan Nicholascb670962017-04-20 19:31:52 -0400784void Compiler::simplifyExpression(DefinitionMap& definitions,
785 BasicBlock& b,
786 std::vector<BasicBlock::Node>::iterator* iter,
787 std::unordered_set<const Variable*>* undefinedVariables,
788 bool* outUpdated,
789 bool* outNeedsRescan) {
790 Expression* expr = (*iter)->expression()->get();
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400791 SkASSERT(expr);
Ethan Nicholascb670962017-04-20 19:31:52 -0400792 if ((*iter)->fConstantPropagation) {
793 std::unique_ptr<Expression> optimized = expr->constantPropagate(*fIRGenerator, definitions);
794 if (optimized) {
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400795 *outUpdated = true;
Ethan Nicholascb670962017-04-20 19:31:52 -0400796 if (!try_replace_expression(&b, iter, &optimized)) {
797 *outNeedsRescan = true;
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400798 return;
Ethan Nicholascb670962017-04-20 19:31:52 -0400799 }
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400800 SkASSERT((*iter)->fKind == BasicBlock::Node::kExpression_Kind);
Ethan Nicholascb670962017-04-20 19:31:52 -0400801 expr = (*iter)->expression()->get();
Ethan Nicholascb670962017-04-20 19:31:52 -0400802 }
803 }
804 switch (expr->fKind) {
805 case Expression::kVariableReference_Kind: {
Ethan Nicholas8f7e28f2018-03-26 14:24:27 -0400806 const VariableReference& ref = (VariableReference&) *expr;
807 const Variable& var = ref.fVariable;
808 if (ref.refKind() != VariableReference::kWrite_RefKind &&
809 ref.refKind() != VariableReference::kPointer_RefKind &&
810 var.fStorage == Variable::kLocal_Storage && !definitions[&var] &&
Ethan Nicholascb670962017-04-20 19:31:52 -0400811 (*undefinedVariables).find(&var) == (*undefinedVariables).end()) {
812 (*undefinedVariables).insert(&var);
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000813 this->error(expr->fOffset,
814 "'" + var.fName + "' has not been assigned");
Ethan Nicholascb670962017-04-20 19:31:52 -0400815 }
816 break;
817 }
818 case Expression::kTernary_Kind: {
819 TernaryExpression* t = (TernaryExpression*) expr;
820 if (t->fTest->fKind == Expression::kBoolLiteral_Kind) {
821 // ternary has a constant test, replace it with either the true or
822 // false branch
823 if (((BoolLiteral&) *t->fTest).fValue) {
824 (*iter)->setExpression(std::move(t->fIfTrue));
825 } else {
826 (*iter)->setExpression(std::move(t->fIfFalse));
827 }
828 *outUpdated = true;
829 *outNeedsRescan = true;
830 }
831 break;
832 }
833 case Expression::kBinary_Kind: {
Ethan Nicholascb670962017-04-20 19:31:52 -0400834 BinaryExpression* bin = (BinaryExpression*) expr;
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400835 if (dead_assignment(*bin)) {
836 delete_left(&b, iter, outUpdated, outNeedsRescan);
837 break;
838 }
839 // collapse useless expressions like x * 1 or x + 0
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400840 if (((bin->fLeft->fType.kind() != Type::kScalar_Kind) &&
841 (bin->fLeft->fType.kind() != Type::kVector_Kind)) ||
842 ((bin->fRight->fType.kind() != Type::kScalar_Kind) &&
843 (bin->fRight->fType.kind() != Type::kVector_Kind))) {
844 break;
845 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400846 switch (bin->fOperator) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400847 case Token::Kind::TK_STAR:
Ethan Nicholascb670962017-04-20 19:31:52 -0400848 if (is_constant(*bin->fLeft, 1)) {
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400849 if (bin->fLeft->fType.kind() == Type::kVector_Kind &&
850 bin->fRight->fType.kind() == Type::kScalar_Kind) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400851 // float4(1) * x -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400852 vectorize_right(&b, iter, outUpdated, outNeedsRescan);
853 } else {
854 // 1 * x -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400855 // 1 * float4(x) -> float4(x)
856 // float4(1) * float4(x) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400857 delete_left(&b, iter, outUpdated, outNeedsRescan);
858 }
859 }
860 else if (is_constant(*bin->fLeft, 0)) {
861 if (bin->fLeft->fType.kind() == Type::kScalar_Kind &&
Ethan Nicholas08dae922018-01-23 10:31:56 -0500862 bin->fRight->fType.kind() == Type::kVector_Kind &&
863 !bin->fRight->hasSideEffects()) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400864 // 0 * float4(x) -> float4(0)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400865 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
866 } else {
867 // 0 * x -> 0
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400868 // float4(0) * x -> float4(0)
869 // float4(0) * float4(x) -> float4(0)
Ethan Nicholas51493ee2017-12-11 12:34:33 -0500870 if (!bin->fRight->hasSideEffects()) {
871 delete_right(&b, iter, outUpdated, outNeedsRescan);
872 }
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400873 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400874 }
875 else if (is_constant(*bin->fRight, 1)) {
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400876 if (bin->fLeft->fType.kind() == Type::kScalar_Kind &&
877 bin->fRight->fType.kind() == Type::kVector_Kind) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400878 // x * float4(1) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400879 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
880 } else {
881 // x * 1 -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400882 // float4(x) * 1 -> float4(x)
883 // float4(x) * float4(1) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400884 delete_right(&b, iter, outUpdated, outNeedsRescan);
885 }
886 }
887 else if (is_constant(*bin->fRight, 0)) {
888 if (bin->fLeft->fType.kind() == Type::kVector_Kind &&
Ethan Nicholas08dae922018-01-23 10:31:56 -0500889 bin->fRight->fType.kind() == Type::kScalar_Kind &&
890 !bin->fLeft->hasSideEffects()) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400891 // float4(x) * 0 -> float4(0)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400892 vectorize_right(&b, iter, outUpdated, outNeedsRescan);
893 } else {
894 // x * 0 -> 0
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400895 // x * float4(0) -> float4(0)
896 // float4(x) * float4(0) -> float4(0)
Ethan Nicholas51493ee2017-12-11 12:34:33 -0500897 if (!bin->fLeft->hasSideEffects()) {
898 delete_left(&b, iter, outUpdated, outNeedsRescan);
899 }
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400900 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400901 }
902 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400903 case Token::Kind::TK_PLUS:
Ethan Nicholascb670962017-04-20 19:31:52 -0400904 if (is_constant(*bin->fLeft, 0)) {
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400905 if (bin->fLeft->fType.kind() == Type::kVector_Kind &&
906 bin->fRight->fType.kind() == Type::kScalar_Kind) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400907 // float4(0) + x -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400908 vectorize_right(&b, iter, outUpdated, outNeedsRescan);
909 } else {
910 // 0 + x -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400911 // 0 + float4(x) -> float4(x)
912 // float4(0) + float4(x) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400913 delete_left(&b, iter, outUpdated, outNeedsRescan);
914 }
915 } else if (is_constant(*bin->fRight, 0)) {
916 if (bin->fLeft->fType.kind() == Type::kScalar_Kind &&
917 bin->fRight->fType.kind() == Type::kVector_Kind) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400918 // x + float4(0) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400919 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
920 } else {
921 // x + 0 -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400922 // float4(x) + 0 -> float4(x)
923 // float4(x) + float4(0) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400924 delete_right(&b, iter, outUpdated, outNeedsRescan);
925 }
Ethan Nicholas56e42712017-04-21 10:23:37 -0400926 }
927 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400928 case Token::Kind::TK_MINUS:
Ethan Nicholas56e42712017-04-21 10:23:37 -0400929 if (is_constant(*bin->fRight, 0)) {
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400930 if (bin->fLeft->fType.kind() == Type::kScalar_Kind &&
931 bin->fRight->fType.kind() == Type::kVector_Kind) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400932 // x - float4(0) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400933 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
934 } else {
935 // x - 0 -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400936 // float4(x) - 0 -> float4(x)
937 // float4(x) - float4(0) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400938 delete_right(&b, iter, outUpdated, outNeedsRescan);
939 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400940 }
941 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400942 case Token::Kind::TK_SLASH:
Ethan Nicholascb670962017-04-20 19:31:52 -0400943 if (is_constant(*bin->fRight, 1)) {
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400944 if (bin->fLeft->fType.kind() == Type::kScalar_Kind &&
945 bin->fRight->fType.kind() == Type::kVector_Kind) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400946 // x / float4(1) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400947 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
948 } else {
949 // x / 1 -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400950 // float4(x) / 1 -> float4(x)
951 // float4(x) / float4(1) -> float4(x)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400952 delete_right(&b, iter, outUpdated, outNeedsRescan);
953 }
954 } else if (is_constant(*bin->fLeft, 0)) {
955 if (bin->fLeft->fType.kind() == Type::kScalar_Kind &&
Ethan Nicholas08dae922018-01-23 10:31:56 -0500956 bin->fRight->fType.kind() == Type::kVector_Kind &&
957 !bin->fRight->hasSideEffects()) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400958 // 0 / float4(x) -> float4(0)
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400959 vectorize_left(&b, iter, outUpdated, outNeedsRescan);
960 } else {
961 // 0 / x -> 0
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400962 // float4(0) / x -> float4(0)
963 // float4(0) / float4(x) -> float4(0)
Ethan Nicholas51493ee2017-12-11 12:34:33 -0500964 if (!bin->fRight->hasSideEffects()) {
965 delete_right(&b, iter, outUpdated, outNeedsRescan);
966 }
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400967 }
968 }
969 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400970 case Token::Kind::TK_PLUSEQ:
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400971 if (is_constant(*bin->fRight, 0)) {
972 clear_write(*bin->fLeft);
973 delete_right(&b, iter, outUpdated, outNeedsRescan);
974 }
975 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400976 case Token::Kind::TK_MINUSEQ:
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400977 if (is_constant(*bin->fRight, 0)) {
978 clear_write(*bin->fLeft);
979 delete_right(&b, iter, outUpdated, outNeedsRescan);
980 }
981 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400982 case Token::Kind::TK_STAREQ:
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400983 if (is_constant(*bin->fRight, 1)) {
984 clear_write(*bin->fLeft);
985 delete_right(&b, iter, outUpdated, outNeedsRescan);
986 }
987 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400988 case Token::Kind::TK_SLASHEQ:
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400989 if (is_constant(*bin->fRight, 1)) {
990 clear_write(*bin->fLeft);
Ethan Nicholascb670962017-04-20 19:31:52 -0400991 delete_right(&b, iter, outUpdated, outNeedsRescan);
992 }
993 break;
994 default:
995 break;
996 }
Ethan Nicholas409f6f02019-09-17 12:34:39 -0400997 break;
998 }
999 case Expression::kSwizzle_Kind: {
1000 Swizzle& s = (Swizzle&) *expr;
1001 // detect identity swizzles like foo.rgba
1002 if ((int) s.fComponents.size() == s.fBase->fType.columns()) {
1003 bool identity = true;
1004 for (int i = 0; i < (int) s.fComponents.size(); ++i) {
1005 if (s.fComponents[i] != i) {
1006 identity = false;
1007 break;
1008 }
1009 }
1010 if (identity) {
1011 *outUpdated = true;
1012 if (!try_replace_expression(&b, iter, &s.fBase)) {
1013 *outNeedsRescan = true;
1014 return;
1015 }
1016 SkASSERT((*iter)->fKind == BasicBlock::Node::kExpression_Kind);
1017 break;
1018 }
1019 }
1020 // detect swizzles of swizzles, e.g. replace foo.argb.r000 with foo.a000
1021 if (s.fBase->fKind == Expression::kSwizzle_Kind) {
1022 Swizzle& base = (Swizzle&) *s.fBase;
1023 std::vector<int> final;
1024 for (int c : s.fComponents) {
1025 if (c == SKSL_SWIZZLE_0 || c == SKSL_SWIZZLE_1) {
1026 final.push_back(c);
1027 } else {
1028 final.push_back(base.fComponents[c]);
1029 }
1030 }
1031 *outUpdated = true;
1032 std::unique_ptr<Expression> replacement(new Swizzle(*fContext, base.fBase->clone(),
1033 std::move(final)));
1034 if (!try_replace_expression(&b, iter, &replacement)) {
1035 *outNeedsRescan = true;
1036 return;
1037 }
1038 SkASSERT((*iter)->fKind == BasicBlock::Node::kExpression_Kind);
1039 break;
1040 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001041 }
1042 default:
1043 break;
1044 }
1045}
1046
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001047// returns true if this statement could potentially execute a break at the current level (we ignore
1048// nested loops and switches, since any breaks inside of them will merely break the loop / switch)
Ethan Nicholas5005a222018-08-24 13:06:27 -04001049static bool contains_conditional_break(Statement& s, bool inConditional) {
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001050 switch (s.fKind) {
1051 case Statement::kBlock_Kind:
1052 for (const auto& sub : ((Block&) s).fStatements) {
Ethan Nicholas5005a222018-08-24 13:06:27 -04001053 if (contains_conditional_break(*sub, inConditional)) {
1054 return true;
1055 }
1056 }
1057 return false;
1058 case Statement::kBreak_Kind:
1059 return inConditional;
1060 case Statement::kIf_Kind: {
1061 const IfStatement& i = (IfStatement&) s;
1062 return contains_conditional_break(*i.fIfTrue, true) ||
1063 (i.fIfFalse && contains_conditional_break(*i.fIfFalse, true));
1064 }
1065 default:
1066 return false;
1067 }
1068}
1069
1070// returns true if this statement definitely executes a break at the current level (we ignore
1071// nested loops and switches, since any breaks inside of them will merely break the loop / switch)
1072static bool contains_unconditional_break(Statement& s) {
1073 switch (s.fKind) {
1074 case Statement::kBlock_Kind:
1075 for (const auto& sub : ((Block&) s).fStatements) {
1076 if (contains_unconditional_break(*sub)) {
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001077 return true;
1078 }
1079 }
1080 return false;
1081 case Statement::kBreak_Kind:
1082 return true;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001083 default:
1084 return false;
1085 }
1086}
1087
1088// Returns a block containing all of the statements that will be run if the given case matches
1089// (which, owing to the statements being owned by unique_ptrs, means the switch itself will be
1090// broken by this call and must then be discarded).
1091// Returns null (and leaves the switch unmodified) if no such simple reduction is possible, such as
1092// when break statements appear inside conditionals.
1093static std::unique_ptr<Statement> block_for_case(SwitchStatement* s, SwitchCase* c) {
1094 bool capturing = false;
1095 std::vector<std::unique_ptr<Statement>*> statementPtrs;
1096 for (const auto& current : s->fCases) {
1097 if (current.get() == c) {
1098 capturing = true;
1099 }
1100 if (capturing) {
1101 for (auto& stmt : current->fStatements) {
Ethan Nicholas5005a222018-08-24 13:06:27 -04001102 if (contains_conditional_break(*stmt, s->fKind == Statement::kIf_Kind)) {
1103 return nullptr;
1104 }
1105 if (contains_unconditional_break(*stmt)) {
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001106 capturing = false;
1107 break;
1108 }
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001109 statementPtrs.push_back(&stmt);
1110 }
1111 if (!capturing) {
1112 break;
1113 }
1114 }
1115 }
1116 std::vector<std::unique_ptr<Statement>> statements;
1117 for (const auto& s : statementPtrs) {
1118 statements.push_back(std::move(*s));
1119 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001120 return std::unique_ptr<Statement>(new Block(-1, std::move(statements), s->fSymbols));
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001121}
1122
Ethan Nicholascb670962017-04-20 19:31:52 -04001123void Compiler::simplifyStatement(DefinitionMap& definitions,
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001124 BasicBlock& b,
1125 std::vector<BasicBlock::Node>::iterator* iter,
1126 std::unordered_set<const Variable*>* undefinedVariables,
1127 bool* outUpdated,
1128 bool* outNeedsRescan) {
Ethan Nicholascb670962017-04-20 19:31:52 -04001129 Statement* stmt = (*iter)->statement()->get();
1130 switch (stmt->fKind) {
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001131 case Statement::kVarDeclaration_Kind: {
1132 const auto& varDecl = (VarDeclaration&) *stmt;
1133 if (varDecl.fVar->dead() &&
1134 (!varDecl.fValue ||
1135 !varDecl.fValue->hasSideEffects())) {
1136 if (varDecl.fValue) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001137 SkASSERT((*iter)->statement()->get() == stmt);
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001138 if (!b.tryRemoveExpressionBefore(iter, varDecl.fValue.get())) {
1139 *outNeedsRescan = true;
Ethan Nicholascb670962017-04-20 19:31:52 -04001140 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001141 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001142 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001143 *outUpdated = true;
Ethan Nicholascb670962017-04-20 19:31:52 -04001144 }
1145 break;
1146 }
1147 case Statement::kIf_Kind: {
1148 IfStatement& i = (IfStatement&) *stmt;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001149 if (i.fTest->fKind == Expression::kBoolLiteral_Kind) {
1150 // constant if, collapse down to a single branch
1151 if (((BoolLiteral&) *i.fTest).fValue) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001152 SkASSERT(i.fIfTrue);
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001153 (*iter)->setStatement(std::move(i.fIfTrue));
1154 } else {
1155 if (i.fIfFalse) {
1156 (*iter)->setStatement(std::move(i.fIfFalse));
1157 } else {
1158 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
1159 }
1160 }
1161 *outUpdated = true;
1162 *outNeedsRescan = true;
1163 break;
1164 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001165 if (i.fIfFalse && i.fIfFalse->isEmpty()) {
1166 // else block doesn't do anything, remove it
1167 i.fIfFalse.reset();
1168 *outUpdated = true;
1169 *outNeedsRescan = true;
1170 }
1171 if (!i.fIfFalse && i.fIfTrue->isEmpty()) {
1172 // if block doesn't do anything, no else block
1173 if (i.fTest->hasSideEffects()) {
1174 // test has side effects, keep it
1175 (*iter)->setStatement(std::unique_ptr<Statement>(
1176 new ExpressionStatement(std::move(i.fTest))));
1177 } else {
1178 // no if, no else, no test side effects, kill the whole if
1179 // statement
1180 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
1181 }
1182 *outUpdated = true;
1183 *outNeedsRescan = true;
1184 }
1185 break;
1186 }
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001187 case Statement::kSwitch_Kind: {
1188 SwitchStatement& s = (SwitchStatement&) *stmt;
1189 if (s.fValue->isConstant()) {
1190 // switch is constant, replace it with the case that matches
1191 bool found = false;
1192 SwitchCase* defaultCase = nullptr;
1193 for (const auto& c : s.fCases) {
1194 if (!c->fValue) {
1195 defaultCase = c.get();
1196 continue;
1197 }
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001198 SkASSERT(c->fValue->fKind == s.fValue->fKind);
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001199 found = c->fValue->compareConstant(*fContext, *s.fValue);
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001200 if (found) {
1201 std::unique_ptr<Statement> newBlock = block_for_case(&s, c.get());
1202 if (newBlock) {
1203 (*iter)->setStatement(std::move(newBlock));
1204 break;
1205 } else {
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -04001206 if (s.fIsStatic && !(fFlags & kPermitInvalidStaticTests_Flag)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001207 this->error(s.fOffset,
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001208 "static switch contains non-static conditional break");
1209 s.fIsStatic = false;
1210 }
1211 return; // can't simplify
1212 }
1213 }
1214 }
1215 if (!found) {
1216 // no matching case. use default if it exists, or kill the whole thing
1217 if (defaultCase) {
1218 std::unique_ptr<Statement> newBlock = block_for_case(&s, defaultCase);
1219 if (newBlock) {
1220 (*iter)->setStatement(std::move(newBlock));
1221 } else {
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -04001222 if (s.fIsStatic && !(fFlags & kPermitInvalidStaticTests_Flag)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001223 this->error(s.fOffset,
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001224 "static switch contains non-static conditional break");
1225 s.fIsStatic = false;
1226 }
1227 return; // can't simplify
1228 }
1229 } else {
1230 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
1231 }
1232 }
1233 *outUpdated = true;
1234 *outNeedsRescan = true;
1235 }
1236 break;
1237 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001238 case Statement::kExpression_Kind: {
1239 ExpressionStatement& e = (ExpressionStatement&) *stmt;
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001240 SkASSERT((*iter)->statement()->get() == &e);
Ethan Nicholascb670962017-04-20 19:31:52 -04001241 if (!e.fExpression->hasSideEffects()) {
1242 // Expression statement with no side effects, kill it
1243 if (!b.tryRemoveExpressionBefore(iter, e.fExpression.get())) {
1244 *outNeedsRescan = true;
1245 }
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001246 SkASSERT((*iter)->statement()->get() == stmt);
Ethan Nicholascb670962017-04-20 19:31:52 -04001247 (*iter)->setStatement(std::unique_ptr<Statement>(new Nop()));
1248 *outUpdated = true;
1249 }
1250 break;
1251 }
1252 default:
1253 break;
1254 }
1255}
1256
1257void Compiler::scanCFG(FunctionDefinition& f) {
1258 CFG cfg = CFGGenerator().getCFG(f);
1259 this->computeDataFlow(&cfg);
ethannicholas22f939e2016-10-13 13:25:34 -07001260
1261 // check for unreachable code
1262 for (size_t i = 0; i < cfg.fBlocks.size(); i++) {
Mike Klein6ad99092016-10-26 10:35:22 -04001263 if (i != cfg.fStart && !cfg.fBlocks[i].fEntrances.size() &&
ethannicholas22f939e2016-10-13 13:25:34 -07001264 cfg.fBlocks[i].fNodes.size()) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001265 int offset;
Ethan Nicholas86a43402017-01-19 13:32:00 -05001266 switch (cfg.fBlocks[i].fNodes[0].fKind) {
1267 case BasicBlock::Node::kStatement_Kind:
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001268 offset = (*cfg.fBlocks[i].fNodes[0].statement())->fOffset;
Ethan Nicholas86a43402017-01-19 13:32:00 -05001269 break;
1270 case BasicBlock::Node::kExpression_Kind:
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001271 offset = (*cfg.fBlocks[i].fNodes[0].expression())->fOffset;
Ethan Nicholas70728ef2020-05-28 07:09:00 -04001272 if ((*cfg.fBlocks[i].fNodes[0].expression())->fKind ==
1273 Expression::kBoolLiteral_Kind) {
1274 // Function inlining can generate do { ... } while(false) loops which always
1275 // break, so the boolean condition is considered unreachable. Since not
1276 // being able to reach a literal is a non-issue in the first place, we
1277 // don't report an error in this case.
1278 continue;
1279 }
Ethan Nicholas86a43402017-01-19 13:32:00 -05001280 break;
1281 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001282 this->error(offset, String("unreachable"));
ethannicholas22f939e2016-10-13 13:25:34 -07001283 }
1284 }
1285 if (fErrorCount) {
1286 return;
1287 }
1288
Ethan Nicholascb670962017-04-20 19:31:52 -04001289 // check for dead code & undefined variables, perform constant propagation
1290 std::unordered_set<const Variable*> undefinedVariables;
1291 bool updated;
1292 bool needsRescan = false;
1293 do {
1294 if (needsRescan) {
1295 cfg = CFGGenerator().getCFG(f);
1296 this->computeDataFlow(&cfg);
1297 needsRescan = false;
Ethan Nicholas113628d2017-02-02 16:11:39 -05001298 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001299
1300 updated = false;
1301 for (BasicBlock& b : cfg.fBlocks) {
1302 DefinitionMap definitions = b.fBefore;
1303
1304 for (auto iter = b.fNodes.begin(); iter != b.fNodes.end() && !needsRescan; ++iter) {
1305 if (iter->fKind == BasicBlock::Node::kExpression_Kind) {
1306 this->simplifyExpression(definitions, b, &iter, &undefinedVariables, &updated,
1307 &needsRescan);
1308 } else {
1309 this->simplifyStatement(definitions, b, &iter, &undefinedVariables, &updated,
1310 &needsRescan);
1311 }
Ethan Nicholas4b330df2017-05-17 10:52:55 -04001312 if (needsRescan) {
1313 break;
1314 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001315 this->addDefinitions(*iter, &definitions);
1316 }
1317 }
1318 } while (updated);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001319 SkASSERT(!needsRescan);
ethannicholas22f939e2016-10-13 13:25:34 -07001320
Ethan Nicholas91a10532017-06-22 11:24:38 -04001321 // verify static ifs & switches, clean up dead variable decls
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001322 for (BasicBlock& b : cfg.fBlocks) {
1323 DefinitionMap definitions = b.fBefore;
1324
Ethan Nicholas91a10532017-06-22 11:24:38 -04001325 for (auto iter = b.fNodes.begin(); iter != b.fNodes.end() && !needsRescan;) {
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001326 if (iter->fKind == BasicBlock::Node::kStatement_Kind) {
1327 const Statement& s = **iter->statement();
1328 switch (s.fKind) {
1329 case Statement::kIf_Kind:
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -04001330 if (((const IfStatement&) s).fIsStatic &&
1331 !(fFlags & kPermitInvalidStaticTests_Flag)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001332 this->error(s.fOffset, "static if has non-static test");
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001333 }
Ethan Nicholas91a10532017-06-22 11:24:38 -04001334 ++iter;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001335 break;
1336 case Statement::kSwitch_Kind:
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -04001337 if (((const SwitchStatement&) s).fIsStatic &&
1338 !(fFlags & kPermitInvalidStaticTests_Flag)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001339 this->error(s.fOffset, "static switch has non-static test");
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001340 }
Ethan Nicholas91a10532017-06-22 11:24:38 -04001341 ++iter;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001342 break;
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001343 case Statement::kVarDeclarations_Kind: {
1344 VarDeclarations& decls = *((VarDeclarationsStatement&) s).fDeclaration;
1345 for (auto varIter = decls.fVars.begin(); varIter != decls.fVars.end();) {
1346 if ((*varIter)->fKind == Statement::kNop_Kind) {
1347 varIter = decls.fVars.erase(varIter);
1348 } else {
1349 ++varIter;
1350 }
1351 }
1352 if (!decls.fVars.size()) {
1353 iter = b.fNodes.erase(iter);
1354 } else {
1355 ++iter;
1356 }
1357 break;
1358 }
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001359 default:
Ethan Nicholas91a10532017-06-22 11:24:38 -04001360 ++iter;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001361 break;
1362 }
Ethan Nicholas91a10532017-06-22 11:24:38 -04001363 } else {
1364 ++iter;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001365 }
1366 }
1367 }
1368
ethannicholas22f939e2016-10-13 13:25:34 -07001369 // check for missing return
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001370 if (f.fDeclaration.fReturnType != *fContext->fVoid_Type) {
ethannicholas22f939e2016-10-13 13:25:34 -07001371 if (cfg.fBlocks[cfg.fExit].fEntrances.size()) {
Ethan Nicholasdb80f692019-11-22 14:06:12 -05001372 this->error(f.fOffset, String("function '" + String(f.fDeclaration.fName) +
1373 "' can exit without returning a value"));
ethannicholas22f939e2016-10-13 13:25:34 -07001374 }
1375 }
1376}
1377
Ethan Nicholas91164d12019-05-15 15:29:54 -04001378void Compiler::registerExternalValue(ExternalValue* value) {
1379 fIRGenerator->fRootSymbolTable->addWithoutOwnership(value->fName, value);
1380}
1381
1382Symbol* Compiler::takeOwnership(std::unique_ptr<Symbol> symbol) {
1383 return fIRGenerator->fRootSymbolTable->takeOwnership(std::move(symbol));
1384}
1385
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001386std::unique_ptr<Program> Compiler::convertProgram(Program::Kind kind, String text,
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001387 const Program::Settings& settings) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001388 fErrorText = "";
1389 fErrorCount = 0;
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001390 std::vector<std::unique_ptr<ProgramElement>>* inherited;
ethannicholasd598f792016-07-25 10:08:54 -07001391 std::vector<std::unique_ptr<ProgramElement>> elements;
ethannicholasb3058bd2016-07-01 08:22:01 -07001392 switch (kind) {
1393 case Program::kVertex_Kind:
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001394 inherited = &fVertexInclude;
1395 fIRGenerator->fSymbolTable = fVertexSymbolTable;
Ethan Nicholasdb80f692019-11-22 14:06:12 -05001396 fIRGenerator->fIntrinsics = &fGPUIntrinsics;
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001397 fIRGenerator->start(&settings, inherited);
ethannicholasb3058bd2016-07-01 08:22:01 -07001398 break;
1399 case Program::kFragment_Kind:
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001400 inherited = &fFragmentInclude;
1401 fIRGenerator->fSymbolTable = fFragmentSymbolTable;
Ethan Nicholasdb80f692019-11-22 14:06:12 -05001402 fIRGenerator->fIntrinsics = &fGPUIntrinsics;
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001403 fIRGenerator->start(&settings, inherited);
ethannicholasb3058bd2016-07-01 08:22:01 -07001404 break;
Ethan Nicholas52cad152017-02-16 16:37:32 -05001405 case Program::kGeometry_Kind:
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001406 inherited = &fGeometryInclude;
1407 fIRGenerator->fSymbolTable = fGeometrySymbolTable;
Ethan Nicholasdb80f692019-11-22 14:06:12 -05001408 fIRGenerator->fIntrinsics = &fGPUIntrinsics;
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001409 fIRGenerator->start(&settings, inherited);
Ethan Nicholas52cad152017-02-16 16:37:32 -05001410 break;
Ethan Nicholas762466e2017-06-29 10:03:38 -04001411 case Program::kFragmentProcessor_Kind:
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001412 inherited = nullptr;
Ethan Nicholas8da1e652019-05-24 11:01:59 -04001413 fIRGenerator->fSymbolTable = fGpuSymbolTable;
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001414 fIRGenerator->start(&settings, nullptr);
Ethan Nicholasdb80f692019-11-22 14:06:12 -05001415 fIRGenerator->fIntrinsics = &fGPUIntrinsics;
Robert Phillipsfe8da172018-01-24 14:52:02 +00001416 fIRGenerator->convertProgram(kind, SKSL_FP_INCLUDE, strlen(SKSL_FP_INCLUDE), *fTypes,
Ethan Nicholasf7b88202017-09-18 14:10:39 -04001417 &elements);
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001418 fIRGenerator->fSymbolTable->markAllFunctionsBuiltin();
Ethan Nicholas762466e2017-06-29 10:03:38 -04001419 break;
Ethan Nicholas8da1e652019-05-24 11:01:59 -04001420 case Program::kPipelineStage_Kind:
1421 inherited = &fPipelineInclude;
1422 fIRGenerator->fSymbolTable = fPipelineSymbolTable;
Ethan Nicholasdb80f692019-11-22 14:06:12 -05001423 fIRGenerator->fIntrinsics = &fGPUIntrinsics;
Ethan Nicholas8da1e652019-05-24 11:01:59 -04001424 fIRGenerator->start(&settings, inherited);
1425 break;
Ethan Nicholas746035a2019-04-23 13:31:09 -04001426 case Program::kGeneric_Kind:
Ethan Nicholas8da1e652019-05-24 11:01:59 -04001427 inherited = &fInterpreterInclude;
1428 fIRGenerator->fSymbolTable = fInterpreterSymbolTable;
Ethan Nicholasdb80f692019-11-22 14:06:12 -05001429 fIRGenerator->fIntrinsics = &fInterpreterIntrinsics;
Ethan Nicholas8da1e652019-05-24 11:01:59 -04001430 fIRGenerator->start(&settings, inherited);
Ethan Nicholas0d997662019-04-08 09:46:01 -04001431 break;
ethannicholasb3058bd2016-07-01 08:22:01 -07001432 }
Ethan Nicholasaae47c82017-11-10 15:34:03 -05001433 for (auto& element : elements) {
1434 if (element->fKind == ProgramElement::kEnum_Kind) {
1435 ((Enum&) *element).fBuiltin = true;
1436 }
1437 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001438 std::unique_ptr<String> textPtr(new String(std::move(text)));
1439 fSource = textPtr.get();
Robert Phillipsfe8da172018-01-24 14:52:02 +00001440 fIRGenerator->convertProgram(kind, textPtr->c_str(), textPtr->size(), *fTypes, &elements);
Ethan Nicholasf7b88202017-09-18 14:10:39 -04001441 auto result = std::unique_ptr<Program>(new Program(kind,
1442 std::move(textPtr),
1443 settings,
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001444 fContext,
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001445 inherited,
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001446 std::move(elements),
1447 fIRGenerator->fSymbolTable,
1448 fIRGenerator->fInputs));
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001449 if (fErrorCount) {
1450 return nullptr;
1451 }
1452 return result;
1453}
1454
Ethan Nicholas00543112018-07-31 09:44:36 -04001455bool Compiler::optimize(Program& program) {
1456 SkASSERT(!fErrorCount);
1457 if (!program.fIsOptimized) {
1458 program.fIsOptimized = true;
1459 fIRGenerator->fKind = program.fKind;
1460 fIRGenerator->fSettings = &program.fSettings;
1461 for (auto& element : program) {
1462 if (element.fKind == ProgramElement::kFunction_Kind) {
1463 this->scanCFG((FunctionDefinition&) element);
1464 }
1465 }
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001466 if (program.fKind != Program::kFragmentProcessor_Kind) {
1467 for (auto iter = program.fElements.begin(); iter != program.fElements.end();) {
1468 if ((*iter)->fKind == ProgramElement::kVar_Kind) {
1469 VarDeclarations& vars = (VarDeclarations&) **iter;
1470 for (auto varIter = vars.fVars.begin(); varIter != vars.fVars.end();) {
1471 const Variable& var = *((VarDeclaration&) **varIter).fVar;
1472 if (var.dead()) {
1473 varIter = vars.fVars.erase(varIter);
1474 } else {
1475 ++varIter;
1476 }
1477 }
1478 if (vars.fVars.size() == 0) {
1479 iter = program.fElements.erase(iter);
1480 continue;
1481 }
1482 }
1483 ++iter;
1484 }
1485 }
Ethan Nicholas00543112018-07-31 09:44:36 -04001486 }
1487 return fErrorCount == 0;
1488}
1489
1490std::unique_ptr<Program> Compiler::specialize(
1491 Program& program,
1492 const std::unordered_map<SkSL::String, SkSL::Program::Settings::Value>& inputs) {
1493 std::vector<std::unique_ptr<ProgramElement>> elements;
1494 for (const auto& e : program) {
1495 elements.push_back(e.clone());
1496 }
1497 Program::Settings settings;
1498 settings.fCaps = program.fSettings.fCaps;
1499 for (auto iter = inputs.begin(); iter != inputs.end(); ++iter) {
1500 settings.fArgs.insert(*iter);
1501 }
Brian Osman808f0212020-01-21 15:36:47 -05001502 std::unique_ptr<String> sourceCopy(new String(*program.fSource));
Ethan Nicholas00543112018-07-31 09:44:36 -04001503 std::unique_ptr<Program> result(new Program(program.fKind,
Brian Osman808f0212020-01-21 15:36:47 -05001504 std::move(sourceCopy),
Ethan Nicholas00543112018-07-31 09:44:36 -04001505 settings,
1506 program.fContext,
1507 program.fInheritedElements,
1508 std::move(elements),
1509 program.fSymbols,
1510 program.fInputs));
1511 return result;
1512}
1513
Brian Osmanfb32ddf2019-06-18 10:14:20 -04001514#if defined(SKSL_STANDALONE) || SK_SUPPORT_GPU
1515
Ethan Nicholas00543112018-07-31 09:44:36 -04001516bool Compiler::toSPIRV(Program& program, OutputStream& out) {
1517 if (!this->optimize(program)) {
1518 return false;
1519 }
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001520#ifdef SK_ENABLE_SPIRV_VALIDATION
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001521 StringStream buffer;
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001522 fSource = program.fSource.get();
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001523 SPIRVCodeGenerator cg(fContext.get(), &program, this, &buffer);
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001524 bool result = cg.generateCode();
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001525 fSource = nullptr;
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001526 if (result) {
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001527 spvtools::SpirvTools tools(SPV_ENV_VULKAN_1_0);
Ethan Nicholas762466e2017-06-29 10:03:38 -04001528 const String& data = buffer.str();
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001529 SkASSERT(0 == data.size() % 4);
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001530 auto dumpmsg = [](spv_message_level_t, const char*, const spv_position_t&, const char* m) {
1531 SkDebugf("SPIR-V validation error: %s\n", m);
1532 };
1533 tools.SetMessageConsumer(dumpmsg);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001534 // Verify that the SPIR-V we produced is valid. If this SkASSERT fails, check the logs prior
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001535 // to the failure to see the validation errors.
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001536 SkAssertResult(tools.Validate((const uint32_t*) data.c_str(), data.size() / 4));
Ethan Nicholas762466e2017-06-29 10:03:38 -04001537 out.write(data.c_str(), data.size());
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001538 }
1539#else
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001540 fSource = program.fSource.get();
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001541 SPIRVCodeGenerator cg(fContext.get(), &program, this, &out);
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001542 bool result = cg.generateCode();
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001543 fSource = nullptr;
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001544#endif
Ethan Nicholasce33f102016-12-09 17:22:59 -05001545 return result;
1546}
1547
Ethan Nicholas00543112018-07-31 09:44:36 -04001548bool Compiler::toSPIRV(Program& program, String* out) {
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001549 StringStream buffer;
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001550 bool result = this->toSPIRV(program, buffer);
1551 if (result) {
Ethan Nicholas762466e2017-06-29 10:03:38 -04001552 *out = buffer.str();
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001553 }
1554 return result;
1555}
1556
Ethan Nicholas00543112018-07-31 09:44:36 -04001557bool Compiler::toGLSL(Program& program, OutputStream& out) {
1558 if (!this->optimize(program)) {
1559 return false;
1560 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001561 fSource = program.fSource.get();
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001562 GLSLCodeGenerator cg(fContext.get(), &program, this, &out);
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001563 bool result = cg.generateCode();
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001564 fSource = nullptr;
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001565 return result;
1566}
1567
Ethan Nicholas00543112018-07-31 09:44:36 -04001568bool Compiler::toGLSL(Program& program, String* out) {
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001569 StringStream buffer;
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001570 bool result = this->toGLSL(program, buffer);
1571 if (result) {
Ethan Nicholas762466e2017-06-29 10:03:38 -04001572 *out = buffer.str();
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001573 }
1574 return result;
1575}
1576
Brian Osmanc0243912020-02-19 15:35:26 -05001577bool Compiler::toHLSL(Program& program, String* out) {
1578 String spirv;
1579 if (!this->toSPIRV(program, &spirv)) {
1580 return false;
1581 }
1582
1583 return SPIRVtoHLSL(spirv, out);
1584}
1585
Ethan Nicholas00543112018-07-31 09:44:36 -04001586bool Compiler::toMetal(Program& program, OutputStream& out) {
1587 if (!this->optimize(program)) {
1588 return false;
1589 }
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001590 MetalCodeGenerator cg(fContext.get(), &program, this, &out);
Ethan Nicholascc305772017-10-13 16:17:45 -04001591 bool result = cg.generateCode();
Ethan Nicholascc305772017-10-13 16:17:45 -04001592 return result;
1593}
1594
Ethan Nicholas00543112018-07-31 09:44:36 -04001595bool Compiler::toMetal(Program& program, String* out) {
1596 if (!this->optimize(program)) {
1597 return false;
1598 }
Timothy Liangb8eeb802018-07-23 16:46:16 -04001599 StringStream buffer;
1600 bool result = this->toMetal(program, buffer);
1601 if (result) {
1602 *out = buffer.str();
1603 }
1604 return result;
1605}
1606
Ethan Nicholas00543112018-07-31 09:44:36 -04001607bool Compiler::toCPP(Program& program, String name, OutputStream& out) {
1608 if (!this->optimize(program)) {
1609 return false;
1610 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001611 fSource = program.fSource.get();
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001612 CPPCodeGenerator cg(fContext.get(), &program, this, name, &out);
Ethan Nicholas762466e2017-06-29 10:03:38 -04001613 bool result = cg.generateCode();
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001614 fSource = nullptr;
Ethan Nicholas762466e2017-06-29 10:03:38 -04001615 return result;
1616}
1617
Ethan Nicholas00543112018-07-31 09:44:36 -04001618bool Compiler::toH(Program& program, String name, OutputStream& out) {
1619 if (!this->optimize(program)) {
1620 return false;
1621 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001622 fSource = program.fSource.get();
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001623 HCodeGenerator cg(fContext.get(), &program, this, name, &out);
Ethan Nicholas762466e2017-06-29 10:03:38 -04001624 bool result = cg.generateCode();
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001625 fSource = nullptr;
Ethan Nicholas00543112018-07-31 09:44:36 -04001626 return result;
1627}
1628
Brian Osman2e29ab52019-09-20 12:19:11 -04001629#endif
1630
1631#if !defined(SKSL_STANDALONE) && SK_SUPPORT_GPU
Brian Osman107c6662019-12-30 15:02:30 -05001632bool Compiler::toPipelineStage(const Program& program, PipelineStageArgs* outArgs) {
Ethan Nicholas00543112018-07-31 09:44:36 -04001633 SkASSERT(program.fIsOptimized);
1634 fSource = program.fSource.get();
1635 StringStream buffer;
Brian Osman300fe1d2020-01-23 15:42:43 -05001636 PipelineStageCodeGenerator cg(fContext.get(), &program, this, &buffer, outArgs);
Ethan Nicholas00543112018-07-31 09:44:36 -04001637 bool result = cg.generateCode();
1638 fSource = nullptr;
1639 if (result) {
Brian Osman107c6662019-12-30 15:02:30 -05001640 outArgs->fCode = buffer.str();
Ethan Nicholas00543112018-07-31 09:44:36 -04001641 }
Ethan Nicholas762466e2017-06-29 10:03:38 -04001642 return result;
1643}
Brian Osmanfb32ddf2019-06-18 10:14:20 -04001644#endif
1645
Ethan Nicholas0e9401d2019-03-21 11:05:37 -04001646std::unique_ptr<ByteCode> Compiler::toByteCode(Program& program) {
Brian Osman489cf882019-07-09 10:48:28 -04001647#if defined(SK_ENABLE_SKSL_INTERPRETER)
Ethan Nicholas0e9401d2019-03-21 11:05:37 -04001648 if (!this->optimize(program)) {
1649 return nullptr;
1650 }
Brian Osman808f0212020-01-21 15:36:47 -05001651 fSource = program.fSource.get();
Ethan Nicholas0e9401d2019-03-21 11:05:37 -04001652 std::unique_ptr<ByteCode> result(new ByteCode());
Brian Osmanb08cc022020-04-02 11:38:40 -04001653 ByteCodeGenerator cg(fContext.get(), &program, this, result.get());
1654 bool success = cg.generateCode();
1655 fSource = nullptr;
1656 if (success) {
Ethan Nicholas0e9401d2019-03-21 11:05:37 -04001657 return result;
1658 }
Brian Osman489cf882019-07-09 10:48:28 -04001659#else
1660 ABORT("ByteCode interpreter not enabled");
1661#endif
Ethan Nicholas0e9401d2019-03-21 11:05:37 -04001662 return nullptr;
1663}
1664
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001665const char* Compiler::OperatorName(Token::Kind kind) {
1666 switch (kind) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001667 case Token::Kind::TK_PLUS: return "+";
1668 case Token::Kind::TK_MINUS: return "-";
1669 case Token::Kind::TK_STAR: return "*";
1670 case Token::Kind::TK_SLASH: return "/";
1671 case Token::Kind::TK_PERCENT: return "%";
1672 case Token::Kind::TK_SHL: return "<<";
1673 case Token::Kind::TK_SHR: return ">>";
1674 case Token::Kind::TK_LOGICALNOT: return "!";
1675 case Token::Kind::TK_LOGICALAND: return "&&";
1676 case Token::Kind::TK_LOGICALOR: return "||";
1677 case Token::Kind::TK_LOGICALXOR: return "^^";
1678 case Token::Kind::TK_BITWISENOT: return "~";
1679 case Token::Kind::TK_BITWISEAND: return "&";
1680 case Token::Kind::TK_BITWISEOR: return "|";
1681 case Token::Kind::TK_BITWISEXOR: return "^";
1682 case Token::Kind::TK_EQ: return "=";
1683 case Token::Kind::TK_EQEQ: return "==";
1684 case Token::Kind::TK_NEQ: return "!=";
1685 case Token::Kind::TK_LT: return "<";
1686 case Token::Kind::TK_GT: return ">";
1687 case Token::Kind::TK_LTEQ: return "<=";
1688 case Token::Kind::TK_GTEQ: return ">=";
1689 case Token::Kind::TK_PLUSEQ: return "+=";
1690 case Token::Kind::TK_MINUSEQ: return "-=";
1691 case Token::Kind::TK_STAREQ: return "*=";
1692 case Token::Kind::TK_SLASHEQ: return "/=";
1693 case Token::Kind::TK_PERCENTEQ: return "%=";
1694 case Token::Kind::TK_SHLEQ: return "<<=";
1695 case Token::Kind::TK_SHREQ: return ">>=";
1696 case Token::Kind::TK_LOGICALANDEQ: return "&&=";
1697 case Token::Kind::TK_LOGICALOREQ: return "||=";
1698 case Token::Kind::TK_LOGICALXOREQ: return "^^=";
1699 case Token::Kind::TK_BITWISEANDEQ: return "&=";
1700 case Token::Kind::TK_BITWISEOREQ: return "|=";
1701 case Token::Kind::TK_BITWISEXOREQ: return "^=";
1702 case Token::Kind::TK_PLUSPLUS: return "++";
1703 case Token::Kind::TK_MINUSMINUS: return "--";
1704 case Token::Kind::TK_COMMA: return ",";
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001705 default:
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001706 ABORT("unsupported operator: %d\n", (int) kind);
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001707 }
1708}
1709
1710
1711bool Compiler::IsAssignment(Token::Kind op) {
1712 switch (op) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001713 case Token::Kind::TK_EQ: // fall through
1714 case Token::Kind::TK_PLUSEQ: // fall through
1715 case Token::Kind::TK_MINUSEQ: // fall through
1716 case Token::Kind::TK_STAREQ: // fall through
1717 case Token::Kind::TK_SLASHEQ: // fall through
1718 case Token::Kind::TK_PERCENTEQ: // fall through
1719 case Token::Kind::TK_SHLEQ: // fall through
1720 case Token::Kind::TK_SHREQ: // fall through
1721 case Token::Kind::TK_BITWISEOREQ: // fall through
1722 case Token::Kind::TK_BITWISEXOREQ: // fall through
1723 case Token::Kind::TK_BITWISEANDEQ: // fall through
1724 case Token::Kind::TK_LOGICALOREQ: // fall through
1725 case Token::Kind::TK_LOGICALXOREQ: // fall through
1726 case Token::Kind::TK_LOGICALANDEQ:
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001727 return true;
1728 default:
1729 return false;
1730 }
1731}
1732
1733Position Compiler::position(int offset) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001734 SkASSERT(fSource);
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001735 int line = 1;
1736 int column = 1;
1737 for (int i = 0; i < offset; i++) {
1738 if ((*fSource)[i] == '\n') {
1739 ++line;
1740 column = 1;
1741 }
1742 else {
1743 ++column;
1744 }
1745 }
1746 return Position(line, column);
1747}
1748
1749void Compiler::error(int offset, String msg) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001750 fErrorCount++;
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001751 Position pos = this->position(offset);
1752 fErrorText += "error: " + to_string(pos.fLine) + ": " + msg.c_str() + "\n";
ethannicholasb3058bd2016-07-01 08:22:01 -07001753}
1754
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001755String Compiler::errorText() {
Ethan Nicholas00543112018-07-31 09:44:36 -04001756 this->writeErrorCount();
1757 fErrorCount = 0;
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001758 String result = fErrorText;
ethannicholasb3058bd2016-07-01 08:22:01 -07001759 return result;
1760}
1761
1762void Compiler::writeErrorCount() {
1763 if (fErrorCount) {
1764 fErrorText += to_string(fErrorCount) + " error";
1765 if (fErrorCount > 1) {
1766 fErrorText += "s";
1767 }
1768 fErrorText += "\n";
1769 }
1770}
1771
ethannicholasb3058bd2016-07-01 08:22:01 -07001772} // namespace