blob: f514d118acc8b61b1e47402ee671133c81645558 [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"
Brian Osmancbb60bd2021-04-12 09:49:20 -040064#include "src/sksl/generated/sksl_rt_shader.dehydrated.sksl"
Ethan Nicholasc18bb512020-07-28 14:46:53 -040065#include "src/sksl/generated/sksl_vert.dehydrated.sksl"
66
Brian Osman3d87e9f2020-10-08 11:50:22 -040067#define MODULE_DATA(name) MakeModuleData(SKSL_INCLUDE_sksl_##name,\
68 SKSL_INCLUDE_sksl_##name##_LENGTH)
Ethan Nicholasc18bb512020-07-28 14:46:53 -040069
70#endif
Ethan Nicholas0d997662019-04-08 09:46:01 -040071
ethannicholasb3058bd2016-07-01 08:22:01 -070072namespace SkSL {
73
John Stiles7247b482021-03-08 10:40:35 -050074// These flags allow tools like Viewer or Nanobench to override the compiler's ProgramSettings.
John Stiles2ee4d7a2021-03-30 10:30:47 -040075Compiler::OverrideFlag Compiler::sOptimizer = OverrideFlag::kDefault;
76Compiler::OverrideFlag Compiler::sInliner = OverrideFlag::kDefault;
John Stiles8ef4d6c2021-03-05 16:01:45 -050077
John Stiles47c0a742021-02-09 09:30:35 -050078using RefKind = VariableReference::RefKind;
79
Brian Osman88cda172020-10-09 12:05:16 -040080class AutoSource {
81public:
Ethan Nicholasb449fff2021-08-04 15:06:37 -040082 AutoSource(Compiler* compiler, const char* source)
John Stilesa289ac22021-05-06 07:35:35 -040083 : fCompiler(compiler) {
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -040084 SkASSERT(!fCompiler->errorReporter().source());
85 fCompiler->errorReporter().setSource(source);
Brian Osman88cda172020-10-09 12:05:16 -040086 }
87
John Stilesa289ac22021-05-06 07:35:35 -040088 ~AutoSource() {
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -040089 fCompiler->errorReporter().setSource(nullptr);
John Stilesa289ac22021-05-06 07:35:35 -040090 }
Brian Osman88cda172020-10-09 12:05:16 -040091
92 Compiler* fCompiler;
Brian Osman88cda172020-10-09 12:05:16 -040093};
94
John Stilesa935c3f2021-02-25 10:35:49 -050095class AutoProgramConfig {
96public:
97 AutoProgramConfig(std::shared_ptr<Context>& context, ProgramConfig* config)
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -040098 : fContext(context.get())
99 , fOldConfig(fContext->fConfig) {
John Stilesa935c3f2021-02-25 10:35:49 -0500100 fContext->fConfig = config;
101 }
102
103 ~AutoProgramConfig() {
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -0400104 fContext->fConfig = fOldConfig;
John Stilesa935c3f2021-02-25 10:35:49 -0500105 }
106
107 Context* fContext;
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -0400108 ProgramConfig* fOldConfig;
John Stilesa935c3f2021-02-25 10:35:49 -0500109};
110
John Stiles10d39d92021-05-04 16:13:14 -0400111class AutoModifiersPool {
112public:
113 AutoModifiersPool(std::shared_ptr<Context>& context, ModifiersPool* modifiersPool)
114 : fContext(context.get()) {
115 SkASSERT(!fContext->fModifiersPool);
116 fContext->fModifiersPool = modifiersPool;
117 }
118
119 ~AutoModifiersPool() {
120 fContext->fModifiersPool = nullptr;
121 }
122
123 Context* fContext;
124};
125
John Stilesd6a5f4492021-02-11 15:46:11 -0500126Compiler::Compiler(const ShaderCapsClass* caps)
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -0400127 : fErrorReporter(this)
128 , fContext(std::make_shared<Context>(fErrorReporter, *caps))
John Stilesa47b3512021-05-04 16:15:00 -0400129 , fInliner(fContext.get()) {
John Stilesc1a98b82021-02-24 13:35:02 -0500130 SkASSERT(caps);
John Stilesb624b722021-08-13 12:16:13 -0400131 fRootModule.fSymbols = this->makeRootSymbolTable();
132 fPrivateModule.fSymbols = this->makePrivateSymbolTable(fRootModule.fSymbols);
John Stilesc1a98b82021-02-24 13:35:02 -0500133 fIRGenerator = std::make_unique<IRGenerator>(fContext.get());
John Stilesb624b722021-08-13 12:16:13 -0400134}
135
136Compiler::~Compiler() {}
ethannicholasb3058bd2016-07-01 08:22:01 -0700137
John Stiles54e7c052021-01-11 14:22:36 -0500138#define TYPE(t) fContext->fTypes.f ## t .get()
ethannicholasb3058bd2016-07-01 08:22:01 -0700139
John Stilesb624b722021-08-13 12:16:13 -0400140std::shared_ptr<SymbolTable> Compiler::makeRootSymbolTable() {
Ethan Nicholasc7774a72021-08-27 15:34:05 -0400141 auto rootSymbolTable = std::make_shared<SymbolTable>(*fContext, /*builtin=*/true);
John Stilesb624b722021-08-13 12:16:13 -0400142
Brian Osmanb06301e2020-11-06 11:45:36 -0500143 const SkSL::Symbol* rootTypes[] = {
144 TYPE(Void),
Brian Salomonbf7b6202016-11-11 16:08:03 -0500145
Brian Osmanb06301e2020-11-06 11:45:36 -0500146 TYPE( Float), TYPE( Float2), TYPE( Float3), TYPE( Float4),
147 TYPE( Half), TYPE( Half2), TYPE( Half3), TYPE( Half4),
148 TYPE( Int), TYPE( Int2), TYPE( Int3), TYPE( Int4),
John Stiles823c5042021-08-17 12:09:00 -0400149 TYPE( UInt), TYPE( UInt2), TYPE( UInt3), TYPE( UInt4),
150 TYPE( Short), TYPE( Short2), TYPE( Short3), TYPE( Short4),
151 TYPE(UShort), TYPE(UShort2), TYPE(UShort3), TYPE(UShort4),
Brian Osmanb06301e2020-11-06 11:45:36 -0500152 TYPE( Bool), TYPE( Bool2), TYPE( Bool3), TYPE( Bool4),
Brian Salomon2a51de82016-11-16 12:06:01 -0500153
John Stiles823c5042021-08-17 12:09:00 -0400154 TYPE(Float2x2), TYPE(Float2x3), TYPE(Float2x4),
155 TYPE(Float3x2), TYPE(Float3x3), TYPE(Float3x4),
156 TYPE(Float4x2), TYPE(Float4x3), TYPE(Float4x4),
157
158 TYPE(Half2x2), TYPE(Half2x3), TYPE(Half2x4),
159 TYPE(Half3x2), TYPE(Half3x3), TYPE(Half3x4),
160 TYPE(Half4x2), TYPE(Half4x3), TYPE(Half4x4),
Greg Daniel64773e62016-11-22 09:44:03 -0500161
Brian Osmanc63f4312020-12-23 11:44:14 -0500162 TYPE(SquareMat), TYPE(SquareHMat),
John Stiles823c5042021-08-17 12:09:00 -0400163 TYPE(Mat), TYPE(HMat),
ethannicholasb3058bd2016-07-01 08:22:01 -0700164
John Stiles823c5042021-08-17 12:09:00 -0400165 // TODO(skia:12349): generic short/ushort
166 TYPE(GenType), TYPE(GenIType), TYPE(GenUType),
167 TYPE(GenHType), /* (GenSType) (GenUSType) */
168 TYPE(GenBType),
169
170 TYPE(Vec), TYPE(IVec), TYPE(UVec),
171 TYPE(HVec), TYPE(SVec), TYPE(USVec),
172 TYPE(BVec),
Brian Osmanb06301e2020-11-06 11:45:36 -0500173
Brian Osman14d00962021-04-02 17:04:35 -0400174 TYPE(ColorFilter),
175 TYPE(Shader),
John Stilesbb2ef922021-07-26 08:32:07 -0400176 TYPE(Blender),
Brian Osmanb06301e2020-11-06 11:45:36 -0500177 };
178
John Stilesb624b722021-08-13 12:16:13 -0400179 for (const SkSL::Symbol* type : rootTypes) {
180 rootSymbolTable->addWithoutOwnership(type);
181 }
182
183 return rootSymbolTable;
184}
185
186std::shared_ptr<SymbolTable> Compiler::makePrivateSymbolTable(std::shared_ptr<SymbolTable> parent) {
187 auto privateSymbolTable = std::make_shared<SymbolTable>(parent, /*builtin=*/true);
188
Brian Osmanb06301e2020-11-06 11:45:36 -0500189 const SkSL::Symbol* privateTypes[] = {
190 TYPE(Sampler1D), TYPE(Sampler2D), TYPE(Sampler3D),
191 TYPE(SamplerExternalOES),
Brian Osmanb06301e2020-11-06 11:45:36 -0500192 TYPE(Sampler2DRect),
Brian Osmanb06301e2020-11-06 11:45:36 -0500193
194 TYPE(ISampler2D),
Brian Osmanb06301e2020-11-06 11:45:36 -0500195 TYPE(SubpassInput), TYPE(SubpassInputMS),
196
Brian Osmanb06301e2020-11-06 11:45:36 -0500197 TYPE(Sampler),
198 TYPE(Texture2D),
199 };
200
Brian Osmanb06301e2020-11-06 11:45:36 -0500201 for (const SkSL::Symbol* type : privateTypes) {
John Stilesb624b722021-08-13 12:16:13 -0400202 privateSymbolTable->addWithoutOwnership(type);
Brian Osmanb06301e2020-11-06 11:45:36 -0500203 }
204
Brian Osman3887a012020-09-30 13:22:27 -0400205 // sk_Caps is "builtin", but all references to it are resolved to Settings, so we don't need to
206 // treat it as builtin (ie, no need to clone it into the Program).
John Stilesb624b722021-08-13 12:16:13 -0400207 privateSymbolTable->add(std::make_unique<Variable>(/*offset=*/-1,
208 fCoreModifiers.add(Modifiers{}),
209 "sk_Caps",
210 fContext->fTypes.fSkCaps.get(),
211 /*builtin=*/false,
212 Variable::Storage::kGlobal));
Ethan Nicholas3605ace2016-11-21 15:59:48 -0500213
John Stilesb624b722021-08-13 12:16:13 -0400214 return privateSymbolTable;
ethannicholasb3058bd2016-07-01 08:22:01 -0700215}
216
John Stilesb624b722021-08-13 12:16:13 -0400217#undef TYPE
ethannicholasb3058bd2016-07-01 08:22:01 -0700218
Brian Osman56269982020-11-20 12:38:07 -0500219const ParsedModule& Compiler::loadGPUModule() {
220 if (!fGPUModule.fSymbols) {
John Stilesdbd4e6f2021-02-16 13:29:15 -0500221 fGPUModule = this->parseModule(ProgramKind::kFragment, MODULE_DATA(gpu), fPrivateModule);
Brian Osman56269982020-11-20 12:38:07 -0500222 }
223 return fGPUModule;
224}
225
226const ParsedModule& Compiler::loadFragmentModule() {
227 if (!fFragmentModule.fSymbols) {
John Stilesdbd4e6f2021-02-16 13:29:15 -0500228 fFragmentModule = this->parseModule(ProgramKind::kFragment, MODULE_DATA(frag),
Brian Osman56269982020-11-20 12:38:07 -0500229 this->loadGPUModule());
230 }
231 return fFragmentModule;
232}
233
234const ParsedModule& Compiler::loadVertexModule() {
235 if (!fVertexModule.fSymbols) {
John Stilesdbd4e6f2021-02-16 13:29:15 -0500236 fVertexModule = this->parseModule(ProgramKind::kVertex, MODULE_DATA(vert),
Brian Osman56269982020-11-20 12:38:07 -0500237 this->loadGPUModule());
238 }
239 return fVertexModule;
240}
241
Brian Osmancbb60bd2021-04-12 09:49:20 -0400242static void add_glsl_type_aliases(SkSL::SymbolTable* symbols, const SkSL::BuiltinTypes& types) {
243 // Add some aliases to the runtime effect modules so that it's friendlier, and more like GLSL
244 symbols->addAlias("vec2", types.fFloat2.get());
245 symbols->addAlias("vec3", types.fFloat3.get());
246 symbols->addAlias("vec4", types.fFloat4.get());
247
248 symbols->addAlias("ivec2", types.fInt2.get());
249 symbols->addAlias("ivec3", types.fInt3.get());
250 symbols->addAlias("ivec4", types.fInt4.get());
251
252 symbols->addAlias("bvec2", types.fBool2.get());
253 symbols->addAlias("bvec3", types.fBool3.get());
254 symbols->addAlias("bvec4", types.fBool4.get());
255
256 symbols->addAlias("mat2", types.fFloat2x2.get());
257 symbols->addAlias("mat3", types.fFloat3x3.get());
258 symbols->addAlias("mat4", types.fFloat4x4.get());
259}
260
Brian Osmana8b897b2021-08-30 16:40:44 -0400261const ParsedModule& Compiler::loadPublicModule() {
262 if (!fPublicModule.fSymbols) {
263 fPublicModule = this->parseModule(ProgramKind::kGeneric, MODULE_DATA(public), fRootModule);
264 add_glsl_type_aliases(fPublicModule.fSymbols.get(), fContext->fTypes);
Brian Osmancbb60bd2021-04-12 09:49:20 -0400265 }
Brian Osmana8b897b2021-08-30 16:40:44 -0400266 return fPublicModule;
Brian Osmancbb60bd2021-04-12 09:49:20 -0400267}
268
269const ParsedModule& Compiler::loadRuntimeShaderModule() {
270 if (!fRuntimeShaderModule.fSymbols) {
271 fRuntimeShaderModule = this->parseModule(
272 ProgramKind::kRuntimeShader, MODULE_DATA(rt_shader), this->loadPublicModule());
Brian Osmancbb60bd2021-04-12 09:49:20 -0400273 }
274 return fRuntimeShaderModule;
275}
276
John Stilesdbd4e6f2021-02-16 13:29:15 -0500277const ParsedModule& Compiler::moduleForProgramKind(ProgramKind kind) {
Brian Osman88cda172020-10-09 12:05:16 -0400278 switch (kind) {
Brian Osmana8b897b2021-08-30 16:40:44 -0400279 case ProgramKind::kVertex: return this->loadVertexModule(); break;
280 case ProgramKind::kFragment: return this->loadFragmentModule(); break;
281 case ProgramKind::kRuntimeColorFilter: return this->loadPublicModule(); break;
282 case ProgramKind::kRuntimeShader: return this->loadRuntimeShaderModule(); break;
283 case ProgramKind::kRuntimeBlender: return this->loadPublicModule(); break;
284 case ProgramKind::kGeneric: return this->loadPublicModule(); break;
Brian Osman88cda172020-10-09 12:05:16 -0400285 }
286 SkUNREACHABLE;
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400287}
288
John Stilesdbd4e6f2021-02-16 13:29:15 -0500289LoadedModule Compiler::loadModule(ProgramKind kind,
Brian Osman3d87e9f2020-10-08 11:50:22 -0400290 ModuleData data,
John Stilesa935c3f2021-02-25 10:35:49 -0500291 std::shared_ptr<SymbolTable> base,
292 bool dehydrate) {
293 if (dehydrate) {
294 // NOTE: This is a workaround. When dehydrating includes, skslc doesn't know which module
295 // it's preparing, nor what the correct base module is. We can't use 'Root', because many
296 // GPU intrinsics reference private types, like samplers or textures. Today, 'Private' does
297 // contain the union of all known types, so this is safe. If we ever have types that only
298 // exist in 'Public' (for example), this logic needs to be smarter (by choosing the correct
299 // base for the module we're compiling).
John Stilesb624b722021-08-13 12:16:13 -0400300 base = fPrivateModule.fSymbols;
Brian Osman3d87e9f2020-10-08 11:50:22 -0400301 }
John Stilesa935c3f2021-02-25 10:35:49 -0500302 SkASSERT(base);
303
John Stilesa47b3512021-05-04 16:15:00 -0400304 // Put the core-module modifier pool into the context.
305 AutoModifiersPool autoPool(fContext, &fCoreModifiers);
John Stiles10d39d92021-05-04 16:13:14 -0400306
John Stilesa935c3f2021-02-25 10:35:49 -0500307 // Built-in modules always use default program settings.
Ethan Nicholas55a63af2021-05-18 10:12:58 -0400308 Program::Settings settings;
309 settings.fReplaceSettings = !dehydrate;
Brian Osman3d87e9f2020-10-08 11:50:22 -0400310
311#if defined(SKSL_STANDALONE)
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -0400312 SkASSERT(this->errorCount() == 0);
Brian Osman3d87e9f2020-10-08 11:50:22 -0400313 SkASSERT(data.fPath);
314 std::ifstream in(data.fPath);
John Stilesd51c9792021-03-18 11:40:14 -0400315 String text{std::istreambuf_iterator<char>(in), std::istreambuf_iterator<char>()};
Ethan Nicholasb33fa3f2020-08-06 13:00:19 -0400316 if (in.rdstate()) {
Brian Osman3d87e9f2020-10-08 11:50:22 -0400317 printf("error reading %s\n", data.fPath);
Ethan Nicholasb33fa3f2020-08-06 13:00:19 -0400318 abort();
319 }
John Stilesb624b722021-08-13 12:16:13 -0400320 const String* source = fRootModule.fSymbols->takeOwnershipOfString(std::move(text));
John Stilesd1204642021-02-17 16:30:02 -0500321
Brian Osman88cda172020-10-09 12:05:16 -0400322 ParsedModule baseModule = {base, /*fIntrinsics=*/nullptr};
Ethan Nicholas55a63af2021-05-18 10:12:58 -0400323 std::vector<std::unique_ptr<ProgramElement>> elements;
324 std::vector<const ProgramElement*> sharedElements;
325 dsl::StartModule(this, kind, settings, baseModule);
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -0400326 dsl::SetErrorReporter(&this->errorReporter());
Ethan Nicholasb449fff2021-08-04 15:06:37 -0400327 AutoSource as(this, source->c_str());
John Stilesd1204642021-02-17 16:30:02 -0500328 IRGenerator::IRBundle ir = fIRGenerator->convertProgram(baseModule, /*isBuiltinCode=*/true,
Ethan Nicholas6823b502021-06-15 11:42:07 -0400329 *source);
Brian Osman133724c2020-10-28 14:14:39 -0400330 SkASSERT(ir.fSharedElements.empty());
Brian Osman0006ad02020-11-18 15:38:39 -0500331 LoadedModule module = { kind, std::move(ir.fSymbolTable), std::move(ir.fElements) };
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -0400332 if (this->errorCount()) {
Ethan Nicholas8da1e652019-05-24 11:01:59 -0400333 printf("Unexpected errors: %s\n", this->fErrorText.c_str());
Brian Osman3d87e9f2020-10-08 11:50:22 -0400334 SkDEBUGFAILF("%s %s\n", data.fPath, this->fErrorText.c_str());
Ethan Nicholas8da1e652019-05-24 11:01:59 -0400335 }
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -0400336 dsl::End();
Brian Osman3d87e9f2020-10-08 11:50:22 -0400337#else
Ethan Nicholas55a63af2021-05-18 10:12:58 -0400338 ProgramConfig config;
339 config.fKind = kind;
340 config.fSettings = settings;
341 AutoProgramConfig autoConfig(fContext, &config);
Brian Osman3d87e9f2020-10-08 11:50:22 -0400342 SkASSERT(data.fData && (data.fSize != 0));
John Stiles10d39d92021-05-04 16:13:14 -0400343 Rehydrator rehydrator(fContext.get(), base, data.fData, data.fSize);
Brian Osman0006ad02020-11-18 15:38:39 -0500344 LoadedModule module = { kind, rehydrator.symbolTable(), rehydrator.elements() };
Brian Osman3d87e9f2020-10-08 11:50:22 -0400345#endif
346
347 return module;
348}
349
John Stilesdbd4e6f2021-02-16 13:29:15 -0500350ParsedModule Compiler::parseModule(ProgramKind kind, ModuleData data, const ParsedModule& base) {
John Stilesa935c3f2021-02-25 10:35:49 -0500351 LoadedModule module = this->loadModule(kind, data, base.fSymbols, /*dehydrate=*/false);
Brian Osman0006ad02020-11-18 15:38:39 -0500352 this->optimize(module);
Brian Osman3d87e9f2020-10-08 11:50:22 -0400353
354 // For modules that just declare (but don't define) intrinsic functions, there will be no new
355 // program elements. In that case, we can share our parent's intrinsic map:
Brian Osman0006ad02020-11-18 15:38:39 -0500356 if (module.fElements.empty()) {
John Stiles10d39d92021-05-04 16:13:14 -0400357 return ParsedModule{module.fSymbols, base.fIntrinsics};
Brian Osman3d87e9f2020-10-08 11:50:22 -0400358 }
359
360 auto intrinsics = std::make_shared<IRIntrinsicMap>(base.fIntrinsics.get());
361
362 // Now, transfer all of the program elements to an intrinsic map. This maps certain types of
363 // global objects to the declaring ProgramElement.
Brian Osman0006ad02020-11-18 15:38:39 -0500364 for (std::unique_ptr<ProgramElement>& element : module.fElements) {
Brian Osman3d87e9f2020-10-08 11:50:22 -0400365 switch (element->kind()) {
366 case ProgramElement::Kind::kFunction: {
367 const FunctionDefinition& f = element->as<FunctionDefinition>();
Ethan Nicholas0a5d0962020-10-14 13:33:18 -0400368 SkASSERT(f.declaration().isBuiltin());
369 intrinsics->insertOrDie(f.declaration().description(), std::move(element));
Brian Osman3d87e9f2020-10-08 11:50:22 -0400370 break;
371 }
John Stiles569249b2020-11-03 12:18:22 -0500372 case ProgramElement::Kind::kFunctionPrototype: {
373 // These are already in the symbol table.
374 break;
375 }
Brian Osman3d87e9f2020-10-08 11:50:22 -0400376 case ProgramElement::Kind::kGlobalVar: {
Ethan Nicholasc51f33e2020-10-13 13:49:44 -0400377 const GlobalVarDeclaration& global = element->as<GlobalVarDeclaration>();
378 const Variable& var = global.declaration()->as<VarDeclaration>().var();
379 SkASSERT(var.isBuiltin());
Ethan Nicholasd2e09602021-06-10 11:21:59 -0400380 intrinsics->insertOrDie(String(var.name()), std::move(element));
Brian Osman3d87e9f2020-10-08 11:50:22 -0400381 break;
382 }
383 case ProgramElement::Kind::kInterfaceBlock: {
Ethan Nicholaseaf47882020-10-15 10:10:08 -0400384 const Variable& var = element->as<InterfaceBlock>().variable();
385 SkASSERT(var.isBuiltin());
Ethan Nicholasd2e09602021-06-10 11:21:59 -0400386 intrinsics->insertOrDie(String(var.name()), std::move(element));
Brian Osman3d87e9f2020-10-08 11:50:22 -0400387 break;
388 }
389 default:
390 printf("Unsupported element: %s\n", element->description().c_str());
391 SkASSERT(false);
392 break;
393 }
394 }
395
John Stiles10d39d92021-05-04 16:13:14 -0400396 return ParsedModule{module.fSymbols, std::move(intrinsics)};
Ethan Nicholas8da1e652019-05-24 11:01:59 -0400397}
398
Brian Osman32d53552020-09-23 13:55:20 -0400399std::unique_ptr<Program> Compiler::convertProgram(
John Stilesdbd4e6f2021-02-16 13:29:15 -0500400 ProgramKind kind,
Brian Osman32d53552020-09-23 13:55:20 -0400401 String text,
Ethan Nicholas55a63af2021-05-18 10:12:58 -0400402 Program::Settings settings) {
Brian Osman7a20b5c2021-03-15 16:23:33 -0400403 TRACE_EVENT0("skia.shaders", "SkSL::Compiler::convertProgram");
Leon Scrogginsb66214e2021-02-11 17:14:18 -0500404
Ethan Nicholas55a63af2021-05-18 10:12:58 -0400405 SkASSERT(!settings.fExternalFunctions || (kind == ProgramKind::kGeneric));
Ethan Nicholas91164d12019-05-15 15:29:54 -0400406
Ethan Nicholasdd2fdea2021-07-20 15:23:04 -0400407#if !SKSL_DSL_PARSER
Brian Osman0006ad02020-11-18 15:38:39 -0500408 // Loading and optimizing our base module might reset the inliner, so do that first,
409 // *then* configure the inliner with the settings for this program.
410 const ParsedModule& baseModule = this->moduleForProgramKind(kind);
Ethan Nicholasdd2fdea2021-07-20 15:23:04 -0400411#endif
Brian Osman0006ad02020-11-18 15:38:39 -0500412
John Stiles2ee4d7a2021-03-30 10:30:47 -0400413 // Honor our optimization-override flags.
414 switch (sOptimizer) {
415 case OverrideFlag::kDefault:
416 break;
417 case OverrideFlag::kOff:
Ethan Nicholas55a63af2021-05-18 10:12:58 -0400418 settings.fOptimize = false;
John Stiles2ee4d7a2021-03-30 10:30:47 -0400419 break;
420 case OverrideFlag::kOn:
Ethan Nicholas55a63af2021-05-18 10:12:58 -0400421 settings.fOptimize = true;
John Stiles2ee4d7a2021-03-30 10:30:47 -0400422 break;
423 }
424
425 switch (sInliner) {
426 case OverrideFlag::kDefault:
427 break;
428 case OverrideFlag::kOff:
Ethan Nicholas55a63af2021-05-18 10:12:58 -0400429 settings.fInlineThreshold = 0;
John Stiles2ee4d7a2021-03-30 10:30:47 -0400430 break;
431 case OverrideFlag::kOn:
Ethan Nicholas55a63af2021-05-18 10:12:58 -0400432 if (settings.fInlineThreshold == 0) {
433 settings.fInlineThreshold = kDefaultInlineThreshold;
John Stiles2ee4d7a2021-03-30 10:30:47 -0400434 }
435 break;
436 }
John Stiles7247b482021-03-08 10:40:35 -0500437
438 // Disable optimization settings that depend on a parent setting which has been disabled.
Ethan Nicholas55a63af2021-05-18 10:12:58 -0400439 settings.fInlineThreshold *= (int)settings.fOptimize;
440 settings.fRemoveDeadFunctions &= settings.fOptimize;
441 settings.fRemoveDeadVariables &= settings.fOptimize;
John Stiles7247b482021-03-08 10:40:35 -0500442
John Stilesaddccaf2021-08-02 19:03:30 -0400443 // Runtime effects always allow narrowing conversions.
444 if (ProgramConfig::IsRuntimeEffect(kind)) {
445 settings.fAllowNarrowingConversions = true;
446 }
447
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -0400448 this->resetErrors();
John Stiles10d39d92021-05-04 16:13:14 -0400449 fInliner.reset();
Brian Osman88cda172020-10-09 12:05:16 -0400450
Ethan Nicholasdd2fdea2021-07-20 15:23:04 -0400451#if SKSL_DSL_PARSER
452 settings.fDSLMangling = false;
453 return DSLParser(this, settings, kind, text).program();
454#else
John Stiles10d39d92021-05-04 16:13:14 -0400455 auto textPtr = std::make_unique<String>(std::move(text));
Ethan Nicholasb449fff2021-08-04 15:06:37 -0400456 AutoSource as(this, textPtr->c_str());
Brian Osman88cda172020-10-09 12:05:16 -0400457
Ethan Nicholas55a63af2021-05-18 10:12:58 -0400458 dsl::Start(this, kind, settings);
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -0400459 dsl::SetErrorReporter(&fErrorReporter);
John Stilesd1204642021-02-17 16:30:02 -0500460 IRGenerator::IRBundle ir = fIRGenerator->convertProgram(baseModule, /*isBuiltinCode=*/false,
Ethan Nicholas6823b502021-06-15 11:42:07 -0400461 *textPtr);
Ethan Nicholas4f3e6a22021-06-15 09:17:05 -0400462 // Ideally, we would just use dsl::ReleaseProgram and not have to do any manual mucking about
463 // with the memory pool, but we've got some impedance mismatches to solve first
Ethan Nicholas55a63af2021-05-18 10:12:58 -0400464 Pool* memoryPool = dsl::DSLWriter::MemoryPool().get();
John Stiles270cec22021-02-17 12:59:36 -0500465 auto program = std::make_unique<Program>(std::move(textPtr),
Ethan Nicholas55a63af2021-05-18 10:12:58 -0400466 std::move(dsl::DSLWriter::GetProgramConfig()),
John Stiles5c7bb322020-10-22 11:09:15 -0400467 fContext,
468 std::move(ir.fElements),
Brian Osman133724c2020-10-28 14:14:39 -0400469 std::move(ir.fSharedElements),
Ethan Nicholas55a63af2021-05-18 10:12:58 -0400470 std::move(dsl::DSLWriter::GetModifiersPool()),
John Stiles5c7bb322020-10-22 11:09:15 -0400471 std::move(ir.fSymbolTable),
Ethan Nicholas55a63af2021-05-18 10:12:58 -0400472 std::move(dsl::DSLWriter::MemoryPool()),
John Stiles5c7bb322020-10-22 11:09:15 -0400473 ir.fInputs);
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -0400474 this->errorReporter().reportPendingErrors(PositionInfo());
John Stiles5c7bb322020-10-22 11:09:15 -0400475 bool success = false;
John Stiles2ecc5952021-09-01 14:41:36 -0400476 if (!this->finalize(*program)) {
John Stiles5c7bb322020-10-22 11:09:15 -0400477 // Do not return programs that failed to compile.
John Stiles7247b482021-03-08 10:40:35 -0500478 } else if (!this->optimize(*program)) {
John Stiles5c7bb322020-10-22 11:09:15 -0400479 // Do not return programs that failed to optimize.
480 } else {
481 // We have a successful program!
482 success = true;
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500483 }
Ethan Nicholas55a63af2021-05-18 10:12:58 -0400484 dsl::End();
485 if (memoryPool) {
486 memoryPool->detachFromThread();
Brian Osman28f702c2021-02-02 11:52:07 -0500487 }
John Stiles5c7bb322020-10-22 11:09:15 -0400488 return success ? std::move(program) : nullptr;
Ethan Nicholasdd2fdea2021-07-20 15:23:04 -0400489#endif // SKSL_DSL_PARSER
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500490}
491
Brian Osman0006ad02020-11-18 15:38:39 -0500492bool Compiler::optimize(LoadedModule& module) {
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -0400493 SkASSERT(!this->errorCount());
Brian Osman0006ad02020-11-18 15:38:39 -0500494
John Stiles270cec22021-02-17 12:59:36 -0500495 // Create a temporary program configuration with default settings.
496 ProgramConfig config;
497 config.fKind = module.fKind;
John Stilesa935c3f2021-02-25 10:35:49 -0500498 AutoProgramConfig autoConfig(fContext, &config);
John Stiles270cec22021-02-17 12:59:36 -0500499
John Stilesd1204642021-02-17 16:30:02 -0500500 // Reset the Inliner.
John Stiles10d39d92021-05-04 16:13:14 -0400501 fInliner.reset();
John Stiles270cec22021-02-17 12:59:36 -0500502
503 std::unique_ptr<ProgramUsage> usage = Analysis::GetUsage(module);
Brian Osman0006ad02020-11-18 15:38:39 -0500504
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -0400505 while (this->errorCount() == 0) {
Brian Osman0006ad02020-11-18 15:38:39 -0500506 // Perform inline-candidate analysis and inline any functions deemed suitable.
John Stilesf3a28db2021-03-10 23:00:47 -0500507 if (!fInliner.analyze(module.fElements, module.fSymbols, usage.get())) {
Brian Osman0006ad02020-11-18 15:38:39 -0500508 break;
509 }
510 }
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -0400511 return this->errorCount() == 0;
Brian Osman0006ad02020-11-18 15:38:39 -0500512}
513
John Stiles0bfeae62021-03-11 09:09:42 -0500514bool Compiler::removeDeadFunctions(Program& program, ProgramUsage* usage) {
515 bool madeChanges = false;
516
517 if (program.fConfig->fSettings.fRemoveDeadFunctions) {
518 auto isDeadFunction = [&](const ProgramElement* element) {
519 if (!element->is<FunctionDefinition>()) {
520 return false;
521 }
522 const FunctionDefinition& fn = element->as<FunctionDefinition>();
John Stilese8da4d22021-03-24 09:19:45 -0400523 if (fn.declaration().isMain() || usage->get(fn.declaration()) > 0) {
John Stiles0bfeae62021-03-11 09:09:42 -0500524 return false;
525 }
526 usage->remove(*element);
527 madeChanges = true;
528 return true;
529 };
530
531 program.fElements.erase(std::remove_if(program.fElements.begin(),
532 program.fElements.end(),
533 [&](const std::unique_ptr<ProgramElement>& element) {
534 return isDeadFunction(element.get());
535 }),
536 program.fElements.end());
537 program.fSharedElements.erase(std::remove_if(program.fSharedElements.begin(),
538 program.fSharedElements.end(),
539 isDeadFunction),
540 program.fSharedElements.end());
541 }
542 return madeChanges;
543}
544
545bool Compiler::removeDeadGlobalVariables(Program& program, ProgramUsage* usage) {
546 bool madeChanges = false;
547
548 if (program.fConfig->fSettings.fRemoveDeadVariables) {
549 auto isDeadVariable = [&](const ProgramElement* element) {
550 if (!element->is<GlobalVarDeclaration>()) {
551 return false;
552 }
553 const GlobalVarDeclaration& global = element->as<GlobalVarDeclaration>();
554 const VarDeclaration& varDecl = global.declaration()->as<VarDeclaration>();
555 if (!usage->isDead(varDecl.var())) {
556 return false;
557 }
558 madeChanges = true;
559 return true;
560 };
561
562 program.fElements.erase(std::remove_if(program.fElements.begin(),
563 program.fElements.end(),
564 [&](const std::unique_ptr<ProgramElement>& element) {
565 return isDeadVariable(element.get());
566 }),
567 program.fElements.end());
568 program.fSharedElements.erase(std::remove_if(program.fSharedElements.begin(),
569 program.fSharedElements.end(),
570 isDeadVariable),
571 program.fSharedElements.end());
572 }
573 return madeChanges;
574}
575
John Stiles26541872021-03-16 12:19:54 -0400576bool Compiler::removeDeadLocalVariables(Program& program, ProgramUsage* usage) {
577 class DeadLocalVariableEliminator : public ProgramWriter {
578 public:
579 DeadLocalVariableEliminator(const Context& context, ProgramUsage* usage)
580 : fContext(context)
581 , fUsage(usage) {}
582
583 using ProgramWriter::visitProgramElement;
584
585 bool visitExpressionPtr(std::unique_ptr<Expression>& expr) override {
586 // We don't need to look inside expressions at all.
587 return false;
588 }
589
590 bool visitStatementPtr(std::unique_ptr<Statement>& stmt) override {
591 if (stmt->is<VarDeclaration>()) {
592 VarDeclaration& varDecl = stmt->as<VarDeclaration>();
593 const Variable* var = &varDecl.var();
594 ProgramUsage::VariableCounts* counts = fUsage->fVariableCounts.find(var);
595 SkASSERT(counts);
596 SkASSERT(counts->fDeclared);
597 if (CanEliminate(var, *counts)) {
598 if (var->initialValue()) {
599 // The variable has an initial-value expression, which might have side
600 // effects. ExpressionStatement::Make will preserve side effects, but
601 // replaces pure expressions with Nop.
602 fUsage->remove(stmt.get());
603 stmt = ExpressionStatement::Make(fContext, std::move(varDecl.value()));
604 fUsage->add(stmt.get());
605 } else {
606 // The variable has no initial-value and can be cleanly eliminated.
607 fUsage->remove(stmt.get());
608 stmt = std::make_unique<Nop>();
609 }
610 fMadeChanges = true;
611 }
612 return false;
613 }
614 return INHERITED::visitStatementPtr(stmt);
615 }
616
617 static bool CanEliminate(const Variable* var, const ProgramUsage::VariableCounts& counts) {
618 if (!counts.fDeclared || counts.fRead || var->storage() != VariableStorage::kLocal) {
619 return false;
620 }
621 if (var->initialValue()) {
622 SkASSERT(counts.fWrite >= 1);
623 return counts.fWrite == 1;
624 } else {
625 return counts.fWrite == 0;
626 }
627 }
628
629 bool fMadeChanges = false;
630 const Context& fContext;
631 ProgramUsage* fUsage;
632
633 using INHERITED = ProgramWriter;
634 };
635
636 DeadLocalVariableEliminator visitor{*fContext, usage};
637
638 if (program.fConfig->fSettings.fRemoveDeadVariables) {
639 for (auto& [var, counts] : usage->fVariableCounts) {
640 if (DeadLocalVariableEliminator::CanEliminate(var, counts)) {
641 // This program contains at least one dead local variable.
642 // Scan the program for any dead local variables and eliminate them all.
643 for (std::unique_ptr<ProgramElement>& pe : program.ownedElements()) {
644 if (pe->is<FunctionDefinition>()) {
645 visitor.visitProgramElement(*pe);
646 }
647 }
648 break;
649 }
650 }
651 }
652
653 return visitor.fMadeChanges;
654}
655
John Stiles25be58e2021-05-20 14:38:40 -0400656void Compiler::removeUnreachableCode(Program& program, ProgramUsage* usage) {
657 class UnreachableCodeEliminator : public ProgramWriter {
658 public:
659 UnreachableCodeEliminator(const Context& context, ProgramUsage* usage)
660 : fContext(context)
661 , fUsage(usage) {
662 fFoundFunctionExit.push(false);
663 fFoundLoopExit.push(false);
664 }
665
666 using ProgramWriter::visitProgramElement;
667
668 bool visitExpressionPtr(std::unique_ptr<Expression>& expr) override {
669 // We don't need to look inside expressions at all.
670 return false;
671 }
672
673 bool visitStatementPtr(std::unique_ptr<Statement>& stmt) override {
674 if (fFoundFunctionExit.top() || fFoundLoopExit.top()) {
675 // If we already found an exit in this section, anything beyond it is dead code.
676 if (!stmt->is<Nop>()) {
677 // Eliminate the dead statement by substituting a Nop.
678 fUsage->remove(stmt.get());
679 stmt = std::make_unique<Nop>();
680 }
681 return false;
682 }
683
684 switch (stmt->kind()) {
685 case Statement::Kind::kReturn:
686 case Statement::Kind::kDiscard:
687 // We found a function exit on this path.
688 fFoundFunctionExit.top() = true;
689 break;
690
691 case Statement::Kind::kBreak:
692 case Statement::Kind::kContinue:
693 // We found a loop exit on this path. Note that we skip over switch statements
694 // completely when eliminating code, so any `break` statement would be breaking
695 // out of a loop, not out of a switch.
696 fFoundLoopExit.top() = true;
697 break;
698
699 case Statement::Kind::kExpression:
700 case Statement::Kind::kInlineMarker:
701 case Statement::Kind::kNop:
702 case Statement::Kind::kVarDeclaration:
703 // These statements don't affect control flow.
704 break;
705
706 case Statement::Kind::kBlock:
707 // Blocks are on the straight-line path and don't affect control flow.
708 return INHERITED::visitStatementPtr(stmt);
709
710 case Statement::Kind::kDo: {
711 // Function-exits are allowed to propagate outside of a do-loop, because it
712 // always executes its body at least once.
713 fFoundLoopExit.push(false);
714 bool result = INHERITED::visitStatementPtr(stmt);
715 fFoundLoopExit.pop();
716 return result;
717 }
718 case Statement::Kind::kFor: {
719 // Function-exits are not allowed to propagate out, because a for-loop or while-
720 // loop could potentially run zero times.
721 fFoundFunctionExit.push(false);
722 fFoundLoopExit.push(false);
723 bool result = INHERITED::visitStatementPtr(stmt);
724 fFoundLoopExit.pop();
725 fFoundFunctionExit.pop();
726 return result;
727 }
728 case Statement::Kind::kIf: {
729 // This statement is conditional and encloses two inner sections of code.
730 // If both sides contain a function-exit or loop-exit, that exit is allowed to
731 // propagate out.
732 IfStatement& ifStmt = stmt->as<IfStatement>();
733
734 fFoundFunctionExit.push(false);
735 fFoundLoopExit.push(false);
736 bool result = (ifStmt.ifTrue() && this->visitStatementPtr(ifStmt.ifTrue()));
737 bool foundFunctionExitOnTrue = fFoundFunctionExit.top();
738 bool foundLoopExitOnTrue = fFoundLoopExit.top();
739 fFoundFunctionExit.pop();
740 fFoundLoopExit.pop();
741
742 fFoundFunctionExit.push(false);
743 fFoundLoopExit.push(false);
744 result |= (ifStmt.ifFalse() && this->visitStatementPtr(ifStmt.ifFalse()));
745 bool foundFunctionExitOnFalse = fFoundFunctionExit.top();
746 bool foundLoopExitOnFalse = fFoundLoopExit.top();
747 fFoundFunctionExit.pop();
748 fFoundLoopExit.pop();
749
750 fFoundFunctionExit.top() |= foundFunctionExitOnTrue && foundFunctionExitOnFalse;
751 fFoundLoopExit.top() |= foundLoopExitOnTrue && foundLoopExitOnFalse;
752 return result;
753 }
754 case Statement::Kind::kSwitch:
755 case Statement::Kind::kSwitchCase:
756 // We skip past switch statements entirely when scanning for dead code. Their
757 // control flow is quite complex and we already do a good job of flattening out
758 // switches on constant values.
759 break;
760 }
761
762 return false;
763 }
764
765 const Context& fContext;
766 ProgramUsage* fUsage;
767 std::stack<bool> fFoundFunctionExit;
768 std::stack<bool> fFoundLoopExit;
769
770 using INHERITED = ProgramWriter;
771 };
772
773 for (std::unique_ptr<ProgramElement>& pe : program.ownedElements()) {
774 if (pe->is<FunctionDefinition>()) {
775 UnreachableCodeEliminator visitor{*fContext, usage};
776 visitor.visitProgramElement(*pe);
777 }
778 }
779}
780
Ethan Nicholas00543112018-07-31 09:44:36 -0400781bool Compiler::optimize(Program& program) {
John Stiles7247b482021-03-08 10:40:35 -0500782 // The optimizer only needs to run when it is enabled.
783 if (!program.fConfig->fSettings.fOptimize) {
784 return true;
785 }
786
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -0400787 SkASSERT(!this->errorCount());
Brian Osman010ce6a2020-10-19 16:34:10 -0400788 ProgramUsage* usage = program.fUsage.get();
John Stiles7954d6c2020-09-01 10:53:02 -0400789
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -0400790 if (this->errorCount() == 0) {
John Stiles87fc6572021-04-01 14:56:34 +0000791 // Run the inliner only once; it is expensive! Multiple passes can occasionally shake out
792 // more wins, but it's diminishing returns.
793 fInliner.analyze(program.ownedElements(), program.fSymbols, usage);
Ethan Nicholas34b19c52020-09-14 11:33:47 -0400794
John Stilesb6664582021-03-19 09:46:00 -0400795 while (this->removeDeadFunctions(program, usage)) {
796 // Removing dead functions may cause more functions to become unreferenced. Try again.
Ethan Nicholas34b19c52020-09-14 11:33:47 -0400797 }
John Stilesb6664582021-03-19 09:46:00 -0400798 while (this->removeDeadLocalVariables(program, usage)) {
799 // Removing dead variables may cause more variables to become unreferenced. Try again.
800 }
John Stiles25be58e2021-05-20 14:38:40 -0400801 // Unreachable code can confuse some drivers, so it's worth removing. (skia:12012)
802 this->removeUnreachableCode(program, usage);
803
Brian Osman8c264792021-07-01 16:41:27 -0400804 this->removeDeadGlobalVariables(program, usage);
Ethan Nicholas00543112018-07-31 09:44:36 -0400805 }
John Stilesbb1505f2021-02-12 09:17:53 -0500806
John Stiles2ecc5952021-09-01 14:41:36 -0400807 return this->errorCount() == 0;
808}
809
810bool Compiler::finalize(Program& program) {
811 // Do a pass looking for @if/@switch statements that didn't optimize away, or dangling
812 // FunctionReference or TypeReference expressions. Report these as errors.
813 Analysis::VerifyStaticTestsAndExpressions(program);
814
815 // If we're in ES2 mode (runtime effects), do a pass to enforce Appendix A, Section 5 of the
816 // GLSL ES 1.00 spec -- Indexing. Don't bother if we've already found errors - this logic
817 // assumes that all loops meet the criteria of Section 4, and if they don't, could crash.
818 if (fContext->fConfig->strictES2Mode() && this->errorCount() == 0) {
819 for (const auto& pe : program.ownedElements()) {
820 Analysis::ValidateIndexingForES2(*pe, this->errorReporter());
821 }
822 }
823
824 if (fContext->fConfig->strictES2Mode()) {
825 Analysis::DetectStaticRecursion(SkMakeSpan(program.ownedElements()), this->errorReporter());
John Stilesbb1505f2021-02-12 09:17:53 -0500826 }
827
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -0400828 return this->errorCount() == 0;
Ethan Nicholas00543112018-07-31 09:44:36 -0400829}
830
Brian Osmanfb32ddf2019-06-18 10:14:20 -0400831#if defined(SKSL_STANDALONE) || SK_SUPPORT_GPU
832
Ethan Nicholas00543112018-07-31 09:44:36 -0400833bool Compiler::toSPIRV(Program& program, OutputStream& out) {
Brian Osman7a20b5c2021-03-15 16:23:33 -0400834 TRACE_EVENT0("skia.shaders", "SkSL::Compiler::toSPIRV");
Ethan Nicholasb449fff2021-08-04 15:06:37 -0400835 AutoSource as(this, program.fSource->c_str());
Brian Salomond8d85b92021-07-07 09:41:17 -0400836 ProgramSettings settings;
837 settings.fDSLUseMemoryPool = false;
838 dsl::Start(this, program.fConfig->fKind, settings);
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -0400839 dsl::SetErrorReporter(&fErrorReporter);
Brian Salomond8d85b92021-07-07 09:41:17 -0400840 dsl::DSLWriter::IRGenerator().fSymbolTable = program.fSymbols;
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -0400841#ifdef SK_ENABLE_SPIRV_VALIDATION
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400842 StringStream buffer;
Ethan Nicholas3abc6c62021-08-13 11:20:09 -0400843 SPIRVCodeGenerator cg(fContext.get(), &program, &buffer);
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -0400844 bool result = cg.generateCode();
John Stiles270cec22021-02-17 12:59:36 -0500845 if (result && program.fConfig->fSettings.fValidateSPIRV) {
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -0400846 spvtools::SpirvTools tools(SPV_ENV_VULKAN_1_0);
Ethan Nicholas762466e2017-06-29 10:03:38 -0400847 const String& data = buffer.str();
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400848 SkASSERT(0 == data.size() % 4);
Brian Osman8d09d4a2020-11-24 15:51:06 -0500849 String errors;
850 auto dumpmsg = [&errors](spv_message_level_t, const char*, const spv_position_t&,
851 const char* m) {
852 errors.appendf("SPIR-V validation error: %s\n", m);
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -0400853 };
854 tools.SetMessageConsumer(dumpmsg);
Brian Osman8d09d4a2020-11-24 15:51:06 -0500855
856 // Verify that the SPIR-V we produced is valid. At runtime, we will abort() with a message
857 // explaining the error. In standalone mode (skslc), we will send the message, plus the
858 // entire disassembled SPIR-V (for easier context & debugging) as *our* error message.
859 result = tools.Validate((const uint32_t*) data.c_str(), data.size() / 4);
860
861 if (!result) {
862#if defined(SKSL_STANDALONE)
863 // Convert the string-stream to a SPIR-V disassembly.
864 std::string disassembly;
865 if (tools.Disassemble((const uint32_t*)data.data(), data.size() / 4, &disassembly)) {
866 errors.append(disassembly);
867 }
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -0400868 this->errorReporter().error(-1, errors);
Brian Osman8d09d4a2020-11-24 15:51:06 -0500869#else
870 SkDEBUGFAILF("%s", errors.c_str());
871#endif
872 }
Ethan Nicholas762466e2017-06-29 10:03:38 -0400873 out.write(data.c_str(), data.size());
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -0400874 }
875#else
Ethan Nicholas3abc6c62021-08-13 11:20:09 -0400876 SPIRVCodeGenerator cg(fContext.get(), &program, &out);
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500877 bool result = cg.generateCode();
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -0400878#endif
Brian Salomond8d85b92021-07-07 09:41:17 -0400879 dsl::End();
Ethan Nicholasce33f102016-12-09 17:22:59 -0500880 return result;
881}
882
Ethan Nicholas00543112018-07-31 09:44:36 -0400883bool Compiler::toSPIRV(Program& program, String* out) {
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400884 StringStream buffer;
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500885 bool result = this->toSPIRV(program, buffer);
886 if (result) {
Ethan Nicholas762466e2017-06-29 10:03:38 -0400887 *out = buffer.str();
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500888 }
889 return result;
890}
891
Ethan Nicholas00543112018-07-31 09:44:36 -0400892bool Compiler::toGLSL(Program& program, OutputStream& out) {
Brian Osman7a20b5c2021-03-15 16:23:33 -0400893 TRACE_EVENT0("skia.shaders", "SkSL::Compiler::toGLSL");
Ethan Nicholasb449fff2021-08-04 15:06:37 -0400894 AutoSource as(this, program.fSource->c_str());
Ethan Nicholas3abc6c62021-08-13 11:20:09 -0400895 GLSLCodeGenerator cg(fContext.get(), &program, &out);
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500896 bool result = cg.generateCode();
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500897 return result;
898}
899
Ethan Nicholas00543112018-07-31 09:44:36 -0400900bool Compiler::toGLSL(Program& program, String* out) {
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400901 StringStream buffer;
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500902 bool result = this->toGLSL(program, buffer);
903 if (result) {
Ethan Nicholas762466e2017-06-29 10:03:38 -0400904 *out = buffer.str();
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500905 }
906 return result;
907}
908
Brian Osmanc0243912020-02-19 15:35:26 -0500909bool Compiler::toHLSL(Program& program, String* out) {
910 String spirv;
911 if (!this->toSPIRV(program, &spirv)) {
912 return false;
913 }
914
915 return SPIRVtoHLSL(spirv, out);
916}
917
Ethan Nicholas00543112018-07-31 09:44:36 -0400918bool Compiler::toMetal(Program& program, OutputStream& out) {
Brian Osman7a20b5c2021-03-15 16:23:33 -0400919 TRACE_EVENT0("skia.shaders", "SkSL::Compiler::toMetal");
Ethan Nicholasb449fff2021-08-04 15:06:37 -0400920 AutoSource as(this, program.fSource->c_str());
Ethan Nicholas3abc6c62021-08-13 11:20:09 -0400921 MetalCodeGenerator cg(fContext.get(), &program, &out);
Ethan Nicholascc305772017-10-13 16:17:45 -0400922 bool result = cg.generateCode();
Ethan Nicholascc305772017-10-13 16:17:45 -0400923 return result;
924}
925
Ethan Nicholas00543112018-07-31 09:44:36 -0400926bool Compiler::toMetal(Program& program, String* out) {
Timothy Liangb8eeb802018-07-23 16:46:16 -0400927 StringStream buffer;
928 bool result = this->toMetal(program, buffer);
929 if (result) {
930 *out = buffer.str();
931 }
932 return result;
933}
934
Ethan Nicholas2a479a52020-08-18 16:29:45 -0400935#endif // defined(SKSL_STANDALONE) || SK_SUPPORT_GPU
Brian Osman2e29ab52019-09-20 12:19:11 -0400936
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -0400937void Compiler::handleError(const char* msg, PositionInfo pos) {
Ethan Nicholasa40ddcd2021-08-06 09:17:18 -0400938 fErrorText += "error: " + (pos.line() >= 1 ? to_string(pos.line()) + ": " : "") + msg + "\n";
ethannicholasb3058bd2016-07-01 08:22:01 -0700939}
940
Ethan Nicholas95046142021-01-07 10:57:27 -0500941String Compiler::errorText(bool showCount) {
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -0400942 this->errorReporter().reportPendingErrors(PositionInfo());
Ethan Nicholas95046142021-01-07 10:57:27 -0500943 if (showCount) {
944 this->writeErrorCount();
945 }
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400946 String result = fErrorText;
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -0400947 this->resetErrors();
ethannicholasb3058bd2016-07-01 08:22:01 -0700948 return result;
949}
950
951void Compiler::writeErrorCount() {
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -0400952 int count = this->errorCount();
953 if (count) {
954 fErrorText += to_string(count) + " error";
955 if (count > 1) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700956 fErrorText += "s";
957 }
958 fErrorText += "\n";
959 }
960}
961
John Stilesa6841be2020-08-06 14:11:56 -0400962} // namespace SkSL