blob: e644cbf4a486d541f04fd62eaf7827ab35a50177 [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
John Stilesb92641c2020-08-31 18:09:01 -040013#include "src/sksl/SkSLAnalysis.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050014#include "src/sksl/SkSLByteCodeGenerator.h"
15#include "src/sksl/SkSLCFGGenerator.h"
16#include "src/sksl/SkSLCPPCodeGenerator.h"
17#include "src/sksl/SkSLGLSLCodeGenerator.h"
18#include "src/sksl/SkSLHCodeGenerator.h"
19#include "src/sksl/SkSLIRGenerator.h"
20#include "src/sksl/SkSLMetalCodeGenerator.h"
21#include "src/sksl/SkSLPipelineStageCodeGenerator.h"
Ethan Nicholasc18bb512020-07-28 14:46:53 -040022#include "src/sksl/SkSLRehydrator.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050023#include "src/sksl/SkSLSPIRVCodeGenerator.h"
Brian Osmanc0243912020-02-19 15:35:26 -050024#include "src/sksl/SkSLSPIRVtoHLSL.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050025#include "src/sksl/ir/SkSLEnum.h"
26#include "src/sksl/ir/SkSLExpression.h"
27#include "src/sksl/ir/SkSLExpressionStatement.h"
28#include "src/sksl/ir/SkSLFunctionCall.h"
29#include "src/sksl/ir/SkSLIntLiteral.h"
30#include "src/sksl/ir/SkSLModifiersDeclaration.h"
31#include "src/sksl/ir/SkSLNop.h"
32#include "src/sksl/ir/SkSLSymbolTable.h"
33#include "src/sksl/ir/SkSLTernaryExpression.h"
34#include "src/sksl/ir/SkSLUnresolvedFunction.h"
35#include "src/sksl/ir/SkSLVarDeclarations.h"
John Stilese6150002020-10-05 12:03:53 -040036#include "src/utils/SkBitSet.h"
ethannicholasb3058bd2016-07-01 08:22:01 -070037
Ethan Nicholasb33fa3f2020-08-06 13:00:19 -040038#include <fstream>
39
Ethan Nicholasa11035b2019-11-26 16:27:47 -050040#if !defined(SKSL_STANDALONE) & SK_SUPPORT_GPU
41#include "include/gpu/GrContextOptions.h"
42#include "src/gpu/GrShaderCaps.h"
43#endif
44
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -040045#ifdef SK_ENABLE_SPIRV_VALIDATION
46#include "spirv-tools/libspirv.hpp"
47#endif
48
Brian Osman3d87e9f2020-10-08 11:50:22 -040049#if defined(SKSL_STANDALONE)
Ethan Nicholasc18bb512020-07-28 14:46:53 -040050
Brian Osman3d87e9f2020-10-08 11:50:22 -040051// In standalone mode, we load the textual sksl source files. GN generates or copies these files
52// to the skslc executable directory. The "data" in this mode is just the filename.
53#define MODULE_DATA(name) MakeModulePath("sksl_" #name ".sksl")
54
55#else
56
57// At runtime, we load the dehydrated sksl data files. The data is a (pointer, size) pair.
Ethan Nicholasc18bb512020-07-28 14:46:53 -040058#include "src/sksl/generated/sksl_fp.dehydrated.sksl"
59#include "src/sksl/generated/sksl_frag.dehydrated.sksl"
60#include "src/sksl/generated/sksl_geom.dehydrated.sksl"
61#include "src/sksl/generated/sksl_gpu.dehydrated.sksl"
62#include "src/sksl/generated/sksl_interp.dehydrated.sksl"
Brian Osmanb06301e2020-11-06 11:45:36 -050063#include "src/sksl/generated/sksl_public.dehydrated.sksl"
Brian Osman91946752020-12-21 13:20:40 -050064#include "src/sksl/generated/sksl_runtime.dehydrated.sksl"
Ethan Nicholasc18bb512020-07-28 14:46:53 -040065#include "src/sksl/generated/sksl_vert.dehydrated.sksl"
66
Brian Osman3d87e9f2020-10-08 11:50:22 -040067#define MODULE_DATA(name) MakeModuleData(SKSL_INCLUDE_sksl_##name,\
68 SKSL_INCLUDE_sksl_##name##_LENGTH)
Ethan Nicholasc18bb512020-07-28 14:46:53 -040069
70#endif
Ethan Nicholas0d997662019-04-08 09:46:01 -040071
ethannicholasb3058bd2016-07-01 08:22:01 -070072namespace SkSL {
73
Brian Osman88cda172020-10-09 12:05:16 -040074class AutoSource {
75public:
76 AutoSource(Compiler* compiler, const String* source)
77 : fCompiler(compiler), fOldSource(fCompiler->fSource) {
78 fCompiler->fSource = source;
79 }
80
81 ~AutoSource() { fCompiler->fSource = fOldSource; }
82
83 Compiler* fCompiler;
84 const String* fOldSource;
85};
86
Brian Osmand7e76592020-11-02 12:26:22 -050087Compiler::Compiler(const ShaderCapsClass* caps, Flags flags)
Brian Osman0006ad02020-11-18 15:38:39 -050088 : fContext(std::make_shared<Context>())
89 , fCaps(caps)
John Stiles7b920442020-12-17 10:43:41 -050090 , fInliner(fContext.get())
Brian Osman0006ad02020-11-18 15:38:39 -050091 , fFlags(flags)
92 , fErrorCount(0) {
93 SkASSERT(fCaps);
John Stiles7c3515b2020-10-16 18:38:39 -040094 fRootSymbolTable = std::make_shared<SymbolTable>(this, /*builtin=*/true);
Brian Osmanb06301e2020-11-06 11:45:36 -050095 fPrivateSymbolTable = std::make_shared<SymbolTable>(fRootSymbolTable, /*builtin=*/true);
John Stiles0f464502020-11-20 12:52:22 -050096 fIRGenerator = std::make_unique<IRGenerator>(fContext.get(), fCaps, *this);
ethannicholasb3058bd2016-07-01 08:22:01 -070097
Brian Osmanb06301e2020-11-06 11:45:36 -050098#define TYPE(t) fContext->f##t##_Type.get()
ethannicholasb3058bd2016-07-01 08:22:01 -070099
Brian Osmanb06301e2020-11-06 11:45:36 -0500100 const SkSL::Symbol* rootTypes[] = {
101 TYPE(Void),
Brian Salomonbf7b6202016-11-11 16:08:03 -0500102
Brian Osmanb06301e2020-11-06 11:45:36 -0500103 TYPE( Float), TYPE( Float2), TYPE( Float3), TYPE( Float4),
104 TYPE( Half), TYPE( Half2), TYPE( Half3), TYPE( Half4),
105 TYPE( Int), TYPE( Int2), TYPE( Int3), TYPE( Int4),
106 TYPE( UInt), TYPE( UInt2), TYPE( UInt3), TYPE( UInt4),
107 TYPE( Short), TYPE( Short2), TYPE( Short3), TYPE( Short4),
108 TYPE(UShort), TYPE(UShort2), TYPE(UShort3), TYPE(UShort4),
109 TYPE( Byte), TYPE( Byte2), TYPE( Byte3), TYPE( Byte4),
110 TYPE( UByte), TYPE( UByte2), TYPE( UByte3), TYPE( UByte4),
111 TYPE( Bool), TYPE( Bool2), TYPE( Bool3), TYPE( Bool4),
Brian Salomon2a51de82016-11-16 12:06:01 -0500112
Brian Osmanc0f2b642020-12-22 13:35:55 -0500113 TYPE(Float2x2), TYPE(Float3x3), TYPE(Float4x4),
Greg Daniel64773e62016-11-22 09:44:03 -0500114
Brian Osmanb06301e2020-11-06 11:45:36 -0500115 TYPE(Half2x2), TYPE(Half2x3), TYPE(Half2x4),
116 TYPE(Half3x2), TYPE(Half3x3), TYPE(Half3x4),
117 TYPE(Half4x2), TYPE(Half4x3), TYPE(Half4x4),
ethannicholasb3058bd2016-07-01 08:22:01 -0700118
Brian Osmanb06301e2020-11-06 11:45:36 -0500119 TYPE(GenType), TYPE(GenHType), TYPE(GenIType), TYPE(GenUType), TYPE(GenBType),
Brian Osmanc0f2b642020-12-22 13:35:55 -0500120 TYPE(SquareMat), TYPE(SquareHMat), TYPE(Vec),
Brian Osmanb06301e2020-11-06 11:45:36 -0500121 TYPE(GVec), TYPE(GVec2), TYPE(GVec3), TYPE(GVec4),
122 TYPE(HVec), TYPE(IVec), TYPE(UVec), TYPE(SVec), TYPE(USVec),
123 TYPE(ByteVec), TYPE(UByteVec), TYPE(BVec),
124
125 TYPE(FragmentProcessor),
126 };
127
128 const SkSL::Symbol* privateTypes[] = {
Brian Osmanc0f2b642020-12-22 13:35:55 -0500129 TYPE(Float2x3), TYPE(Float2x4),
130 TYPE(Float3x2), TYPE(Float3x4),
131 TYPE(Float4x2), TYPE(Float4x3),
132
133 TYPE(Mat), TYPE(HMat),
134
Brian Osmanb06301e2020-11-06 11:45:36 -0500135 TYPE(Sampler1D), TYPE(Sampler2D), TYPE(Sampler3D),
136 TYPE(SamplerExternalOES),
137 TYPE(SamplerCube),
138 TYPE(Sampler2DRect),
139 TYPE(Sampler1DArray), TYPE(Sampler2DArray), TYPE(SamplerCubeArray),
140 TYPE(SamplerBuffer),
141 TYPE(Sampler2DMS), TYPE(Sampler2DMSArray),
142
143 TYPE(ISampler2D),
144 TYPE(Image2D), TYPE(IImage2D),
145 TYPE(SubpassInput), TYPE(SubpassInputMS),
146
147 TYPE(GSampler1D), TYPE(GSampler2D), TYPE(GSampler3D),
148 TYPE(GSamplerCube),
149 TYPE(GSampler2DRect),
150 TYPE(GSampler1DArray), TYPE(GSampler2DArray), TYPE(GSamplerCubeArray),
151 TYPE(GSamplerBuffer),
152 TYPE(GSampler2DMS), TYPE(GSampler2DMSArray),
153
154 TYPE(Sampler1DShadow), TYPE(Sampler2DShadow), TYPE(SamplerCubeShadow),
155 TYPE(Sampler2DRectShadow),
156 TYPE(Sampler1DArrayShadow), TYPE(Sampler2DArrayShadow), TYPE(SamplerCubeArrayShadow),
157
158 TYPE(GSampler2DArrayShadow), TYPE(GSamplerCubeArrayShadow),
159 TYPE(Sampler),
160 TYPE(Texture2D),
161 };
162
163 for (const SkSL::Symbol* type : rootTypes) {
164 fRootSymbolTable->addWithoutOwnership(type);
165 }
166 for (const SkSL::Symbol* type : privateTypes) {
167 fPrivateSymbolTable->addWithoutOwnership(type);
168 }
169
170#undef TYPE
ethannicholasb3058bd2016-07-01 08:22:01 -0700171
Brian Osman3887a012020-09-30 13:22:27 -0400172 // sk_Caps is "builtin", but all references to it are resolved to Settings, so we don't need to
173 // treat it as builtin (ie, no need to clone it into the Program).
Brian Osmanb06301e2020-11-06 11:45:36 -0500174 fPrivateSymbolTable->add(
175 std::make_unique<Variable>(/*offset=*/-1,
John Stiles586df952020-11-12 18:27:13 -0500176 fIRGenerator->fModifiers->addToPool(Modifiers()),
Brian Osmanb06301e2020-11-06 11:45:36 -0500177 "sk_Caps",
178 fContext->fSkCaps_Type.get(),
179 /*builtin=*/false,
180 Variable::Storage::kGlobal));
Ethan Nicholas3605ace2016-11-21 15:59:48 -0500181
Brian Osman3d87e9f2020-10-08 11:50:22 -0400182 fRootModule = {fRootSymbolTable, /*fIntrinsics=*/nullptr};
Brian Osmanb06301e2020-11-06 11:45:36 -0500183 fPrivateModule = {fPrivateSymbolTable, /*fIntrinsics=*/nullptr};
ethannicholasb3058bd2016-07-01 08:22:01 -0700184}
185
John Stilesdd13dba2020-10-29 10:45:34 -0400186Compiler::~Compiler() {}
ethannicholasb3058bd2016-07-01 08:22:01 -0700187
Brian Osman56269982020-11-20 12:38:07 -0500188const ParsedModule& Compiler::loadGPUModule() {
189 if (!fGPUModule.fSymbols) {
190 fGPUModule = this->parseModule(Program::kFragment_Kind, MODULE_DATA(gpu), fPrivateModule);
191 }
192 return fGPUModule;
193}
194
195const ParsedModule& Compiler::loadFragmentModule() {
196 if (!fFragmentModule.fSymbols) {
197 fFragmentModule = this->parseModule(Program::kFragment_Kind, MODULE_DATA(frag),
198 this->loadGPUModule());
199 }
200 return fFragmentModule;
201}
202
203const ParsedModule& Compiler::loadVertexModule() {
204 if (!fVertexModule.fSymbols) {
205 fVertexModule = this->parseModule(Program::kVertex_Kind, MODULE_DATA(vert),
206 this->loadGPUModule());
207 }
208 return fVertexModule;
209}
210
Brian Osman88cda172020-10-09 12:05:16 -0400211const ParsedModule& Compiler::loadGeometryModule() {
Brian Osman3d87e9f2020-10-08 11:50:22 -0400212 if (!fGeometryModule.fSymbols) {
Brian Osman56269982020-11-20 12:38:07 -0500213 fGeometryModule = this->parseModule(Program::kGeometry_Kind, MODULE_DATA(geom),
214 this->loadGPUModule());
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400215 }
Brian Osman88cda172020-10-09 12:05:16 -0400216 return fGeometryModule;
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400217}
218
Brian Osman88cda172020-10-09 12:05:16 -0400219const ParsedModule& Compiler::loadFPModule() {
Brian Osman3d87e9f2020-10-08 11:50:22 -0400220 if (!fFPModule.fSymbols) {
Brian Osman56269982020-11-20 12:38:07 -0500221 fFPModule = this->parseModule(Program::kFragmentProcessor_Kind, MODULE_DATA(fp),
222 this->loadGPUModule());
Brian Osman8e2ef022020-09-30 13:26:43 -0400223 }
Brian Osman88cda172020-10-09 12:05:16 -0400224 return fFPModule;
Brian Osman8e2ef022020-09-30 13:26:43 -0400225}
226
Brian Osmanb06301e2020-11-06 11:45:36 -0500227const ParsedModule& Compiler::loadPublicModule() {
228 if (!fPublicModule.fSymbols) {
229 fPublicModule = this->parseModule(Program::kGeneric_Kind, MODULE_DATA(public), fRootModule);
230 }
231 return fPublicModule;
232}
233
Brian Osman91946752020-12-21 13:20:40 -0500234const ParsedModule& Compiler::loadRuntimeEffectModule() {
235 if (!fRuntimeEffectModule.fSymbols) {
236 fRuntimeEffectModule = this->parseModule(Program::kRuntimeEffect_Kind, MODULE_DATA(runtime),
237 this->loadPublicModule());
Brian Osmanf1319c32020-10-13 09:34:23 -0400238
Brian Osman91946752020-12-21 13:20:40 -0500239 // Add some aliases to the runtime effect module so that it's friendlier, and more like GLSL
240 fRuntimeEffectModule.fSymbols->addAlias("shader", fContext->fFragmentProcessor_Type.get());
Brian Osmanf1319c32020-10-13 09:34:23 -0400241
Brian Osman91946752020-12-21 13:20:40 -0500242 fRuntimeEffectModule.fSymbols->addAlias("vec2", fContext->fFloat2_Type.get());
243 fRuntimeEffectModule.fSymbols->addAlias("vec3", fContext->fFloat3_Type.get());
244 fRuntimeEffectModule.fSymbols->addAlias("vec4", fContext->fFloat4_Type.get());
Brian Osmanf1319c32020-10-13 09:34:23 -0400245
Brian Osman91946752020-12-21 13:20:40 -0500246 fRuntimeEffectModule.fSymbols->addAlias("bvec2", fContext->fBool2_Type.get());
247 fRuntimeEffectModule.fSymbols->addAlias("bvec3", fContext->fBool3_Type.get());
248 fRuntimeEffectModule.fSymbols->addAlias("bvec4", fContext->fBool4_Type.get());
Brian Osmanf1319c32020-10-13 09:34:23 -0400249
Brian Osman91946752020-12-21 13:20:40 -0500250 fRuntimeEffectModule.fSymbols->addAlias("mat2", fContext->fFloat2x2_Type.get());
251 fRuntimeEffectModule.fSymbols->addAlias("mat3", fContext->fFloat3x3_Type.get());
252 fRuntimeEffectModule.fSymbols->addAlias("mat4", fContext->fFloat4x4_Type.get());
Brian Osmanf1319c32020-10-13 09:34:23 -0400253
Brian Osman91946752020-12-21 13:20:40 -0500254 fRuntimeEffectModule.fSymbols->addAlias("mat2x2", fContext->fFloat2x2_Type.get());
255 fRuntimeEffectModule.fSymbols->addAlias("mat2x3", fContext->fFloat2x3_Type.get());
256 fRuntimeEffectModule.fSymbols->addAlias("mat2x4", fContext->fFloat2x4_Type.get());
Brian Osmanf1319c32020-10-13 09:34:23 -0400257
Brian Osman91946752020-12-21 13:20:40 -0500258 fRuntimeEffectModule.fSymbols->addAlias("mat3x2", fContext->fFloat3x2_Type.get());
259 fRuntimeEffectModule.fSymbols->addAlias("mat3x3", fContext->fFloat3x3_Type.get());
260 fRuntimeEffectModule.fSymbols->addAlias("mat3x4", fContext->fFloat3x4_Type.get());
Brian Osmanf1319c32020-10-13 09:34:23 -0400261
Brian Osman91946752020-12-21 13:20:40 -0500262 fRuntimeEffectModule.fSymbols->addAlias("mat4x2", fContext->fFloat4x2_Type.get());
263 fRuntimeEffectModule.fSymbols->addAlias("mat4x3", fContext->fFloat4x3_Type.get());
264 fRuntimeEffectModule.fSymbols->addAlias("mat4x4", fContext->fFloat4x4_Type.get());
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400265 }
Brian Osman91946752020-12-21 13:20:40 -0500266 return fRuntimeEffectModule;
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400267}
268
Brian Osman88cda172020-10-09 12:05:16 -0400269const ParsedModule& Compiler::loadInterpreterModule() {
Brian Osman3d87e9f2020-10-08 11:50:22 -0400270 if (!fInterpreterModule.fSymbols) {
Brian Osmanb06301e2020-11-06 11:45:36 -0500271 fInterpreterModule = this->parseModule(Program::kGeneric_Kind, MODULE_DATA(interp),
272 this->loadPublicModule());
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400273 }
Brian Osman88cda172020-10-09 12:05:16 -0400274 return fInterpreterModule;
275}
276
277const ParsedModule& Compiler::moduleForProgramKind(Program::Kind kind) {
278 switch (kind) {
Brian Osman91946752020-12-21 13:20:40 -0500279 case Program::kVertex_Kind: return this->loadVertexModule(); break;
280 case Program::kFragment_Kind: return this->loadFragmentModule(); break;
281 case Program::kGeometry_Kind: return this->loadGeometryModule(); break;
282 case Program::kFragmentProcessor_Kind: return this->loadFPModule(); break;
283 case Program::kRuntimeEffect_Kind: return this->loadRuntimeEffectModule(); break;
284 case Program::kGeneric_Kind: return this->loadInterpreterModule(); break;
Brian Osman88cda172020-10-09 12:05:16 -0400285 }
286 SkUNREACHABLE;
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400287}
288
Brian Osman3d87e9f2020-10-08 11:50:22 -0400289LoadedModule Compiler::loadModule(Program::Kind kind,
290 ModuleData data,
291 std::shared_ptr<SymbolTable> base) {
Brian Osman3d87e9f2020-10-08 11:50:22 -0400292 if (!base) {
Brian Osmanb06301e2020-11-06 11:45:36 -0500293 // NOTE: This is a workaround. The only time 'base' is null is when dehydrating includes.
294 // In that case, skslc doesn't know which module it's preparing, nor what the correct base
295 // module is. We can't use 'Root', because many GPU intrinsics reference private types,
296 // like samplers or textures. Today, 'Private' does contain the union of all known types,
297 // so this is safe. If we ever have types that only exist in 'Public' (for example), this
298 // logic needs to be smarter (by choosing the correct base for the module we're compiling).
299 base = fPrivateSymbolTable;
Brian Osman3d87e9f2020-10-08 11:50:22 -0400300 }
301
302#if defined(SKSL_STANDALONE)
303 SkASSERT(data.fPath);
304 std::ifstream in(data.fPath);
Brian Osmane498b3c2020-09-23 14:42:11 -0400305 std::unique_ptr<String> text = std::make_unique<String>(std::istreambuf_iterator<char>(in),
306 std::istreambuf_iterator<char>());
Ethan Nicholasb33fa3f2020-08-06 13:00:19 -0400307 if (in.rdstate()) {
Brian Osman3d87e9f2020-10-08 11:50:22 -0400308 printf("error reading %s\n", data.fPath);
Ethan Nicholasb33fa3f2020-08-06 13:00:19 -0400309 abort();
310 }
Brian Osmane498b3c2020-09-23 14:42:11 -0400311 const String* source = fRootSymbolTable->takeOwnershipOfString(std::move(text));
Brian Osman88cda172020-10-09 12:05:16 -0400312 AutoSource as(this, source);
Ethan Nicholas8da1e652019-05-24 11:01:59 -0400313 Program::Settings settings;
John Stiles881a10c2020-09-19 10:13:24 -0400314 SkASSERT(fIRGenerator->fCanInline);
315 fIRGenerator->fCanInline = false;
Brian Osman88cda172020-10-09 12:05:16 -0400316 ParsedModule baseModule = {base, /*fIntrinsics=*/nullptr};
Brian Osmand7e76592020-11-02 12:26:22 -0500317 IRGenerator::IRBundle ir =
Brian Osman0006ad02020-11-18 15:38:39 -0500318 fIRGenerator->convertProgram(kind, &settings, baseModule,
Brian Osmand7e76592020-11-02 12:26:22 -0500319 /*isBuiltinCode=*/true, source->c_str(), source->length(),
320 /*externalValues=*/nullptr);
Brian Osman133724c2020-10-28 14:14:39 -0400321 SkASSERT(ir.fSharedElements.empty());
Brian Osman0006ad02020-11-18 15:38:39 -0500322 LoadedModule module = { kind, std::move(ir.fSymbolTable), std::move(ir.fElements) };
John Stiles881a10c2020-09-19 10:13:24 -0400323 fIRGenerator->fCanInline = true;
Ethan Nicholas8da1e652019-05-24 11:01:59 -0400324 if (this->fErrorCount) {
325 printf("Unexpected errors: %s\n", this->fErrorText.c_str());
Brian Osman3d87e9f2020-10-08 11:50:22 -0400326 SkDEBUGFAILF("%s %s\n", data.fPath, this->fErrorText.c_str());
Ethan Nicholas8da1e652019-05-24 11:01:59 -0400327 }
Brian Osman88cda172020-10-09 12:05:16 -0400328 fModifiers.push_back(std::move(ir.fModifiers));
Brian Osman3d87e9f2020-10-08 11:50:22 -0400329#else
330 SkASSERT(data.fData && (data.fSize != 0));
331 Rehydrator rehydrator(fContext.get(), fIRGenerator->fModifiers.get(), base, this,
332 data.fData, data.fSize);
Brian Osman0006ad02020-11-18 15:38:39 -0500333 LoadedModule module = { kind, rehydrator.symbolTable(), rehydrator.elements() };
Brian Osman3d87e9f2020-10-08 11:50:22 -0400334 fModifiers.push_back(fIRGenerator->releaseModifiers());
335#endif
336
337 return module;
338}
339
340ParsedModule Compiler::parseModule(Program::Kind kind, ModuleData data, const ParsedModule& base) {
Brian Osman0006ad02020-11-18 15:38:39 -0500341 LoadedModule module = this->loadModule(kind, data, base.fSymbols);
342 this->optimize(module);
Brian Osman3d87e9f2020-10-08 11:50:22 -0400343
344 // For modules that just declare (but don't define) intrinsic functions, there will be no new
345 // program elements. In that case, we can share our parent's intrinsic map:
Brian Osman0006ad02020-11-18 15:38:39 -0500346 if (module.fElements.empty()) {
347 return {module.fSymbols, base.fIntrinsics};
Brian Osman3d87e9f2020-10-08 11:50:22 -0400348 }
349
350 auto intrinsics = std::make_shared<IRIntrinsicMap>(base.fIntrinsics.get());
351
352 // Now, transfer all of the program elements to an intrinsic map. This maps certain types of
353 // global objects to the declaring ProgramElement.
Brian Osman0006ad02020-11-18 15:38:39 -0500354 for (std::unique_ptr<ProgramElement>& element : module.fElements) {
Brian Osman3d87e9f2020-10-08 11:50:22 -0400355 switch (element->kind()) {
356 case ProgramElement::Kind::kFunction: {
357 const FunctionDefinition& f = element->as<FunctionDefinition>();
Ethan Nicholas0a5d0962020-10-14 13:33:18 -0400358 SkASSERT(f.declaration().isBuiltin());
359 intrinsics->insertOrDie(f.declaration().description(), std::move(element));
Brian Osman3d87e9f2020-10-08 11:50:22 -0400360 break;
361 }
John Stiles569249b2020-11-03 12:18:22 -0500362 case ProgramElement::Kind::kFunctionPrototype: {
363 // These are already in the symbol table.
364 break;
365 }
Brian Osman3d87e9f2020-10-08 11:50:22 -0400366 case ProgramElement::Kind::kEnum: {
367 const Enum& e = element->as<Enum>();
368 SkASSERT(e.isBuiltin());
369 intrinsics->insertOrDie(e.typeName(), std::move(element));
370 break;
371 }
372 case ProgramElement::Kind::kGlobalVar: {
Ethan Nicholasc51f33e2020-10-13 13:49:44 -0400373 const GlobalVarDeclaration& global = element->as<GlobalVarDeclaration>();
374 const Variable& var = global.declaration()->as<VarDeclaration>().var();
375 SkASSERT(var.isBuiltin());
376 intrinsics->insertOrDie(var.name(), std::move(element));
Brian Osman3d87e9f2020-10-08 11:50:22 -0400377 break;
378 }
379 case ProgramElement::Kind::kInterfaceBlock: {
Ethan Nicholaseaf47882020-10-15 10:10:08 -0400380 const Variable& var = element->as<InterfaceBlock>().variable();
381 SkASSERT(var.isBuiltin());
382 intrinsics->insertOrDie(var.name(), std::move(element));
Brian Osman3d87e9f2020-10-08 11:50:22 -0400383 break;
384 }
385 default:
386 printf("Unsupported element: %s\n", element->description().c_str());
387 SkASSERT(false);
388 break;
389 }
390 }
391
Brian Osman0006ad02020-11-18 15:38:39 -0500392 return {module.fSymbols, std::move(intrinsics)};
Ethan Nicholas8da1e652019-05-24 11:01:59 -0400393}
394
ethannicholas22f939e2016-10-13 13:25:34 -0700395// add the definition created by assigning to the lvalue to the definition set
Ethan Nicholas86a43402017-01-19 13:32:00 -0500396void Compiler::addDefinition(const Expression* lvalue, std::unique_ptr<Expression>* expr,
397 DefinitionMap* definitions) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400398 switch (lvalue->kind()) {
399 case Expression::Kind::kVariableReference: {
Ethan Nicholas78686922020-10-08 06:46:27 -0400400 const Variable& var = *lvalue->as<VariableReference>().variable();
Ethan Nicholas453f67f2020-10-09 10:43:45 -0400401 if (var.storage() == Variable::Storage::kLocal) {
John Stiles796cdb72020-10-08 12:06:53 -0400402 definitions->set(&var, expr);
ethannicholas22f939e2016-10-13 13:25:34 -0700403 }
404 break;
405 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400406 case Expression::Kind::kSwizzle:
ethannicholas22f939e2016-10-13 13:25:34 -0700407 // We consider the variable written to as long as at least some of its components have
408 // been written to. This will lead to some false negatives (we won't catch it if you
409 // write to foo.x and then read foo.y), but being stricter could lead to false positives
Mike Klein6ad99092016-10-26 10:35:22 -0400410 // (we write to foo.x, and then pass foo to a function which happens to only read foo.x,
411 // 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 -0700412 // more complicated whole-program analysis. This is probably good enough.
Ethan Nicholas6b4d5812020-10-12 16:11:51 -0400413 this->addDefinition(lvalue->as<Swizzle>().base().get(),
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400414 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
ethannicholas22f939e2016-10-13 13:25:34 -0700415 definitions);
416 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400417 case Expression::Kind::kIndex:
ethannicholas22f939e2016-10-13 13:25:34 -0700418 // see comments in Swizzle
Ethan Nicholas2a4952d2020-10-08 15:35:56 -0400419 this->addDefinition(lvalue->as<IndexExpression>().base().get(),
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400420 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
ethannicholas22f939e2016-10-13 13:25:34 -0700421 definitions);
422 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400423 case Expression::Kind::kFieldAccess:
ethannicholas22f939e2016-10-13 13:25:34 -0700424 // see comments in Swizzle
Ethan Nicholas7a95b202020-10-09 11:55:40 -0400425 this->addDefinition(lvalue->as<FieldAccess>().base().get(),
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400426 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
ethannicholas22f939e2016-10-13 13:25:34 -0700427 definitions);
428 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400429 case Expression::Kind::kTernary:
Ethan Nicholasa583b812018-01-18 13:32:11 -0500430 // To simplify analysis, we just pretend that we write to both sides of the ternary.
431 // This allows for false positives (meaning we fail to detect that a variable might not
432 // have been assigned), but is preferable to false negatives.
Ethan Nicholasdd218162020-10-08 05:48:01 -0400433 this->addDefinition(lvalue->as<TernaryExpression>().ifTrue().get(),
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400434 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
Ethan Nicholasa583b812018-01-18 13:32:11 -0500435 definitions);
Ethan Nicholasdd218162020-10-08 05:48:01 -0400436 this->addDefinition(lvalue->as<TernaryExpression>().ifFalse().get(),
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400437 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
Ethan Nicholasa583b812018-01-18 13:32:11 -0500438 definitions);
439 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400440 case Expression::Kind::kExternalValue:
Ethan Nicholas91164d12019-05-15 15:29:54 -0400441 break;
ethannicholas22f939e2016-10-13 13:25:34 -0700442 default:
443 // not an lvalue, can't happen
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400444 SkASSERT(false);
ethannicholas22f939e2016-10-13 13:25:34 -0700445 }
446}
447
448// add local variables defined by this node to the set
John Stiles796cdb72020-10-08 12:06:53 -0400449void Compiler::addDefinitions(const BasicBlock::Node& node, DefinitionMap* definitions) {
John Stiles70025e52020-09-28 16:08:58 -0400450 if (node.isExpression()) {
451 Expression* expr = node.expression()->get();
452 switch (expr->kind()) {
453 case Expression::Kind::kBinary: {
454 BinaryExpression* b = &expr->as<BinaryExpression>();
455 if (b->getOperator() == Token::Kind::TK_EQ) {
John Stiles2d4f9592020-10-30 10:29:12 -0400456 this->addDefinition(b->left().get(), &b->right(), definitions);
John Stiles70025e52020-09-28 16:08:58 -0400457 } else if (Compiler::IsAssignment(b->getOperator())) {
458 this->addDefinition(
John Stiles2d4f9592020-10-30 10:29:12 -0400459 b->left().get(),
John Stiles70025e52020-09-28 16:08:58 -0400460 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
461 definitions);
Ethan Nicholas86a43402017-01-19 13:32:00 -0500462
ethannicholas22f939e2016-10-13 13:25:34 -0700463 }
John Stiles70025e52020-09-28 16:08:58 -0400464 break;
ethannicholas22f939e2016-10-13 13:25:34 -0700465 }
John Stiles70025e52020-09-28 16:08:58 -0400466 case Expression::Kind::kFunctionCall: {
467 const FunctionCall& c = expr->as<FunctionCall>();
Brian Osman5bf3e202020-10-13 10:34:18 -0400468 const std::vector<const Variable*>& parameters = c.function().parameters();
Ethan Nicholased84b732020-10-08 11:45:44 -0400469 for (size_t i = 0; i < parameters.size(); ++i) {
470 if (parameters[i]->modifiers().fFlags & Modifiers::kOut_Flag) {
John Stiles70025e52020-09-28 16:08:58 -0400471 this->addDefinition(
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400472 c.arguments()[i].get(),
John Stiles70025e52020-09-28 16:08:58 -0400473 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
474 definitions);
475 }
476 }
477 break;
478 }
479 case Expression::Kind::kPrefix: {
480 const PrefixExpression* p = &expr->as<PrefixExpression>();
Ethan Nicholas444ccc62020-10-09 10:16:22 -0400481 if (p->getOperator() == Token::Kind::TK_MINUSMINUS ||
482 p->getOperator() == Token::Kind::TK_PLUSPLUS) {
John Stiles70025e52020-09-28 16:08:58 -0400483 this->addDefinition(
Ethan Nicholas444ccc62020-10-09 10:16:22 -0400484 p->operand().get(),
John Stiles70025e52020-09-28 16:08:58 -0400485 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
486 definitions);
487 }
488 break;
489 }
490 case Expression::Kind::kPostfix: {
491 const PostfixExpression* p = &expr->as<PostfixExpression>();
Ethan Nicholas444ccc62020-10-09 10:16:22 -0400492 if (p->getOperator() == Token::Kind::TK_MINUSMINUS ||
493 p->getOperator() == Token::Kind::TK_PLUSPLUS) {
John Stiles70025e52020-09-28 16:08:58 -0400494 this->addDefinition(
Ethan Nicholas444ccc62020-10-09 10:16:22 -0400495 p->operand().get(),
John Stiles70025e52020-09-28 16:08:58 -0400496 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
497 definitions);
498 }
499 break;
500 }
501 case Expression::Kind::kVariableReference: {
502 const VariableReference* v = &expr->as<VariableReference>();
Ethan Nicholas453f67f2020-10-09 10:43:45 -0400503 if (v->refKind() != VariableReference::RefKind::kRead) {
John Stiles70025e52020-09-28 16:08:58 -0400504 this->addDefinition(
505 v,
506 (std::unique_ptr<Expression>*) &fContext->fDefined_Expression,
507 definitions);
508 }
509 break;
510 }
511 default:
512 break;
ethannicholas22f939e2016-10-13 13:25:34 -0700513 }
John Stiles70025e52020-09-28 16:08:58 -0400514 } else if (node.isStatement()) {
515 Statement* stmt = node.statement()->get();
516 if (stmt->is<VarDeclaration>()) {
517 VarDeclaration& vd = stmt->as<VarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -0400518 if (vd.value()) {
519 definitions->set(&vd.var(), &vd.value());
ethannicholas22f939e2016-10-13 13:25:34 -0700520 }
ethannicholas22f939e2016-10-13 13:25:34 -0700521 }
522 }
523}
524
John Stilese6150002020-10-05 12:03:53 -0400525void Compiler::scanCFG(CFG* cfg, BlockId blockId, SkBitSet* processedSet) {
ethannicholas22f939e2016-10-13 13:25:34 -0700526 BasicBlock& block = cfg->fBlocks[blockId];
527
528 // compute definitions after this block
Ethan Nicholas86a43402017-01-19 13:32:00 -0500529 DefinitionMap after = block.fBefore;
ethannicholas22f939e2016-10-13 13:25:34 -0700530 for (const BasicBlock::Node& n : block.fNodes) {
531 this->addDefinitions(n, &after);
532 }
533
534 // propagate definitions to exits
535 for (BlockId exitId : block.fExits) {
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400536 if (exitId == blockId) {
537 continue;
538 }
ethannicholas22f939e2016-10-13 13:25:34 -0700539 BasicBlock& exit = cfg->fBlocks[exitId];
John Stiles65b48272020-12-22 17:18:34 -0500540 for (const auto& [var, e1] : after) {
John Stiles796cdb72020-10-08 12:06:53 -0400541 std::unique_ptr<Expression>** exitDef = exit.fBefore.find(var);
542 if (!exitDef) {
John Stilese6150002020-10-05 12:03:53 -0400543 // exit has no definition for it, just copy it and reprocess exit block
544 processedSet->reset(exitId);
John Stiles796cdb72020-10-08 12:06:53 -0400545 exit.fBefore[var] = e1;
ethannicholas22f939e2016-10-13 13:25:34 -0700546 } else {
Ethan Nicholas86a43402017-01-19 13:32:00 -0500547 // exit has a (possibly different) value already defined
John Stiles796cdb72020-10-08 12:06:53 -0400548 std::unique_ptr<Expression>* e2 = *exitDef;
ethannicholas22f939e2016-10-13 13:25:34 -0700549 if (e1 != e2) {
John Stilese6150002020-10-05 12:03:53 -0400550 // definition has changed, merge and reprocess the exit block
551 processedSet->reset(exitId);
Ethan Nicholasaf197692017-02-27 13:26:45 -0500552 if (e1 && e2) {
John Stiles796cdb72020-10-08 12:06:53 -0400553 *exitDef = (std::unique_ptr<Expression>*)&fContext->fDefined_Expression;
Ethan Nicholasaf197692017-02-27 13:26:45 -0500554 } else {
John Stiles796cdb72020-10-08 12:06:53 -0400555 *exitDef = nullptr;
Ethan Nicholasaf197692017-02-27 13:26:45 -0500556 }
ethannicholas22f939e2016-10-13 13:25:34 -0700557 }
558 }
John Stiles65b48272020-12-22 17:18:34 -0500559 }
ethannicholas22f939e2016-10-13 13:25:34 -0700560 }
561}
562
563// returns a map which maps all local variables in the function to null, indicating that their value
564// is initially unknown
Ethan Nicholas86a43402017-01-19 13:32:00 -0500565static DefinitionMap compute_start_state(const CFG& cfg) {
566 DefinitionMap result;
Mike Klein6ad99092016-10-26 10:35:22 -0400567 for (const auto& block : cfg.fBlocks) {
568 for (const auto& node : block.fNodes) {
John Stiles70025e52020-09-28 16:08:58 -0400569 if (node.isStatement()) {
Ethan Nicholascb670962017-04-20 19:31:52 -0400570 const Statement* s = node.statement()->get();
Brian Osmanc0213602020-10-06 14:43:32 -0400571 if (s->is<VarDeclaration>()) {
Ethan Nicholasc51f33e2020-10-13 13:49:44 -0400572 result[&s->as<VarDeclaration>().var()] = nullptr;
ethannicholas22f939e2016-10-13 13:25:34 -0700573 }
574 }
575 }
576 }
577 return result;
578}
579
Ethan Nicholascb670962017-04-20 19:31:52 -0400580/**
581 * Returns true if assigning to this lvalue has no effect.
582 */
Brian Osman010ce6a2020-10-19 16:34:10 -0400583static bool is_dead(const Expression& lvalue, ProgramUsage* usage) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400584 switch (lvalue.kind()) {
585 case Expression::Kind::kVariableReference:
Brian Osman010ce6a2020-10-19 16:34:10 -0400586 return usage->isDead(*lvalue.as<VariableReference>().variable());
Ethan Nicholase6592142020-09-08 10:22:09 -0400587 case Expression::Kind::kSwizzle:
Brian Osman010ce6a2020-10-19 16:34:10 -0400588 return is_dead(*lvalue.as<Swizzle>().base(), usage);
Ethan Nicholase6592142020-09-08 10:22:09 -0400589 case Expression::Kind::kFieldAccess:
Brian Osman010ce6a2020-10-19 16:34:10 -0400590 return is_dead(*lvalue.as<FieldAccess>().base(), usage);
Ethan Nicholase6592142020-09-08 10:22:09 -0400591 case Expression::Kind::kIndex: {
John Stilesa5a97b42020-08-18 11:19:07 -0400592 const IndexExpression& idx = lvalue.as<IndexExpression>();
Brian Osman010ce6a2020-10-19 16:34:10 -0400593 return is_dead(*idx.base(), usage) &&
Ethan Nicholas2a4952d2020-10-08 15:35:56 -0400594 !idx.index()->hasProperty(Expression::Property::kSideEffects);
Ethan Nicholascb670962017-04-20 19:31:52 -0400595 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400596 case Expression::Kind::kTernary: {
John Stilesa5a97b42020-08-18 11:19:07 -0400597 const TernaryExpression& t = lvalue.as<TernaryExpression>();
Brian Osman010ce6a2020-10-19 16:34:10 -0400598 return !t.test()->hasSideEffects() &&
599 is_dead(*t.ifTrue(), usage) &&
600 is_dead(*t.ifFalse(), usage);
Ethan Nicholasa583b812018-01-18 13:32:11 -0500601 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400602 case Expression::Kind::kExternalValue:
Ethan Nicholas91164d12019-05-15 15:29:54 -0400603 return false;
Ethan Nicholascb670962017-04-20 19:31:52 -0400604 default:
Ethan Nicholas2a099da2020-01-02 14:40:54 -0500605#ifdef SK_DEBUG
Ethan Nicholascb670962017-04-20 19:31:52 -0400606 ABORT("invalid lvalue: %s\n", lvalue.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -0500607#endif
608 return false;
Ethan Nicholascb670962017-04-20 19:31:52 -0400609 }
610}
ethannicholas22f939e2016-10-13 13:25:34 -0700611
Ethan Nicholascb670962017-04-20 19:31:52 -0400612/**
613 * Returns true if this is an assignment which can be collapsed down to just the right hand side due
614 * to a dead target and lack of side effects on the left hand side.
615 */
Brian Osman010ce6a2020-10-19 16:34:10 -0400616static bool dead_assignment(const BinaryExpression& b, ProgramUsage* usage) {
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400617 if (!Compiler::IsAssignment(b.getOperator())) {
Ethan Nicholascb670962017-04-20 19:31:52 -0400618 return false;
619 }
John Stiles2d4f9592020-10-30 10:29:12 -0400620 return is_dead(*b.left(), usage);
Ethan Nicholascb670962017-04-20 19:31:52 -0400621}
622
623void Compiler::computeDataFlow(CFG* cfg) {
624 cfg->fBlocks[cfg->fStart].fBefore = compute_start_state(*cfg);
John Stilese6150002020-10-05 12:03:53 -0400625
626 // We set bits in the "processed" set after a block has been scanned.
627 SkBitSet processedSet(cfg->fBlocks.size());
628 while (SkBitSet::OptionalIndex blockId = processedSet.findFirstUnset()) {
629 processedSet.set(*blockId);
630 this->scanCFG(cfg, *blockId, &processedSet);
ethannicholas22f939e2016-10-13 13:25:34 -0700631 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400632}
633
634/**
635 * Attempts to replace the expression pointed to by iter with a new one (in both the CFG and the
636 * IR). If the expression can be cleanly removed, returns true and updates the iterator to point to
637 * the newly-inserted element. Otherwise updates only the IR and returns false (and the CFG will
638 * need to be regenerated).
639 */
John Stilesafbf8992020-08-18 10:08:21 -0400640static bool try_replace_expression(BasicBlock* b,
641 std::vector<BasicBlock::Node>::iterator* iter,
642 std::unique_ptr<Expression>* newExpression) {
Ethan Nicholascb670962017-04-20 19:31:52 -0400643 std::unique_ptr<Expression>* target = (*iter)->expression();
644 if (!b->tryRemoveExpression(iter)) {
645 *target = std::move(*newExpression);
646 return false;
647 }
648 *target = std::move(*newExpression);
649 return b->tryInsertExpression(iter, target);
650}
651
652/**
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400653 * Returns true if the expression is a constant numeric literal with the specified value, or a
654 * constant vector with all elements equal to the specified value.
Ethan Nicholascb670962017-04-20 19:31:52 -0400655 */
Ethan Nicholasa3f22f12020-10-01 12:13:17 -0400656template <typename T = SKSL_FLOAT>
John Stiles9d944232020-08-19 09:56:49 -0400657static bool is_constant(const Expression& expr, T value) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400658 switch (expr.kind()) {
659 case Expression::Kind::kIntLiteral:
Ethan Nicholase96cdd12020-09-28 16:27:18 -0400660 return expr.as<IntLiteral>().value() == value;
John Stiles9d944232020-08-19 09:56:49 -0400661
Ethan Nicholase6592142020-09-08 10:22:09 -0400662 case Expression::Kind::kFloatLiteral:
Ethan Nicholasa3f22f12020-10-01 12:13:17 -0400663 return expr.as<FloatLiteral>().value() == value;
John Stiles9d944232020-08-19 09:56:49 -0400664
Ethan Nicholase6592142020-09-08 10:22:09 -0400665 case Expression::Kind::kConstructor: {
John Stiles9d944232020-08-19 09:56:49 -0400666 const Constructor& constructor = expr.as<Constructor>();
667 if (constructor.isCompileTimeConstant()) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400668 const Type& constructorType = constructor.type();
Ethan Nicholas30d30222020-09-11 12:27:26 -0400669 switch (constructorType.typeKind()) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400670 case Type::TypeKind::kVector:
John Stilesbc75ebb2020-11-24 12:04:47 -0500671 if (constructor.componentType().isFloat()) {
672 for (int i = 0; i < constructorType.columns(); ++i) {
John Stiles9d944232020-08-19 09:56:49 -0400673 if (constructor.getFVecComponent(i) != value) {
674 return false;
675 }
John Stilesbc75ebb2020-11-24 12:04:47 -0500676 }
677 return true;
678 } else if (constructor.componentType().isInteger()) {
679 for (int i = 0; i < constructorType.columns(); ++i) {
John Stiles9d944232020-08-19 09:56:49 -0400680 if (constructor.getIVecComponent(i) != value) {
681 return false;
682 }
683 }
John Stilesbc75ebb2020-11-24 12:04:47 -0500684 return true;
Ethan Nicholasd188c182019-06-10 15:55:38 -0400685 }
John Stilesbc75ebb2020-11-24 12:04:47 -0500686 // Other types (e.g. boolean) might occur, but aren't supported here.
687 return false;
John Stiles9d944232020-08-19 09:56:49 -0400688
Ethan Nicholase6592142020-09-08 10:22:09 -0400689 case Type::TypeKind::kScalar:
Ethan Nicholasf70f0442020-09-29 12:41:35 -0400690 SkASSERT(constructor.arguments().size() == 1);
691 return is_constant<T>(*constructor.arguments()[0], value);
John Stiles9d944232020-08-19 09:56:49 -0400692
693 default:
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400694 return false;
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400695 }
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400696 }
697 return false;
698 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400699 default:
700 return false;
701 }
702}
703
704/**
705 * Collapses the binary expression pointed to by iter down to just the right side (in both the IR
706 * and CFG structures).
707 */
John Stilesafbf8992020-08-18 10:08:21 -0400708static void delete_left(BasicBlock* b,
709 std::vector<BasicBlock::Node>::iterator* iter,
Ethan Nicholascdeae8c2020-10-22 14:39:46 -0400710 Compiler::OptimizationContext* optimizationContext) {
711 optimizationContext->fUpdated = true;
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400712 std::unique_ptr<Expression>* target = (*iter)->expression();
John Stilesa5a97b42020-08-18 11:19:07 -0400713 BinaryExpression& bin = (*target)->as<BinaryExpression>();
John Stiles2d4f9592020-10-30 10:29:12 -0400714 Expression& left = *bin.left();
715 std::unique_ptr<Expression>& rightPointer = bin.right();
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400716 SkASSERT(!left.hasSideEffects());
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400717 bool result;
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400718 if (bin.getOperator() == Token::Kind::TK_EQ) {
719 result = b->tryRemoveLValueBefore(iter, &left);
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400720 } else {
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400721 result = b->tryRemoveExpressionBefore(iter, &left);
Ethan Nicholascb670962017-04-20 19:31:52 -0400722 }
Brian Osman010ce6a2020-10-19 16:34:10 -0400723 // Remove references within LHS.
724 optimizationContext->fUsage->remove(&left);
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400725 *target = std::move(rightPointer);
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400726 if (!result) {
Ethan Nicholascdeae8c2020-10-22 14:39:46 -0400727 optimizationContext->fNeedsRescan = true;
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400728 return;
729 }
730 if (*iter == b->fNodes.begin()) {
Ethan Nicholascdeae8c2020-10-22 14:39:46 -0400731 optimizationContext->fNeedsRescan = true;
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400732 return;
733 }
734 --(*iter);
John Stiles70025e52020-09-28 16:08:58 -0400735 if (!(*iter)->isExpression() || (*iter)->expression() != &rightPointer) {
Ethan Nicholascdeae8c2020-10-22 14:39:46 -0400736 optimizationContext->fNeedsRescan = true;
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400737 return;
738 }
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400739 *iter = b->fNodes.erase(*iter);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400740 SkASSERT((*iter)->expression() == target);
Ethan Nicholascb670962017-04-20 19:31:52 -0400741}
742
743/**
744 * Collapses the binary expression pointed to by iter down to just the left side (in both the IR and
745 * CFG structures).
746 */
John Stilesafbf8992020-08-18 10:08:21 -0400747static void delete_right(BasicBlock* b,
748 std::vector<BasicBlock::Node>::iterator* iter,
Ethan Nicholascdeae8c2020-10-22 14:39:46 -0400749 Compiler::OptimizationContext* optimizationContext) {
750 optimizationContext->fUpdated = true;
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400751 std::unique_ptr<Expression>* target = (*iter)->expression();
John Stilesa5a97b42020-08-18 11:19:07 -0400752 BinaryExpression& bin = (*target)->as<BinaryExpression>();
John Stiles2d4f9592020-10-30 10:29:12 -0400753 std::unique_ptr<Expression>& leftPointer = bin.left();
754 Expression& right = *bin.right();
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400755 SkASSERT(!right.hasSideEffects());
Brian Osman010ce6a2020-10-19 16:34:10 -0400756 // Remove references within RHS.
757 optimizationContext->fUsage->remove(&right);
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400758 if (!b->tryRemoveExpressionBefore(iter, &right)) {
759 *target = std::move(leftPointer);
Ethan Nicholascdeae8c2020-10-22 14:39:46 -0400760 optimizationContext->fNeedsRescan = true;
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400761 return;
Ethan Nicholascb670962017-04-20 19:31:52 -0400762 }
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400763 *target = std::move(leftPointer);
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400764 if (*iter == b->fNodes.begin()) {
Ethan Nicholascdeae8c2020-10-22 14:39:46 -0400765 optimizationContext->fNeedsRescan = true;
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400766 return;
767 }
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400768 --(*iter);
John Stiles70025e52020-09-28 16:08:58 -0400769 if ((!(*iter)->isExpression() || (*iter)->expression() != &leftPointer)) {
Ethan Nicholascdeae8c2020-10-22 14:39:46 -0400770 optimizationContext->fNeedsRescan = true;
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400771 return;
772 }
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400773 *iter = b->fNodes.erase(*iter);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400774 SkASSERT((*iter)->expression() == target);
Ethan Nicholascb670962017-04-20 19:31:52 -0400775}
776
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400777/**
778 * Constructs the specified type using a single argument.
779 */
Ethan Nicholas30d30222020-09-11 12:27:26 -0400780static std::unique_ptr<Expression> construct(const Type* type, std::unique_ptr<Expression> v) {
John Stiles8e3b6be2020-10-13 11:14:08 -0400781 ExpressionArray args;
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400782 args.push_back(std::move(v));
Ethan Nicholase6592142020-09-08 10:22:09 -0400783 std::unique_ptr<Expression> result = std::make_unique<Constructor>(-1, type, std::move(args));
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400784 return result;
785}
786
787/**
788 * Used in the implementations of vectorize_left and vectorize_right. Given a vector type and an
789 * expression x, deletes the expression pointed to by iter and replaces it with <type>(x).
790 */
791static void vectorize(BasicBlock* b,
792 std::vector<BasicBlock::Node>::iterator* iter,
793 const Type& type,
794 std::unique_ptr<Expression>* otherExpression,
Ethan Nicholascdeae8c2020-10-22 14:39:46 -0400795 Compiler::OptimizationContext* optimizationContext) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400796 SkASSERT((*(*iter)->expression())->kind() == Expression::Kind::kBinary);
John Stiles9aeed132020-11-24 17:36:06 -0500797 SkASSERT(type.isVector());
798 SkASSERT((*otherExpression)->type().isScalar());
Ethan Nicholascdeae8c2020-10-22 14:39:46 -0400799 optimizationContext->fUpdated = true;
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400800 std::unique_ptr<Expression>* target = (*iter)->expression();
801 if (!b->tryRemoveExpression(iter)) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400802 *target = construct(&type, std::move(*otherExpression));
Ethan Nicholascdeae8c2020-10-22 14:39:46 -0400803 optimizationContext->fNeedsRescan = true;
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400804 } else {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400805 *target = construct(&type, std::move(*otherExpression));
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400806 if (!b->tryInsertExpression(iter, target)) {
Ethan Nicholascdeae8c2020-10-22 14:39:46 -0400807 optimizationContext->fNeedsRescan = true;
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400808 }
809 }
810}
811
812/**
813 * Given a binary expression of the form x <op> vec<n>(y), deletes the right side and vectorizes the
814 * left to yield vec<n>(x).
815 */
816static void vectorize_left(BasicBlock* b,
817 std::vector<BasicBlock::Node>::iterator* iter,
Ethan Nicholascdeae8c2020-10-22 14:39:46 -0400818 Compiler::OptimizationContext* optimizationContext) {
John Stilesa5a97b42020-08-18 11:19:07 -0400819 BinaryExpression& bin = (*(*iter)->expression())->as<BinaryExpression>();
Brian Osman010ce6a2020-10-19 16:34:10 -0400820 // Remove references within RHS. Vectorization of LHS doesn't change reference counts.
John Stiles2d4f9592020-10-30 10:29:12 -0400821 optimizationContext->fUsage->remove(bin.right().get());
822 vectorize(b, iter, bin.right()->type(), &bin.left(), optimizationContext);
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400823}
824
825/**
826 * Given a binary expression of the form vec<n>(x) <op> y, deletes the left side and vectorizes the
827 * right to yield vec<n>(y).
828 */
829static void vectorize_right(BasicBlock* b,
830 std::vector<BasicBlock::Node>::iterator* iter,
Ethan Nicholascdeae8c2020-10-22 14:39:46 -0400831 Compiler::OptimizationContext* optimizationContext) {
John Stilesa5a97b42020-08-18 11:19:07 -0400832 BinaryExpression& bin = (*(*iter)->expression())->as<BinaryExpression>();
Brian Osman010ce6a2020-10-19 16:34:10 -0400833 // Remove references within LHS. Vectorization of RHS doesn't change reference counts.
John Stiles2d4f9592020-10-30 10:29:12 -0400834 optimizationContext->fUsage->remove(bin.left().get());
835 vectorize(b, iter, bin.left()->type(), &bin.right(), optimizationContext);
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400836}
837
838// Mark that an expression which we were writing to is no longer being written to
John Stilesa5a97b42020-08-18 11:19:07 -0400839static void clear_write(Expression& expr) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400840 switch (expr.kind()) {
841 case Expression::Kind::kVariableReference: {
Ethan Nicholas453f67f2020-10-09 10:43:45 -0400842 expr.as<VariableReference>().setRefKind(VariableReference::RefKind::kRead);
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400843 break;
844 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400845 case Expression::Kind::kFieldAccess:
Ethan Nicholas7a95b202020-10-09 11:55:40 -0400846 clear_write(*expr.as<FieldAccess>().base());
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400847 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400848 case Expression::Kind::kSwizzle:
Ethan Nicholas6b4d5812020-10-12 16:11:51 -0400849 clear_write(*expr.as<Swizzle>().base());
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400850 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400851 case Expression::Kind::kIndex:
Ethan Nicholas2a4952d2020-10-08 15:35:56 -0400852 clear_write(*expr.as<IndexExpression>().base());
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400853 break;
854 default:
855 ABORT("shouldn't be writing to this kind of expression\n");
856 break;
857 }
858}
859
Ethan Nicholascb670962017-04-20 19:31:52 -0400860void Compiler::simplifyExpression(DefinitionMap& definitions,
861 BasicBlock& b,
862 std::vector<BasicBlock::Node>::iterator* iter,
Ethan Nicholascdeae8c2020-10-22 14:39:46 -0400863 OptimizationContext* optimizationContext) {
Ethan Nicholascb670962017-04-20 19:31:52 -0400864 Expression* expr = (*iter)->expression()->get();
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400865 SkASSERT(expr);
John Stiles108bbe22020-11-18 11:10:38 -0500866
Ethan Nicholascb670962017-04-20 19:31:52 -0400867 if ((*iter)->fConstantPropagation) {
Ethan Nicholascdeae8c2020-10-22 14:39:46 -0400868 std::unique_ptr<Expression> optimized = expr->constantPropagate(*fIRGenerator,
869 definitions);
Ethan Nicholascb670962017-04-20 19:31:52 -0400870 if (optimized) {
Ethan Nicholascdeae8c2020-10-22 14:39:46 -0400871 optimizationContext->fUpdated = true;
Ethan Nicholas30d30222020-09-11 12:27:26 -0400872 optimized = fIRGenerator->coerce(std::move(optimized), expr->type());
Ethan Nicholas1d881522020-09-11 09:32:54 -0400873 SkASSERT(optimized);
Brian Osman010ce6a2020-10-19 16:34:10 -0400874 // Remove references within 'expr', add references within 'optimized'
875 optimizationContext->fUsage->replace(expr, optimized.get());
Ethan Nicholascb670962017-04-20 19:31:52 -0400876 if (!try_replace_expression(&b, iter, &optimized)) {
Ethan Nicholascdeae8c2020-10-22 14:39:46 -0400877 optimizationContext->fNeedsRescan = true;
Ethan Nicholas4b330df2017-05-17 10:52:55 -0400878 return;
Ethan Nicholascb670962017-04-20 19:31:52 -0400879 }
John Stiles70025e52020-09-28 16:08:58 -0400880 SkASSERT((*iter)->isExpression());
Ethan Nicholascb670962017-04-20 19:31:52 -0400881 expr = (*iter)->expression()->get();
Ethan Nicholascb670962017-04-20 19:31:52 -0400882 }
883 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400884 switch (expr->kind()) {
885 case Expression::Kind::kVariableReference: {
John Stilesa5a97b42020-08-18 11:19:07 -0400886 const VariableReference& ref = expr->as<VariableReference>();
Ethan Nicholas78686922020-10-08 06:46:27 -0400887 const Variable* var = ref.variable();
Ethan Nicholas453f67f2020-10-09 10:43:45 -0400888 if (ref.refKind() != VariableReference::RefKind::kWrite &&
889 ref.refKind() != VariableReference::RefKind::kPointer &&
890 var->storage() == Variable::Storage::kLocal && !definitions[var] &&
Ethan Nicholascdeae8c2020-10-22 14:39:46 -0400891 optimizationContext->fSilences.find(var) == optimizationContext->fSilences.end()) {
892 optimizationContext->fSilences.insert(var);
Ethan Nicholas82a62d22017-11-07 14:42:10 +0000893 this->error(expr->fOffset,
Ethan Nicholase2c49992020-10-05 11:49:11 -0400894 "'" + var->name() + "' has not been assigned");
Ethan Nicholascb670962017-04-20 19:31:52 -0400895 }
896 break;
897 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400898 case Expression::Kind::kTernary: {
John Stiles403a3632020-08-20 12:11:48 -0400899 TernaryExpression* t = &expr->as<TernaryExpression>();
Ethan Nicholasdd218162020-10-08 05:48:01 -0400900 if (t->test()->is<BoolLiteral>()) {
Ethan Nicholascb670962017-04-20 19:31:52 -0400901 // ternary has a constant test, replace it with either the true or
902 // false branch
Ethan Nicholasdd218162020-10-08 05:48:01 -0400903 if (t->test()->as<BoolLiteral>().value()) {
Brian Osman010ce6a2020-10-19 16:34:10 -0400904 (*iter)->setExpression(std::move(t->ifTrue()), optimizationContext->fUsage);
Ethan Nicholascb670962017-04-20 19:31:52 -0400905 } else {
Brian Osman010ce6a2020-10-19 16:34:10 -0400906 (*iter)->setExpression(std::move(t->ifFalse()), optimizationContext->fUsage);
Ethan Nicholascb670962017-04-20 19:31:52 -0400907 }
Ethan Nicholascdeae8c2020-10-22 14:39:46 -0400908 optimizationContext->fUpdated = true;
909 optimizationContext->fNeedsRescan = true;
Ethan Nicholascb670962017-04-20 19:31:52 -0400910 }
911 break;
912 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400913 case Expression::Kind::kBinary: {
John Stiles403a3632020-08-20 12:11:48 -0400914 BinaryExpression* bin = &expr->as<BinaryExpression>();
Brian Osman010ce6a2020-10-19 16:34:10 -0400915 if (dead_assignment(*bin, optimizationContext->fUsage)) {
Ethan Nicholascdeae8c2020-10-22 14:39:46 -0400916 delete_left(&b, iter, optimizationContext);
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400917 break;
918 }
John Stiles2d4f9592020-10-30 10:29:12 -0400919 Expression& left = *bin->left();
920 Expression& right = *bin->right();
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400921 const Type& leftType = left.type();
922 const Type& rightType = right.type();
Ethan Nicholasc2371a42017-05-05 10:04:06 -0400923 // collapse useless expressions like x * 1 or x + 0
John Stiles9aeed132020-11-24 17:36:06 -0500924 if ((!leftType.isScalar() && !leftType.isVector()) ||
925 (!rightType.isScalar() && !rightType.isVector())) {
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400926 break;
927 }
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400928 switch (bin->getOperator()) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400929 case Token::Kind::TK_STAR:
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400930 if (is_constant(left, 1)) {
John Stiles9aeed132020-11-24 17:36:06 -0500931 if (leftType.isVector() && rightType.isScalar()) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400932 // float4(1) * x -> float4(x)
Ethan Nicholascdeae8c2020-10-22 14:39:46 -0400933 vectorize_right(&b, iter, optimizationContext);
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400934 } else {
935 // 1 * x -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400936 // 1 * float4(x) -> float4(x)
937 // float4(1) * float4(x) -> float4(x)
Ethan Nicholascdeae8c2020-10-22 14:39:46 -0400938 delete_left(&b, iter, optimizationContext);
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400939 }
940 }
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400941 else if (is_constant(left, 0)) {
John Stiles9aeed132020-11-24 17:36:06 -0500942 if (leftType.isScalar() && rightType.isVector() &&
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400943 !right.hasSideEffects()) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400944 // 0 * float4(x) -> float4(0)
Ethan Nicholascdeae8c2020-10-22 14:39:46 -0400945 vectorize_left(&b, iter, optimizationContext);
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400946 } else {
947 // 0 * x -> 0
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400948 // float4(0) * x -> float4(0)
949 // float4(0) * float4(x) -> float4(0)
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400950 if (!right.hasSideEffects()) {
Ethan Nicholascdeae8c2020-10-22 14:39:46 -0400951 delete_right(&b, iter, optimizationContext);
Ethan Nicholas51493ee2017-12-11 12:34:33 -0500952 }
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400953 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400954 }
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400955 else if (is_constant(right, 1)) {
John Stiles9aeed132020-11-24 17:36:06 -0500956 if (leftType.isScalar() && rightType.isVector()) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400957 // x * float4(1) -> float4(x)
Ethan Nicholascdeae8c2020-10-22 14:39:46 -0400958 vectorize_left(&b, iter, optimizationContext);
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400959 } else {
960 // x * 1 -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400961 // float4(x) * 1 -> float4(x)
962 // float4(x) * float4(1) -> float4(x)
Ethan Nicholascdeae8c2020-10-22 14:39:46 -0400963 delete_right(&b, iter, optimizationContext);
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400964 }
965 }
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400966 else if (is_constant(right, 0)) {
John Stiles9aeed132020-11-24 17:36:06 -0500967 if (leftType.isVector() && rightType.isScalar() && !left.hasSideEffects()) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400968 // float4(x) * 0 -> float4(0)
Ethan Nicholascdeae8c2020-10-22 14:39:46 -0400969 vectorize_right(&b, iter, optimizationContext);
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400970 } else {
971 // x * 0 -> 0
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400972 // x * float4(0) -> float4(0)
973 // float4(x) * float4(0) -> float4(0)
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400974 if (!left.hasSideEffects()) {
Ethan Nicholascdeae8c2020-10-22 14:39:46 -0400975 delete_left(&b, iter, optimizationContext);
Ethan Nicholas51493ee2017-12-11 12:34:33 -0500976 }
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400977 }
Ethan Nicholascb670962017-04-20 19:31:52 -0400978 }
979 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400980 case Token::Kind::TK_PLUS:
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400981 if (is_constant(left, 0)) {
John Stiles9aeed132020-11-24 17:36:06 -0500982 if (leftType.isVector() && rightType.isScalar()) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400983 // float4(0) + x -> float4(x)
Ethan Nicholascdeae8c2020-10-22 14:39:46 -0400984 vectorize_right(&b, iter, optimizationContext);
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400985 } else {
986 // 0 + x -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400987 // 0 + float4(x) -> float4(x)
988 // float4(0) + float4(x) -> float4(x)
Ethan Nicholascdeae8c2020-10-22 14:39:46 -0400989 delete_left(&b, iter, optimizationContext);
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400990 }
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400991 } else if (is_constant(right, 0)) {
John Stiles9aeed132020-11-24 17:36:06 -0500992 if (leftType.isScalar() && rightType.isVector()) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400993 // x + float4(0) -> float4(x)
Ethan Nicholascdeae8c2020-10-22 14:39:46 -0400994 vectorize_left(&b, iter, optimizationContext);
Ethan Nicholasfe53e582017-04-27 16:24:51 -0400995 } else {
996 // x + 0 -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -0400997 // float4(x) + 0 -> float4(x)
998 // float4(x) + float4(0) -> float4(x)
Ethan Nicholascdeae8c2020-10-22 14:39:46 -0400999 delete_right(&b, iter, optimizationContext);
Ethan Nicholasfe53e582017-04-27 16:24:51 -04001000 }
Ethan Nicholas56e42712017-04-21 10:23:37 -04001001 }
1002 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001003 case Token::Kind::TK_MINUS:
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001004 if (is_constant(right, 0)) {
John Stiles9aeed132020-11-24 17:36:06 -05001005 if (leftType.isScalar() && rightType.isVector()) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -04001006 // x - float4(0) -> float4(x)
Ethan Nicholascdeae8c2020-10-22 14:39:46 -04001007 vectorize_left(&b, iter, optimizationContext);
Ethan Nicholasfe53e582017-04-27 16:24:51 -04001008 } else {
1009 // x - 0 -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -04001010 // float4(x) - 0 -> float4(x)
1011 // float4(x) - float4(0) -> float4(x)
Ethan Nicholascdeae8c2020-10-22 14:39:46 -04001012 delete_right(&b, iter, optimizationContext);
Ethan Nicholasfe53e582017-04-27 16:24:51 -04001013 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001014 }
1015 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001016 case Token::Kind::TK_SLASH:
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001017 if (is_constant(right, 1)) {
John Stiles9aeed132020-11-24 17:36:06 -05001018 if (leftType.isScalar() && rightType.isVector()) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -04001019 // x / float4(1) -> float4(x)
Ethan Nicholascdeae8c2020-10-22 14:39:46 -04001020 vectorize_left(&b, iter, optimizationContext);
Ethan Nicholasfe53e582017-04-27 16:24:51 -04001021 } else {
1022 // x / 1 -> x
Ethan Nicholas5af9ea32017-07-28 15:19:46 -04001023 // float4(x) / 1 -> float4(x)
1024 // float4(x) / float4(1) -> float4(x)
Ethan Nicholascdeae8c2020-10-22 14:39:46 -04001025 delete_right(&b, iter, optimizationContext);
Ethan Nicholasfe53e582017-04-27 16:24:51 -04001026 }
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001027 } else if (is_constant(left, 0)) {
John Stiles9aeed132020-11-24 17:36:06 -05001028 if (leftType.isScalar() && rightType.isVector() &&
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001029 !right.hasSideEffects()) {
Ethan Nicholas5af9ea32017-07-28 15:19:46 -04001030 // 0 / float4(x) -> float4(0)
Ethan Nicholascdeae8c2020-10-22 14:39:46 -04001031 vectorize_left(&b, iter, optimizationContext);
Ethan Nicholasfe53e582017-04-27 16:24:51 -04001032 } else {
1033 // 0 / x -> 0
Ethan Nicholas5af9ea32017-07-28 15:19:46 -04001034 // float4(0) / x -> float4(0)
1035 // float4(0) / float4(x) -> float4(0)
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001036 if (!right.hasSideEffects()) {
Ethan Nicholascdeae8c2020-10-22 14:39:46 -04001037 delete_right(&b, iter, optimizationContext);
Ethan Nicholas51493ee2017-12-11 12:34:33 -05001038 }
Ethan Nicholasfe53e582017-04-27 16:24:51 -04001039 }
1040 }
1041 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001042 case Token::Kind::TK_PLUSEQ:
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001043 if (is_constant(right, 0)) {
1044 clear_write(left);
Ethan Nicholascdeae8c2020-10-22 14:39:46 -04001045 delete_right(&b, iter, optimizationContext);
Ethan Nicholasfe53e582017-04-27 16:24:51 -04001046 }
1047 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001048 case Token::Kind::TK_MINUSEQ:
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001049 if (is_constant(right, 0)) {
1050 clear_write(left);
Ethan Nicholascdeae8c2020-10-22 14:39:46 -04001051 delete_right(&b, iter, optimizationContext);
Ethan Nicholasfe53e582017-04-27 16:24:51 -04001052 }
1053 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001054 case Token::Kind::TK_STAREQ:
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001055 if (is_constant(right, 1)) {
1056 clear_write(left);
Ethan Nicholascdeae8c2020-10-22 14:39:46 -04001057 delete_right(&b, iter, optimizationContext);
Ethan Nicholasfe53e582017-04-27 16:24:51 -04001058 }
1059 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001060 case Token::Kind::TK_SLASHEQ:
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001061 if (is_constant(right, 1)) {
1062 clear_write(left);
Ethan Nicholascdeae8c2020-10-22 14:39:46 -04001063 delete_right(&b, iter, optimizationContext);
Ethan Nicholascb670962017-04-20 19:31:52 -04001064 }
1065 break;
1066 default:
1067 break;
1068 }
Ethan Nicholas409f6f02019-09-17 12:34:39 -04001069 break;
1070 }
John Stilesf5c1d042020-11-21 23:26:07 -05001071 case Expression::Kind::kConstructor: {
1072 // Find constructors embedded inside constructors and flatten them out where possible.
1073 // - float4(float2(1, 2), 3, 4) --> float4(1, 2, 3, 4)
1074 // - float4(w, float3(sin(x), cos(y), tan(z))) --> float4(w, sin(x), cos(y), tan(z))
1075 // Leave single-argument constructors alone, though. These might be casts or splats.
1076 Constructor& c = expr->as<Constructor>();
1077 if (c.type().columns() > 1) {
1078 // Inspect each constructor argument to see if it's a candidate for flattening.
1079 // Remember matched arguments in a bitfield, "argsToOptimize".
1080 int argsToOptimize = 0;
1081 int currBit = 1;
1082 for (const std::unique_ptr<Expression>& arg : c.arguments()) {
1083 if (arg->is<Constructor>()) {
1084 Constructor& inner = arg->as<Constructor>();
1085 if (inner.arguments().size() > 1 &&
1086 inner.type().componentType() == c.type().componentType()) {
1087 argsToOptimize |= currBit;
1088 }
1089 }
1090 currBit <<= 1;
1091 }
1092 if (argsToOptimize) {
1093 // We found at least one argument that could be flattened out. Re-walk the
1094 // constructor args and flatten the candidates we found during our initial pass.
1095 ExpressionArray flattened;
1096 flattened.reserve_back(c.type().columns());
1097 currBit = 1;
1098 for (const std::unique_ptr<Expression>& arg : c.arguments()) {
1099 if (argsToOptimize & currBit) {
1100 Constructor& inner = arg->as<Constructor>();
1101 for (const std::unique_ptr<Expression>& innerArg : inner.arguments()) {
1102 flattened.push_back(innerArg->clone());
1103 }
1104 } else {
1105 flattened.push_back(arg->clone());
1106 }
1107 currBit <<= 1;
1108 }
1109 auto optimized = std::unique_ptr<Expression>(
1110 new Constructor(c.fOffset, &c.type(), std::move(flattened)));
1111 // No fUsage change; no references have been added or removed anywhere.
1112 optimizationContext->fUpdated = true;
1113 if (!try_replace_expression(&b, iter, &optimized)) {
1114 optimizationContext->fNeedsRescan = true;
1115 return;
1116 }
1117 SkASSERT((*iter)->isExpression());
1118 break;
1119 }
1120 }
1121 break;
1122 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001123 case Expression::Kind::kSwizzle: {
John Stiles403a3632020-08-20 12:11:48 -04001124 Swizzle& s = expr->as<Swizzle>();
John Stiles108bbe22020-11-18 11:10:38 -05001125 // Detect identity swizzles like `foo.rgba`.
Ethan Nicholas6b4d5812020-10-12 16:11:51 -04001126 if ((int) s.components().size() == s.base()->type().columns()) {
Ethan Nicholas409f6f02019-09-17 12:34:39 -04001127 bool identity = true;
Ethan Nicholas6b4d5812020-10-12 16:11:51 -04001128 for (int i = 0; i < (int) s.components().size(); ++i) {
1129 if (s.components()[i] != i) {
Ethan Nicholas409f6f02019-09-17 12:34:39 -04001130 identity = false;
1131 break;
1132 }
1133 }
1134 if (identity) {
Ethan Nicholascdeae8c2020-10-22 14:39:46 -04001135 optimizationContext->fUpdated = true;
Brian Osman010ce6a2020-10-19 16:34:10 -04001136 // No fUsage change: foo.rgba and foo have equivalent reference counts
Ethan Nicholas6b4d5812020-10-12 16:11:51 -04001137 if (!try_replace_expression(&b, iter, &s.base())) {
Ethan Nicholascdeae8c2020-10-22 14:39:46 -04001138 optimizationContext->fNeedsRescan = true;
Ethan Nicholas409f6f02019-09-17 12:34:39 -04001139 return;
1140 }
John Stiles70025e52020-09-28 16:08:58 -04001141 SkASSERT((*iter)->isExpression());
Ethan Nicholas409f6f02019-09-17 12:34:39 -04001142 break;
1143 }
1144 }
John Stiles108bbe22020-11-18 11:10:38 -05001145 // Detect swizzles of swizzles, e.g. replace `foo.argb.r000` with `foo.a000`.
1146 if (s.base()->is<Swizzle>()) {
Ethan Nicholas6b4d5812020-10-12 16:11:51 -04001147 Swizzle& base = s.base()->as<Swizzle>();
John Stiles750109b2020-10-30 13:45:46 -04001148 ComponentArray final;
Ethan Nicholas6b4d5812020-10-12 16:11:51 -04001149 for (int c : s.components()) {
1150 final.push_back(base.components()[c]);
Ethan Nicholas409f6f02019-09-17 12:34:39 -04001151 }
Ethan Nicholascdeae8c2020-10-22 14:39:46 -04001152 optimizationContext->fUpdated = true;
Ethan Nicholas6b4d5812020-10-12 16:11:51 -04001153 std::unique_ptr<Expression> replacement(new Swizzle(*fContext, base.base()->clone(),
John Stiles750109b2020-10-30 13:45:46 -04001154 final));
John Stiles108bbe22020-11-18 11:10:38 -05001155 // No fUsage change: `foo.gbr.gbr` and `foo.brg` have equivalent reference counts
Ethan Nicholas409f6f02019-09-17 12:34:39 -04001156 if (!try_replace_expression(&b, iter, &replacement)) {
Ethan Nicholascdeae8c2020-10-22 14:39:46 -04001157 optimizationContext->fNeedsRescan = true;
Ethan Nicholas409f6f02019-09-17 12:34:39 -04001158 return;
1159 }
John Stiles70025e52020-09-28 16:08:58 -04001160 SkASSERT((*iter)->isExpression());
John Stiles108bbe22020-11-18 11:10:38 -05001161 break;
1162 }
1163 // Optimize swizzles of constructors.
1164 if (s.base()->is<Constructor>()) {
1165 Constructor& base = s.base()->as<Constructor>();
1166 std::unique_ptr<Expression> replacement;
1167 const Type& componentType = base.type().componentType();
1168 int swizzleSize = s.components().size();
1169
1170 // The IR generator has already converted any zero/one swizzle components into
1171 // constructors containing zero/one args. Confirm that this is true by checking that
1172 // our swizzle components are all `xyzw` (values 0 through 3).
1173 SkASSERT(std::all_of(s.components().begin(), s.components().end(),
1174 [](int8_t c) { return c >= 0 && c <= 3; }));
1175
John Stiles9aeed132020-11-24 17:36:06 -05001176 if (base.arguments().size() == 1 && base.arguments().front()->type().isScalar()) {
John Stiles108bbe22020-11-18 11:10:38 -05001177 // `half4(scalar).zyy` can be optimized to `half3(scalar)`. The swizzle
1178 // components don't actually matter since all fields are the same.
1179 ExpressionArray newArgs;
1180 newArgs.push_back(base.arguments().front()->clone());
1181 replacement = std::make_unique<Constructor>(
1182 base.fOffset,
1183 &componentType.toCompound(*fContext, swizzleSize, /*rows=*/1),
1184 std::move(newArgs));
1185
John Stilesa60ac0c2020-12-22 08:59:51 -05001186 // We're replacing an expression with a cloned version; we'll need a rescan.
1187 // There's no fUsage change: `half4(foo).xy` and `half2(foo)` have equivalent
1188 // reference counts.
1189 try_replace_expression(&b, iter, &replacement);
John Stiles0777ac42020-11-19 11:06:47 -05001190 optimizationContext->fUpdated = true;
John Stilesa60ac0c2020-12-22 08:59:51 -05001191 optimizationContext->fNeedsRescan = true;
John Stiles108bbe22020-11-18 11:10:38 -05001192 break;
1193 }
1194
John Stiles0777ac42020-11-19 11:06:47 -05001195 // Swizzles can duplicate some elements and discard others, e.g.
1196 // `half4(1, 2, 3, 4).xxz` --> `half3(1, 1, 3)`. However, there are constraints:
1197 // - Expressions with side effects need to occur exactly once, even if they
1198 // would otherwise be swizzle-eliminated
1199 // - Non-trivial expressions should not be repeated, but elimination is OK.
1200 //
1201 // Look up the argument for the constructor at each index. This is typically simple
1202 // but for weird cases like `half4(bar.yz, half2(foo))`, it can be harder than it
1203 // seems. This example would result in:
1204 // argMap[0] = {.fArgIndex = 0, .fComponent = 0} (bar.yz .x)
1205 // argMap[1] = {.fArgIndex = 0, .fComponent = 1} (bar.yz .y)
1206 // argMap[2] = {.fArgIndex = 1, .fComponent = 0} (half2(foo) .x)
1207 // argMap[3] = {.fArgIndex = 1, .fComponent = 1} (half2(foo) .y)
1208 struct ConstructorArgMap {
1209 int8_t fArgIndex;
1210 int8_t fComponent;
1211 };
1212
1213 int numConstructorArgs = base.type().columns();
1214 ConstructorArgMap argMap[4] = {};
1215 int writeIdx = 0;
1216 for (int argIdx = 0; argIdx < (int) base.arguments().size(); ++argIdx) {
1217 const Expression& expr = *base.arguments()[argIdx];
1218 int argWidth = expr.type().columns();
1219 for (int componentIdx = 0; componentIdx < argWidth; ++componentIdx) {
1220 argMap[writeIdx].fArgIndex = argIdx;
1221 argMap[writeIdx].fComponent = componentIdx;
1222 ++writeIdx;
1223 }
1224 }
1225 SkASSERT(writeIdx == numConstructorArgs);
1226
1227 // Count up the number of times each constructor argument is used by the
1228 // swizzle.
1229 // `half4(bar.yz, half2(foo)).xwxy` -> { 3, 1 }
1230 // - bar.yz is referenced 3 times, by `.x_xy`
1231 // - half(foo) is referenced 1 time, by `._w__`
1232 int8_t exprUsed[4] = {};
1233 for (int c : s.components()) {
1234 exprUsed[argMap[c].fArgIndex]++;
1235 }
1236
1237 bool safeToOptimize = true;
1238 for (int index = 0; index < numConstructorArgs; ++index) {
1239 int8_t constructorArgIndex = argMap[index].fArgIndex;
1240 const Expression& baseArg = *base.arguments()[constructorArgIndex];
1241
1242 // Check that non-trivial expressions are not swizzled in more than once.
John Stilesc30fbca2020-11-19 16:25:49 -05001243 if (exprUsed[constructorArgIndex] > 1 &&
1244 !Analysis::IsTrivialExpression(baseArg)) {
John Stiles0777ac42020-11-19 11:06:47 -05001245 safeToOptimize = false;
1246 break;
1247 }
1248 // Check that side-effect-bearing expressions are swizzled in exactly once.
1249 if (exprUsed[constructorArgIndex] != 1 && baseArg.hasSideEffects()) {
1250 safeToOptimize = false;
1251 break;
1252 }
1253 }
1254
1255 if (safeToOptimize) {
John Stilesd9076cb2020-11-19 12:18:36 -05001256 struct ReorderedArgument {
1257 int8_t fArgIndex;
1258 ComponentArray fComponents;
1259 };
1260 SkSTArray<4, ReorderedArgument> reorderedArgs;
John Stiles0777ac42020-11-19 11:06:47 -05001261 for (int c : s.components()) {
1262 const ConstructorArgMap& argument = argMap[c];
1263 const Expression& baseArg = *base.arguments()[argument.fArgIndex];
1264
John Stiles9aeed132020-11-24 17:36:06 -05001265 if (baseArg.type().isScalar()) {
John Stilesd9076cb2020-11-19 12:18:36 -05001266 // This argument is a scalar; add it to the list as-is.
John Stiles0777ac42020-11-19 11:06:47 -05001267 SkASSERT(argument.fComponent == 0);
John Stilesd9076cb2020-11-19 12:18:36 -05001268 reorderedArgs.push_back({argument.fArgIndex,
1269 ComponentArray{}});
John Stiles0777ac42020-11-19 11:06:47 -05001270 } else {
John Stilesd9076cb2020-11-19 12:18:36 -05001271 // This argument is a component from a vector.
John Stiles0777ac42020-11-19 11:06:47 -05001272 SkASSERT(argument.fComponent < baseArg.type().columns());
John Stilesd9076cb2020-11-19 12:18:36 -05001273 if (reorderedArgs.empty() ||
1274 reorderedArgs.back().fArgIndex != argument.fArgIndex) {
1275 // This can't be combined with the previous argument. Add a new one.
1276 reorderedArgs.push_back({argument.fArgIndex,
1277 ComponentArray{argument.fComponent}});
1278 } else {
1279 // Since we know this argument uses components, it should already
1280 // have at least one component set.
1281 SkASSERT(!reorderedArgs.back().fComponents.empty());
1282 // Build up the current argument with one more component.
1283 reorderedArgs.back().fComponents.push_back(argument.fComponent);
1284 }
John Stiles0777ac42020-11-19 11:06:47 -05001285 }
1286 }
John Stilesd9076cb2020-11-19 12:18:36 -05001287
1288 // Convert our reordered argument list to an actual array of expressions, with
1289 // the new order and any new inner swizzles that need to be applied. Note that
1290 // we expect followup passes to clean up the inner swizzles.
1291 ExpressionArray newArgs;
1292 newArgs.reserve_back(swizzleSize);
1293 for (const ReorderedArgument& reorderedArg : reorderedArgs) {
1294 const Expression& baseArg = *base.arguments()[reorderedArg.fArgIndex];
1295 if (reorderedArg.fComponents.empty()) {
1296 newArgs.push_back(baseArg.clone());
1297 } else {
1298 newArgs.push_back(std::make_unique<Swizzle>(*fContext, baseArg.clone(),
1299 reorderedArg.fComponents));
1300 }
1301 }
1302
1303 // Create a new constructor.
John Stiles0777ac42020-11-19 11:06:47 -05001304 replacement = std::make_unique<Constructor>(
1305 base.fOffset,
1306 &componentType.toCompound(*fContext, swizzleSize, /*rows=*/1),
1307 std::move(newArgs));
1308
John Stilesa60ac0c2020-12-22 08:59:51 -05001309 // Remove references within 'expr', add references within 'replacement.'
John Stiles0777ac42020-11-19 11:06:47 -05001310 optimizationContext->fUsage->replace(expr, replacement.get());
John Stilesa60ac0c2020-12-22 08:59:51 -05001311
1312 // We're replacing an expression with a cloned version; we'll need a rescan.
1313 try_replace_expression(&b, iter, &replacement);
1314 optimizationContext->fUpdated = true;
1315 optimizationContext->fNeedsRescan = true;
John Stiles0777ac42020-11-19 11:06:47 -05001316 }
John Stiles108bbe22020-11-18 11:10:38 -05001317 break;
Ethan Nicholas409f6f02019-09-17 12:34:39 -04001318 }
John Stiles30212b72020-06-11 17:55:07 -04001319 break;
Ethan Nicholascb670962017-04-20 19:31:52 -04001320 }
1321 default:
1322 break;
1323 }
1324}
1325
John Stiles92219b42020-06-15 12:32:24 -04001326// Returns true if this statement could potentially execute a break at the current level. We ignore
1327// nested loops and switches, since any breaks inside of them will merely break the loop / switch.
John Stilesb92641c2020-08-31 18:09:01 -04001328static bool contains_conditional_break(Statement& stmt) {
1329 class ContainsConditionalBreak : public ProgramVisitor {
1330 public:
1331 bool visitStatement(const Statement& stmt) override {
Ethan Nicholase6592142020-09-08 10:22:09 -04001332 switch (stmt.kind()) {
1333 case Statement::Kind::kBlock:
John Stilesb92641c2020-08-31 18:09:01 -04001334 return this->INHERITED::visitStatement(stmt);
1335
Ethan Nicholase6592142020-09-08 10:22:09 -04001336 case Statement::Kind::kBreak:
John Stilesb92641c2020-08-31 18:09:01 -04001337 return fInConditional > 0;
1338
Ethan Nicholase6592142020-09-08 10:22:09 -04001339 case Statement::Kind::kIf: {
John Stilesb92641c2020-08-31 18:09:01 -04001340 ++fInConditional;
1341 bool result = this->INHERITED::visitStatement(stmt);
1342 --fInConditional;
1343 return result;
1344 }
1345
1346 default:
1347 return false;
1348 }
1349 }
1350
1351 int fInConditional = 0;
1352 using INHERITED = ProgramVisitor;
1353 };
1354
1355 return ContainsConditionalBreak{}.visitStatement(stmt);
John Stiles92219b42020-06-15 12:32:24 -04001356}
1357
Ethan Nicholas5005a222018-08-24 13:06:27 -04001358// returns true if this statement definitely executes a break at the current level (we ignore
1359// nested loops and switches, since any breaks inside of them will merely break the loop / switch)
John Stilesb92641c2020-08-31 18:09:01 -04001360static bool contains_unconditional_break(Statement& stmt) {
1361 class ContainsUnconditionalBreak : public ProgramVisitor {
1362 public:
1363 bool visitStatement(const Statement& stmt) override {
Ethan Nicholase6592142020-09-08 10:22:09 -04001364 switch (stmt.kind()) {
1365 case Statement::Kind::kBlock:
John Stilesb92641c2020-08-31 18:09:01 -04001366 return this->INHERITED::visitStatement(stmt);
1367
Ethan Nicholase6592142020-09-08 10:22:09 -04001368 case Statement::Kind::kBreak:
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001369 return true;
John Stilesb92641c2020-08-31 18:09:01 -04001370
1371 default:
1372 return false;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001373 }
John Stilesb92641c2020-08-31 18:09:01 -04001374 }
John Stiles92219b42020-06-15 12:32:24 -04001375
John Stilesb92641c2020-08-31 18:09:01 -04001376 using INHERITED = ProgramVisitor;
1377 };
John Stiles92219b42020-06-15 12:32:24 -04001378
John Stilesb92641c2020-08-31 18:09:01 -04001379 return ContainsUnconditionalBreak{}.visitStatement(stmt);
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001380}
1381
John Stiles8f2a0cf2020-10-13 12:48:21 -04001382static void move_all_but_break(std::unique_ptr<Statement>& stmt, StatementArray* target) {
Ethan Nicholase6592142020-09-08 10:22:09 -04001383 switch (stmt->kind()) {
1384 case Statement::Kind::kBlock: {
John Stiles92219b42020-06-15 12:32:24 -04001385 // Recurse into the block.
1386 Block& block = static_cast<Block&>(*stmt);
1387
John Stiles8f2a0cf2020-10-13 12:48:21 -04001388 StatementArray blockStmts;
John Stilesf4bda742020-10-14 16:57:41 -04001389 blockStmts.reserve_back(block.children().size());
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001390 for (std::unique_ptr<Statement>& stmt : block.children()) {
1391 move_all_but_break(stmt, &blockStmts);
Ethan Nicholas739e1ca2020-06-11 12:16:14 -04001392 }
John Stiles92219b42020-06-15 12:32:24 -04001393
1394 target->push_back(std::make_unique<Block>(block.fOffset, std::move(blockStmts),
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001395 block.symbolTable(), block.isScope()));
Ethan Nicholas739e1ca2020-06-11 12:16:14 -04001396 break;
John Stiles92219b42020-06-15 12:32:24 -04001397 }
1398
Ethan Nicholase6592142020-09-08 10:22:09 -04001399 case Statement::Kind::kBreak:
John Stiles92219b42020-06-15 12:32:24 -04001400 // Do not append a break to the target.
1401 break;
1402
Ethan Nicholas739e1ca2020-06-11 12:16:14 -04001403 default:
John Stiles92219b42020-06-15 12:32:24 -04001404 // Append normal statements to the target.
1405 target->push_back(std::move(stmt));
1406 break;
Ethan Nicholas739e1ca2020-06-11 12:16:14 -04001407 }
1408}
1409
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001410// Returns a block containing all of the statements that will be run if the given case matches
1411// (which, owing to the statements being owned by unique_ptrs, means the switch itself will be
1412// broken by this call and must then be discarded).
1413// Returns null (and leaves the switch unmodified) if no such simple reduction is possible, such as
1414// when break statements appear inside conditionals.
John Stiles92219b42020-06-15 12:32:24 -04001415static std::unique_ptr<Statement> block_for_case(SwitchStatement* switchStatement,
1416 SwitchCase* caseToCapture) {
1417 // We have to be careful to not move any of the pointers until after we're sure we're going to
1418 // succeed, so before we make any changes at all, we check the switch-cases to decide on a plan
1419 // of action. First, find the switch-case we are interested in.
Ethan Nicholas01b05e52020-10-22 15:53:41 -04001420 auto iter = switchStatement->cases().begin();
1421 for (; iter != switchStatement->cases().end(); ++iter) {
John Stiles2d4f9592020-10-30 10:29:12 -04001422 if (iter->get() == caseToCapture) {
John Stiles92219b42020-06-15 12:32:24 -04001423 break;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001424 }
John Stiles92219b42020-06-15 12:32:24 -04001425 }
1426
1427 // Next, walk forward through the rest of the switch. If we find a conditional break, we're
1428 // stuck and can't simplify at all. If we find an unconditional break, we have a range of
1429 // statements that we can use for simplification.
1430 auto startIter = iter;
1431 Statement* unconditionalBreakStmt = nullptr;
Ethan Nicholas01b05e52020-10-22 15:53:41 -04001432 for (; iter != switchStatement->cases().end(); ++iter) {
John Stiles2d4f9592020-10-30 10:29:12 -04001433 for (std::unique_ptr<Statement>& stmt : (*iter)->statements()) {
John Stiles92219b42020-06-15 12:32:24 -04001434 if (contains_conditional_break(*stmt)) {
1435 // We can't reduce switch-cases to a block when they have conditional breaks.
1436 return nullptr;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001437 }
John Stiles92219b42020-06-15 12:32:24 -04001438
1439 if (contains_unconditional_break(*stmt)) {
1440 // We found an unconditional break. We can use this block, but we need to strip
1441 // out the break statement.
1442 unconditionalBreakStmt = stmt.get();
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001443 break;
1444 }
1445 }
John Stiles92219b42020-06-15 12:32:24 -04001446
1447 if (unconditionalBreakStmt != nullptr) {
1448 break;
1449 }
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001450 }
John Stiles92219b42020-06-15 12:32:24 -04001451
1452 // We fell off the bottom of the switch or encountered a break. We know the range of statements
1453 // that we need to move over, and we know it's safe to do so.
John Stiles8f2a0cf2020-10-13 12:48:21 -04001454 StatementArray caseStmts;
John Stiles92219b42020-06-15 12:32:24 -04001455
1456 // We can move over most of the statements as-is.
1457 while (startIter != iter) {
John Stiles2d4f9592020-10-30 10:29:12 -04001458 for (std::unique_ptr<Statement>& stmt : (*startIter)->statements()) {
John Stiles92219b42020-06-15 12:32:24 -04001459 caseStmts.push_back(std::move(stmt));
1460 }
1461 ++startIter;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001462 }
John Stiles92219b42020-06-15 12:32:24 -04001463
1464 // If we found an unconditional break at the end, we need to move what we can while avoiding
1465 // that break.
1466 if (unconditionalBreakStmt != nullptr) {
John Stiles2d4f9592020-10-30 10:29:12 -04001467 for (std::unique_ptr<Statement>& stmt : (*startIter)->statements()) {
John Stiles92219b42020-06-15 12:32:24 -04001468 if (stmt.get() == unconditionalBreakStmt) {
1469 move_all_but_break(stmt, &caseStmts);
1470 unconditionalBreakStmt = nullptr;
1471 break;
1472 }
1473
1474 caseStmts.push_back(std::move(stmt));
1475 }
1476 }
1477
1478 SkASSERT(unconditionalBreakStmt == nullptr); // Verify that we fixed the unconditional break.
1479
1480 // Return our newly-synthesized block.
Ethan Nicholas01b05e52020-10-22 15:53:41 -04001481 return std::make_unique<Block>(/*offset=*/-1, std::move(caseStmts), switchStatement->symbols());
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001482}
1483
Ethan Nicholascb670962017-04-20 19:31:52 -04001484void Compiler::simplifyStatement(DefinitionMap& definitions,
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001485 BasicBlock& b,
1486 std::vector<BasicBlock::Node>::iterator* iter,
Ethan Nicholascdeae8c2020-10-22 14:39:46 -04001487 OptimizationContext* optimizationContext) {
Brian Osman010ce6a2020-10-19 16:34:10 -04001488 ProgramUsage* usage = optimizationContext->fUsage;
Ethan Nicholascb670962017-04-20 19:31:52 -04001489 Statement* stmt = (*iter)->statement()->get();
Ethan Nicholase6592142020-09-08 10:22:09 -04001490 switch (stmt->kind()) {
1491 case Statement::Kind::kVarDeclaration: {
John Stilesa5a97b42020-08-18 11:19:07 -04001492 const auto& varDecl = stmt->as<VarDeclaration>();
Brian Osman010ce6a2020-10-19 16:34:10 -04001493 if (usage->isDead(varDecl.var()) &&
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001494 (!varDecl.value() ||
1495 !varDecl.value()->hasSideEffects())) {
1496 if (varDecl.value()) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001497 SkASSERT((*iter)->statement()->get() == stmt);
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001498 if (!b.tryRemoveExpressionBefore(iter, varDecl.value().get())) {
Ethan Nicholascdeae8c2020-10-22 14:39:46 -04001499 optimizationContext->fNeedsRescan = true;
Ethan Nicholascb670962017-04-20 19:31:52 -04001500 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001501 }
Brian Osman010ce6a2020-10-19 16:34:10 -04001502 (*iter)->setStatement(std::make_unique<Nop>(), usage);
Ethan Nicholascdeae8c2020-10-22 14:39:46 -04001503 optimizationContext->fUpdated = true;
Ethan Nicholascb670962017-04-20 19:31:52 -04001504 }
1505 break;
1506 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001507 case Statement::Kind::kIf: {
John Stilesa5a97b42020-08-18 11:19:07 -04001508 IfStatement& i = stmt->as<IfStatement>();
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04001509 if (i.test()->kind() == Expression::Kind::kBoolLiteral) {
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001510 // constant if, collapse down to a single branch
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04001511 if (i.test()->as<BoolLiteral>().value()) {
1512 SkASSERT(i.ifTrue());
Brian Osman010ce6a2020-10-19 16:34:10 -04001513 (*iter)->setStatement(std::move(i.ifTrue()), usage);
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001514 } else {
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04001515 if (i.ifFalse()) {
Brian Osman010ce6a2020-10-19 16:34:10 -04001516 (*iter)->setStatement(std::move(i.ifFalse()), usage);
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001517 } else {
Brian Osman010ce6a2020-10-19 16:34:10 -04001518 (*iter)->setStatement(std::make_unique<Nop>(), usage);
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001519 }
1520 }
Ethan Nicholascdeae8c2020-10-22 14:39:46 -04001521 optimizationContext->fUpdated = true;
1522 optimizationContext->fNeedsRescan = true;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001523 break;
1524 }
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04001525 if (i.ifFalse() && i.ifFalse()->isEmpty()) {
Ethan Nicholascb670962017-04-20 19:31:52 -04001526 // else block doesn't do anything, remove it
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04001527 i.ifFalse().reset();
Ethan Nicholascdeae8c2020-10-22 14:39:46 -04001528 optimizationContext->fUpdated = true;
1529 optimizationContext->fNeedsRescan = true;
Ethan Nicholascb670962017-04-20 19:31:52 -04001530 }
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04001531 if (!i.ifFalse() && i.ifTrue()->isEmpty()) {
Ethan Nicholascb670962017-04-20 19:31:52 -04001532 // if block doesn't do anything, no else block
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04001533 if (i.test()->hasSideEffects()) {
Ethan Nicholascb670962017-04-20 19:31:52 -04001534 // test has side effects, keep it
Brian Osman010ce6a2020-10-19 16:34:10 -04001535 (*iter)->setStatement(
1536 std::make_unique<ExpressionStatement>(std::move(i.test())), usage);
Ethan Nicholascb670962017-04-20 19:31:52 -04001537 } else {
1538 // no if, no else, no test side effects, kill the whole if
1539 // statement
Brian Osman010ce6a2020-10-19 16:34:10 -04001540 (*iter)->setStatement(std::make_unique<Nop>(), usage);
Ethan Nicholascb670962017-04-20 19:31:52 -04001541 }
Ethan Nicholascdeae8c2020-10-22 14:39:46 -04001542 optimizationContext->fUpdated = true;
1543 optimizationContext->fNeedsRescan = true;
Ethan Nicholascb670962017-04-20 19:31:52 -04001544 }
1545 break;
1546 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001547 case Statement::Kind::kSwitch: {
John Stilesa5a97b42020-08-18 11:19:07 -04001548 SwitchStatement& s = stmt->as<SwitchStatement>();
Ethan Nicholas34b19c52020-09-14 11:33:47 -04001549 int64_t switchValue;
Ethan Nicholas01b05e52020-10-22 15:53:41 -04001550 if (fIRGenerator->getConstantInt(*s.value(), &switchValue)) {
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001551 // switch is constant, replace it with the case that matches
1552 bool found = false;
1553 SwitchCase* defaultCase = nullptr;
John Stiles2d4f9592020-10-30 10:29:12 -04001554 for (const std::unique_ptr<SwitchCase>& c : s.cases()) {
1555 if (!c->value()) {
1556 defaultCase = c.get();
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001557 continue;
1558 }
Ethan Nicholas34b19c52020-09-14 11:33:47 -04001559 int64_t caseValue;
John Stiles2d4f9592020-10-30 10:29:12 -04001560 SkAssertResult(fIRGenerator->getConstantInt(*c->value(), &caseValue));
Ethan Nicholas34b19c52020-09-14 11:33:47 -04001561 if (caseValue == switchValue) {
John Stiles2d4f9592020-10-30 10:29:12 -04001562 std::unique_ptr<Statement> newBlock = block_for_case(&s, c.get());
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001563 if (newBlock) {
Brian Osman010ce6a2020-10-19 16:34:10 -04001564 (*iter)->setStatement(std::move(newBlock), usage);
John Stiles9d944232020-08-19 09:56:49 -04001565 found = true;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001566 break;
1567 } else {
Ethan Nicholas01b05e52020-10-22 15:53:41 -04001568 if (s.isStatic() && !(fFlags & kPermitInvalidStaticTests_Flag) &&
1569 optimizationContext->fSilences.find(&s) ==
1570 optimizationContext->fSilences.end()) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001571 this->error(s.fOffset,
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001572 "static switch contains non-static conditional break");
Ethan Nicholas01b05e52020-10-22 15:53:41 -04001573 optimizationContext->fSilences.insert(&s);
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001574 }
1575 return; // can't simplify
1576 }
1577 }
1578 }
1579 if (!found) {
1580 // no matching case. use default if it exists, or kill the whole thing
1581 if (defaultCase) {
1582 std::unique_ptr<Statement> newBlock = block_for_case(&s, defaultCase);
1583 if (newBlock) {
Brian Osman010ce6a2020-10-19 16:34:10 -04001584 (*iter)->setStatement(std::move(newBlock), usage);
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001585 } else {
Ethan Nicholas01b05e52020-10-22 15:53:41 -04001586 if (s.isStatic() && !(fFlags & kPermitInvalidStaticTests_Flag) &&
1587 optimizationContext->fSilences.find(&s) ==
1588 optimizationContext->fSilences.end()) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001589 this->error(s.fOffset,
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001590 "static switch contains non-static conditional break");
Ethan Nicholas01b05e52020-10-22 15:53:41 -04001591 optimizationContext->fSilences.insert(&s);
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001592 }
1593 return; // can't simplify
1594 }
1595 } else {
Brian Osman010ce6a2020-10-19 16:34:10 -04001596 (*iter)->setStatement(std::make_unique<Nop>(), usage);
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001597 }
1598 }
Ethan Nicholascdeae8c2020-10-22 14:39:46 -04001599 optimizationContext->fUpdated = true;
1600 optimizationContext->fNeedsRescan = true;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001601 }
1602 break;
1603 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001604 case Statement::Kind::kExpression: {
John Stilesa5a97b42020-08-18 11:19:07 -04001605 ExpressionStatement& e = stmt->as<ExpressionStatement>();
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001606 SkASSERT((*iter)->statement()->get() == &e);
Ethan Nicholasd503a5a2020-09-30 09:29:55 -04001607 if (!e.expression()->hasSideEffects()) {
Ethan Nicholascb670962017-04-20 19:31:52 -04001608 // Expression statement with no side effects, kill it
Ethan Nicholasd503a5a2020-09-30 09:29:55 -04001609 if (!b.tryRemoveExpressionBefore(iter, e.expression().get())) {
Ethan Nicholascdeae8c2020-10-22 14:39:46 -04001610 optimizationContext->fNeedsRescan = true;
Ethan Nicholascb670962017-04-20 19:31:52 -04001611 }
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001612 SkASSERT((*iter)->statement()->get() == stmt);
Brian Osman010ce6a2020-10-19 16:34:10 -04001613 (*iter)->setStatement(std::make_unique<Nop>(), usage);
Ethan Nicholascdeae8c2020-10-22 14:39:46 -04001614 optimizationContext->fUpdated = true;
Ethan Nicholascb670962017-04-20 19:31:52 -04001615 }
1616 break;
1617 }
1618 default:
1619 break;
1620 }
1621}
1622
Brian Osman010ce6a2020-10-19 16:34:10 -04001623bool Compiler::scanCFG(FunctionDefinition& f, ProgramUsage* usage) {
John Stiles0cc193a2020-09-09 09:39:34 -04001624 bool madeChanges = false;
1625
Ethan Nicholascb670962017-04-20 19:31:52 -04001626 CFG cfg = CFGGenerator().getCFG(f);
1627 this->computeDataFlow(&cfg);
ethannicholas22f939e2016-10-13 13:25:34 -07001628
1629 // check for unreachable code
1630 for (size_t i = 0; i < cfg.fBlocks.size(); i++) {
John Stiles0cc193a2020-09-09 09:39:34 -04001631 const BasicBlock& block = cfg.fBlocks[i];
John Stiles40525102020-12-16 18:10:44 -05001632 if (!block.fIsReachable && !block.fAllowUnreachable && block.fNodes.size()) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001633 int offset;
John Stiles0cc193a2020-09-09 09:39:34 -04001634 const BasicBlock::Node& node = block.fNodes[0];
John Stiles70025e52020-09-28 16:08:58 -04001635 if (node.isStatement()) {
1636 offset = (*node.statement())->fOffset;
1637 } else {
1638 offset = (*node.expression())->fOffset;
1639 if ((*node.expression())->is<BoolLiteral>()) {
1640 // Function inlining can generate do { ... } while(false) loops which always
1641 // break, so the boolean condition is considered unreachable. Since not being
1642 // able to reach a literal is a non-issue in the first place, we don't report an
1643 // error in this case.
1644 continue;
1645 }
Ethan Nicholas86a43402017-01-19 13:32:00 -05001646 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001647 this->error(offset, String("unreachable"));
ethannicholas22f939e2016-10-13 13:25:34 -07001648 }
1649 }
1650 if (fErrorCount) {
John Stiles0cc193a2020-09-09 09:39:34 -04001651 return madeChanges;
ethannicholas22f939e2016-10-13 13:25:34 -07001652 }
1653
Ethan Nicholascb670962017-04-20 19:31:52 -04001654 // check for dead code & undefined variables, perform constant propagation
Ethan Nicholascdeae8c2020-10-22 14:39:46 -04001655 OptimizationContext optimizationContext;
Brian Osman010ce6a2020-10-19 16:34:10 -04001656 optimizationContext.fUsage = usage;
John Stiles7d3f0892020-11-03 11:35:01 -05001657 SkBitSet eliminatedBlockIds(cfg.fBlocks.size());
Ethan Nicholascb670962017-04-20 19:31:52 -04001658 do {
Ethan Nicholascdeae8c2020-10-22 14:39:46 -04001659 if (optimizationContext.fNeedsRescan) {
Ethan Nicholascb670962017-04-20 19:31:52 -04001660 cfg = CFGGenerator().getCFG(f);
1661 this->computeDataFlow(&cfg);
Ethan Nicholascdeae8c2020-10-22 14:39:46 -04001662 optimizationContext.fNeedsRescan = false;
Ethan Nicholas113628d2017-02-02 16:11:39 -05001663 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001664
John Stiles7d3f0892020-11-03 11:35:01 -05001665 eliminatedBlockIds.reset();
Ethan Nicholascdeae8c2020-10-22 14:39:46 -04001666 optimizationContext.fUpdated = false;
John Stiles7d3f0892020-11-03 11:35:01 -05001667
1668 for (BlockId blockId = 0; blockId < cfg.fBlocks.size(); ++blockId) {
1669 if (eliminatedBlockIds.test(blockId)) {
1670 // We reached a block ID that might have been eliminated. Be cautious and rescan.
1671 optimizationContext.fUpdated = true;
1672 optimizationContext.fNeedsRescan = true;
1673 break;
1674 }
1675
1676 BasicBlock& b = cfg.fBlocks[blockId];
1677 if (blockId > 0 && !b.fIsReachable) {
Ethan Nicholas1de14812020-06-19 15:32:49 -04001678 // Block was reachable before optimization, but has since become unreachable. In
1679 // addition to being dead code, it's broken - since control flow can't reach it, no
1680 // prior variable definitions can reach it, and therefore variables might look to
Brian Osmanc0213602020-10-06 14:43:32 -04001681 // have not been properly assigned. Kill it by replacing all statements with Nops.
Ethan Nicholas1de14812020-06-19 15:32:49 -04001682 for (BasicBlock::Node& node : b.fNodes) {
John Stiles70025e52020-09-28 16:08:58 -04001683 if (node.isStatement() && !(*node.statement())->is<Nop>()) {
John Stiles7d3f0892020-11-03 11:35:01 -05001684 // Eliminating a node runs the risk of eliminating that node's exits as
1685 // well. Keep track of this and do a rescan if we are about to access one
1686 // of these.
1687 for (BlockId id : b.fExits) {
1688 eliminatedBlockIds.set(id);
1689 }
Brian Osman010ce6a2020-10-19 16:34:10 -04001690 node.setStatement(std::make_unique<Nop>(), usage);
John Stiles0cc193a2020-09-09 09:39:34 -04001691 madeChanges = true;
Ethan Nicholas1de14812020-06-19 15:32:49 -04001692 }
1693 }
1694 continue;
1695 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001696 DefinitionMap definitions = b.fBefore;
1697
Ethan Nicholascdeae8c2020-10-22 14:39:46 -04001698 for (auto iter = b.fNodes.begin(); iter != b.fNodes.end() &&
1699 !optimizationContext.fNeedsRescan; ++iter) {
John Stiles70025e52020-09-28 16:08:58 -04001700 if (iter->isExpression()) {
Ethan Nicholascdeae8c2020-10-22 14:39:46 -04001701 this->simplifyExpression(definitions, b, &iter, &optimizationContext);
Ethan Nicholascb670962017-04-20 19:31:52 -04001702 } else {
Ethan Nicholascdeae8c2020-10-22 14:39:46 -04001703 this->simplifyStatement(definitions, b, &iter, &optimizationContext);
Ethan Nicholascb670962017-04-20 19:31:52 -04001704 }
Ethan Nicholascdeae8c2020-10-22 14:39:46 -04001705 if (optimizationContext.fNeedsRescan) {
Ethan Nicholas4b330df2017-05-17 10:52:55 -04001706 break;
1707 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001708 this->addDefinitions(*iter, &definitions);
1709 }
Brian Osman01a3eb42020-09-14 11:32:49 -04001710
Ethan Nicholascdeae8c2020-10-22 14:39:46 -04001711 if (optimizationContext.fNeedsRescan) {
Brian Osman01a3eb42020-09-14 11:32:49 -04001712 break;
1713 }
Ethan Nicholascb670962017-04-20 19:31:52 -04001714 }
Ethan Nicholascdeae8c2020-10-22 14:39:46 -04001715 madeChanges |= optimizationContext.fUpdated;
1716 } while (optimizationContext.fUpdated);
1717 SkASSERT(!optimizationContext.fNeedsRescan);
ethannicholas22f939e2016-10-13 13:25:34 -07001718
Ethan Nicholas91a10532017-06-22 11:24:38 -04001719 // verify static ifs & switches, clean up dead variable decls
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001720 for (BasicBlock& b : cfg.fBlocks) {
Ethan Nicholascdeae8c2020-10-22 14:39:46 -04001721 for (auto iter = b.fNodes.begin(); iter != b.fNodes.end() &&
1722 !optimizationContext.fNeedsRescan;) {
John Stiles70025e52020-09-28 16:08:58 -04001723 if (iter->isStatement()) {
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001724 const Statement& s = **iter->statement();
Ethan Nicholase6592142020-09-08 10:22:09 -04001725 switch (s.kind()) {
1726 case Statement::Kind::kIf:
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04001727 if (s.as<IfStatement>().isStatic() &&
Ethan Nicholas6e1cbc02017-07-14 10:12:15 -04001728 !(fFlags & kPermitInvalidStaticTests_Flag)) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001729 this->error(s.fOffset, "static if has non-static test");
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001730 }
Ethan Nicholas91a10532017-06-22 11:24:38 -04001731 ++iter;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001732 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001733 case Statement::Kind::kSwitch:
Ethan Nicholas01b05e52020-10-22 15:53:41 -04001734 if (s.as<SwitchStatement>().isStatic() &&
1735 !(fFlags & kPermitInvalidStaticTests_Flag) &&
1736 optimizationContext.fSilences.find(&s) ==
1737 optimizationContext.fSilences.end()) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001738 this->error(s.fOffset, "static switch has non-static test");
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001739 }
Ethan Nicholas91a10532017-06-22 11:24:38 -04001740 ++iter;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001741 break;
1742 default:
Ethan Nicholas91a10532017-06-22 11:24:38 -04001743 ++iter;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001744 break;
1745 }
Ethan Nicholas91a10532017-06-22 11:24:38 -04001746 } else {
1747 ++iter;
Ethan Nicholas5ac13c22017-05-10 15:06:17 -04001748 }
1749 }
1750 }
1751
ethannicholas22f939e2016-10-13 13:25:34 -07001752 // check for missing return
Ethan Nicholas0a5d0962020-10-14 13:33:18 -04001753 if (f.declaration().returnType() != *fContext->fVoid_Type) {
John Stiles61e75e32020-10-01 15:42:37 -04001754 if (cfg.fBlocks[cfg.fExit].fIsReachable) {
Ethan Nicholas0a5d0962020-10-14 13:33:18 -04001755 this->error(f.fOffset, String("function '" + String(f.declaration().name()) +
Ethan Nicholasdb80f692019-11-22 14:06:12 -05001756 "' can exit without returning a value"));
ethannicholas22f939e2016-10-13 13:25:34 -07001757 }
1758 }
John Stiles0cc193a2020-09-09 09:39:34 -04001759
1760 return madeChanges;
ethannicholas22f939e2016-10-13 13:25:34 -07001761}
1762
Brian Osman32d53552020-09-23 13:55:20 -04001763std::unique_ptr<Program> Compiler::convertProgram(
1764 Program::Kind kind,
1765 String text,
1766 const Program::Settings& settings,
1767 const std::vector<std::unique_ptr<ExternalValue>>* externalValues) {
1768 SkASSERT(!externalValues || (kind == Program::kGeneric_Kind));
Ethan Nicholas91164d12019-05-15 15:29:54 -04001769
Brian Osman0006ad02020-11-18 15:38:39 -05001770 // Loading and optimizing our base module might reset the inliner, so do that first,
1771 // *then* configure the inliner with the settings for this program.
1772 const ParsedModule& baseModule = this->moduleForProgramKind(kind);
1773
ethannicholasb3058bd2016-07-01 08:22:01 -07001774 fErrorText = "";
1775 fErrorCount = 0;
Brian Osman0006ad02020-11-18 15:38:39 -05001776 fInliner.reset(fIRGenerator->fModifiers.get(), &settings);
Brian Osman88cda172020-10-09 12:05:16 -04001777
1778 // Not using AutoSource, because caller is likely to call errorText() if we fail to compile
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001779 std::unique_ptr<String> textPtr(new String(std::move(text)));
1780 fSource = textPtr.get();
Brian Osman88cda172020-10-09 12:05:16 -04001781
John Stiles5c7bb322020-10-22 11:09:15 -04001782 // Enable node pooling while converting and optimizing the program for a performance boost.
1783 // The Program will take ownership of the pool.
John Stiles2d68ea32020-10-22 15:42:27 -04001784 std::unique_ptr<Pool> pool = Pool::Create();
1785 pool->attachToThread();
Brian Osman0006ad02020-11-18 15:38:39 -05001786 IRGenerator::IRBundle ir =
1787 fIRGenerator->convertProgram(kind, &settings, baseModule, /*isBuiltinCode=*/false,
1788 textPtr->c_str(), textPtr->size(), externalValues);
John Stiles5c7bb322020-10-22 11:09:15 -04001789 auto program = std::make_unique<Program>(kind,
1790 std::move(textPtr),
1791 settings,
Brian Osmand7e76592020-11-02 12:26:22 -05001792 fCaps,
John Stiles5c7bb322020-10-22 11:09:15 -04001793 fContext,
1794 std::move(ir.fElements),
Brian Osman133724c2020-10-28 14:14:39 -04001795 std::move(ir.fSharedElements),
John Stiles5c7bb322020-10-22 11:09:15 -04001796 std::move(ir.fModifiers),
1797 std::move(ir.fSymbolTable),
1798 std::move(pool),
1799 ir.fInputs);
1800 bool success = false;
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001801 if (fErrorCount) {
John Stiles5c7bb322020-10-22 11:09:15 -04001802 // Do not return programs that failed to compile.
1803 } else if (settings.fOptimize && !this->optimize(*program)) {
1804 // Do not return programs that failed to optimize.
1805 } else {
1806 // We have a successful program!
1807 success = true;
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001808 }
John Stiles5c7bb322020-10-22 11:09:15 -04001809
1810 program->fPool->detachFromThread();
1811 return success ? std::move(program) : nullptr;
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001812}
1813
Brian Osman0006ad02020-11-18 15:38:39 -05001814bool Compiler::optimize(LoadedModule& module) {
1815 SkASSERT(!fErrorCount);
1816 Program::Settings settings;
1817 fIRGenerator->fKind = module.fKind;
1818 fIRGenerator->fSettings = &settings;
1819 std::unique_ptr<ProgramUsage> usage = Analysis::GetUsage(module);
1820
1821 fInliner.reset(fModifiers.back().get(), &settings);
1822
1823 while (fErrorCount == 0) {
1824 bool madeChanges = false;
1825
1826 // Scan and optimize based on the control-flow graph for each function.
1827 for (const auto& element : module.fElements) {
1828 if (element->is<FunctionDefinition>()) {
1829 madeChanges |= this->scanCFG(element->as<FunctionDefinition>(), usage.get());
1830 }
1831 }
1832
1833 // Perform inline-candidate analysis and inline any functions deemed suitable.
John Stiles78047582020-12-16 16:17:41 -05001834 madeChanges |= fInliner.analyze(module.fElements, module.fSymbols, usage.get());
Brian Osman0006ad02020-11-18 15:38:39 -05001835
1836 if (!madeChanges) {
1837 break;
1838 }
1839 }
1840 return fErrorCount == 0;
1841}
1842
Ethan Nicholas00543112018-07-31 09:44:36 -04001843bool Compiler::optimize(Program& program) {
1844 SkASSERT(!fErrorCount);
Ethan Nicholas34b19c52020-09-14 11:33:47 -04001845 fIRGenerator->fKind = program.fKind;
1846 fIRGenerator->fSettings = &program.fSettings;
Brian Osman010ce6a2020-10-19 16:34:10 -04001847 ProgramUsage* usage = program.fUsage.get();
John Stiles7954d6c2020-09-01 10:53:02 -04001848
Ethan Nicholas34b19c52020-09-14 11:33:47 -04001849 while (fErrorCount == 0) {
1850 bool madeChanges = false;
John Stiles7954d6c2020-09-01 10:53:02 -04001851
Ethan Nicholas34b19c52020-09-14 11:33:47 -04001852 // Scan and optimize based on the control-flow graph for each function.
Brian Osman133724c2020-10-28 14:14:39 -04001853 for (const auto& element : program.ownedElements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04001854 if (element->is<FunctionDefinition>()) {
Brian Osman010ce6a2020-10-19 16:34:10 -04001855 madeChanges |= this->scanCFG(element->as<FunctionDefinition>(), usage);
Ethan Nicholas34b19c52020-09-14 11:33:47 -04001856 }
1857 }
1858
1859 // Perform inline-candidate analysis and inline any functions deemed suitable.
John Stiles78047582020-12-16 16:17:41 -05001860 madeChanges |= fInliner.analyze(program.ownedElements(), program.fSymbols, usage);
Ethan Nicholas34b19c52020-09-14 11:33:47 -04001861
1862 // Remove dead functions. We wait until after analysis so that we still report errors,
1863 // even in unused code.
1864 if (program.fSettings.fRemoveDeadFunctions) {
Brian Osman133724c2020-10-28 14:14:39 -04001865 auto isDeadFunction = [&](const ProgramElement* element) {
1866 if (!element->is<FunctionDefinition>()) {
1867 return false;
1868 }
1869 const FunctionDefinition& fn = element->as<FunctionDefinition>();
1870 if (fn.declaration().name() != "main" && usage->get(fn.declaration()) == 0) {
1871 usage->remove(*element);
1872 madeChanges = true;
1873 return true;
1874 }
1875 return false;
1876 };
Ethan Nicholas34b19c52020-09-14 11:33:47 -04001877 program.fElements.erase(
Brian Osman133724c2020-10-28 14:14:39 -04001878 std::remove_if(program.fElements.begin(), program.fElements.end(),
Ethan Nicholas34b19c52020-09-14 11:33:47 -04001879 [&](const std::unique_ptr<ProgramElement>& element) {
Brian Osman133724c2020-10-28 14:14:39 -04001880 return isDeadFunction(element.get());
Ethan Nicholas34b19c52020-09-14 11:33:47 -04001881 }),
1882 program.fElements.end());
Brian Osman133724c2020-10-28 14:14:39 -04001883 program.fSharedElements.erase(
1884 std::remove_if(program.fSharedElements.begin(), program.fSharedElements.end(),
1885 isDeadFunction),
1886 program.fSharedElements.end());
Ethan Nicholas34b19c52020-09-14 11:33:47 -04001887 }
1888
1889 if (program.fKind != Program::kFragmentProcessor_Kind) {
Brian Osmanc0213602020-10-06 14:43:32 -04001890 // Remove declarations of dead global variables
Brian Osman133724c2020-10-28 14:14:39 -04001891 auto isDeadVariable = [&](const ProgramElement* element) {
1892 if (!element->is<GlobalVarDeclaration>()) {
1893 return false;
1894 }
1895 const GlobalVarDeclaration& global = element->as<GlobalVarDeclaration>();
1896 const VarDeclaration& varDecl = global.declaration()->as<VarDeclaration>();
1897 if (usage->isDead(varDecl.var())) {
1898 madeChanges = true;
1899 return true;
1900 }
1901 return false;
1902 };
Ethan Nicholas34b19c52020-09-14 11:33:47 -04001903 program.fElements.erase(
1904 std::remove_if(program.fElements.begin(), program.fElements.end(),
1905 [&](const std::unique_ptr<ProgramElement>& element) {
Brian Osman133724c2020-10-28 14:14:39 -04001906 return isDeadVariable(element.get());
Ethan Nicholas34b19c52020-09-14 11:33:47 -04001907 }),
1908 program.fElements.end());
Brian Osman133724c2020-10-28 14:14:39 -04001909 program.fSharedElements.erase(
1910 std::remove_if(program.fSharedElements.begin(), program.fSharedElements.end(),
1911 isDeadVariable),
1912 program.fSharedElements.end());
Ethan Nicholas34b19c52020-09-14 11:33:47 -04001913 }
John Stiles73a6bff2020-09-09 13:40:37 -04001914
Ethan Nicholas34b19c52020-09-14 11:33:47 -04001915 if (!madeChanges) {
1916 break;
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001917 }
Ethan Nicholas00543112018-07-31 09:44:36 -04001918 }
1919 return fErrorCount == 0;
1920}
1921
Brian Osmanfb32ddf2019-06-18 10:14:20 -04001922#if defined(SKSL_STANDALONE) || SK_SUPPORT_GPU
1923
Ethan Nicholas00543112018-07-31 09:44:36 -04001924bool Compiler::toSPIRV(Program& program, OutputStream& out) {
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001925#ifdef SK_ENABLE_SPIRV_VALIDATION
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001926 StringStream buffer;
Brian Osman88cda172020-10-09 12:05:16 -04001927 AutoSource as(this, program.fSource.get());
Brian Osman8b43dad2020-10-09 13:31:42 -04001928 SPIRVCodeGenerator cg(fContext.get(), &program, this, &buffer);
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001929 bool result = cg.generateCode();
Ethan Nicholasba9a04f2020-11-06 09:28:04 -05001930 if (result && program.fSettings.fValidateSPIRV) {
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001931 spvtools::SpirvTools tools(SPV_ENV_VULKAN_1_0);
Ethan Nicholas762466e2017-06-29 10:03:38 -04001932 const String& data = buffer.str();
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001933 SkASSERT(0 == data.size() % 4);
Brian Osman8d09d4a2020-11-24 15:51:06 -05001934 String errors;
1935 auto dumpmsg = [&errors](spv_message_level_t, const char*, const spv_position_t&,
1936 const char* m) {
1937 errors.appendf("SPIR-V validation error: %s\n", m);
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001938 };
1939 tools.SetMessageConsumer(dumpmsg);
Brian Osman8d09d4a2020-11-24 15:51:06 -05001940
1941 // Verify that the SPIR-V we produced is valid. At runtime, we will abort() with a message
1942 // explaining the error. In standalone mode (skslc), we will send the message, plus the
1943 // entire disassembled SPIR-V (for easier context & debugging) as *our* error message.
1944 result = tools.Validate((const uint32_t*) data.c_str(), data.size() / 4);
1945
1946 if (!result) {
1947#if defined(SKSL_STANDALONE)
1948 // Convert the string-stream to a SPIR-V disassembly.
1949 std::string disassembly;
1950 if (tools.Disassemble((const uint32_t*)data.data(), data.size() / 4, &disassembly)) {
1951 errors.append(disassembly);
1952 }
1953 this->error(-1, errors);
1954#else
1955 SkDEBUGFAILF("%s", errors.c_str());
1956#endif
1957 }
Ethan Nicholas762466e2017-06-29 10:03:38 -04001958 out.write(data.c_str(), data.size());
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001959 }
1960#else
Brian Osman88cda172020-10-09 12:05:16 -04001961 AutoSource as(this, program.fSource.get());
Brian Osman8b43dad2020-10-09 13:31:42 -04001962 SPIRVCodeGenerator cg(fContext.get(), &program, this, &out);
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001963 bool result = cg.generateCode();
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -04001964#endif
Ethan Nicholasce33f102016-12-09 17:22:59 -05001965 return result;
1966}
1967
Ethan Nicholas00543112018-07-31 09:44:36 -04001968bool Compiler::toSPIRV(Program& program, String* out) {
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001969 StringStream buffer;
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001970 bool result = this->toSPIRV(program, buffer);
1971 if (result) {
Ethan Nicholas762466e2017-06-29 10:03:38 -04001972 *out = buffer.str();
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001973 }
1974 return result;
1975}
1976
Ethan Nicholas00543112018-07-31 09:44:36 -04001977bool Compiler::toGLSL(Program& program, OutputStream& out) {
Brian Osman88cda172020-10-09 12:05:16 -04001978 AutoSource as(this, program.fSource.get());
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04001979 GLSLCodeGenerator cg(fContext.get(), &program, this, &out);
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001980 bool result = cg.generateCode();
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001981 return result;
1982}
1983
Ethan Nicholas00543112018-07-31 09:44:36 -04001984bool Compiler::toGLSL(Program& program, String* out) {
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001985 StringStream buffer;
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001986 bool result = this->toGLSL(program, buffer);
1987 if (result) {
Ethan Nicholas762466e2017-06-29 10:03:38 -04001988 *out = buffer.str();
Ethan Nicholas941e7e22016-12-12 15:33:30 -05001989 }
1990 return result;
1991}
1992
Brian Osmanc0243912020-02-19 15:35:26 -05001993bool Compiler::toHLSL(Program& program, String* out) {
1994 String spirv;
1995 if (!this->toSPIRV(program, &spirv)) {
1996 return false;
1997 }
1998
1999 return SPIRVtoHLSL(spirv, out);
2000}
2001
Ethan Nicholas00543112018-07-31 09:44:36 -04002002bool Compiler::toMetal(Program& program, OutputStream& out) {
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04002003 MetalCodeGenerator cg(fContext.get(), &program, this, &out);
Ethan Nicholascc305772017-10-13 16:17:45 -04002004 bool result = cg.generateCode();
Ethan Nicholascc305772017-10-13 16:17:45 -04002005 return result;
2006}
2007
Ethan Nicholas00543112018-07-31 09:44:36 -04002008bool Compiler::toMetal(Program& program, String* out) {
Timothy Liangb8eeb802018-07-23 16:46:16 -04002009 StringStream buffer;
2010 bool result = this->toMetal(program, buffer);
2011 if (result) {
2012 *out = buffer.str();
2013 }
2014 return result;
2015}
2016
Greg Daniela28ea672020-09-25 11:12:56 -04002017#if defined(SKSL_STANDALONE) || GR_TEST_UTILS
Ethan Nicholas00543112018-07-31 09:44:36 -04002018bool Compiler::toCPP(Program& program, String name, OutputStream& out) {
Brian Osman88cda172020-10-09 12:05:16 -04002019 AutoSource as(this, program.fSource.get());
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04002020 CPPCodeGenerator cg(fContext.get(), &program, this, name, &out);
Ethan Nicholas762466e2017-06-29 10:03:38 -04002021 bool result = cg.generateCode();
Ethan Nicholas762466e2017-06-29 10:03:38 -04002022 return result;
2023}
2024
Ethan Nicholas00543112018-07-31 09:44:36 -04002025bool Compiler::toH(Program& program, String name, OutputStream& out) {
Brian Osman88cda172020-10-09 12:05:16 -04002026 AutoSource as(this, program.fSource.get());
Ethan Nicholas26a9aad2018-03-27 14:10:52 -04002027 HCodeGenerator cg(fContext.get(), &program, this, name, &out);
Ethan Nicholas762466e2017-06-29 10:03:38 -04002028 bool result = cg.generateCode();
Ethan Nicholas00543112018-07-31 09:44:36 -04002029 return result;
2030}
Greg Daniela28ea672020-09-25 11:12:56 -04002031#endif // defined(SKSL_STANDALONE) || GR_TEST_UTILS
Ethan Nicholas00543112018-07-31 09:44:36 -04002032
Ethan Nicholas2a479a52020-08-18 16:29:45 -04002033#endif // defined(SKSL_STANDALONE) || SK_SUPPORT_GPU
Brian Osman2e29ab52019-09-20 12:19:11 -04002034
2035#if !defined(SKSL_STANDALONE) && SK_SUPPORT_GPU
Brian Osmana4b91692020-08-10 14:26:16 -04002036bool Compiler::toPipelineStage(Program& program, PipelineStageArgs* outArgs) {
Brian Osman88cda172020-10-09 12:05:16 -04002037 AutoSource as(this, program.fSource.get());
Ethan Nicholas00543112018-07-31 09:44:36 -04002038 StringStream buffer;
Brian Osman300fe1d2020-01-23 15:42:43 -05002039 PipelineStageCodeGenerator cg(fContext.get(), &program, this, &buffer, outArgs);
Ethan Nicholas00543112018-07-31 09:44:36 -04002040 bool result = cg.generateCode();
Ethan Nicholas00543112018-07-31 09:44:36 -04002041 if (result) {
Brian Osman107c6662019-12-30 15:02:30 -05002042 outArgs->fCode = buffer.str();
Ethan Nicholas00543112018-07-31 09:44:36 -04002043 }
Ethan Nicholas762466e2017-06-29 10:03:38 -04002044 return result;
2045}
Brian Osmanfb32ddf2019-06-18 10:14:20 -04002046#endif
2047
Ethan Nicholas0e9401d2019-03-21 11:05:37 -04002048std::unique_ptr<ByteCode> Compiler::toByteCode(Program& program) {
Brian Osman88cda172020-10-09 12:05:16 -04002049 AutoSource as(this, program.fSource.get());
Ethan Nicholas0e9401d2019-03-21 11:05:37 -04002050 std::unique_ptr<ByteCode> result(new ByteCode());
Brian Osmanb08cc022020-04-02 11:38:40 -04002051 ByteCodeGenerator cg(fContext.get(), &program, this, result.get());
2052 bool success = cg.generateCode();
Brian Osmanb08cc022020-04-02 11:38:40 -04002053 if (success) {
Ethan Nicholas0e9401d2019-03-21 11:05:37 -04002054 return result;
2055 }
2056 return nullptr;
2057}
2058
Brian Osman401a0092020-09-10 14:47:24 -04002059const char* Compiler::OperatorName(Token::Kind op) {
2060 switch (op) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002061 case Token::Kind::TK_PLUS: return "+";
2062 case Token::Kind::TK_MINUS: return "-";
2063 case Token::Kind::TK_STAR: return "*";
2064 case Token::Kind::TK_SLASH: return "/";
2065 case Token::Kind::TK_PERCENT: return "%";
2066 case Token::Kind::TK_SHL: return "<<";
2067 case Token::Kind::TK_SHR: return ">>";
2068 case Token::Kind::TK_LOGICALNOT: return "!";
2069 case Token::Kind::TK_LOGICALAND: return "&&";
2070 case Token::Kind::TK_LOGICALOR: return "||";
2071 case Token::Kind::TK_LOGICALXOR: return "^^";
2072 case Token::Kind::TK_BITWISENOT: return "~";
2073 case Token::Kind::TK_BITWISEAND: return "&";
2074 case Token::Kind::TK_BITWISEOR: return "|";
2075 case Token::Kind::TK_BITWISEXOR: return "^";
2076 case Token::Kind::TK_EQ: return "=";
2077 case Token::Kind::TK_EQEQ: return "==";
2078 case Token::Kind::TK_NEQ: return "!=";
2079 case Token::Kind::TK_LT: return "<";
2080 case Token::Kind::TK_GT: return ">";
2081 case Token::Kind::TK_LTEQ: return "<=";
2082 case Token::Kind::TK_GTEQ: return ">=";
2083 case Token::Kind::TK_PLUSEQ: return "+=";
2084 case Token::Kind::TK_MINUSEQ: return "-=";
2085 case Token::Kind::TK_STAREQ: return "*=";
2086 case Token::Kind::TK_SLASHEQ: return "/=";
2087 case Token::Kind::TK_PERCENTEQ: return "%=";
2088 case Token::Kind::TK_SHLEQ: return "<<=";
2089 case Token::Kind::TK_SHREQ: return ">>=";
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002090 case Token::Kind::TK_BITWISEANDEQ: return "&=";
2091 case Token::Kind::TK_BITWISEOREQ: return "|=";
2092 case Token::Kind::TK_BITWISEXOREQ: return "^=";
2093 case Token::Kind::TK_PLUSPLUS: return "++";
2094 case Token::Kind::TK_MINUSMINUS: return "--";
2095 case Token::Kind::TK_COMMA: return ",";
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002096 default:
Brian Osman401a0092020-09-10 14:47:24 -04002097 ABORT("unsupported operator: %d\n", (int) op);
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002098 }
2099}
2100
2101
2102bool Compiler::IsAssignment(Token::Kind op) {
2103 switch (op) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002104 case Token::Kind::TK_EQ: // fall through
2105 case Token::Kind::TK_PLUSEQ: // fall through
2106 case Token::Kind::TK_MINUSEQ: // fall through
2107 case Token::Kind::TK_STAREQ: // fall through
2108 case Token::Kind::TK_SLASHEQ: // fall through
2109 case Token::Kind::TK_PERCENTEQ: // fall through
2110 case Token::Kind::TK_SHLEQ: // fall through
2111 case Token::Kind::TK_SHREQ: // fall through
2112 case Token::Kind::TK_BITWISEOREQ: // fall through
2113 case Token::Kind::TK_BITWISEXOREQ: // fall through
John Stiles8b3b1592020-11-23 11:06:44 -05002114 case Token::Kind::TK_BITWISEANDEQ:
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002115 return true;
2116 default:
2117 return false;
2118 }
2119}
2120
Brian Osman401a0092020-09-10 14:47:24 -04002121Token::Kind Compiler::RemoveAssignment(Token::Kind op) {
2122 switch (op) {
2123 case Token::Kind::TK_PLUSEQ: return Token::Kind::TK_PLUS;
2124 case Token::Kind::TK_MINUSEQ: return Token::Kind::TK_MINUS;
2125 case Token::Kind::TK_STAREQ: return Token::Kind::TK_STAR;
2126 case Token::Kind::TK_SLASHEQ: return Token::Kind::TK_SLASH;
2127 case Token::Kind::TK_PERCENTEQ: return Token::Kind::TK_PERCENT;
2128 case Token::Kind::TK_SHLEQ: return Token::Kind::TK_SHL;
2129 case Token::Kind::TK_SHREQ: return Token::Kind::TK_SHR;
2130 case Token::Kind::TK_BITWISEOREQ: return Token::Kind::TK_BITWISEOR;
2131 case Token::Kind::TK_BITWISEXOREQ: return Token::Kind::TK_BITWISEXOR;
2132 case Token::Kind::TK_BITWISEANDEQ: return Token::Kind::TK_BITWISEAND;
Brian Osman401a0092020-09-10 14:47:24 -04002133 default: return op;
2134 }
2135}
2136
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002137Position Compiler::position(int offset) {
Ethan Nicholas3c729892020-12-07 12:47:17 -05002138 if (fSource && offset >= 0) {
2139 int line = 1;
2140 int column = 1;
2141 for (int i = 0; i < offset; i++) {
2142 if ((*fSource)[i] == '\n') {
2143 ++line;
2144 column = 1;
2145 }
2146 else {
2147 ++column;
2148 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002149 }
Ethan Nicholas3c729892020-12-07 12:47:17 -05002150 return Position(line, column);
2151 } else {
2152 return Position(-1, -1);
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002153 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002154}
2155
2156void Compiler::error(int offset, String msg) {
ethannicholasb3058bd2016-07-01 08:22:01 -07002157 fErrorCount++;
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07002158 Position pos = this->position(offset);
Ethan Nicholas3c729892020-12-07 12:47:17 -05002159 fErrorText += "error: " + (pos.fLine >= 1 ? to_string(pos.fLine) + ": " : "") + msg + "\n";
ethannicholasb3058bd2016-07-01 08:22:01 -07002160}
2161
Ethan Nicholasdcd2f862020-12-17 23:24:25 +00002162String Compiler::errorText() {
2163 this->writeErrorCount();
Ethan Nicholas00543112018-07-31 09:44:36 -04002164 fErrorCount = 0;
Ethan Nicholas0df1b042017-03-31 13:56:23 -04002165 String result = fErrorText;
ethannicholasb3058bd2016-07-01 08:22:01 -07002166 return result;
2167}
2168
2169void Compiler::writeErrorCount() {
2170 if (fErrorCount) {
2171 fErrorText += to_string(fErrorCount) + " error";
2172 if (fErrorCount > 1) {
2173 fErrorText += "s";
2174 }
2175 fErrorText += "\n";
2176 }
2177}
2178
John Stilesa6841be2020-08-06 14:11:56 -04002179} // namespace SkSL