blob: f1393001944d5bd1de0509d979314130aa310b39 [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"
62#include "src/sksl/generated/sksl_geom.dehydrated.sksl"
63#include "src/sksl/generated/sksl_gpu.dehydrated.sksl"
Brian Osmanb06301e2020-11-06 11:45:36 -050064#include "src/sksl/generated/sksl_public.dehydrated.sksl"
John Stilesf7f36ae2021-06-08 14:06:22 -040065#include "src/sksl/generated/sksl_rt_blend.dehydrated.sksl"
Brian Osmancbb60bd2021-04-12 09:49:20 -040066#include "src/sksl/generated/sksl_rt_colorfilter.dehydrated.sksl"
67#include "src/sksl/generated/sksl_rt_shader.dehydrated.sksl"
Ethan Nicholasc18bb512020-07-28 14:46:53 -040068#include "src/sksl/generated/sksl_vert.dehydrated.sksl"
69
Brian Osman3d87e9f2020-10-08 11:50:22 -040070#define MODULE_DATA(name) MakeModuleData(SKSL_INCLUDE_sksl_##name,\
71 SKSL_INCLUDE_sksl_##name##_LENGTH)
Ethan Nicholasc18bb512020-07-28 14:46:53 -040072
73#endif
Ethan Nicholas0d997662019-04-08 09:46:01 -040074
ethannicholasb3058bd2016-07-01 08:22:01 -070075namespace SkSL {
76
John Stiles7247b482021-03-08 10:40:35 -050077// These flags allow tools like Viewer or Nanobench to override the compiler's ProgramSettings.
John Stiles2ee4d7a2021-03-30 10:30:47 -040078Compiler::OverrideFlag Compiler::sOptimizer = OverrideFlag::kDefault;
79Compiler::OverrideFlag Compiler::sInliner = OverrideFlag::kDefault;
John Stiles8ef4d6c2021-03-05 16:01:45 -050080
John Stiles47c0a742021-02-09 09:30:35 -050081using RefKind = VariableReference::RefKind;
82
Brian Osman88cda172020-10-09 12:05:16 -040083class AutoSource {
84public:
85 AutoSource(Compiler* compiler, const String* source)
John Stilesa289ac22021-05-06 07:35:35 -040086 : fCompiler(compiler) {
87 SkASSERT(!fCompiler->fSource);
Brian Osman88cda172020-10-09 12:05:16 -040088 fCompiler->fSource = source;
89 }
90
John Stilesa289ac22021-05-06 07:35:35 -040091 ~AutoSource() {
92 fCompiler->fSource = nullptr;
93 }
Brian Osman88cda172020-10-09 12:05:16 -040094
95 Compiler* fCompiler;
Brian Osman88cda172020-10-09 12:05:16 -040096};
97
John Stilesa935c3f2021-02-25 10:35:49 -050098class AutoProgramConfig {
99public:
100 AutoProgramConfig(std::shared_ptr<Context>& context, ProgramConfig* config)
101 : fContext(context.get()) {
102 SkASSERT(!fContext->fConfig);
103 fContext->fConfig = config;
104 }
105
106 ~AutoProgramConfig() {
107 fContext->fConfig = nullptr;
108 }
109
110 Context* fContext;
111};
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)
John Stilesc1a98b82021-02-24 13:35:02 -0500129 : fContext(std::make_shared<Context>(/*errors=*/*this, *caps))
John Stilesa47b3512021-05-04 16:15:00 -0400130 , fInliner(fContext.get()) {
John Stilesc1a98b82021-02-24 13:35:02 -0500131 SkASSERT(caps);
John Stiles7c3515b2020-10-16 18:38:39 -0400132 fRootSymbolTable = std::make_shared<SymbolTable>(this, /*builtin=*/true);
Brian Osmanb06301e2020-11-06 11:45:36 -0500133 fPrivateSymbolTable = std::make_shared<SymbolTable>(fRootSymbolTable, /*builtin=*/true);
John Stilesc1a98b82021-02-24 13:35:02 -0500134 fIRGenerator = std::make_unique<IRGenerator>(fContext.get());
ethannicholasb3058bd2016-07-01 08:22:01 -0700135
John Stiles54e7c052021-01-11 14:22:36 -0500136#define TYPE(t) fContext->fTypes.f ## t .get()
ethannicholasb3058bd2016-07-01 08:22:01 -0700137
Brian Osmanb06301e2020-11-06 11:45:36 -0500138 const SkSL::Symbol* rootTypes[] = {
139 TYPE(Void),
Brian Salomonbf7b6202016-11-11 16:08:03 -0500140
Brian Osmanb06301e2020-11-06 11:45:36 -0500141 TYPE( Float), TYPE( Float2), TYPE( Float3), TYPE( Float4),
142 TYPE( Half), TYPE( Half2), TYPE( Half3), TYPE( Half4),
143 TYPE( Int), TYPE( Int2), TYPE( Int3), TYPE( Int4),
Brian Osmanb06301e2020-11-06 11:45:36 -0500144 TYPE( Bool), TYPE( Bool2), TYPE( Bool3), TYPE( Bool4),
Brian Salomon2a51de82016-11-16 12:06:01 -0500145
Brian Osmanc0f2b642020-12-22 13:35:55 -0500146 TYPE(Float2x2), TYPE(Float3x3), TYPE(Float4x4),
Brian Osmanc63f4312020-12-23 11:44:14 -0500147 TYPE( Half2x2), TYPE( Half3x3), TYPE(Half4x4),
Greg Daniel64773e62016-11-22 09:44:03 -0500148
Brian Osmanc63f4312020-12-23 11:44:14 -0500149 TYPE(SquareMat), TYPE(SquareHMat),
ethannicholasb3058bd2016-07-01 08:22:01 -0700150
Brian Osman20fad322020-12-23 12:42:33 -0500151 TYPE(GenType), TYPE(GenHType), TYPE(GenIType), TYPE(GenBType),
152 TYPE(Vec), TYPE(HVec), TYPE(IVec), TYPE(BVec),
Brian Osmanb06301e2020-11-06 11:45:36 -0500153
Brian Osman14d00962021-04-02 17:04:35 -0400154 TYPE(ColorFilter),
155 TYPE(Shader),
Brian Osmanb06301e2020-11-06 11:45:36 -0500156 };
157
158 const SkSL::Symbol* privateTypes[] = {
Brian Osman20fad322020-12-23 12:42:33 -0500159 TYPE( UInt), TYPE( UInt2), TYPE( UInt3), TYPE( UInt4),
160 TYPE( Short), TYPE( Short2), TYPE( Short3), TYPE( Short4),
161 TYPE(UShort), TYPE(UShort2), TYPE(UShort3), TYPE(UShort4),
Brian Osman20fad322020-12-23 12:42:33 -0500162
163 TYPE(GenUType), TYPE(UVec),
Ethan Nicholas722c83e2021-05-04 11:39:30 -0400164 TYPE(SVec), TYPE(USVec),
Brian Osman20fad322020-12-23 12:42:33 -0500165
Brian Osmanc0f2b642020-12-22 13:35:55 -0500166 TYPE(Float2x3), TYPE(Float2x4),
167 TYPE(Float3x2), TYPE(Float3x4),
168 TYPE(Float4x2), TYPE(Float4x3),
169
Brian Osmanc63f4312020-12-23 11:44:14 -0500170 TYPE(Half2x3), TYPE(Half2x4),
171 TYPE(Half3x2), TYPE(Half3x4),
172 TYPE(Half4x2), TYPE(Half4x3),
173
Brian Osmanc0f2b642020-12-22 13:35:55 -0500174 TYPE(Mat), TYPE(HMat),
175
Brian Osmanb06301e2020-11-06 11:45:36 -0500176 TYPE(Sampler1D), TYPE(Sampler2D), TYPE(Sampler3D),
177 TYPE(SamplerExternalOES),
Brian Osmanb06301e2020-11-06 11:45:36 -0500178 TYPE(Sampler2DRect),
Brian Osmanb06301e2020-11-06 11:45:36 -0500179
180 TYPE(ISampler2D),
Brian Osmanb06301e2020-11-06 11:45:36 -0500181 TYPE(SubpassInput), TYPE(SubpassInputMS),
182
Brian Osmanb06301e2020-11-06 11:45:36 -0500183 TYPE(Sampler),
184 TYPE(Texture2D),
185 };
186
187 for (const SkSL::Symbol* type : rootTypes) {
188 fRootSymbolTable->addWithoutOwnership(type);
189 }
190 for (const SkSL::Symbol* type : privateTypes) {
191 fPrivateSymbolTable->addWithoutOwnership(type);
192 }
193
194#undef TYPE
ethannicholasb3058bd2016-07-01 08:22:01 -0700195
Brian Osman3887a012020-09-30 13:22:27 -0400196 // sk_Caps is "builtin", but all references to it are resolved to Settings, so we don't need to
197 // treat it as builtin (ie, no need to clone it into the Program).
John Stiles10d39d92021-05-04 16:13:14 -0400198 fPrivateSymbolTable->add(std::make_unique<Variable>(/*offset=*/-1,
John Stilesa47b3512021-05-04 16:15:00 -0400199 fCoreModifiers.add(Modifiers{}),
John Stiles10d39d92021-05-04 16:13:14 -0400200 "sk_Caps",
201 fContext->fTypes.fSkCaps.get(),
202 /*builtin=*/false,
203 Variable::Storage::kGlobal));
Ethan Nicholas3605ace2016-11-21 15:59:48 -0500204
Brian Osman3d87e9f2020-10-08 11:50:22 -0400205 fRootModule = {fRootSymbolTable, /*fIntrinsics=*/nullptr};
Brian Osmanb06301e2020-11-06 11:45:36 -0500206 fPrivateModule = {fPrivateSymbolTable, /*fIntrinsics=*/nullptr};
ethannicholasb3058bd2016-07-01 08:22:01 -0700207}
208
John Stilesdd13dba2020-10-29 10:45:34 -0400209Compiler::~Compiler() {}
ethannicholasb3058bd2016-07-01 08:22:01 -0700210
Brian Osman56269982020-11-20 12:38:07 -0500211const ParsedModule& Compiler::loadGPUModule() {
212 if (!fGPUModule.fSymbols) {
John Stilesdbd4e6f2021-02-16 13:29:15 -0500213 fGPUModule = this->parseModule(ProgramKind::kFragment, MODULE_DATA(gpu), fPrivateModule);
Brian Osman56269982020-11-20 12:38:07 -0500214 }
215 return fGPUModule;
216}
217
218const ParsedModule& Compiler::loadFragmentModule() {
219 if (!fFragmentModule.fSymbols) {
John Stilesdbd4e6f2021-02-16 13:29:15 -0500220 fFragmentModule = this->parseModule(ProgramKind::kFragment, MODULE_DATA(frag),
Brian Osman56269982020-11-20 12:38:07 -0500221 this->loadGPUModule());
222 }
223 return fFragmentModule;
224}
225
226const ParsedModule& Compiler::loadVertexModule() {
227 if (!fVertexModule.fSymbols) {
John Stilesdbd4e6f2021-02-16 13:29:15 -0500228 fVertexModule = this->parseModule(ProgramKind::kVertex, MODULE_DATA(vert),
Brian Osman56269982020-11-20 12:38:07 -0500229 this->loadGPUModule());
230 }
231 return fVertexModule;
232}
233
Brian Osman88cda172020-10-09 12:05:16 -0400234const ParsedModule& Compiler::loadGeometryModule() {
Brian Osman3d87e9f2020-10-08 11:50:22 -0400235 if (!fGeometryModule.fSymbols) {
John Stilesdbd4e6f2021-02-16 13:29:15 -0500236 fGeometryModule = this->parseModule(ProgramKind::kGeometry, MODULE_DATA(geom),
Brian Osman56269982020-11-20 12:38:07 -0500237 this->loadGPUModule());
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400238 }
Brian Osman88cda172020-10-09 12:05:16 -0400239 return fGeometryModule;
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400240}
241
Brian Osmanb06301e2020-11-06 11:45:36 -0500242const ParsedModule& Compiler::loadPublicModule() {
243 if (!fPublicModule.fSymbols) {
John Stilesdbd4e6f2021-02-16 13:29:15 -0500244 fPublicModule = this->parseModule(ProgramKind::kGeneric, MODULE_DATA(public), fRootModule);
Brian Osmanb06301e2020-11-06 11:45:36 -0500245 }
246 return fPublicModule;
247}
248
Brian Osmancbb60bd2021-04-12 09:49:20 -0400249static void add_glsl_type_aliases(SkSL::SymbolTable* symbols, const SkSL::BuiltinTypes& types) {
250 // Add some aliases to the runtime effect modules so that it's friendlier, and more like GLSL
251 symbols->addAlias("vec2", types.fFloat2.get());
252 symbols->addAlias("vec3", types.fFloat3.get());
253 symbols->addAlias("vec4", types.fFloat4.get());
254
255 symbols->addAlias("ivec2", types.fInt2.get());
256 symbols->addAlias("ivec3", types.fInt3.get());
257 symbols->addAlias("ivec4", types.fInt4.get());
258
259 symbols->addAlias("bvec2", types.fBool2.get());
260 symbols->addAlias("bvec3", types.fBool3.get());
261 symbols->addAlias("bvec4", types.fBool4.get());
262
263 symbols->addAlias("mat2", types.fFloat2x2.get());
264 symbols->addAlias("mat3", types.fFloat3x3.get());
265 symbols->addAlias("mat4", types.fFloat4x4.get());
266}
267
Brian Osmancbb60bd2021-04-12 09:49:20 -0400268const ParsedModule& Compiler::loadRuntimeColorFilterModule() {
269 if (!fRuntimeColorFilterModule.fSymbols) {
270 fRuntimeColorFilterModule = this->parseModule(ProgramKind::kRuntimeColorFilter,
271 MODULE_DATA(rt_colorfilter),
272 this->loadPublicModule());
273 add_glsl_type_aliases(fRuntimeColorFilterModule.fSymbols.get(), fContext->fTypes);
274 }
275 return fRuntimeColorFilterModule;
276}
277
278const ParsedModule& Compiler::loadRuntimeShaderModule() {
279 if (!fRuntimeShaderModule.fSymbols) {
280 fRuntimeShaderModule = this->parseModule(
281 ProgramKind::kRuntimeShader, MODULE_DATA(rt_shader), this->loadPublicModule());
282 add_glsl_type_aliases(fRuntimeShaderModule.fSymbols.get(), fContext->fTypes);
283 }
284 return fRuntimeShaderModule;
285}
286
John Stiles2d8b8352021-06-16 11:33:13 -0400287const ParsedModule& Compiler::loadRuntimeBlenderModule() {
288 if (!fRuntimeBlenderModule.fSymbols) {
289 fRuntimeBlenderModule = this->parseModule(
290 ProgramKind::kRuntimeBlender, MODULE_DATA(rt_blend), this->loadPublicModule());
291 add_glsl_type_aliases(fRuntimeBlenderModule.fSymbols.get(), fContext->fTypes);
John Stilesf7f36ae2021-06-08 14:06:22 -0400292 }
John Stiles2d8b8352021-06-16 11:33:13 -0400293 return fRuntimeBlenderModule;
John Stilesf7f36ae2021-06-08 14:06:22 -0400294}
295
John Stilesdbd4e6f2021-02-16 13:29:15 -0500296const ParsedModule& Compiler::moduleForProgramKind(ProgramKind kind) {
Brian Osman88cda172020-10-09 12:05:16 -0400297 switch (kind) {
Brian Osmancbb60bd2021-04-12 09:49:20 -0400298 case ProgramKind::kVertex: return this->loadVertexModule(); break;
299 case ProgramKind::kFragment: return this->loadFragmentModule(); break;
300 case ProgramKind::kGeometry: return this->loadGeometryModule(); break;
Brian Osmancbb60bd2021-04-12 09:49:20 -0400301 case ProgramKind::kRuntimeColorFilter: return this->loadRuntimeColorFilterModule(); break;
302 case ProgramKind::kRuntimeShader: return this->loadRuntimeShaderModule(); break;
John Stiles2d8b8352021-06-16 11:33:13 -0400303 case ProgramKind::kRuntimeBlender: return this->loadRuntimeBlenderModule(); break;
Brian Osmancbb60bd2021-04-12 09:49:20 -0400304 case ProgramKind::kGeneric: return this->loadPublicModule(); break;
Brian Osman88cda172020-10-09 12:05:16 -0400305 }
306 SkUNREACHABLE;
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400307}
308
John Stilesdbd4e6f2021-02-16 13:29:15 -0500309LoadedModule Compiler::loadModule(ProgramKind kind,
Brian Osman3d87e9f2020-10-08 11:50:22 -0400310 ModuleData data,
John Stilesa935c3f2021-02-25 10:35:49 -0500311 std::shared_ptr<SymbolTable> base,
312 bool dehydrate) {
313 if (dehydrate) {
314 // NOTE: This is a workaround. When dehydrating includes, skslc doesn't know which module
315 // it's preparing, nor what the correct base module is. We can't use 'Root', because many
316 // GPU intrinsics reference private types, like samplers or textures. Today, 'Private' does
317 // contain the union of all known types, so this is safe. If we ever have types that only
318 // exist in 'Public' (for example), this logic needs to be smarter (by choosing the correct
319 // base for the module we're compiling).
Brian Osmanb06301e2020-11-06 11:45:36 -0500320 base = fPrivateSymbolTable;
Brian Osman3d87e9f2020-10-08 11:50:22 -0400321 }
John Stilesa935c3f2021-02-25 10:35:49 -0500322 SkASSERT(base);
323
John Stilesa47b3512021-05-04 16:15:00 -0400324 // Put the core-module modifier pool into the context.
325 AutoModifiersPool autoPool(fContext, &fCoreModifiers);
John Stiles10d39d92021-05-04 16:13:14 -0400326
John Stilesa935c3f2021-02-25 10:35:49 -0500327 // Built-in modules always use default program settings.
Ethan Nicholas55a63af2021-05-18 10:12:58 -0400328 Program::Settings settings;
329 settings.fReplaceSettings = !dehydrate;
Brian Osman3d87e9f2020-10-08 11:50:22 -0400330
331#if defined(SKSL_STANDALONE)
332 SkASSERT(data.fPath);
333 std::ifstream in(data.fPath);
John Stilesd51c9792021-03-18 11:40:14 -0400334 String text{std::istreambuf_iterator<char>(in), std::istreambuf_iterator<char>()};
Ethan Nicholasb33fa3f2020-08-06 13:00:19 -0400335 if (in.rdstate()) {
Brian Osman3d87e9f2020-10-08 11:50:22 -0400336 printf("error reading %s\n", data.fPath);
Ethan Nicholasb33fa3f2020-08-06 13:00:19 -0400337 abort();
338 }
Brian Osmane498b3c2020-09-23 14:42:11 -0400339 const String* source = fRootSymbolTable->takeOwnershipOfString(std::move(text));
John Stilesd1204642021-02-17 16:30:02 -0500340
Brian Osman88cda172020-10-09 12:05:16 -0400341 ParsedModule baseModule = {base, /*fIntrinsics=*/nullptr};
Ethan Nicholas55a63af2021-05-18 10:12:58 -0400342 std::vector<std::unique_ptr<ProgramElement>> elements;
343 std::vector<const ProgramElement*> sharedElements;
344 dsl::StartModule(this, kind, settings, baseModule);
345 AutoSource as(this, source);
John Stilesd1204642021-02-17 16:30:02 -0500346 IRGenerator::IRBundle ir = fIRGenerator->convertProgram(baseModule, /*isBuiltinCode=*/true,
Ethan Nicholas6823b502021-06-15 11:42:07 -0400347 *source);
Brian Osman133724c2020-10-28 14:14:39 -0400348 SkASSERT(ir.fSharedElements.empty());
Brian Osman0006ad02020-11-18 15:38:39 -0500349 LoadedModule module = { kind, std::move(ir.fSymbolTable), std::move(ir.fElements) };
Ethan Nicholas55a63af2021-05-18 10:12:58 -0400350 dsl::End();
Ethan Nicholas8da1e652019-05-24 11:01:59 -0400351 if (this->fErrorCount) {
352 printf("Unexpected errors: %s\n", this->fErrorText.c_str());
Brian Osman3d87e9f2020-10-08 11:50:22 -0400353 SkDEBUGFAILF("%s %s\n", data.fPath, this->fErrorText.c_str());
Ethan Nicholas8da1e652019-05-24 11:01:59 -0400354 }
Brian Osman3d87e9f2020-10-08 11:50:22 -0400355#else
Ethan Nicholas55a63af2021-05-18 10:12:58 -0400356 ProgramConfig config;
357 config.fKind = kind;
358 config.fSettings = settings;
359 AutoProgramConfig autoConfig(fContext, &config);
Brian Osman3d87e9f2020-10-08 11:50:22 -0400360 SkASSERT(data.fData && (data.fSize != 0));
John Stiles10d39d92021-05-04 16:13:14 -0400361 Rehydrator rehydrator(fContext.get(), base, data.fData, data.fSize);
Brian Osman0006ad02020-11-18 15:38:39 -0500362 LoadedModule module = { kind, rehydrator.symbolTable(), rehydrator.elements() };
Brian Osman3d87e9f2020-10-08 11:50:22 -0400363#endif
364
365 return module;
366}
367
John Stilesdbd4e6f2021-02-16 13:29:15 -0500368ParsedModule Compiler::parseModule(ProgramKind kind, ModuleData data, const ParsedModule& base) {
John Stilesa935c3f2021-02-25 10:35:49 -0500369 LoadedModule module = this->loadModule(kind, data, base.fSymbols, /*dehydrate=*/false);
Brian Osman0006ad02020-11-18 15:38:39 -0500370 this->optimize(module);
Brian Osman3d87e9f2020-10-08 11:50:22 -0400371
372 // For modules that just declare (but don't define) intrinsic functions, there will be no new
373 // program elements. In that case, we can share our parent's intrinsic map:
Brian Osman0006ad02020-11-18 15:38:39 -0500374 if (module.fElements.empty()) {
John Stiles10d39d92021-05-04 16:13:14 -0400375 return ParsedModule{module.fSymbols, base.fIntrinsics};
Brian Osman3d87e9f2020-10-08 11:50:22 -0400376 }
377
378 auto intrinsics = std::make_shared<IRIntrinsicMap>(base.fIntrinsics.get());
379
380 // Now, transfer all of the program elements to an intrinsic map. This maps certain types of
381 // global objects to the declaring ProgramElement.
Brian Osman0006ad02020-11-18 15:38:39 -0500382 for (std::unique_ptr<ProgramElement>& element : module.fElements) {
Brian Osman3d87e9f2020-10-08 11:50:22 -0400383 switch (element->kind()) {
384 case ProgramElement::Kind::kFunction: {
385 const FunctionDefinition& f = element->as<FunctionDefinition>();
Ethan Nicholas0a5d0962020-10-14 13:33:18 -0400386 SkASSERT(f.declaration().isBuiltin());
387 intrinsics->insertOrDie(f.declaration().description(), std::move(element));
Brian Osman3d87e9f2020-10-08 11:50:22 -0400388 break;
389 }
John Stiles569249b2020-11-03 12:18:22 -0500390 case ProgramElement::Kind::kFunctionPrototype: {
391 // These are already in the symbol table.
392 break;
393 }
Brian Osman3d87e9f2020-10-08 11:50:22 -0400394 case ProgramElement::Kind::kGlobalVar: {
Ethan Nicholasc51f33e2020-10-13 13:49:44 -0400395 const GlobalVarDeclaration& global = element->as<GlobalVarDeclaration>();
396 const Variable& var = global.declaration()->as<VarDeclaration>().var();
397 SkASSERT(var.isBuiltin());
Ethan Nicholasd2e09602021-06-10 11:21:59 -0400398 intrinsics->insertOrDie(String(var.name()), std::move(element));
Brian Osman3d87e9f2020-10-08 11:50:22 -0400399 break;
400 }
401 case ProgramElement::Kind::kInterfaceBlock: {
Ethan Nicholaseaf47882020-10-15 10:10:08 -0400402 const Variable& var = element->as<InterfaceBlock>().variable();
403 SkASSERT(var.isBuiltin());
Ethan Nicholasd2e09602021-06-10 11:21:59 -0400404 intrinsics->insertOrDie(String(var.name()), std::move(element));
Brian Osman3d87e9f2020-10-08 11:50:22 -0400405 break;
406 }
407 default:
408 printf("Unsupported element: %s\n", element->description().c_str());
409 SkASSERT(false);
410 break;
411 }
412 }
413
John Stiles10d39d92021-05-04 16:13:14 -0400414 return ParsedModule{module.fSymbols, std::move(intrinsics)};
Ethan Nicholas8da1e652019-05-24 11:01:59 -0400415}
416
Brian Osman32d53552020-09-23 13:55:20 -0400417std::unique_ptr<Program> Compiler::convertProgram(
John Stilesdbd4e6f2021-02-16 13:29:15 -0500418 ProgramKind kind,
Brian Osman32d53552020-09-23 13:55:20 -0400419 String text,
Ethan Nicholas55a63af2021-05-18 10:12:58 -0400420 Program::Settings settings) {
Brian Osman7a20b5c2021-03-15 16:23:33 -0400421 TRACE_EVENT0("skia.shaders", "SkSL::Compiler::convertProgram");
Leon Scrogginsb66214e2021-02-11 17:14:18 -0500422
Ethan Nicholas55a63af2021-05-18 10:12:58 -0400423 SkASSERT(!settings.fExternalFunctions || (kind == ProgramKind::kGeneric));
Ethan Nicholas91164d12019-05-15 15:29:54 -0400424
Ethan Nicholasdd2fdea2021-07-20 15:23:04 -0400425#if !SKSL_DSL_PARSER
Brian Osman0006ad02020-11-18 15:38:39 -0500426 // Loading and optimizing our base module might reset the inliner, so do that first,
427 // *then* configure the inliner with the settings for this program.
428 const ParsedModule& baseModule = this->moduleForProgramKind(kind);
Ethan Nicholasdd2fdea2021-07-20 15:23:04 -0400429#endif
Brian Osman0006ad02020-11-18 15:38:39 -0500430
John Stiles2ee4d7a2021-03-30 10:30:47 -0400431 // Honor our optimization-override flags.
432 switch (sOptimizer) {
433 case OverrideFlag::kDefault:
434 break;
435 case OverrideFlag::kOff:
Ethan Nicholas55a63af2021-05-18 10:12:58 -0400436 settings.fOptimize = false;
John Stiles2ee4d7a2021-03-30 10:30:47 -0400437 break;
438 case OverrideFlag::kOn:
Ethan Nicholas55a63af2021-05-18 10:12:58 -0400439 settings.fOptimize = true;
John Stiles2ee4d7a2021-03-30 10:30:47 -0400440 break;
441 }
442
443 switch (sInliner) {
444 case OverrideFlag::kDefault:
445 break;
446 case OverrideFlag::kOff:
Ethan Nicholas55a63af2021-05-18 10:12:58 -0400447 settings.fInlineThreshold = 0;
John Stiles2ee4d7a2021-03-30 10:30:47 -0400448 break;
449 case OverrideFlag::kOn:
Ethan Nicholas55a63af2021-05-18 10:12:58 -0400450 if (settings.fInlineThreshold == 0) {
451 settings.fInlineThreshold = kDefaultInlineThreshold;
John Stiles2ee4d7a2021-03-30 10:30:47 -0400452 }
453 break;
454 }
John Stiles7247b482021-03-08 10:40:35 -0500455
456 // Disable optimization settings that depend on a parent setting which has been disabled.
Ethan Nicholas55a63af2021-05-18 10:12:58 -0400457 settings.fInlineThreshold *= (int)settings.fOptimize;
458 settings.fRemoveDeadFunctions &= settings.fOptimize;
459 settings.fRemoveDeadVariables &= settings.fOptimize;
John Stiles7247b482021-03-08 10:40:35 -0500460
ethannicholasb3058bd2016-07-01 08:22:01 -0700461 fErrorText = "";
462 fErrorCount = 0;
John Stiles10d39d92021-05-04 16:13:14 -0400463 fInliner.reset();
Brian Osman88cda172020-10-09 12:05:16 -0400464
Ethan Nicholasdd2fdea2021-07-20 15:23:04 -0400465#if SKSL_DSL_PARSER
466 settings.fDSLMangling = false;
467 return DSLParser(this, settings, kind, text).program();
468#else
John Stiles10d39d92021-05-04 16:13:14 -0400469 auto textPtr = std::make_unique<String>(std::move(text));
John Stilesa289ac22021-05-06 07:35:35 -0400470 AutoSource as(this, textPtr.get());
Brian Osman88cda172020-10-09 12:05:16 -0400471
Ethan Nicholas55a63af2021-05-18 10:12:58 -0400472 dsl::Start(this, kind, settings);
John Stilesd1204642021-02-17 16:30:02 -0500473 IRGenerator::IRBundle ir = fIRGenerator->convertProgram(baseModule, /*isBuiltinCode=*/false,
Ethan Nicholas6823b502021-06-15 11:42:07 -0400474 *textPtr);
Ethan Nicholas4f3e6a22021-06-15 09:17:05 -0400475 // Ideally, we would just use dsl::ReleaseProgram and not have to do any manual mucking about
476 // with the memory pool, but we've got some impedance mismatches to solve first
Ethan Nicholas55a63af2021-05-18 10:12:58 -0400477 Pool* memoryPool = dsl::DSLWriter::MemoryPool().get();
John Stiles270cec22021-02-17 12:59:36 -0500478 auto program = std::make_unique<Program>(std::move(textPtr),
Ethan Nicholas55a63af2021-05-18 10:12:58 -0400479 std::move(dsl::DSLWriter::GetProgramConfig()),
John Stiles5c7bb322020-10-22 11:09:15 -0400480 fContext,
481 std::move(ir.fElements),
Brian Osman133724c2020-10-28 14:14:39 -0400482 std::move(ir.fSharedElements),
Ethan Nicholas55a63af2021-05-18 10:12:58 -0400483 std::move(dsl::DSLWriter::GetModifiersPool()),
John Stiles5c7bb322020-10-22 11:09:15 -0400484 std::move(ir.fSymbolTable),
Ethan Nicholas55a63af2021-05-18 10:12:58 -0400485 std::move(dsl::DSLWriter::MemoryPool()),
John Stiles5c7bb322020-10-22 11:09:15 -0400486 ir.fInputs);
487 bool success = false;
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500488 if (fErrorCount) {
John Stiles5c7bb322020-10-22 11:09:15 -0400489 // Do not return programs that failed to compile.
John Stiles7247b482021-03-08 10:40:35 -0500490 } else if (!this->optimize(*program)) {
John Stiles5c7bb322020-10-22 11:09:15 -0400491 // Do not return programs that failed to optimize.
492 } else {
493 // We have a successful program!
494 success = true;
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500495 }
Ethan Nicholas55a63af2021-05-18 10:12:58 -0400496 dsl::End();
497 if (memoryPool) {
498 memoryPool->detachFromThread();
Brian Osman28f702c2021-02-02 11:52:07 -0500499 }
John Stiles5c7bb322020-10-22 11:09:15 -0400500 return success ? std::move(program) : nullptr;
Ethan Nicholasdd2fdea2021-07-20 15:23:04 -0400501#endif // SKSL_DSL_PARSER
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500502}
503
John Stilesbb1505f2021-02-12 09:17:53 -0500504void Compiler::verifyStaticTests(const Program& program) {
505 class StaticTestVerifier : public ProgramVisitor {
506 public:
507 StaticTestVerifier(ErrorReporter* r) : fReporter(r) {}
508
509 using ProgramVisitor::visitProgramElement;
510
511 bool visitStatement(const Statement& stmt) override {
512 switch (stmt.kind()) {
513 case Statement::Kind::kIf:
514 if (stmt.as<IfStatement>().isStatic()) {
515 fReporter->error(stmt.fOffset, "static if has non-static test");
516 }
517 break;
518
519 case Statement::Kind::kSwitch:
520 if (stmt.as<SwitchStatement>().isStatic()) {
521 fReporter->error(stmt.fOffset, "static switch has non-static test");
522 }
523 break;
524
525 default:
526 break;
527 }
528 return INHERITED::visitStatement(stmt);
529 }
530
John Stiles59e34562021-02-12 16:56:39 -0500531 bool visitExpression(const Expression&) override {
532 // We aren't looking for anything inside an Expression, so skip them entirely.
533 return false;
534 }
535
John Stilesbb1505f2021-02-12 09:17:53 -0500536 private:
537 using INHERITED = ProgramVisitor;
538 ErrorReporter* fReporter;
539 };
540
541 // If invalid static tests are permitted, we don't need to check anything.
John Stilesd1204642021-02-17 16:30:02 -0500542 if (fContext->fConfig->fSettings.fPermitInvalidStaticTests) {
John Stilesbb1505f2021-02-12 09:17:53 -0500543 return;
544 }
545
546 // Check all of the program's owned elements. (Built-in elements are assumed to be valid.)
547 StaticTestVerifier visitor{this};
548 for (const std::unique_ptr<ProgramElement>& element : program.ownedElements()) {
549 if (element->is<FunctionDefinition>()) {
550 visitor.visitProgramElement(*element);
551 }
552 }
553}
554
Brian Osman0006ad02020-11-18 15:38:39 -0500555bool Compiler::optimize(LoadedModule& module) {
556 SkASSERT(!fErrorCount);
Brian Osman0006ad02020-11-18 15:38:39 -0500557
John Stiles270cec22021-02-17 12:59:36 -0500558 // Create a temporary program configuration with default settings.
559 ProgramConfig config;
560 config.fKind = module.fKind;
John Stilesa935c3f2021-02-25 10:35:49 -0500561 AutoProgramConfig autoConfig(fContext, &config);
John Stiles270cec22021-02-17 12:59:36 -0500562
John Stilesd1204642021-02-17 16:30:02 -0500563 // Reset the Inliner.
John Stiles10d39d92021-05-04 16:13:14 -0400564 fInliner.reset();
John Stiles270cec22021-02-17 12:59:36 -0500565
566 std::unique_ptr<ProgramUsage> usage = Analysis::GetUsage(module);
Brian Osman0006ad02020-11-18 15:38:39 -0500567
568 while (fErrorCount == 0) {
Brian Osman0006ad02020-11-18 15:38:39 -0500569 // Perform inline-candidate analysis and inline any functions deemed suitable.
John Stilesf3a28db2021-03-10 23:00:47 -0500570 if (!fInliner.analyze(module.fElements, module.fSymbols, usage.get())) {
Brian Osman0006ad02020-11-18 15:38:39 -0500571 break;
572 }
573 }
574 return fErrorCount == 0;
575}
576
John Stiles0bfeae62021-03-11 09:09:42 -0500577bool Compiler::removeDeadFunctions(Program& program, ProgramUsage* usage) {
578 bool madeChanges = false;
579
580 if (program.fConfig->fSettings.fRemoveDeadFunctions) {
581 auto isDeadFunction = [&](const ProgramElement* element) {
582 if (!element->is<FunctionDefinition>()) {
583 return false;
584 }
585 const FunctionDefinition& fn = element->as<FunctionDefinition>();
John Stilese8da4d22021-03-24 09:19:45 -0400586 if (fn.declaration().isMain() || usage->get(fn.declaration()) > 0) {
John Stiles0bfeae62021-03-11 09:09:42 -0500587 return false;
588 }
589 usage->remove(*element);
590 madeChanges = true;
591 return true;
592 };
593
594 program.fElements.erase(std::remove_if(program.fElements.begin(),
595 program.fElements.end(),
596 [&](const std::unique_ptr<ProgramElement>& element) {
597 return isDeadFunction(element.get());
598 }),
599 program.fElements.end());
600 program.fSharedElements.erase(std::remove_if(program.fSharedElements.begin(),
601 program.fSharedElements.end(),
602 isDeadFunction),
603 program.fSharedElements.end());
604 }
605 return madeChanges;
606}
607
608bool Compiler::removeDeadGlobalVariables(Program& program, ProgramUsage* usage) {
609 bool madeChanges = false;
610
611 if (program.fConfig->fSettings.fRemoveDeadVariables) {
612 auto isDeadVariable = [&](const ProgramElement* element) {
613 if (!element->is<GlobalVarDeclaration>()) {
614 return false;
615 }
616 const GlobalVarDeclaration& global = element->as<GlobalVarDeclaration>();
617 const VarDeclaration& varDecl = global.declaration()->as<VarDeclaration>();
618 if (!usage->isDead(varDecl.var())) {
619 return false;
620 }
621 madeChanges = true;
622 return true;
623 };
624
625 program.fElements.erase(std::remove_if(program.fElements.begin(),
626 program.fElements.end(),
627 [&](const std::unique_ptr<ProgramElement>& element) {
628 return isDeadVariable(element.get());
629 }),
630 program.fElements.end());
631 program.fSharedElements.erase(std::remove_if(program.fSharedElements.begin(),
632 program.fSharedElements.end(),
633 isDeadVariable),
634 program.fSharedElements.end());
635 }
636 return madeChanges;
637}
638
John Stiles26541872021-03-16 12:19:54 -0400639bool Compiler::removeDeadLocalVariables(Program& program, ProgramUsage* usage) {
640 class DeadLocalVariableEliminator : public ProgramWriter {
641 public:
642 DeadLocalVariableEliminator(const Context& context, ProgramUsage* usage)
643 : fContext(context)
644 , fUsage(usage) {}
645
646 using ProgramWriter::visitProgramElement;
647
648 bool visitExpressionPtr(std::unique_ptr<Expression>& expr) override {
649 // We don't need to look inside expressions at all.
650 return false;
651 }
652
653 bool visitStatementPtr(std::unique_ptr<Statement>& stmt) override {
654 if (stmt->is<VarDeclaration>()) {
655 VarDeclaration& varDecl = stmt->as<VarDeclaration>();
656 const Variable* var = &varDecl.var();
657 ProgramUsage::VariableCounts* counts = fUsage->fVariableCounts.find(var);
658 SkASSERT(counts);
659 SkASSERT(counts->fDeclared);
660 if (CanEliminate(var, *counts)) {
661 if (var->initialValue()) {
662 // The variable has an initial-value expression, which might have side
663 // effects. ExpressionStatement::Make will preserve side effects, but
664 // replaces pure expressions with Nop.
665 fUsage->remove(stmt.get());
666 stmt = ExpressionStatement::Make(fContext, std::move(varDecl.value()));
667 fUsage->add(stmt.get());
668 } else {
669 // The variable has no initial-value and can be cleanly eliminated.
670 fUsage->remove(stmt.get());
671 stmt = std::make_unique<Nop>();
672 }
673 fMadeChanges = true;
674 }
675 return false;
676 }
677 return INHERITED::visitStatementPtr(stmt);
678 }
679
680 static bool CanEliminate(const Variable* var, const ProgramUsage::VariableCounts& counts) {
681 if (!counts.fDeclared || counts.fRead || var->storage() != VariableStorage::kLocal) {
682 return false;
683 }
684 if (var->initialValue()) {
685 SkASSERT(counts.fWrite >= 1);
686 return counts.fWrite == 1;
687 } else {
688 return counts.fWrite == 0;
689 }
690 }
691
692 bool fMadeChanges = false;
693 const Context& fContext;
694 ProgramUsage* fUsage;
695
696 using INHERITED = ProgramWriter;
697 };
698
699 DeadLocalVariableEliminator visitor{*fContext, usage};
700
701 if (program.fConfig->fSettings.fRemoveDeadVariables) {
702 for (auto& [var, counts] : usage->fVariableCounts) {
703 if (DeadLocalVariableEliminator::CanEliminate(var, counts)) {
704 // This program contains at least one dead local variable.
705 // Scan the program for any dead local variables and eliminate them all.
706 for (std::unique_ptr<ProgramElement>& pe : program.ownedElements()) {
707 if (pe->is<FunctionDefinition>()) {
708 visitor.visitProgramElement(*pe);
709 }
710 }
711 break;
712 }
713 }
714 }
715
716 return visitor.fMadeChanges;
717}
718
John Stiles25be58e2021-05-20 14:38:40 -0400719void Compiler::removeUnreachableCode(Program& program, ProgramUsage* usage) {
720 class UnreachableCodeEliminator : public ProgramWriter {
721 public:
722 UnreachableCodeEliminator(const Context& context, ProgramUsage* usage)
723 : fContext(context)
724 , fUsage(usage) {
725 fFoundFunctionExit.push(false);
726 fFoundLoopExit.push(false);
727 }
728
729 using ProgramWriter::visitProgramElement;
730
731 bool visitExpressionPtr(std::unique_ptr<Expression>& expr) override {
732 // We don't need to look inside expressions at all.
733 return false;
734 }
735
736 bool visitStatementPtr(std::unique_ptr<Statement>& stmt) override {
737 if (fFoundFunctionExit.top() || fFoundLoopExit.top()) {
738 // If we already found an exit in this section, anything beyond it is dead code.
739 if (!stmt->is<Nop>()) {
740 // Eliminate the dead statement by substituting a Nop.
741 fUsage->remove(stmt.get());
742 stmt = std::make_unique<Nop>();
743 }
744 return false;
745 }
746
747 switch (stmt->kind()) {
748 case Statement::Kind::kReturn:
749 case Statement::Kind::kDiscard:
750 // We found a function exit on this path.
751 fFoundFunctionExit.top() = true;
752 break;
753
754 case Statement::Kind::kBreak:
755 case Statement::Kind::kContinue:
756 // We found a loop exit on this path. Note that we skip over switch statements
757 // completely when eliminating code, so any `break` statement would be breaking
758 // out of a loop, not out of a switch.
759 fFoundLoopExit.top() = true;
760 break;
761
762 case Statement::Kind::kExpression:
763 case Statement::Kind::kInlineMarker:
764 case Statement::Kind::kNop:
765 case Statement::Kind::kVarDeclaration:
766 // These statements don't affect control flow.
767 break;
768
769 case Statement::Kind::kBlock:
770 // Blocks are on the straight-line path and don't affect control flow.
771 return INHERITED::visitStatementPtr(stmt);
772
773 case Statement::Kind::kDo: {
774 // Function-exits are allowed to propagate outside of a do-loop, because it
775 // always executes its body at least once.
776 fFoundLoopExit.push(false);
777 bool result = INHERITED::visitStatementPtr(stmt);
778 fFoundLoopExit.pop();
779 return result;
780 }
781 case Statement::Kind::kFor: {
782 // Function-exits are not allowed to propagate out, because a for-loop or while-
783 // loop could potentially run zero times.
784 fFoundFunctionExit.push(false);
785 fFoundLoopExit.push(false);
786 bool result = INHERITED::visitStatementPtr(stmt);
787 fFoundLoopExit.pop();
788 fFoundFunctionExit.pop();
789 return result;
790 }
791 case Statement::Kind::kIf: {
792 // This statement is conditional and encloses two inner sections of code.
793 // If both sides contain a function-exit or loop-exit, that exit is allowed to
794 // propagate out.
795 IfStatement& ifStmt = stmt->as<IfStatement>();
796
797 fFoundFunctionExit.push(false);
798 fFoundLoopExit.push(false);
799 bool result = (ifStmt.ifTrue() && this->visitStatementPtr(ifStmt.ifTrue()));
800 bool foundFunctionExitOnTrue = fFoundFunctionExit.top();
801 bool foundLoopExitOnTrue = fFoundLoopExit.top();
802 fFoundFunctionExit.pop();
803 fFoundLoopExit.pop();
804
805 fFoundFunctionExit.push(false);
806 fFoundLoopExit.push(false);
807 result |= (ifStmt.ifFalse() && this->visitStatementPtr(ifStmt.ifFalse()));
808 bool foundFunctionExitOnFalse = fFoundFunctionExit.top();
809 bool foundLoopExitOnFalse = fFoundLoopExit.top();
810 fFoundFunctionExit.pop();
811 fFoundLoopExit.pop();
812
813 fFoundFunctionExit.top() |= foundFunctionExitOnTrue && foundFunctionExitOnFalse;
814 fFoundLoopExit.top() |= foundLoopExitOnTrue && foundLoopExitOnFalse;
815 return result;
816 }
817 case Statement::Kind::kSwitch:
818 case Statement::Kind::kSwitchCase:
819 // We skip past switch statements entirely when scanning for dead code. Their
820 // control flow is quite complex and we already do a good job of flattening out
821 // switches on constant values.
822 break;
823 }
824
825 return false;
826 }
827
828 const Context& fContext;
829 ProgramUsage* fUsage;
830 std::stack<bool> fFoundFunctionExit;
831 std::stack<bool> fFoundLoopExit;
832
833 using INHERITED = ProgramWriter;
834 };
835
836 for (std::unique_ptr<ProgramElement>& pe : program.ownedElements()) {
837 if (pe->is<FunctionDefinition>()) {
838 UnreachableCodeEliminator visitor{*fContext, usage};
839 visitor.visitProgramElement(*pe);
840 }
841 }
842}
843
Ethan Nicholas00543112018-07-31 09:44:36 -0400844bool Compiler::optimize(Program& program) {
John Stiles7247b482021-03-08 10:40:35 -0500845 // The optimizer only needs to run when it is enabled.
846 if (!program.fConfig->fSettings.fOptimize) {
847 return true;
848 }
849
Ethan Nicholas00543112018-07-31 09:44:36 -0400850 SkASSERT(!fErrorCount);
Brian Osman010ce6a2020-10-19 16:34:10 -0400851 ProgramUsage* usage = program.fUsage.get();
John Stiles7954d6c2020-09-01 10:53:02 -0400852
John Stilesb6664582021-03-19 09:46:00 -0400853 if (fErrorCount == 0) {
John Stiles87fc6572021-04-01 14:56:34 +0000854 // Run the inliner only once; it is expensive! Multiple passes can occasionally shake out
855 // more wins, but it's diminishing returns.
856 fInliner.analyze(program.ownedElements(), program.fSymbols, usage);
Ethan Nicholas34b19c52020-09-14 11:33:47 -0400857
John Stilesb6664582021-03-19 09:46:00 -0400858 while (this->removeDeadFunctions(program, usage)) {
859 // Removing dead functions may cause more functions to become unreferenced. Try again.
Ethan Nicholas34b19c52020-09-14 11:33:47 -0400860 }
John Stilesb6664582021-03-19 09:46:00 -0400861 while (this->removeDeadLocalVariables(program, usage)) {
862 // Removing dead variables may cause more variables to become unreferenced. Try again.
863 }
John Stiles25be58e2021-05-20 14:38:40 -0400864 // Unreachable code can confuse some drivers, so it's worth removing. (skia:12012)
865 this->removeUnreachableCode(program, usage);
866
Brian Osman8c264792021-07-01 16:41:27 -0400867 this->removeDeadGlobalVariables(program, usage);
Ethan Nicholas00543112018-07-31 09:44:36 -0400868 }
John Stilesbb1505f2021-02-12 09:17:53 -0500869
870 if (fErrorCount == 0) {
871 this->verifyStaticTests(program);
872 }
873
Ethan Nicholas00543112018-07-31 09:44:36 -0400874 return fErrorCount == 0;
875}
876
Brian Osmanfb32ddf2019-06-18 10:14:20 -0400877#if defined(SKSL_STANDALONE) || SK_SUPPORT_GPU
878
Ethan Nicholas00543112018-07-31 09:44:36 -0400879bool Compiler::toSPIRV(Program& program, OutputStream& out) {
Brian Osman7a20b5c2021-03-15 16:23:33 -0400880 TRACE_EVENT0("skia.shaders", "SkSL::Compiler::toSPIRV");
John Stilesa289ac22021-05-06 07:35:35 -0400881 AutoSource as(this, program.fSource.get());
Brian Salomond8d85b92021-07-07 09:41:17 -0400882 ProgramSettings settings;
883 settings.fDSLUseMemoryPool = false;
884 dsl::Start(this, program.fConfig->fKind, settings);
885 dsl::DSLWriter::IRGenerator().fSymbolTable = program.fSymbols;
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -0400886#ifdef SK_ENABLE_SPIRV_VALIDATION
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400887 StringStream buffer;
Brian Osman8b43dad2020-10-09 13:31:42 -0400888 SPIRVCodeGenerator cg(fContext.get(), &program, this, &buffer);
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -0400889 bool result = cg.generateCode();
John Stiles270cec22021-02-17 12:59:36 -0500890 if (result && program.fConfig->fSettings.fValidateSPIRV) {
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -0400891 spvtools::SpirvTools tools(SPV_ENV_VULKAN_1_0);
Ethan Nicholas762466e2017-06-29 10:03:38 -0400892 const String& data = buffer.str();
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400893 SkASSERT(0 == data.size() % 4);
Brian Osman8d09d4a2020-11-24 15:51:06 -0500894 String errors;
895 auto dumpmsg = [&errors](spv_message_level_t, const char*, const spv_position_t&,
896 const char* m) {
897 errors.appendf("SPIR-V validation error: %s\n", m);
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -0400898 };
899 tools.SetMessageConsumer(dumpmsg);
Brian Osman8d09d4a2020-11-24 15:51:06 -0500900
901 // Verify that the SPIR-V we produced is valid. At runtime, we will abort() with a message
902 // explaining the error. In standalone mode (skslc), we will send the message, plus the
903 // entire disassembled SPIR-V (for easier context & debugging) as *our* error message.
904 result = tools.Validate((const uint32_t*) data.c_str(), data.size() / 4);
905
906 if (!result) {
907#if defined(SKSL_STANDALONE)
908 // Convert the string-stream to a SPIR-V disassembly.
909 std::string disassembly;
910 if (tools.Disassemble((const uint32_t*)data.data(), data.size() / 4, &disassembly)) {
911 errors.append(disassembly);
912 }
913 this->error(-1, errors);
914#else
915 SkDEBUGFAILF("%s", errors.c_str());
916#endif
917 }
Ethan Nicholas762466e2017-06-29 10:03:38 -0400918 out.write(data.c_str(), data.size());
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -0400919 }
920#else
Brian Osman8b43dad2020-10-09 13:31:42 -0400921 SPIRVCodeGenerator cg(fContext.get(), &program, this, &out);
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500922 bool result = cg.generateCode();
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -0400923#endif
Brian Salomond8d85b92021-07-07 09:41:17 -0400924 dsl::End();
Ethan Nicholasce33f102016-12-09 17:22:59 -0500925 return result;
926}
927
Ethan Nicholas00543112018-07-31 09:44:36 -0400928bool Compiler::toSPIRV(Program& program, String* out) {
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400929 StringStream buffer;
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500930 bool result = this->toSPIRV(program, buffer);
931 if (result) {
Ethan Nicholas762466e2017-06-29 10:03:38 -0400932 *out = buffer.str();
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500933 }
934 return result;
935}
936
Ethan Nicholas00543112018-07-31 09:44:36 -0400937bool Compiler::toGLSL(Program& program, OutputStream& out) {
Brian Osman7a20b5c2021-03-15 16:23:33 -0400938 TRACE_EVENT0("skia.shaders", "SkSL::Compiler::toGLSL");
Brian Osman88cda172020-10-09 12:05:16 -0400939 AutoSource as(this, program.fSource.get());
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400940 GLSLCodeGenerator cg(fContext.get(), &program, this, &out);
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500941 bool result = cg.generateCode();
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500942 return result;
943}
944
Ethan Nicholas00543112018-07-31 09:44:36 -0400945bool Compiler::toGLSL(Program& program, String* out) {
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400946 StringStream buffer;
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500947 bool result = this->toGLSL(program, buffer);
948 if (result) {
Ethan Nicholas762466e2017-06-29 10:03:38 -0400949 *out = buffer.str();
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500950 }
951 return result;
952}
953
Brian Osmanc0243912020-02-19 15:35:26 -0500954bool Compiler::toHLSL(Program& program, String* out) {
955 String spirv;
956 if (!this->toSPIRV(program, &spirv)) {
957 return false;
958 }
959
960 return SPIRVtoHLSL(spirv, out);
961}
962
Ethan Nicholas00543112018-07-31 09:44:36 -0400963bool Compiler::toMetal(Program& program, OutputStream& out) {
Brian Osman7a20b5c2021-03-15 16:23:33 -0400964 TRACE_EVENT0("skia.shaders", "SkSL::Compiler::toMetal");
John Stilesa289ac22021-05-06 07:35:35 -0400965 AutoSource as(this, program.fSource.get());
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400966 MetalCodeGenerator cg(fContext.get(), &program, this, &out);
Ethan Nicholascc305772017-10-13 16:17:45 -0400967 bool result = cg.generateCode();
Ethan Nicholascc305772017-10-13 16:17:45 -0400968 return result;
969}
970
Ethan Nicholas00543112018-07-31 09:44:36 -0400971bool Compiler::toMetal(Program& program, String* out) {
Timothy Liangb8eeb802018-07-23 16:46:16 -0400972 StringStream buffer;
973 bool result = this->toMetal(program, buffer);
974 if (result) {
975 *out = buffer.str();
976 }
977 return result;
978}
979
Ethan Nicholas2a479a52020-08-18 16:29:45 -0400980#endif // defined(SKSL_STANDALONE) || SK_SUPPORT_GPU
Brian Osman2e29ab52019-09-20 12:19:11 -0400981
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700982Position Compiler::position(int offset) {
Ethan Nicholas3c729892020-12-07 12:47:17 -0500983 if (fSource && offset >= 0) {
984 int line = 1;
985 int column = 1;
986 for (int i = 0; i < offset; i++) {
987 if ((*fSource)[i] == '\n') {
988 ++line;
989 column = 1;
990 }
991 else {
992 ++column;
993 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700994 }
Ethan Nicholas3c729892020-12-07 12:47:17 -0500995 return Position(line, column);
996 } else {
997 return Position(-1, -1);
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700998 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700999}
1000
1001void Compiler::error(int offset, String msg) {
Ethan Nicholas549c6b82021-06-25 12:31:44 -04001002 if (strstr(msg.c_str(), POISON_TAG)) {
1003 // don't report errors on poison values
1004 return;
1005 }
ethannicholasb3058bd2016-07-01 08:22:01 -07001006 fErrorCount++;
Ethan Nicholas5b5f0962017-09-11 13:50:14 -07001007 Position pos = this->position(offset);
John Stiles8d3642e2021-01-22 09:50:04 -05001008 fErrorTextLength.push_back(fErrorText.length());
Ethan Nicholasdd2fdea2021-07-20 15:23:04 -04001009 if (!msg.starts_with("error: ")) {
1010 fErrorText += "error: ";
1011 }
1012 fErrorText += (pos.fLine >= 1 ? to_string(pos.fLine) + ": " : "") + msg + "\n";
ethannicholasb3058bd2016-07-01 08:22:01 -07001013}
1014
John Stiles8d3642e2021-01-22 09:50:04 -05001015void Compiler::setErrorCount(int c) {
1016 if (c < fErrorCount) {
1017 fErrorText.resize(fErrorTextLength[c]);
1018 fErrorTextLength.resize(c);
1019 fErrorCount = c;
1020 }
1021}
1022
Ethan Nicholas95046142021-01-07 10:57:27 -05001023String Compiler::errorText(bool showCount) {
1024 if (showCount) {
1025 this->writeErrorCount();
1026 }
Ethan Nicholas00543112018-07-31 09:44:36 -04001027 fErrorCount = 0;
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001028 String result = fErrorText;
Ethan Nicholas95046142021-01-07 10:57:27 -05001029 fErrorText = "";
ethannicholasb3058bd2016-07-01 08:22:01 -07001030 return result;
1031}
1032
1033void Compiler::writeErrorCount() {
1034 if (fErrorCount) {
1035 fErrorText += to_string(fErrorCount) + " error";
1036 if (fErrorCount > 1) {
1037 fErrorText += "s";
1038 }
1039 fErrorText += "\n";
1040 }
1041}
1042
John Stilesa6841be2020-08-06 14:11:56 -04001043} // namespace SkSL