blob: ab3bc8e6c852609b6409719fa92b0274304ed126 [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
Ethan Nicholas55a63af2021-05-18 10:12:58 -040013#include "include/sksl/DSLCore.h"
John Stiles270cec22021-02-17 12:59:36 -050014#include "src/core/SkScopeExit.h"
Leon Scrogginsb66214e2021-02-11 17:14:18 -050015#include "src/core/SkTraceEvent.h"
John Stilesb92641c2020-08-31 18:09:01 -040016#include "src/sksl/SkSLAnalysis.h"
John Stilesf3a28db2021-03-10 23:00:47 -050017#include "src/sksl/SkSLConstantFolder.h"
Ethan Nicholasdd2fdea2021-07-20 15:23:04 -040018#include "src/sksl/SkSLDSLParser.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050019#include "src/sksl/SkSLIRGenerator.h"
Brian Osman00185012021-02-04 16:07:11 -050020#include "src/sksl/SkSLOperators.h"
John Stiles270cec22021-02-17 12:59:36 -050021#include "src/sksl/SkSLProgramSettings.h"
Ethan Nicholasc18bb512020-07-28 14:46:53 -040022#include "src/sksl/SkSLRehydrator.h"
John Stiles3738ef52021-04-13 10:41:57 -040023#include "src/sksl/codegen/SkSLGLSLCodeGenerator.h"
John Stiles3738ef52021-04-13 10:41:57 -040024#include "src/sksl/codegen/SkSLMetalCodeGenerator.h"
25#include "src/sksl/codegen/SkSLSPIRVCodeGenerator.h"
26#include "src/sksl/codegen/SkSLSPIRVtoHLSL.h"
Ethan Nicholas55a63af2021-05-18 10:12:58 -040027#include "src/sksl/dsl/priv/DSLWriter.h"
28#include "src/sksl/dsl/priv/DSL_priv.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050029#include "src/sksl/ir/SkSLExpression.h"
30#include "src/sksl/ir/SkSLExpressionStatement.h"
31#include "src/sksl/ir/SkSLFunctionCall.h"
32#include "src/sksl/ir/SkSLIntLiteral.h"
33#include "src/sksl/ir/SkSLModifiersDeclaration.h"
34#include "src/sksl/ir/SkSLNop.h"
35#include "src/sksl/ir/SkSLSymbolTable.h"
36#include "src/sksl/ir/SkSLTernaryExpression.h"
37#include "src/sksl/ir/SkSLUnresolvedFunction.h"
38#include "src/sksl/ir/SkSLVarDeclarations.h"
John Stilese6150002020-10-05 12:03:53 -040039#include "src/utils/SkBitSet.h"
ethannicholasb3058bd2016-07-01 08:22:01 -070040
Ethan Nicholasb33fa3f2020-08-06 13:00:19 -040041#include <fstream>
42
Ethan Nicholasa11035b2019-11-26 16:27:47 -050043#if !defined(SKSL_STANDALONE) & SK_SUPPORT_GPU
44#include "include/gpu/GrContextOptions.h"
45#include "src/gpu/GrShaderCaps.h"
46#endif
47
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -040048#ifdef SK_ENABLE_SPIRV_VALIDATION
49#include "spirv-tools/libspirv.hpp"
50#endif
51
Brian Osman3d87e9f2020-10-08 11:50:22 -040052#if defined(SKSL_STANDALONE)
Ethan Nicholasc18bb512020-07-28 14:46:53 -040053
Brian Osman3d87e9f2020-10-08 11:50:22 -040054// In standalone mode, we load the textual sksl source files. GN generates or copies these files
55// to the skslc executable directory. The "data" in this mode is just the filename.
56#define MODULE_DATA(name) MakeModulePath("sksl_" #name ".sksl")
57
58#else
59
60// At runtime, we load the dehydrated sksl data files. The data is a (pointer, size) pair.
Ethan Nicholasc18bb512020-07-28 14:46:53 -040061#include "src/sksl/generated/sksl_frag.dehydrated.sksl"
Ethan Nicholasc18bb512020-07-28 14:46:53 -040062#include "src/sksl/generated/sksl_gpu.dehydrated.sksl"
Brian Osmanb06301e2020-11-06 11:45:36 -050063#include "src/sksl/generated/sksl_public.dehydrated.sksl"
John Stilesf7f36ae2021-06-08 14:06:22 -040064#include "src/sksl/generated/sksl_rt_blend.dehydrated.sksl"
Brian Osmancbb60bd2021-04-12 09:49:20 -040065#include "src/sksl/generated/sksl_rt_colorfilter.dehydrated.sksl"
66#include "src/sksl/generated/sksl_rt_shader.dehydrated.sksl"
Ethan Nicholasc18bb512020-07-28 14:46:53 -040067#include "src/sksl/generated/sksl_vert.dehydrated.sksl"
68
Brian Osman3d87e9f2020-10-08 11:50:22 -040069#define MODULE_DATA(name) MakeModuleData(SKSL_INCLUDE_sksl_##name,\
70 SKSL_INCLUDE_sksl_##name##_LENGTH)
Ethan Nicholasc18bb512020-07-28 14:46:53 -040071
72#endif
Ethan Nicholas0d997662019-04-08 09:46:01 -040073
ethannicholasb3058bd2016-07-01 08:22:01 -070074namespace SkSL {
75
John Stiles7247b482021-03-08 10:40:35 -050076// These flags allow tools like Viewer or Nanobench to override the compiler's ProgramSettings.
John Stiles2ee4d7a2021-03-30 10:30:47 -040077Compiler::OverrideFlag Compiler::sOptimizer = OverrideFlag::kDefault;
78Compiler::OverrideFlag Compiler::sInliner = OverrideFlag::kDefault;
John Stiles8ef4d6c2021-03-05 16:01:45 -050079
John Stiles47c0a742021-02-09 09:30:35 -050080using RefKind = VariableReference::RefKind;
81
Brian Osman88cda172020-10-09 12:05:16 -040082class AutoSource {
83public:
Ethan Nicholasb449fff2021-08-04 15:06:37 -040084 AutoSource(Compiler* compiler, const char* source)
John Stilesa289ac22021-05-06 07:35:35 -040085 : fCompiler(compiler) {
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -040086 SkASSERT(!fCompiler->errorReporter().source());
87 fCompiler->errorReporter().setSource(source);
Brian Osman88cda172020-10-09 12:05:16 -040088 }
89
John Stilesa289ac22021-05-06 07:35:35 -040090 ~AutoSource() {
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -040091 fCompiler->errorReporter().setSource(nullptr);
John Stilesa289ac22021-05-06 07:35:35 -040092 }
Brian Osman88cda172020-10-09 12:05:16 -040093
94 Compiler* fCompiler;
Brian Osman88cda172020-10-09 12:05:16 -040095};
96
John Stilesa935c3f2021-02-25 10:35:49 -050097class AutoProgramConfig {
98public:
99 AutoProgramConfig(std::shared_ptr<Context>& context, ProgramConfig* config)
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -0400100 : fContext(context.get())
101 , fOldConfig(fContext->fConfig) {
John Stilesa935c3f2021-02-25 10:35:49 -0500102 fContext->fConfig = config;
103 }
104
105 ~AutoProgramConfig() {
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -0400106 fContext->fConfig = fOldConfig;
John Stilesa935c3f2021-02-25 10:35:49 -0500107 }
108
109 Context* fContext;
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -0400110 ProgramConfig* fOldConfig;
John Stilesa935c3f2021-02-25 10:35:49 -0500111};
112
John Stiles10d39d92021-05-04 16:13:14 -0400113class AutoModifiersPool {
114public:
115 AutoModifiersPool(std::shared_ptr<Context>& context, ModifiersPool* modifiersPool)
116 : fContext(context.get()) {
117 SkASSERT(!fContext->fModifiersPool);
118 fContext->fModifiersPool = modifiersPool;
119 }
120
121 ~AutoModifiersPool() {
122 fContext->fModifiersPool = nullptr;
123 }
124
125 Context* fContext;
126};
127
John Stilesd6a5f4492021-02-11 15:46:11 -0500128Compiler::Compiler(const ShaderCapsClass* caps)
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -0400129 : fErrorReporter(this)
130 , fContext(std::make_shared<Context>(fErrorReporter, *caps))
John Stilesa47b3512021-05-04 16:15:00 -0400131 , fInliner(fContext.get()) {
John Stilesc1a98b82021-02-24 13:35:02 -0500132 SkASSERT(caps);
John Stilesb624b722021-08-13 12:16:13 -0400133 fRootModule.fSymbols = this->makeRootSymbolTable();
134 fPrivateModule.fSymbols = this->makePrivateSymbolTable(fRootModule.fSymbols);
John Stilesc1a98b82021-02-24 13:35:02 -0500135 fIRGenerator = std::make_unique<IRGenerator>(fContext.get());
John Stilesb624b722021-08-13 12:16:13 -0400136}
137
138Compiler::~Compiler() {}
ethannicholasb3058bd2016-07-01 08:22:01 -0700139
John Stiles54e7c052021-01-11 14:22:36 -0500140#define TYPE(t) fContext->fTypes.f ## t .get()
ethannicholasb3058bd2016-07-01 08:22:01 -0700141
John Stilesb624b722021-08-13 12:16:13 -0400142std::shared_ptr<SymbolTable> Compiler::makeRootSymbolTable() {
Ethan Nicholasc7774a72021-08-27 15:34:05 -0400143 auto rootSymbolTable = std::make_shared<SymbolTable>(*fContext, /*builtin=*/true);
John Stilesb624b722021-08-13 12:16:13 -0400144
Brian Osmanb06301e2020-11-06 11:45:36 -0500145 const SkSL::Symbol* rootTypes[] = {
146 TYPE(Void),
Brian Salomonbf7b6202016-11-11 16:08:03 -0500147
Brian Osmanb06301e2020-11-06 11:45:36 -0500148 TYPE( Float), TYPE( Float2), TYPE( Float3), TYPE( Float4),
149 TYPE( Half), TYPE( Half2), TYPE( Half3), TYPE( Half4),
150 TYPE( Int), TYPE( Int2), TYPE( Int3), TYPE( Int4),
John Stiles823c5042021-08-17 12:09:00 -0400151 TYPE( UInt), TYPE( UInt2), TYPE( UInt3), TYPE( UInt4),
152 TYPE( Short), TYPE( Short2), TYPE( Short3), TYPE( Short4),
153 TYPE(UShort), TYPE(UShort2), TYPE(UShort3), TYPE(UShort4),
Brian Osmanb06301e2020-11-06 11:45:36 -0500154 TYPE( Bool), TYPE( Bool2), TYPE( Bool3), TYPE( Bool4),
Brian Salomon2a51de82016-11-16 12:06:01 -0500155
John Stiles823c5042021-08-17 12:09:00 -0400156 TYPE(Float2x2), TYPE(Float2x3), TYPE(Float2x4),
157 TYPE(Float3x2), TYPE(Float3x3), TYPE(Float3x4),
158 TYPE(Float4x2), TYPE(Float4x3), TYPE(Float4x4),
159
160 TYPE(Half2x2), TYPE(Half2x3), TYPE(Half2x4),
161 TYPE(Half3x2), TYPE(Half3x3), TYPE(Half3x4),
162 TYPE(Half4x2), TYPE(Half4x3), TYPE(Half4x4),
Greg Daniel64773e62016-11-22 09:44:03 -0500163
Brian Osmanc63f4312020-12-23 11:44:14 -0500164 TYPE(SquareMat), TYPE(SquareHMat),
John Stiles823c5042021-08-17 12:09:00 -0400165 TYPE(Mat), TYPE(HMat),
ethannicholasb3058bd2016-07-01 08:22:01 -0700166
John Stiles823c5042021-08-17 12:09:00 -0400167 // TODO(skia:12349): generic short/ushort
168 TYPE(GenType), TYPE(GenIType), TYPE(GenUType),
169 TYPE(GenHType), /* (GenSType) (GenUSType) */
170 TYPE(GenBType),
171
172 TYPE(Vec), TYPE(IVec), TYPE(UVec),
173 TYPE(HVec), TYPE(SVec), TYPE(USVec),
174 TYPE(BVec),
Brian Osmanb06301e2020-11-06 11:45:36 -0500175
Brian Osman14d00962021-04-02 17:04:35 -0400176 TYPE(ColorFilter),
177 TYPE(Shader),
John Stilesbb2ef922021-07-26 08:32:07 -0400178 TYPE(Blender),
Brian Osmanb06301e2020-11-06 11:45:36 -0500179 };
180
John Stilesb624b722021-08-13 12:16:13 -0400181 for (const SkSL::Symbol* type : rootTypes) {
182 rootSymbolTable->addWithoutOwnership(type);
183 }
184
185 return rootSymbolTable;
186}
187
188std::shared_ptr<SymbolTable> Compiler::makePrivateSymbolTable(std::shared_ptr<SymbolTable> parent) {
189 auto privateSymbolTable = std::make_shared<SymbolTable>(parent, /*builtin=*/true);
190
Brian Osmanb06301e2020-11-06 11:45:36 -0500191 const SkSL::Symbol* privateTypes[] = {
192 TYPE(Sampler1D), TYPE(Sampler2D), TYPE(Sampler3D),
193 TYPE(SamplerExternalOES),
Brian Osmanb06301e2020-11-06 11:45:36 -0500194 TYPE(Sampler2DRect),
Brian Osmanb06301e2020-11-06 11:45:36 -0500195
196 TYPE(ISampler2D),
Brian Osmanb06301e2020-11-06 11:45:36 -0500197 TYPE(SubpassInput), TYPE(SubpassInputMS),
198
Brian Osmanb06301e2020-11-06 11:45:36 -0500199 TYPE(Sampler),
200 TYPE(Texture2D),
201 };
202
Brian Osmanb06301e2020-11-06 11:45:36 -0500203 for (const SkSL::Symbol* type : privateTypes) {
John Stilesb624b722021-08-13 12:16:13 -0400204 privateSymbolTable->addWithoutOwnership(type);
Brian Osmanb06301e2020-11-06 11:45:36 -0500205 }
206
Brian Osman3887a012020-09-30 13:22:27 -0400207 // sk_Caps is "builtin", but all references to it are resolved to Settings, so we don't need to
208 // treat it as builtin (ie, no need to clone it into the Program).
John Stilesb624b722021-08-13 12:16:13 -0400209 privateSymbolTable->add(std::make_unique<Variable>(/*offset=*/-1,
210 fCoreModifiers.add(Modifiers{}),
211 "sk_Caps",
212 fContext->fTypes.fSkCaps.get(),
213 /*builtin=*/false,
214 Variable::Storage::kGlobal));
Ethan Nicholas3605ace2016-11-21 15:59:48 -0500215
John Stilesb624b722021-08-13 12:16:13 -0400216 return privateSymbolTable;
ethannicholasb3058bd2016-07-01 08:22:01 -0700217}
218
John Stilesb624b722021-08-13 12:16:13 -0400219#undef TYPE
ethannicholasb3058bd2016-07-01 08:22:01 -0700220
Brian Osman56269982020-11-20 12:38:07 -0500221const ParsedModule& Compiler::loadGPUModule() {
222 if (!fGPUModule.fSymbols) {
John Stilesdbd4e6f2021-02-16 13:29:15 -0500223 fGPUModule = this->parseModule(ProgramKind::kFragment, MODULE_DATA(gpu), fPrivateModule);
Brian Osman56269982020-11-20 12:38:07 -0500224 }
225 return fGPUModule;
226}
227
228const ParsedModule& Compiler::loadFragmentModule() {
229 if (!fFragmentModule.fSymbols) {
John Stilesdbd4e6f2021-02-16 13:29:15 -0500230 fFragmentModule = this->parseModule(ProgramKind::kFragment, MODULE_DATA(frag),
Brian Osman56269982020-11-20 12:38:07 -0500231 this->loadGPUModule());
232 }
233 return fFragmentModule;
234}
235
236const ParsedModule& Compiler::loadVertexModule() {
237 if (!fVertexModule.fSymbols) {
John Stilesdbd4e6f2021-02-16 13:29:15 -0500238 fVertexModule = this->parseModule(ProgramKind::kVertex, MODULE_DATA(vert),
Brian Osman56269982020-11-20 12:38:07 -0500239 this->loadGPUModule());
240 }
241 return fVertexModule;
242}
243
Brian Osmanb06301e2020-11-06 11:45:36 -0500244const ParsedModule& Compiler::loadPublicModule() {
245 if (!fPublicModule.fSymbols) {
John Stilesdbd4e6f2021-02-16 13:29:15 -0500246 fPublicModule = this->parseModule(ProgramKind::kGeneric, MODULE_DATA(public), fRootModule);
Brian Osmanb06301e2020-11-06 11:45:36 -0500247 }
248 return fPublicModule;
249}
250
Brian Osmancbb60bd2021-04-12 09:49:20 -0400251static void add_glsl_type_aliases(SkSL::SymbolTable* symbols, const SkSL::BuiltinTypes& types) {
252 // Add some aliases to the runtime effect modules so that it's friendlier, and more like GLSL
253 symbols->addAlias("vec2", types.fFloat2.get());
254 symbols->addAlias("vec3", types.fFloat3.get());
255 symbols->addAlias("vec4", types.fFloat4.get());
256
257 symbols->addAlias("ivec2", types.fInt2.get());
258 symbols->addAlias("ivec3", types.fInt3.get());
259 symbols->addAlias("ivec4", types.fInt4.get());
260
261 symbols->addAlias("bvec2", types.fBool2.get());
262 symbols->addAlias("bvec3", types.fBool3.get());
263 symbols->addAlias("bvec4", types.fBool4.get());
264
265 symbols->addAlias("mat2", types.fFloat2x2.get());
266 symbols->addAlias("mat3", types.fFloat3x3.get());
267 symbols->addAlias("mat4", types.fFloat4x4.get());
268}
269
Brian Osmancbb60bd2021-04-12 09:49:20 -0400270const ParsedModule& Compiler::loadRuntimeColorFilterModule() {
271 if (!fRuntimeColorFilterModule.fSymbols) {
272 fRuntimeColorFilterModule = this->parseModule(ProgramKind::kRuntimeColorFilter,
273 MODULE_DATA(rt_colorfilter),
274 this->loadPublicModule());
275 add_glsl_type_aliases(fRuntimeColorFilterModule.fSymbols.get(), fContext->fTypes);
276 }
277 return fRuntimeColorFilterModule;
278}
279
280const ParsedModule& Compiler::loadRuntimeShaderModule() {
281 if (!fRuntimeShaderModule.fSymbols) {
282 fRuntimeShaderModule = this->parseModule(
283 ProgramKind::kRuntimeShader, MODULE_DATA(rt_shader), this->loadPublicModule());
284 add_glsl_type_aliases(fRuntimeShaderModule.fSymbols.get(), fContext->fTypes);
285 }
286 return fRuntimeShaderModule;
287}
288
John Stiles2d8b8352021-06-16 11:33:13 -0400289const ParsedModule& Compiler::loadRuntimeBlenderModule() {
290 if (!fRuntimeBlenderModule.fSymbols) {
291 fRuntimeBlenderModule = this->parseModule(
292 ProgramKind::kRuntimeBlender, MODULE_DATA(rt_blend), this->loadPublicModule());
293 add_glsl_type_aliases(fRuntimeBlenderModule.fSymbols.get(), fContext->fTypes);
John Stilesf7f36ae2021-06-08 14:06:22 -0400294 }
John Stiles2d8b8352021-06-16 11:33:13 -0400295 return fRuntimeBlenderModule;
John Stilesf7f36ae2021-06-08 14:06:22 -0400296}
297
John Stilesdbd4e6f2021-02-16 13:29:15 -0500298const ParsedModule& Compiler::moduleForProgramKind(ProgramKind kind) {
Brian Osman88cda172020-10-09 12:05:16 -0400299 switch (kind) {
Brian Osmancbb60bd2021-04-12 09:49:20 -0400300 case ProgramKind::kVertex: return this->loadVertexModule(); break;
301 case ProgramKind::kFragment: return this->loadFragmentModule(); break;
Brian Osmancbb60bd2021-04-12 09:49:20 -0400302 case ProgramKind::kRuntimeColorFilter: return this->loadRuntimeColorFilterModule(); break;
303 case ProgramKind::kRuntimeShader: return this->loadRuntimeShaderModule(); break;
John Stiles2d8b8352021-06-16 11:33:13 -0400304 case ProgramKind::kRuntimeBlender: return this->loadRuntimeBlenderModule(); break;
Brian Osmancbb60bd2021-04-12 09:49:20 -0400305 case ProgramKind::kGeneric: return this->loadPublicModule(); break;
Brian Osman88cda172020-10-09 12:05:16 -0400306 }
307 SkUNREACHABLE;
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400308}
309
John Stilesdbd4e6f2021-02-16 13:29:15 -0500310LoadedModule Compiler::loadModule(ProgramKind kind,
Brian Osman3d87e9f2020-10-08 11:50:22 -0400311 ModuleData data,
John Stilesa935c3f2021-02-25 10:35:49 -0500312 std::shared_ptr<SymbolTable> base,
313 bool dehydrate) {
314 if (dehydrate) {
315 // NOTE: This is a workaround. When dehydrating includes, skslc doesn't know which module
316 // it's preparing, nor what the correct base module is. We can't use 'Root', because many
317 // GPU intrinsics reference private types, like samplers or textures. Today, 'Private' does
318 // contain the union of all known types, so this is safe. If we ever have types that only
319 // exist in 'Public' (for example), this logic needs to be smarter (by choosing the correct
320 // base for the module we're compiling).
John Stilesb624b722021-08-13 12:16:13 -0400321 base = fPrivateModule.fSymbols;
Brian Osman3d87e9f2020-10-08 11:50:22 -0400322 }
John Stilesa935c3f2021-02-25 10:35:49 -0500323 SkASSERT(base);
324
John Stilesa47b3512021-05-04 16:15:00 -0400325 // Put the core-module modifier pool into the context.
326 AutoModifiersPool autoPool(fContext, &fCoreModifiers);
John Stiles10d39d92021-05-04 16:13:14 -0400327
John Stilesa935c3f2021-02-25 10:35:49 -0500328 // Built-in modules always use default program settings.
Ethan Nicholas55a63af2021-05-18 10:12:58 -0400329 Program::Settings settings;
330 settings.fReplaceSettings = !dehydrate;
Brian Osman3d87e9f2020-10-08 11:50:22 -0400331
332#if defined(SKSL_STANDALONE)
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -0400333 SkASSERT(this->errorCount() == 0);
Brian Osman3d87e9f2020-10-08 11:50:22 -0400334 SkASSERT(data.fPath);
335 std::ifstream in(data.fPath);
John Stilesd51c9792021-03-18 11:40:14 -0400336 String text{std::istreambuf_iterator<char>(in), std::istreambuf_iterator<char>()};
Ethan Nicholasb33fa3f2020-08-06 13:00:19 -0400337 if (in.rdstate()) {
Brian Osman3d87e9f2020-10-08 11:50:22 -0400338 printf("error reading %s\n", data.fPath);
Ethan Nicholasb33fa3f2020-08-06 13:00:19 -0400339 abort();
340 }
John Stilesb624b722021-08-13 12:16:13 -0400341 const String* source = fRootModule.fSymbols->takeOwnershipOfString(std::move(text));
John Stilesd1204642021-02-17 16:30:02 -0500342
Brian Osman88cda172020-10-09 12:05:16 -0400343 ParsedModule baseModule = {base, /*fIntrinsics=*/nullptr};
Ethan Nicholas55a63af2021-05-18 10:12:58 -0400344 std::vector<std::unique_ptr<ProgramElement>> elements;
345 std::vector<const ProgramElement*> sharedElements;
346 dsl::StartModule(this, kind, settings, baseModule);
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -0400347 dsl::SetErrorReporter(&this->errorReporter());
Ethan Nicholasb449fff2021-08-04 15:06:37 -0400348 AutoSource as(this, source->c_str());
John Stilesd1204642021-02-17 16:30:02 -0500349 IRGenerator::IRBundle ir = fIRGenerator->convertProgram(baseModule, /*isBuiltinCode=*/true,
Ethan Nicholas6823b502021-06-15 11:42:07 -0400350 *source);
Brian Osman133724c2020-10-28 14:14:39 -0400351 SkASSERT(ir.fSharedElements.empty());
Brian Osman0006ad02020-11-18 15:38:39 -0500352 LoadedModule module = { kind, std::move(ir.fSymbolTable), std::move(ir.fElements) };
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -0400353 if (this->errorCount()) {
Ethan Nicholas8da1e652019-05-24 11:01:59 -0400354 printf("Unexpected errors: %s\n", this->fErrorText.c_str());
Brian Osman3d87e9f2020-10-08 11:50:22 -0400355 SkDEBUGFAILF("%s %s\n", data.fPath, this->fErrorText.c_str());
Ethan Nicholas8da1e652019-05-24 11:01:59 -0400356 }
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -0400357 dsl::End();
Brian Osman3d87e9f2020-10-08 11:50:22 -0400358#else
Ethan Nicholas55a63af2021-05-18 10:12:58 -0400359 ProgramConfig config;
360 config.fKind = kind;
361 config.fSettings = settings;
362 AutoProgramConfig autoConfig(fContext, &config);
Brian Osman3d87e9f2020-10-08 11:50:22 -0400363 SkASSERT(data.fData && (data.fSize != 0));
John Stiles10d39d92021-05-04 16:13:14 -0400364 Rehydrator rehydrator(fContext.get(), base, data.fData, data.fSize);
Brian Osman0006ad02020-11-18 15:38:39 -0500365 LoadedModule module = { kind, rehydrator.symbolTable(), rehydrator.elements() };
Brian Osman3d87e9f2020-10-08 11:50:22 -0400366#endif
367
368 return module;
369}
370
John Stilesdbd4e6f2021-02-16 13:29:15 -0500371ParsedModule Compiler::parseModule(ProgramKind kind, ModuleData data, const ParsedModule& base) {
John Stilesa935c3f2021-02-25 10:35:49 -0500372 LoadedModule module = this->loadModule(kind, data, base.fSymbols, /*dehydrate=*/false);
Brian Osman0006ad02020-11-18 15:38:39 -0500373 this->optimize(module);
Brian Osman3d87e9f2020-10-08 11:50:22 -0400374
375 // For modules that just declare (but don't define) intrinsic functions, there will be no new
376 // program elements. In that case, we can share our parent's intrinsic map:
Brian Osman0006ad02020-11-18 15:38:39 -0500377 if (module.fElements.empty()) {
John Stiles10d39d92021-05-04 16:13:14 -0400378 return ParsedModule{module.fSymbols, base.fIntrinsics};
Brian Osman3d87e9f2020-10-08 11:50:22 -0400379 }
380
381 auto intrinsics = std::make_shared<IRIntrinsicMap>(base.fIntrinsics.get());
382
383 // Now, transfer all of the program elements to an intrinsic map. This maps certain types of
384 // global objects to the declaring ProgramElement.
Brian Osman0006ad02020-11-18 15:38:39 -0500385 for (std::unique_ptr<ProgramElement>& element : module.fElements) {
Brian Osman3d87e9f2020-10-08 11:50:22 -0400386 switch (element->kind()) {
387 case ProgramElement::Kind::kFunction: {
388 const FunctionDefinition& f = element->as<FunctionDefinition>();
Ethan Nicholas0a5d0962020-10-14 13:33:18 -0400389 SkASSERT(f.declaration().isBuiltin());
390 intrinsics->insertOrDie(f.declaration().description(), std::move(element));
Brian Osman3d87e9f2020-10-08 11:50:22 -0400391 break;
392 }
John Stiles569249b2020-11-03 12:18:22 -0500393 case ProgramElement::Kind::kFunctionPrototype: {
394 // These are already in the symbol table.
395 break;
396 }
Brian Osman3d87e9f2020-10-08 11:50:22 -0400397 case ProgramElement::Kind::kGlobalVar: {
Ethan Nicholasc51f33e2020-10-13 13:49:44 -0400398 const GlobalVarDeclaration& global = element->as<GlobalVarDeclaration>();
399 const Variable& var = global.declaration()->as<VarDeclaration>().var();
400 SkASSERT(var.isBuiltin());
Ethan Nicholasd2e09602021-06-10 11:21:59 -0400401 intrinsics->insertOrDie(String(var.name()), std::move(element));
Brian Osman3d87e9f2020-10-08 11:50:22 -0400402 break;
403 }
404 case ProgramElement::Kind::kInterfaceBlock: {
Ethan Nicholaseaf47882020-10-15 10:10:08 -0400405 const Variable& var = element->as<InterfaceBlock>().variable();
406 SkASSERT(var.isBuiltin());
Ethan Nicholasd2e09602021-06-10 11:21:59 -0400407 intrinsics->insertOrDie(String(var.name()), std::move(element));
Brian Osman3d87e9f2020-10-08 11:50:22 -0400408 break;
409 }
410 default:
411 printf("Unsupported element: %s\n", element->description().c_str());
412 SkASSERT(false);
413 break;
414 }
415 }
416
John Stiles10d39d92021-05-04 16:13:14 -0400417 return ParsedModule{module.fSymbols, std::move(intrinsics)};
Ethan Nicholas8da1e652019-05-24 11:01:59 -0400418}
419
Brian Osman32d53552020-09-23 13:55:20 -0400420std::unique_ptr<Program> Compiler::convertProgram(
John Stilesdbd4e6f2021-02-16 13:29:15 -0500421 ProgramKind kind,
Brian Osman32d53552020-09-23 13:55:20 -0400422 String text,
Ethan Nicholas55a63af2021-05-18 10:12:58 -0400423 Program::Settings settings) {
Brian Osman7a20b5c2021-03-15 16:23:33 -0400424 TRACE_EVENT0("skia.shaders", "SkSL::Compiler::convertProgram");
Leon Scrogginsb66214e2021-02-11 17:14:18 -0500425
Ethan Nicholas55a63af2021-05-18 10:12:58 -0400426 SkASSERT(!settings.fExternalFunctions || (kind == ProgramKind::kGeneric));
Ethan Nicholas91164d12019-05-15 15:29:54 -0400427
Ethan Nicholasdd2fdea2021-07-20 15:23:04 -0400428#if !SKSL_DSL_PARSER
Brian Osman0006ad02020-11-18 15:38:39 -0500429 // Loading and optimizing our base module might reset the inliner, so do that first,
430 // *then* configure the inliner with the settings for this program.
431 const ParsedModule& baseModule = this->moduleForProgramKind(kind);
Ethan Nicholasdd2fdea2021-07-20 15:23:04 -0400432#endif
Brian Osman0006ad02020-11-18 15:38:39 -0500433
John Stiles2ee4d7a2021-03-30 10:30:47 -0400434 // Honor our optimization-override flags.
435 switch (sOptimizer) {
436 case OverrideFlag::kDefault:
437 break;
438 case OverrideFlag::kOff:
Ethan Nicholas55a63af2021-05-18 10:12:58 -0400439 settings.fOptimize = false;
John Stiles2ee4d7a2021-03-30 10:30:47 -0400440 break;
441 case OverrideFlag::kOn:
Ethan Nicholas55a63af2021-05-18 10:12:58 -0400442 settings.fOptimize = true;
John Stiles2ee4d7a2021-03-30 10:30:47 -0400443 break;
444 }
445
446 switch (sInliner) {
447 case OverrideFlag::kDefault:
448 break;
449 case OverrideFlag::kOff:
Ethan Nicholas55a63af2021-05-18 10:12:58 -0400450 settings.fInlineThreshold = 0;
John Stiles2ee4d7a2021-03-30 10:30:47 -0400451 break;
452 case OverrideFlag::kOn:
Ethan Nicholas55a63af2021-05-18 10:12:58 -0400453 if (settings.fInlineThreshold == 0) {
454 settings.fInlineThreshold = kDefaultInlineThreshold;
John Stiles2ee4d7a2021-03-30 10:30:47 -0400455 }
456 break;
457 }
John Stiles7247b482021-03-08 10:40:35 -0500458
459 // Disable optimization settings that depend on a parent setting which has been disabled.
Ethan Nicholas55a63af2021-05-18 10:12:58 -0400460 settings.fInlineThreshold *= (int)settings.fOptimize;
461 settings.fRemoveDeadFunctions &= settings.fOptimize;
462 settings.fRemoveDeadVariables &= settings.fOptimize;
John Stiles7247b482021-03-08 10:40:35 -0500463
John Stilesaddccaf2021-08-02 19:03:30 -0400464 // Runtime effects always allow narrowing conversions.
465 if (ProgramConfig::IsRuntimeEffect(kind)) {
466 settings.fAllowNarrowingConversions = true;
467 }
468
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -0400469 this->resetErrors();
John Stiles10d39d92021-05-04 16:13:14 -0400470 fInliner.reset();
Brian Osman88cda172020-10-09 12:05:16 -0400471
Ethan Nicholasdd2fdea2021-07-20 15:23:04 -0400472#if SKSL_DSL_PARSER
473 settings.fDSLMangling = false;
474 return DSLParser(this, settings, kind, text).program();
475#else
John Stiles10d39d92021-05-04 16:13:14 -0400476 auto textPtr = std::make_unique<String>(std::move(text));
Ethan Nicholasb449fff2021-08-04 15:06:37 -0400477 AutoSource as(this, textPtr->c_str());
Brian Osman88cda172020-10-09 12:05:16 -0400478
Ethan Nicholas55a63af2021-05-18 10:12:58 -0400479 dsl::Start(this, kind, settings);
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -0400480 dsl::SetErrorReporter(&fErrorReporter);
John Stilesd1204642021-02-17 16:30:02 -0500481 IRGenerator::IRBundle ir = fIRGenerator->convertProgram(baseModule, /*isBuiltinCode=*/false,
Ethan Nicholas6823b502021-06-15 11:42:07 -0400482 *textPtr);
Ethan Nicholas4f3e6a22021-06-15 09:17:05 -0400483 // Ideally, we would just use dsl::ReleaseProgram and not have to do any manual mucking about
484 // with the memory pool, but we've got some impedance mismatches to solve first
Ethan Nicholas55a63af2021-05-18 10:12:58 -0400485 Pool* memoryPool = dsl::DSLWriter::MemoryPool().get();
John Stiles270cec22021-02-17 12:59:36 -0500486 auto program = std::make_unique<Program>(std::move(textPtr),
Ethan Nicholas55a63af2021-05-18 10:12:58 -0400487 std::move(dsl::DSLWriter::GetProgramConfig()),
John Stiles5c7bb322020-10-22 11:09:15 -0400488 fContext,
489 std::move(ir.fElements),
Brian Osman133724c2020-10-28 14:14:39 -0400490 std::move(ir.fSharedElements),
Ethan Nicholas55a63af2021-05-18 10:12:58 -0400491 std::move(dsl::DSLWriter::GetModifiersPool()),
John Stiles5c7bb322020-10-22 11:09:15 -0400492 std::move(ir.fSymbolTable),
Ethan Nicholas55a63af2021-05-18 10:12:58 -0400493 std::move(dsl::DSLWriter::MemoryPool()),
John Stiles5c7bb322020-10-22 11:09:15 -0400494 ir.fInputs);
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -0400495 this->errorReporter().reportPendingErrors(PositionInfo());
John Stiles5c7bb322020-10-22 11:09:15 -0400496 bool success = false;
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -0400497 if (this->errorCount()) {
John Stiles5c7bb322020-10-22 11:09:15 -0400498 // Do not return programs that failed to compile.
John Stiles7247b482021-03-08 10:40:35 -0500499 } else if (!this->optimize(*program)) {
John Stiles5c7bb322020-10-22 11:09:15 -0400500 // Do not return programs that failed to optimize.
501 } else {
502 // We have a successful program!
503 success = true;
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500504 }
Ethan Nicholas55a63af2021-05-18 10:12:58 -0400505 dsl::End();
506 if (memoryPool) {
507 memoryPool->detachFromThread();
Brian Osman28f702c2021-02-02 11:52:07 -0500508 }
John Stiles5c7bb322020-10-22 11:09:15 -0400509 return success ? std::move(program) : nullptr;
Ethan Nicholasdd2fdea2021-07-20 15:23:04 -0400510#endif // SKSL_DSL_PARSER
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500511}
512
John Stilesbb1505f2021-02-12 09:17:53 -0500513void Compiler::verifyStaticTests(const Program& program) {
514 class StaticTestVerifier : public ProgramVisitor {
515 public:
516 StaticTestVerifier(ErrorReporter* r) : fReporter(r) {}
517
518 using ProgramVisitor::visitProgramElement;
519
520 bool visitStatement(const Statement& stmt) override {
521 switch (stmt.kind()) {
522 case Statement::Kind::kIf:
523 if (stmt.as<IfStatement>().isStatic()) {
524 fReporter->error(stmt.fOffset, "static if has non-static test");
525 }
526 break;
527
528 case Statement::Kind::kSwitch:
529 if (stmt.as<SwitchStatement>().isStatic()) {
530 fReporter->error(stmt.fOffset, "static switch has non-static test");
531 }
532 break;
533
534 default:
535 break;
536 }
537 return INHERITED::visitStatement(stmt);
538 }
539
John Stiles59e34562021-02-12 16:56:39 -0500540 bool visitExpression(const Expression&) override {
541 // We aren't looking for anything inside an Expression, so skip them entirely.
542 return false;
543 }
544
John Stilesbb1505f2021-02-12 09:17:53 -0500545 private:
546 using INHERITED = ProgramVisitor;
547 ErrorReporter* fReporter;
548 };
549
550 // If invalid static tests are permitted, we don't need to check anything.
John Stilesd1204642021-02-17 16:30:02 -0500551 if (fContext->fConfig->fSettings.fPermitInvalidStaticTests) {
John Stilesbb1505f2021-02-12 09:17:53 -0500552 return;
553 }
554
555 // Check all of the program's owned elements. (Built-in elements are assumed to be valid.)
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -0400556 StaticTestVerifier visitor{&this->errorReporter()};
John Stilesbb1505f2021-02-12 09:17:53 -0500557 for (const std::unique_ptr<ProgramElement>& element : program.ownedElements()) {
558 if (element->is<FunctionDefinition>()) {
559 visitor.visitProgramElement(*element);
560 }
561 }
562}
563
Brian Osman0006ad02020-11-18 15:38:39 -0500564bool Compiler::optimize(LoadedModule& module) {
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -0400565 SkASSERT(!this->errorCount());
Brian Osman0006ad02020-11-18 15:38:39 -0500566
John Stiles270cec22021-02-17 12:59:36 -0500567 // Create a temporary program configuration with default settings.
568 ProgramConfig config;
569 config.fKind = module.fKind;
John Stilesa935c3f2021-02-25 10:35:49 -0500570 AutoProgramConfig autoConfig(fContext, &config);
John Stiles270cec22021-02-17 12:59:36 -0500571
John Stilesd1204642021-02-17 16:30:02 -0500572 // Reset the Inliner.
John Stiles10d39d92021-05-04 16:13:14 -0400573 fInliner.reset();
John Stiles270cec22021-02-17 12:59:36 -0500574
575 std::unique_ptr<ProgramUsage> usage = Analysis::GetUsage(module);
Brian Osman0006ad02020-11-18 15:38:39 -0500576
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -0400577 while (this->errorCount() == 0) {
Brian Osman0006ad02020-11-18 15:38:39 -0500578 // Perform inline-candidate analysis and inline any functions deemed suitable.
John Stilesf3a28db2021-03-10 23:00:47 -0500579 if (!fInliner.analyze(module.fElements, module.fSymbols, usage.get())) {
Brian Osman0006ad02020-11-18 15:38:39 -0500580 break;
581 }
582 }
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -0400583 return this->errorCount() == 0;
Brian Osman0006ad02020-11-18 15:38:39 -0500584}
585
John Stiles0bfeae62021-03-11 09:09:42 -0500586bool Compiler::removeDeadFunctions(Program& program, ProgramUsage* usage) {
587 bool madeChanges = false;
588
589 if (program.fConfig->fSettings.fRemoveDeadFunctions) {
590 auto isDeadFunction = [&](const ProgramElement* element) {
591 if (!element->is<FunctionDefinition>()) {
592 return false;
593 }
594 const FunctionDefinition& fn = element->as<FunctionDefinition>();
John Stilese8da4d22021-03-24 09:19:45 -0400595 if (fn.declaration().isMain() || usage->get(fn.declaration()) > 0) {
John Stiles0bfeae62021-03-11 09:09:42 -0500596 return false;
597 }
598 usage->remove(*element);
599 madeChanges = true;
600 return true;
601 };
602
603 program.fElements.erase(std::remove_if(program.fElements.begin(),
604 program.fElements.end(),
605 [&](const std::unique_ptr<ProgramElement>& element) {
606 return isDeadFunction(element.get());
607 }),
608 program.fElements.end());
609 program.fSharedElements.erase(std::remove_if(program.fSharedElements.begin(),
610 program.fSharedElements.end(),
611 isDeadFunction),
612 program.fSharedElements.end());
613 }
614 return madeChanges;
615}
616
617bool Compiler::removeDeadGlobalVariables(Program& program, ProgramUsage* usage) {
618 bool madeChanges = false;
619
620 if (program.fConfig->fSettings.fRemoveDeadVariables) {
621 auto isDeadVariable = [&](const ProgramElement* element) {
622 if (!element->is<GlobalVarDeclaration>()) {
623 return false;
624 }
625 const GlobalVarDeclaration& global = element->as<GlobalVarDeclaration>();
626 const VarDeclaration& varDecl = global.declaration()->as<VarDeclaration>();
627 if (!usage->isDead(varDecl.var())) {
628 return false;
629 }
630 madeChanges = true;
631 return true;
632 };
633
634 program.fElements.erase(std::remove_if(program.fElements.begin(),
635 program.fElements.end(),
636 [&](const std::unique_ptr<ProgramElement>& element) {
637 return isDeadVariable(element.get());
638 }),
639 program.fElements.end());
640 program.fSharedElements.erase(std::remove_if(program.fSharedElements.begin(),
641 program.fSharedElements.end(),
642 isDeadVariable),
643 program.fSharedElements.end());
644 }
645 return madeChanges;
646}
647
John Stiles26541872021-03-16 12:19:54 -0400648bool Compiler::removeDeadLocalVariables(Program& program, ProgramUsage* usage) {
649 class DeadLocalVariableEliminator : public ProgramWriter {
650 public:
651 DeadLocalVariableEliminator(const Context& context, ProgramUsage* usage)
652 : fContext(context)
653 , fUsage(usage) {}
654
655 using ProgramWriter::visitProgramElement;
656
657 bool visitExpressionPtr(std::unique_ptr<Expression>& expr) override {
658 // We don't need to look inside expressions at all.
659 return false;
660 }
661
662 bool visitStatementPtr(std::unique_ptr<Statement>& stmt) override {
663 if (stmt->is<VarDeclaration>()) {
664 VarDeclaration& varDecl = stmt->as<VarDeclaration>();
665 const Variable* var = &varDecl.var();
666 ProgramUsage::VariableCounts* counts = fUsage->fVariableCounts.find(var);
667 SkASSERT(counts);
668 SkASSERT(counts->fDeclared);
669 if (CanEliminate(var, *counts)) {
670 if (var->initialValue()) {
671 // The variable has an initial-value expression, which might have side
672 // effects. ExpressionStatement::Make will preserve side effects, but
673 // replaces pure expressions with Nop.
674 fUsage->remove(stmt.get());
675 stmt = ExpressionStatement::Make(fContext, std::move(varDecl.value()));
676 fUsage->add(stmt.get());
677 } else {
678 // The variable has no initial-value and can be cleanly eliminated.
679 fUsage->remove(stmt.get());
680 stmt = std::make_unique<Nop>();
681 }
682 fMadeChanges = true;
683 }
684 return false;
685 }
686 return INHERITED::visitStatementPtr(stmt);
687 }
688
689 static bool CanEliminate(const Variable* var, const ProgramUsage::VariableCounts& counts) {
690 if (!counts.fDeclared || counts.fRead || var->storage() != VariableStorage::kLocal) {
691 return false;
692 }
693 if (var->initialValue()) {
694 SkASSERT(counts.fWrite >= 1);
695 return counts.fWrite == 1;
696 } else {
697 return counts.fWrite == 0;
698 }
699 }
700
701 bool fMadeChanges = false;
702 const Context& fContext;
703 ProgramUsage* fUsage;
704
705 using INHERITED = ProgramWriter;
706 };
707
708 DeadLocalVariableEliminator visitor{*fContext, usage};
709
710 if (program.fConfig->fSettings.fRemoveDeadVariables) {
711 for (auto& [var, counts] : usage->fVariableCounts) {
712 if (DeadLocalVariableEliminator::CanEliminate(var, counts)) {
713 // This program contains at least one dead local variable.
714 // Scan the program for any dead local variables and eliminate them all.
715 for (std::unique_ptr<ProgramElement>& pe : program.ownedElements()) {
716 if (pe->is<FunctionDefinition>()) {
717 visitor.visitProgramElement(*pe);
718 }
719 }
720 break;
721 }
722 }
723 }
724
725 return visitor.fMadeChanges;
726}
727
John Stiles25be58e2021-05-20 14:38:40 -0400728void Compiler::removeUnreachableCode(Program& program, ProgramUsage* usage) {
729 class UnreachableCodeEliminator : public ProgramWriter {
730 public:
731 UnreachableCodeEliminator(const Context& context, ProgramUsage* usage)
732 : fContext(context)
733 , fUsage(usage) {
734 fFoundFunctionExit.push(false);
735 fFoundLoopExit.push(false);
736 }
737
738 using ProgramWriter::visitProgramElement;
739
740 bool visitExpressionPtr(std::unique_ptr<Expression>& expr) override {
741 // We don't need to look inside expressions at all.
742 return false;
743 }
744
745 bool visitStatementPtr(std::unique_ptr<Statement>& stmt) override {
746 if (fFoundFunctionExit.top() || fFoundLoopExit.top()) {
747 // If we already found an exit in this section, anything beyond it is dead code.
748 if (!stmt->is<Nop>()) {
749 // Eliminate the dead statement by substituting a Nop.
750 fUsage->remove(stmt.get());
751 stmt = std::make_unique<Nop>();
752 }
753 return false;
754 }
755
756 switch (stmt->kind()) {
757 case Statement::Kind::kReturn:
758 case Statement::Kind::kDiscard:
759 // We found a function exit on this path.
760 fFoundFunctionExit.top() = true;
761 break;
762
763 case Statement::Kind::kBreak:
764 case Statement::Kind::kContinue:
765 // We found a loop exit on this path. Note that we skip over switch statements
766 // completely when eliminating code, so any `break` statement would be breaking
767 // out of a loop, not out of a switch.
768 fFoundLoopExit.top() = true;
769 break;
770
771 case Statement::Kind::kExpression:
772 case Statement::Kind::kInlineMarker:
773 case Statement::Kind::kNop:
774 case Statement::Kind::kVarDeclaration:
775 // These statements don't affect control flow.
776 break;
777
778 case Statement::Kind::kBlock:
779 // Blocks are on the straight-line path and don't affect control flow.
780 return INHERITED::visitStatementPtr(stmt);
781
782 case Statement::Kind::kDo: {
783 // Function-exits are allowed to propagate outside of a do-loop, because it
784 // always executes its body at least once.
785 fFoundLoopExit.push(false);
786 bool result = INHERITED::visitStatementPtr(stmt);
787 fFoundLoopExit.pop();
788 return result;
789 }
790 case Statement::Kind::kFor: {
791 // Function-exits are not allowed to propagate out, because a for-loop or while-
792 // loop could potentially run zero times.
793 fFoundFunctionExit.push(false);
794 fFoundLoopExit.push(false);
795 bool result = INHERITED::visitStatementPtr(stmt);
796 fFoundLoopExit.pop();
797 fFoundFunctionExit.pop();
798 return result;
799 }
800 case Statement::Kind::kIf: {
801 // This statement is conditional and encloses two inner sections of code.
802 // If both sides contain a function-exit or loop-exit, that exit is allowed to
803 // propagate out.
804 IfStatement& ifStmt = stmt->as<IfStatement>();
805
806 fFoundFunctionExit.push(false);
807 fFoundLoopExit.push(false);
808 bool result = (ifStmt.ifTrue() && this->visitStatementPtr(ifStmt.ifTrue()));
809 bool foundFunctionExitOnTrue = fFoundFunctionExit.top();
810 bool foundLoopExitOnTrue = fFoundLoopExit.top();
811 fFoundFunctionExit.pop();
812 fFoundLoopExit.pop();
813
814 fFoundFunctionExit.push(false);
815 fFoundLoopExit.push(false);
816 result |= (ifStmt.ifFalse() && this->visitStatementPtr(ifStmt.ifFalse()));
817 bool foundFunctionExitOnFalse = fFoundFunctionExit.top();
818 bool foundLoopExitOnFalse = fFoundLoopExit.top();
819 fFoundFunctionExit.pop();
820 fFoundLoopExit.pop();
821
822 fFoundFunctionExit.top() |= foundFunctionExitOnTrue && foundFunctionExitOnFalse;
823 fFoundLoopExit.top() |= foundLoopExitOnTrue && foundLoopExitOnFalse;
824 return result;
825 }
826 case Statement::Kind::kSwitch:
827 case Statement::Kind::kSwitchCase:
828 // We skip past switch statements entirely when scanning for dead code. Their
829 // control flow is quite complex and we already do a good job of flattening out
830 // switches on constant values.
831 break;
832 }
833
834 return false;
835 }
836
837 const Context& fContext;
838 ProgramUsage* fUsage;
839 std::stack<bool> fFoundFunctionExit;
840 std::stack<bool> fFoundLoopExit;
841
842 using INHERITED = ProgramWriter;
843 };
844
845 for (std::unique_ptr<ProgramElement>& pe : program.ownedElements()) {
846 if (pe->is<FunctionDefinition>()) {
847 UnreachableCodeEliminator visitor{*fContext, usage};
848 visitor.visitProgramElement(*pe);
849 }
850 }
851}
852
Ethan Nicholas00543112018-07-31 09:44:36 -0400853bool Compiler::optimize(Program& program) {
John Stiles7247b482021-03-08 10:40:35 -0500854 // The optimizer only needs to run when it is enabled.
855 if (!program.fConfig->fSettings.fOptimize) {
856 return true;
857 }
858
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -0400859 SkASSERT(!this->errorCount());
Brian Osman010ce6a2020-10-19 16:34:10 -0400860 ProgramUsage* usage = program.fUsage.get();
John Stiles7954d6c2020-09-01 10:53:02 -0400861
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -0400862 if (this->errorCount() == 0) {
John Stiles87fc6572021-04-01 14:56:34 +0000863 // Run the inliner only once; it is expensive! Multiple passes can occasionally shake out
864 // more wins, but it's diminishing returns.
865 fInliner.analyze(program.ownedElements(), program.fSymbols, usage);
Ethan Nicholas34b19c52020-09-14 11:33:47 -0400866
John Stilesb6664582021-03-19 09:46:00 -0400867 while (this->removeDeadFunctions(program, usage)) {
868 // Removing dead functions may cause more functions to become unreferenced. Try again.
Ethan Nicholas34b19c52020-09-14 11:33:47 -0400869 }
John Stilesb6664582021-03-19 09:46:00 -0400870 while (this->removeDeadLocalVariables(program, usage)) {
871 // Removing dead variables may cause more variables to become unreferenced. Try again.
872 }
John Stiles25be58e2021-05-20 14:38:40 -0400873 // Unreachable code can confuse some drivers, so it's worth removing. (skia:12012)
874 this->removeUnreachableCode(program, usage);
875
Brian Osman8c264792021-07-01 16:41:27 -0400876 this->removeDeadGlobalVariables(program, usage);
Ethan Nicholas00543112018-07-31 09:44:36 -0400877 }
John Stilesbb1505f2021-02-12 09:17:53 -0500878
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -0400879 if (this->errorCount() == 0) {
John Stilesbb1505f2021-02-12 09:17:53 -0500880 this->verifyStaticTests(program);
881 }
882
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -0400883 return this->errorCount() == 0;
Ethan Nicholas00543112018-07-31 09:44:36 -0400884}
885
Brian Osmanfb32ddf2019-06-18 10:14:20 -0400886#if defined(SKSL_STANDALONE) || SK_SUPPORT_GPU
887
Ethan Nicholas00543112018-07-31 09:44:36 -0400888bool Compiler::toSPIRV(Program& program, OutputStream& out) {
Brian Osman7a20b5c2021-03-15 16:23:33 -0400889 TRACE_EVENT0("skia.shaders", "SkSL::Compiler::toSPIRV");
Ethan Nicholasb449fff2021-08-04 15:06:37 -0400890 AutoSource as(this, program.fSource->c_str());
Brian Salomond8d85b92021-07-07 09:41:17 -0400891 ProgramSettings settings;
892 settings.fDSLUseMemoryPool = false;
893 dsl::Start(this, program.fConfig->fKind, settings);
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -0400894 dsl::SetErrorReporter(&fErrorReporter);
Brian Salomond8d85b92021-07-07 09:41:17 -0400895 dsl::DSLWriter::IRGenerator().fSymbolTable = program.fSymbols;
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -0400896#ifdef SK_ENABLE_SPIRV_VALIDATION
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400897 StringStream buffer;
Ethan Nicholas3abc6c62021-08-13 11:20:09 -0400898 SPIRVCodeGenerator cg(fContext.get(), &program, &buffer);
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -0400899 bool result = cg.generateCode();
John Stiles270cec22021-02-17 12:59:36 -0500900 if (result && program.fConfig->fSettings.fValidateSPIRV) {
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -0400901 spvtools::SpirvTools tools(SPV_ENV_VULKAN_1_0);
Ethan Nicholas762466e2017-06-29 10:03:38 -0400902 const String& data = buffer.str();
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400903 SkASSERT(0 == data.size() % 4);
Brian Osman8d09d4a2020-11-24 15:51:06 -0500904 String errors;
905 auto dumpmsg = [&errors](spv_message_level_t, const char*, const spv_position_t&,
906 const char* m) {
907 errors.appendf("SPIR-V validation error: %s\n", m);
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -0400908 };
909 tools.SetMessageConsumer(dumpmsg);
Brian Osman8d09d4a2020-11-24 15:51:06 -0500910
911 // Verify that the SPIR-V we produced is valid. At runtime, we will abort() with a message
912 // explaining the error. In standalone mode (skslc), we will send the message, plus the
913 // entire disassembled SPIR-V (for easier context & debugging) as *our* error message.
914 result = tools.Validate((const uint32_t*) data.c_str(), data.size() / 4);
915
916 if (!result) {
917#if defined(SKSL_STANDALONE)
918 // Convert the string-stream to a SPIR-V disassembly.
919 std::string disassembly;
920 if (tools.Disassemble((const uint32_t*)data.data(), data.size() / 4, &disassembly)) {
921 errors.append(disassembly);
922 }
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -0400923 this->errorReporter().error(-1, errors);
Brian Osman8d09d4a2020-11-24 15:51:06 -0500924#else
925 SkDEBUGFAILF("%s", errors.c_str());
926#endif
927 }
Ethan Nicholas762466e2017-06-29 10:03:38 -0400928 out.write(data.c_str(), data.size());
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -0400929 }
930#else
Ethan Nicholas3abc6c62021-08-13 11:20:09 -0400931 SPIRVCodeGenerator cg(fContext.get(), &program, &out);
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500932 bool result = cg.generateCode();
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -0400933#endif
Brian Salomond8d85b92021-07-07 09:41:17 -0400934 dsl::End();
Ethan Nicholasce33f102016-12-09 17:22:59 -0500935 return result;
936}
937
Ethan Nicholas00543112018-07-31 09:44:36 -0400938bool Compiler::toSPIRV(Program& program, String* out) {
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400939 StringStream buffer;
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500940 bool result = this->toSPIRV(program, buffer);
941 if (result) {
Ethan Nicholas762466e2017-06-29 10:03:38 -0400942 *out = buffer.str();
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500943 }
944 return result;
945}
946
Ethan Nicholas00543112018-07-31 09:44:36 -0400947bool Compiler::toGLSL(Program& program, OutputStream& out) {
Brian Osman7a20b5c2021-03-15 16:23:33 -0400948 TRACE_EVENT0("skia.shaders", "SkSL::Compiler::toGLSL");
Ethan Nicholasb449fff2021-08-04 15:06:37 -0400949 AutoSource as(this, program.fSource->c_str());
Ethan Nicholas3abc6c62021-08-13 11:20:09 -0400950 GLSLCodeGenerator cg(fContext.get(), &program, &out);
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500951 bool result = cg.generateCode();
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500952 return result;
953}
954
Ethan Nicholas00543112018-07-31 09:44:36 -0400955bool Compiler::toGLSL(Program& program, String* out) {
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400956 StringStream buffer;
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500957 bool result = this->toGLSL(program, buffer);
958 if (result) {
Ethan Nicholas762466e2017-06-29 10:03:38 -0400959 *out = buffer.str();
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500960 }
961 return result;
962}
963
Brian Osmanc0243912020-02-19 15:35:26 -0500964bool Compiler::toHLSL(Program& program, String* out) {
965 String spirv;
966 if (!this->toSPIRV(program, &spirv)) {
967 return false;
968 }
969
970 return SPIRVtoHLSL(spirv, out);
971}
972
Ethan Nicholas00543112018-07-31 09:44:36 -0400973bool Compiler::toMetal(Program& program, OutputStream& out) {
Brian Osman7a20b5c2021-03-15 16:23:33 -0400974 TRACE_EVENT0("skia.shaders", "SkSL::Compiler::toMetal");
Ethan Nicholasb449fff2021-08-04 15:06:37 -0400975 AutoSource as(this, program.fSource->c_str());
Ethan Nicholas3abc6c62021-08-13 11:20:09 -0400976 MetalCodeGenerator cg(fContext.get(), &program, &out);
Ethan Nicholascc305772017-10-13 16:17:45 -0400977 bool result = cg.generateCode();
Ethan Nicholascc305772017-10-13 16:17:45 -0400978 return result;
979}
980
Ethan Nicholas00543112018-07-31 09:44:36 -0400981bool Compiler::toMetal(Program& program, String* out) {
Timothy Liangb8eeb802018-07-23 16:46:16 -0400982 StringStream buffer;
983 bool result = this->toMetal(program, buffer);
984 if (result) {
985 *out = buffer.str();
986 }
987 return result;
988}
989
Ethan Nicholas2a479a52020-08-18 16:29:45 -0400990#endif // defined(SKSL_STANDALONE) || SK_SUPPORT_GPU
Brian Osman2e29ab52019-09-20 12:19:11 -0400991
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -0400992void Compiler::handleError(const char* msg, PositionInfo pos) {
Ethan Nicholasb449fff2021-08-04 15:06:37 -0400993 if (strstr(msg, POISON_TAG)) {
Ethan Nicholas549c6b82021-06-25 12:31:44 -0400994 // don't report errors on poison values
995 return;
996 }
Ethan Nicholasa40ddcd2021-08-06 09:17:18 -0400997 fErrorText += "error: " + (pos.line() >= 1 ? to_string(pos.line()) + ": " : "") + msg + "\n";
ethannicholasb3058bd2016-07-01 08:22:01 -0700998}
999
Ethan Nicholas95046142021-01-07 10:57:27 -05001000String Compiler::errorText(bool showCount) {
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -04001001 this->errorReporter().reportPendingErrors(PositionInfo());
Ethan Nicholas95046142021-01-07 10:57:27 -05001002 if (showCount) {
1003 this->writeErrorCount();
1004 }
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001005 String result = fErrorText;
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -04001006 this->resetErrors();
ethannicholasb3058bd2016-07-01 08:22:01 -07001007 return result;
1008}
1009
1010void Compiler::writeErrorCount() {
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -04001011 int count = this->errorCount();
1012 if (count) {
1013 fErrorText += to_string(count) + " error";
1014 if (count > 1) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001015 fErrorText += "s";
1016 }
1017 fErrorText += "\n";
1018 }
1019}
1020
John Stilesa6841be2020-08-06 14:11:56 -04001021} // namespace SkSL