blob: 67f1958d4b2650974e718b2dbad11adb204bf48d [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"
Leon Scrogginsb66214e2021-02-11 17:14:18 -050014#include "src/core/SkTraceEvent.h"
John Stilesb92641c2020-08-31 18:09:01 -040015#include "src/sksl/SkSLAnalysis.h"
John Stilesf3a28db2021-03-10 23:00:47 -050016#include "src/sksl/SkSLConstantFolder.h"
Ethan Nicholasdd2fdea2021-07-20 15:23:04 -040017#include "src/sksl/SkSLDSLParser.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050018#include "src/sksl/SkSLIRGenerator.h"
Brian Osman00185012021-02-04 16:07:11 -050019#include "src/sksl/SkSLOperators.h"
John Stiles270cec22021-02-17 12:59:36 -050020#include "src/sksl/SkSLProgramSettings.h"
Ethan Nicholasc18bb512020-07-28 14:46:53 -040021#include "src/sksl/SkSLRehydrator.h"
John Stiles3738ef52021-04-13 10:41:57 -040022#include "src/sksl/codegen/SkSLGLSLCodeGenerator.h"
John Stiles3738ef52021-04-13 10:41:57 -040023#include "src/sksl/codegen/SkSLMetalCodeGenerator.h"
24#include "src/sksl/codegen/SkSLSPIRVCodeGenerator.h"
25#include "src/sksl/codegen/SkSLSPIRVtoHLSL.h"
Ethan Nicholas55a63af2021-05-18 10:12:58 -040026#include "src/sksl/dsl/priv/DSLWriter.h"
27#include "src/sksl/dsl/priv/DSL_priv.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050028#include "src/sksl/ir/SkSLExpression.h"
29#include "src/sksl/ir/SkSLExpressionStatement.h"
30#include "src/sksl/ir/SkSLFunctionCall.h"
John Stiles7591d4b2021-09-13 13:32:06 -040031#include "src/sksl/ir/SkSLLiteral.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050032#include "src/sksl/ir/SkSLModifiersDeclaration.h"
33#include "src/sksl/ir/SkSLNop.h"
34#include "src/sksl/ir/SkSLSymbolTable.h"
35#include "src/sksl/ir/SkSLTernaryExpression.h"
36#include "src/sksl/ir/SkSLUnresolvedFunction.h"
37#include "src/sksl/ir/SkSLVarDeclarations.h"
John Stilese6150002020-10-05 12:03:53 -040038#include "src/utils/SkBitSet.h"
ethannicholasb3058bd2016-07-01 08:22:01 -070039
Ethan Nicholasb33fa3f2020-08-06 13:00:19 -040040#include <fstream>
41
Ethan Nicholasa11035b2019-11-26 16:27:47 -050042#if !defined(SKSL_STANDALONE) & SK_SUPPORT_GPU
43#include "include/gpu/GrContextOptions.h"
44#include "src/gpu/GrShaderCaps.h"
45#endif
46
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -040047#ifdef SK_ENABLE_SPIRV_VALIDATION
48#include "spirv-tools/libspirv.hpp"
49#endif
50
Brian Osman3d87e9f2020-10-08 11:50:22 -040051#if defined(SKSL_STANDALONE)
Ethan Nicholasc18bb512020-07-28 14:46:53 -040052
Brian Osman3d87e9f2020-10-08 11:50:22 -040053// In standalone mode, we load the textual sksl source files. GN generates or copies these files
54// to the skslc executable directory. The "data" in this mode is just the filename.
55#define MODULE_DATA(name) MakeModulePath("sksl_" #name ".sksl")
56
57#else
58
59// At runtime, we load the dehydrated sksl data files. The data is a (pointer, size) pair.
Ethan Nicholasc18bb512020-07-28 14:46:53 -040060#include "src/sksl/generated/sksl_frag.dehydrated.sksl"
Ethan Nicholasc18bb512020-07-28 14:46:53 -040061#include "src/sksl/generated/sksl_gpu.dehydrated.sksl"
Brian Osmanb06301e2020-11-06 11:45:36 -050062#include "src/sksl/generated/sksl_public.dehydrated.sksl"
Brian Osmancbb60bd2021-04-12 09:49:20 -040063#include "src/sksl/generated/sksl_rt_shader.dehydrated.sksl"
Ethan Nicholasc18bb512020-07-28 14:46:53 -040064#include "src/sksl/generated/sksl_vert.dehydrated.sksl"
65
Brian Osman3d87e9f2020-10-08 11:50:22 -040066#define MODULE_DATA(name) MakeModuleData(SKSL_INCLUDE_sksl_##name,\
67 SKSL_INCLUDE_sksl_##name##_LENGTH)
Ethan Nicholasc18bb512020-07-28 14:46:53 -040068
69#endif
Ethan Nicholas0d997662019-04-08 09:46:01 -040070
ethannicholasb3058bd2016-07-01 08:22:01 -070071namespace SkSL {
72
John Stiles7247b482021-03-08 10:40:35 -050073// These flags allow tools like Viewer or Nanobench to override the compiler's ProgramSettings.
John Stiles2ee4d7a2021-03-30 10:30:47 -040074Compiler::OverrideFlag Compiler::sOptimizer = OverrideFlag::kDefault;
75Compiler::OverrideFlag Compiler::sInliner = OverrideFlag::kDefault;
John Stiles8ef4d6c2021-03-05 16:01:45 -050076
John Stiles47c0a742021-02-09 09:30:35 -050077using RefKind = VariableReference::RefKind;
78
Brian Osman88cda172020-10-09 12:05:16 -040079class AutoSource {
80public:
Ethan Nicholasb449fff2021-08-04 15:06:37 -040081 AutoSource(Compiler* compiler, const char* source)
John Stilesa289ac22021-05-06 07:35:35 -040082 : fCompiler(compiler) {
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -040083 SkASSERT(!fCompiler->errorReporter().source());
84 fCompiler->errorReporter().setSource(source);
Brian Osman88cda172020-10-09 12:05:16 -040085 }
86
John Stilesa289ac22021-05-06 07:35:35 -040087 ~AutoSource() {
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -040088 fCompiler->errorReporter().setSource(nullptr);
John Stilesa289ac22021-05-06 07:35:35 -040089 }
Brian Osman88cda172020-10-09 12:05:16 -040090
91 Compiler* fCompiler;
Brian Osman88cda172020-10-09 12:05:16 -040092};
93
John Stilesa935c3f2021-02-25 10:35:49 -050094class AutoProgramConfig {
95public:
96 AutoProgramConfig(std::shared_ptr<Context>& context, ProgramConfig* config)
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -040097 : fContext(context.get())
98 , fOldConfig(fContext->fConfig) {
John Stilesa935c3f2021-02-25 10:35:49 -050099 fContext->fConfig = config;
100 }
101
102 ~AutoProgramConfig() {
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -0400103 fContext->fConfig = fOldConfig;
John Stilesa935c3f2021-02-25 10:35:49 -0500104 }
105
106 Context* fContext;
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -0400107 ProgramConfig* fOldConfig;
John Stilesa935c3f2021-02-25 10:35:49 -0500108};
109
John Stiles10d39d92021-05-04 16:13:14 -0400110class AutoModifiersPool {
111public:
112 AutoModifiersPool(std::shared_ptr<Context>& context, ModifiersPool* modifiersPool)
113 : fContext(context.get()) {
114 SkASSERT(!fContext->fModifiersPool);
115 fContext->fModifiersPool = modifiersPool;
116 }
117
118 ~AutoModifiersPool() {
119 fContext->fModifiersPool = nullptr;
120 }
121
122 Context* fContext;
123};
124
John Stilesd6a5f4492021-02-11 15:46:11 -0500125Compiler::Compiler(const ShaderCapsClass* caps)
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -0400126 : fErrorReporter(this)
John Stiles2dda4b62021-09-16 13:18:10 -0400127 , fContext(std::make_shared<Context>(fErrorReporter, *caps, fMangler))
John Stilesa47b3512021-05-04 16:15:00 -0400128 , fInliner(fContext.get()) {
John Stilesc1a98b82021-02-24 13:35:02 -0500129 SkASSERT(caps);
John Stilesb624b722021-08-13 12:16:13 -0400130 fRootModule.fSymbols = this->makeRootSymbolTable();
131 fPrivateModule.fSymbols = this->makePrivateSymbolTable(fRootModule.fSymbols);
John Stilesc1a98b82021-02-24 13:35:02 -0500132 fIRGenerator = std::make_unique<IRGenerator>(fContext.get());
John Stilesb624b722021-08-13 12:16:13 -0400133}
134
135Compiler::~Compiler() {}
ethannicholasb3058bd2016-07-01 08:22:01 -0700136
John Stiles54e7c052021-01-11 14:22:36 -0500137#define TYPE(t) fContext->fTypes.f ## t .get()
ethannicholasb3058bd2016-07-01 08:22:01 -0700138
John Stilesb624b722021-08-13 12:16:13 -0400139std::shared_ptr<SymbolTable> Compiler::makeRootSymbolTable() {
Ethan Nicholasc7774a72021-08-27 15:34:05 -0400140 auto rootSymbolTable = std::make_shared<SymbolTable>(*fContext, /*builtin=*/true);
John Stilesb624b722021-08-13 12:16:13 -0400141
Brian Osmanb06301e2020-11-06 11:45:36 -0500142 const SkSL::Symbol* rootTypes[] = {
143 TYPE(Void),
Brian Salomonbf7b6202016-11-11 16:08:03 -0500144
Brian Osmanb06301e2020-11-06 11:45:36 -0500145 TYPE( Float), TYPE( Float2), TYPE( Float3), TYPE( Float4),
146 TYPE( Half), TYPE( Half2), TYPE( Half3), TYPE( Half4),
147 TYPE( Int), TYPE( Int2), TYPE( Int3), TYPE( Int4),
John Stiles823c5042021-08-17 12:09:00 -0400148 TYPE( UInt), TYPE( UInt2), TYPE( UInt3), TYPE( UInt4),
149 TYPE( Short), TYPE( Short2), TYPE( Short3), TYPE( Short4),
150 TYPE(UShort), TYPE(UShort2), TYPE(UShort3), TYPE(UShort4),
Brian Osmanb06301e2020-11-06 11:45:36 -0500151 TYPE( Bool), TYPE( Bool2), TYPE( Bool3), TYPE( Bool4),
Brian Salomon2a51de82016-11-16 12:06:01 -0500152
John Stiles823c5042021-08-17 12:09:00 -0400153 TYPE(Float2x2), TYPE(Float2x3), TYPE(Float2x4),
154 TYPE(Float3x2), TYPE(Float3x3), TYPE(Float3x4),
155 TYPE(Float4x2), TYPE(Float4x3), TYPE(Float4x4),
156
157 TYPE(Half2x2), TYPE(Half2x3), TYPE(Half2x4),
158 TYPE(Half3x2), TYPE(Half3x3), TYPE(Half3x4),
159 TYPE(Half4x2), TYPE(Half4x3), TYPE(Half4x4),
Greg Daniel64773e62016-11-22 09:44:03 -0500160
Brian Osmanc63f4312020-12-23 11:44:14 -0500161 TYPE(SquareMat), TYPE(SquareHMat),
John Stiles823c5042021-08-17 12:09:00 -0400162 TYPE(Mat), TYPE(HMat),
ethannicholasb3058bd2016-07-01 08:22:01 -0700163
John Stiles823c5042021-08-17 12:09:00 -0400164 // TODO(skia:12349): generic short/ushort
165 TYPE(GenType), TYPE(GenIType), TYPE(GenUType),
166 TYPE(GenHType), /* (GenSType) (GenUSType) */
167 TYPE(GenBType),
168
169 TYPE(Vec), TYPE(IVec), TYPE(UVec),
170 TYPE(HVec), TYPE(SVec), TYPE(USVec),
171 TYPE(BVec),
Brian Osmanb06301e2020-11-06 11:45:36 -0500172
Brian Osman14d00962021-04-02 17:04:35 -0400173 TYPE(ColorFilter),
174 TYPE(Shader),
John Stilesbb2ef922021-07-26 08:32:07 -0400175 TYPE(Blender),
Brian Osmanb06301e2020-11-06 11:45:36 -0500176 };
177
John Stilesb624b722021-08-13 12:16:13 -0400178 for (const SkSL::Symbol* type : rootTypes) {
179 rootSymbolTable->addWithoutOwnership(type);
180 }
181
182 return rootSymbolTable;
183}
184
185std::shared_ptr<SymbolTable> Compiler::makePrivateSymbolTable(std::shared_ptr<SymbolTable> parent) {
186 auto privateSymbolTable = std::make_shared<SymbolTable>(parent, /*builtin=*/true);
187
Brian Osmanb06301e2020-11-06 11:45:36 -0500188 const SkSL::Symbol* privateTypes[] = {
189 TYPE(Sampler1D), TYPE(Sampler2D), TYPE(Sampler3D),
190 TYPE(SamplerExternalOES),
Brian Osmanb06301e2020-11-06 11:45:36 -0500191 TYPE(Sampler2DRect),
Brian Osmanb06301e2020-11-06 11:45:36 -0500192
193 TYPE(ISampler2D),
Brian Osmanb06301e2020-11-06 11:45:36 -0500194 TYPE(SubpassInput), TYPE(SubpassInputMS),
195
Brian Osmanb06301e2020-11-06 11:45:36 -0500196 TYPE(Sampler),
197 TYPE(Texture2D),
198 };
199
Brian Osmanb06301e2020-11-06 11:45:36 -0500200 for (const SkSL::Symbol* type : privateTypes) {
John Stilesb624b722021-08-13 12:16:13 -0400201 privateSymbolTable->addWithoutOwnership(type);
Brian Osmanb06301e2020-11-06 11:45:36 -0500202 }
203
Brian Osman3887a012020-09-30 13:22:27 -0400204 // sk_Caps is "builtin", but all references to it are resolved to Settings, so we don't need to
205 // treat it as builtin (ie, no need to clone it into the Program).
John Stilesb624b722021-08-13 12:16:13 -0400206 privateSymbolTable->add(std::make_unique<Variable>(/*offset=*/-1,
207 fCoreModifiers.add(Modifiers{}),
208 "sk_Caps",
209 fContext->fTypes.fSkCaps.get(),
210 /*builtin=*/false,
211 Variable::Storage::kGlobal));
Ethan Nicholas3605ace2016-11-21 15:59:48 -0500212
John Stilesb624b722021-08-13 12:16:13 -0400213 return privateSymbolTable;
ethannicholasb3058bd2016-07-01 08:22:01 -0700214}
215
John Stilesb624b722021-08-13 12:16:13 -0400216#undef TYPE
ethannicholasb3058bd2016-07-01 08:22:01 -0700217
Brian Osman56269982020-11-20 12:38:07 -0500218const ParsedModule& Compiler::loadGPUModule() {
219 if (!fGPUModule.fSymbols) {
John Stilesdbd4e6f2021-02-16 13:29:15 -0500220 fGPUModule = this->parseModule(ProgramKind::kFragment, MODULE_DATA(gpu), fPrivateModule);
Brian Osman56269982020-11-20 12:38:07 -0500221 }
222 return fGPUModule;
223}
224
225const ParsedModule& Compiler::loadFragmentModule() {
226 if (!fFragmentModule.fSymbols) {
John Stilesdbd4e6f2021-02-16 13:29:15 -0500227 fFragmentModule = this->parseModule(ProgramKind::kFragment, MODULE_DATA(frag),
Brian Osman56269982020-11-20 12:38:07 -0500228 this->loadGPUModule());
229 }
230 return fFragmentModule;
231}
232
233const ParsedModule& Compiler::loadVertexModule() {
234 if (!fVertexModule.fSymbols) {
John Stilesdbd4e6f2021-02-16 13:29:15 -0500235 fVertexModule = this->parseModule(ProgramKind::kVertex, MODULE_DATA(vert),
Brian Osman56269982020-11-20 12:38:07 -0500236 this->loadGPUModule());
237 }
238 return fVertexModule;
239}
240
Brian Osmancbb60bd2021-04-12 09:49:20 -0400241static void add_glsl_type_aliases(SkSL::SymbolTable* symbols, const SkSL::BuiltinTypes& types) {
242 // Add some aliases to the runtime effect modules so that it's friendlier, and more like GLSL
243 symbols->addAlias("vec2", types.fFloat2.get());
244 symbols->addAlias("vec3", types.fFloat3.get());
245 symbols->addAlias("vec4", types.fFloat4.get());
246
247 symbols->addAlias("ivec2", types.fInt2.get());
248 symbols->addAlias("ivec3", types.fInt3.get());
249 symbols->addAlias("ivec4", types.fInt4.get());
250
251 symbols->addAlias("bvec2", types.fBool2.get());
252 symbols->addAlias("bvec3", types.fBool3.get());
253 symbols->addAlias("bvec4", types.fBool4.get());
254
255 symbols->addAlias("mat2", types.fFloat2x2.get());
256 symbols->addAlias("mat3", types.fFloat3x3.get());
257 symbols->addAlias("mat4", types.fFloat4x4.get());
258}
259
Brian Osmana8b897b2021-08-30 16:40:44 -0400260const ParsedModule& Compiler::loadPublicModule() {
261 if (!fPublicModule.fSymbols) {
262 fPublicModule = this->parseModule(ProgramKind::kGeneric, MODULE_DATA(public), fRootModule);
263 add_glsl_type_aliases(fPublicModule.fSymbols.get(), fContext->fTypes);
Brian Osmancbb60bd2021-04-12 09:49:20 -0400264 }
Brian Osmana8b897b2021-08-30 16:40:44 -0400265 return fPublicModule;
Brian Osmancbb60bd2021-04-12 09:49:20 -0400266}
267
268const ParsedModule& Compiler::loadRuntimeShaderModule() {
269 if (!fRuntimeShaderModule.fSymbols) {
270 fRuntimeShaderModule = this->parseModule(
271 ProgramKind::kRuntimeShader, MODULE_DATA(rt_shader), this->loadPublicModule());
Brian Osmancbb60bd2021-04-12 09:49:20 -0400272 }
273 return fRuntimeShaderModule;
274}
275
John Stilesdbd4e6f2021-02-16 13:29:15 -0500276const ParsedModule& Compiler::moduleForProgramKind(ProgramKind kind) {
Brian Osman88cda172020-10-09 12:05:16 -0400277 switch (kind) {
Brian Osmana8b897b2021-08-30 16:40:44 -0400278 case ProgramKind::kVertex: return this->loadVertexModule(); break;
279 case ProgramKind::kFragment: return this->loadFragmentModule(); break;
280 case ProgramKind::kRuntimeColorFilter: return this->loadPublicModule(); break;
281 case ProgramKind::kRuntimeShader: return this->loadRuntimeShaderModule(); break;
282 case ProgramKind::kRuntimeBlender: return this->loadPublicModule(); break;
283 case ProgramKind::kGeneric: return this->loadPublicModule(); break;
Brian Osman88cda172020-10-09 12:05:16 -0400284 }
285 SkUNREACHABLE;
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400286}
287
John Stilesdbd4e6f2021-02-16 13:29:15 -0500288LoadedModule Compiler::loadModule(ProgramKind kind,
Brian Osman3d87e9f2020-10-08 11:50:22 -0400289 ModuleData data,
John Stilesa935c3f2021-02-25 10:35:49 -0500290 std::shared_ptr<SymbolTable> base,
291 bool dehydrate) {
292 if (dehydrate) {
293 // NOTE: This is a workaround. When dehydrating includes, skslc doesn't know which module
294 // it's preparing, nor what the correct base module is. We can't use 'Root', because many
295 // GPU intrinsics reference private types, like samplers or textures. Today, 'Private' does
296 // contain the union of all known types, so this is safe. If we ever have types that only
297 // exist in 'Public' (for example), this logic needs to be smarter (by choosing the correct
298 // base for the module we're compiling).
John Stilesb624b722021-08-13 12:16:13 -0400299 base = fPrivateModule.fSymbols;
Brian Osman3d87e9f2020-10-08 11:50:22 -0400300 }
John Stilesa935c3f2021-02-25 10:35:49 -0500301 SkASSERT(base);
302
John Stilesa47b3512021-05-04 16:15:00 -0400303 // Put the core-module modifier pool into the context.
304 AutoModifiersPool autoPool(fContext, &fCoreModifiers);
John Stiles10d39d92021-05-04 16:13:14 -0400305
John Stilesa935c3f2021-02-25 10:35:49 -0500306 // Built-in modules always use default program settings.
Ethan Nicholas55a63af2021-05-18 10:12:58 -0400307 Program::Settings settings;
308 settings.fReplaceSettings = !dehydrate;
Brian Osman3d87e9f2020-10-08 11:50:22 -0400309
310#if defined(SKSL_STANDALONE)
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -0400311 SkASSERT(this->errorCount() == 0);
Brian Osman3d87e9f2020-10-08 11:50:22 -0400312 SkASSERT(data.fPath);
313 std::ifstream in(data.fPath);
John Stilesd51c9792021-03-18 11:40:14 -0400314 String text{std::istreambuf_iterator<char>(in), std::istreambuf_iterator<char>()};
Ethan Nicholasb33fa3f2020-08-06 13:00:19 -0400315 if (in.rdstate()) {
Brian Osman3d87e9f2020-10-08 11:50:22 -0400316 printf("error reading %s\n", data.fPath);
Ethan Nicholasb33fa3f2020-08-06 13:00:19 -0400317 abort();
318 }
John Stilesb624b722021-08-13 12:16:13 -0400319 const String* source = fRootModule.fSymbols->takeOwnershipOfString(std::move(text));
John Stilesd1204642021-02-17 16:30:02 -0500320
Brian Osman88cda172020-10-09 12:05:16 -0400321 ParsedModule baseModule = {base, /*fIntrinsics=*/nullptr};
Ethan Nicholas55a63af2021-05-18 10:12:58 -0400322 std::vector<std::unique_ptr<ProgramElement>> elements;
323 std::vector<const ProgramElement*> sharedElements;
324 dsl::StartModule(this, kind, settings, baseModule);
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -0400325 dsl::SetErrorReporter(&this->errorReporter());
Ethan Nicholasb449fff2021-08-04 15:06:37 -0400326 AutoSource as(this, source->c_str());
John Stilesd1204642021-02-17 16:30:02 -0500327 IRGenerator::IRBundle ir = fIRGenerator->convertProgram(baseModule, /*isBuiltinCode=*/true,
Ethan Nicholas6823b502021-06-15 11:42:07 -0400328 *source);
Brian Osman133724c2020-10-28 14:14:39 -0400329 SkASSERT(ir.fSharedElements.empty());
Brian Osman0006ad02020-11-18 15:38:39 -0500330 LoadedModule module = { kind, std::move(ir.fSymbolTable), std::move(ir.fElements) };
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -0400331 if (this->errorCount()) {
Ethan Nicholas8da1e652019-05-24 11:01:59 -0400332 printf("Unexpected errors: %s\n", this->fErrorText.c_str());
Brian Osman3d87e9f2020-10-08 11:50:22 -0400333 SkDEBUGFAILF("%s %s\n", data.fPath, this->fErrorText.c_str());
Ethan Nicholas8da1e652019-05-24 11:01:59 -0400334 }
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -0400335 dsl::End();
Brian Osman3d87e9f2020-10-08 11:50:22 -0400336#else
Ethan Nicholas55a63af2021-05-18 10:12:58 -0400337 ProgramConfig config;
338 config.fKind = kind;
339 config.fSettings = settings;
340 AutoProgramConfig autoConfig(fContext, &config);
Brian Osman3d87e9f2020-10-08 11:50:22 -0400341 SkASSERT(data.fData && (data.fSize != 0));
John Stiles10d39d92021-05-04 16:13:14 -0400342 Rehydrator rehydrator(fContext.get(), base, data.fData, data.fSize);
Brian Osman0006ad02020-11-18 15:38:39 -0500343 LoadedModule module = { kind, rehydrator.symbolTable(), rehydrator.elements() };
Brian Osman3d87e9f2020-10-08 11:50:22 -0400344#endif
345
346 return module;
347}
348
John Stilesdbd4e6f2021-02-16 13:29:15 -0500349ParsedModule Compiler::parseModule(ProgramKind kind, ModuleData data, const ParsedModule& base) {
John Stilesa935c3f2021-02-25 10:35:49 -0500350 LoadedModule module = this->loadModule(kind, data, base.fSymbols, /*dehydrate=*/false);
Brian Osman0006ad02020-11-18 15:38:39 -0500351 this->optimize(module);
Brian Osman3d87e9f2020-10-08 11:50:22 -0400352
353 // For modules that just declare (but don't define) intrinsic functions, there will be no new
354 // program elements. In that case, we can share our parent's intrinsic map:
Brian Osman0006ad02020-11-18 15:38:39 -0500355 if (module.fElements.empty()) {
John Stiles10d39d92021-05-04 16:13:14 -0400356 return ParsedModule{module.fSymbols, base.fIntrinsics};
Brian Osman3d87e9f2020-10-08 11:50:22 -0400357 }
358
359 auto intrinsics = std::make_shared<IRIntrinsicMap>(base.fIntrinsics.get());
360
361 // Now, transfer all of the program elements to an intrinsic map. This maps certain types of
362 // global objects to the declaring ProgramElement.
Brian Osman0006ad02020-11-18 15:38:39 -0500363 for (std::unique_ptr<ProgramElement>& element : module.fElements) {
Brian Osman3d87e9f2020-10-08 11:50:22 -0400364 switch (element->kind()) {
365 case ProgramElement::Kind::kFunction: {
366 const FunctionDefinition& f = element->as<FunctionDefinition>();
Ethan Nicholas0a5d0962020-10-14 13:33:18 -0400367 SkASSERT(f.declaration().isBuiltin());
368 intrinsics->insertOrDie(f.declaration().description(), std::move(element));
Brian Osman3d87e9f2020-10-08 11:50:22 -0400369 break;
370 }
John Stiles569249b2020-11-03 12:18:22 -0500371 case ProgramElement::Kind::kFunctionPrototype: {
372 // These are already in the symbol table.
373 break;
374 }
Brian Osman3d87e9f2020-10-08 11:50:22 -0400375 case ProgramElement::Kind::kGlobalVar: {
Ethan Nicholasc51f33e2020-10-13 13:49:44 -0400376 const GlobalVarDeclaration& global = element->as<GlobalVarDeclaration>();
377 const Variable& var = global.declaration()->as<VarDeclaration>().var();
378 SkASSERT(var.isBuiltin());
Ethan Nicholasd2e09602021-06-10 11:21:59 -0400379 intrinsics->insertOrDie(String(var.name()), std::move(element));
Brian Osman3d87e9f2020-10-08 11:50:22 -0400380 break;
381 }
382 case ProgramElement::Kind::kInterfaceBlock: {
Ethan Nicholaseaf47882020-10-15 10:10:08 -0400383 const Variable& var = element->as<InterfaceBlock>().variable();
384 SkASSERT(var.isBuiltin());
Ethan Nicholasd2e09602021-06-10 11:21:59 -0400385 intrinsics->insertOrDie(String(var.name()), std::move(element));
Brian Osman3d87e9f2020-10-08 11:50:22 -0400386 break;
387 }
388 default:
389 printf("Unsupported element: %s\n", element->description().c_str());
390 SkASSERT(false);
391 break;
392 }
393 }
394
John Stiles10d39d92021-05-04 16:13:14 -0400395 return ParsedModule{module.fSymbols, std::move(intrinsics)};
Ethan Nicholas8da1e652019-05-24 11:01:59 -0400396}
397
Brian Osman32d53552020-09-23 13:55:20 -0400398std::unique_ptr<Program> Compiler::convertProgram(
John Stilesdbd4e6f2021-02-16 13:29:15 -0500399 ProgramKind kind,
Brian Osman32d53552020-09-23 13:55:20 -0400400 String text,
Ethan Nicholas55a63af2021-05-18 10:12:58 -0400401 Program::Settings settings) {
Brian Osman7a20b5c2021-03-15 16:23:33 -0400402 TRACE_EVENT0("skia.shaders", "SkSL::Compiler::convertProgram");
Leon Scrogginsb66214e2021-02-11 17:14:18 -0500403
Ethan Nicholas55a63af2021-05-18 10:12:58 -0400404 SkASSERT(!settings.fExternalFunctions || (kind == ProgramKind::kGeneric));
Ethan Nicholas91164d12019-05-15 15:29:54 -0400405
Ethan Nicholasdd2fdea2021-07-20 15:23:04 -0400406#if !SKSL_DSL_PARSER
Brian Osman0006ad02020-11-18 15:38:39 -0500407 // Loading and optimizing our base module might reset the inliner, so do that first,
408 // *then* configure the inliner with the settings for this program.
409 const ParsedModule& baseModule = this->moduleForProgramKind(kind);
Ethan Nicholasdd2fdea2021-07-20 15:23:04 -0400410#endif
Brian Osman0006ad02020-11-18 15:38:39 -0500411
John Stiles2ee4d7a2021-03-30 10:30:47 -0400412 // Honor our optimization-override flags.
413 switch (sOptimizer) {
414 case OverrideFlag::kDefault:
415 break;
416 case OverrideFlag::kOff:
Ethan Nicholas55a63af2021-05-18 10:12:58 -0400417 settings.fOptimize = false;
John Stiles2ee4d7a2021-03-30 10:30:47 -0400418 break;
419 case OverrideFlag::kOn:
Ethan Nicholas55a63af2021-05-18 10:12:58 -0400420 settings.fOptimize = true;
John Stiles2ee4d7a2021-03-30 10:30:47 -0400421 break;
422 }
423
424 switch (sInliner) {
425 case OverrideFlag::kDefault:
426 break;
427 case OverrideFlag::kOff:
Ethan Nicholas55a63af2021-05-18 10:12:58 -0400428 settings.fInlineThreshold = 0;
John Stiles2ee4d7a2021-03-30 10:30:47 -0400429 break;
430 case OverrideFlag::kOn:
Ethan Nicholas55a63af2021-05-18 10:12:58 -0400431 if (settings.fInlineThreshold == 0) {
432 settings.fInlineThreshold = kDefaultInlineThreshold;
John Stiles2ee4d7a2021-03-30 10:30:47 -0400433 }
434 break;
435 }
John Stiles7247b482021-03-08 10:40:35 -0500436
437 // Disable optimization settings that depend on a parent setting which has been disabled.
Ethan Nicholas55a63af2021-05-18 10:12:58 -0400438 settings.fInlineThreshold *= (int)settings.fOptimize;
439 settings.fRemoveDeadFunctions &= settings.fOptimize;
440 settings.fRemoveDeadVariables &= settings.fOptimize;
John Stiles7247b482021-03-08 10:40:35 -0500441
John Stilesaddccaf2021-08-02 19:03:30 -0400442 // Runtime effects always allow narrowing conversions.
443 if (ProgramConfig::IsRuntimeEffect(kind)) {
444 settings.fAllowNarrowingConversions = true;
445 }
446
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -0400447 this->resetErrors();
John Stiles10d39d92021-05-04 16:13:14 -0400448 fInliner.reset();
Brian Osman88cda172020-10-09 12:05:16 -0400449
Ethan Nicholasdd2fdea2021-07-20 15:23:04 -0400450#if SKSL_DSL_PARSER
451 settings.fDSLMangling = false;
452 return DSLParser(this, settings, kind, text).program();
453#else
John Stiles10d39d92021-05-04 16:13:14 -0400454 auto textPtr = std::make_unique<String>(std::move(text));
Ethan Nicholasb449fff2021-08-04 15:06:37 -0400455 AutoSource as(this, textPtr->c_str());
Brian Osman88cda172020-10-09 12:05:16 -0400456
Ethan Nicholas55a63af2021-05-18 10:12:58 -0400457 dsl::Start(this, kind, settings);
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -0400458 dsl::SetErrorReporter(&fErrorReporter);
John Stilesd1204642021-02-17 16:30:02 -0500459 IRGenerator::IRBundle ir = fIRGenerator->convertProgram(baseModule, /*isBuiltinCode=*/false,
Ethan Nicholas6823b502021-06-15 11:42:07 -0400460 *textPtr);
Ethan Nicholas4f3e6a22021-06-15 09:17:05 -0400461 // Ideally, we would just use dsl::ReleaseProgram and not have to do any manual mucking about
462 // with the memory pool, but we've got some impedance mismatches to solve first
Ethan Nicholas55a63af2021-05-18 10:12:58 -0400463 Pool* memoryPool = dsl::DSLWriter::MemoryPool().get();
John Stiles270cec22021-02-17 12:59:36 -0500464 auto program = std::make_unique<Program>(std::move(textPtr),
Ethan Nicholas55a63af2021-05-18 10:12:58 -0400465 std::move(dsl::DSLWriter::GetProgramConfig()),
John Stiles5c7bb322020-10-22 11:09:15 -0400466 fContext,
467 std::move(ir.fElements),
Brian Osman133724c2020-10-28 14:14:39 -0400468 std::move(ir.fSharedElements),
Ethan Nicholas55a63af2021-05-18 10:12:58 -0400469 std::move(dsl::DSLWriter::GetModifiersPool()),
John Stiles5c7bb322020-10-22 11:09:15 -0400470 std::move(ir.fSymbolTable),
Ethan Nicholas55a63af2021-05-18 10:12:58 -0400471 std::move(dsl::DSLWriter::MemoryPool()),
John Stiles5c7bb322020-10-22 11:09:15 -0400472 ir.fInputs);
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -0400473 this->errorReporter().reportPendingErrors(PositionInfo());
John Stiles5c7bb322020-10-22 11:09:15 -0400474 bool success = false;
John Stiles2ecc5952021-09-01 14:41:36 -0400475 if (!this->finalize(*program)) {
John Stiles5c7bb322020-10-22 11:09:15 -0400476 // Do not return programs that failed to compile.
John Stiles7247b482021-03-08 10:40:35 -0500477 } else if (!this->optimize(*program)) {
John Stiles5c7bb322020-10-22 11:09:15 -0400478 // Do not return programs that failed to optimize.
479 } else {
480 // We have a successful program!
481 success = true;
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500482 }
Ethan Nicholas55a63af2021-05-18 10:12:58 -0400483 dsl::End();
484 if (memoryPool) {
485 memoryPool->detachFromThread();
Brian Osman28f702c2021-02-02 11:52:07 -0500486 }
John Stiles5c7bb322020-10-22 11:09:15 -0400487 return success ? std::move(program) : nullptr;
Ethan Nicholasdd2fdea2021-07-20 15:23:04 -0400488#endif // SKSL_DSL_PARSER
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500489}
490
Brian Osman0006ad02020-11-18 15:38:39 -0500491bool Compiler::optimize(LoadedModule& module) {
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -0400492 SkASSERT(!this->errorCount());
Brian Osman0006ad02020-11-18 15:38:39 -0500493
John Stiles270cec22021-02-17 12:59:36 -0500494 // Create a temporary program configuration with default settings.
495 ProgramConfig config;
496 config.fKind = module.fKind;
John Stilesa935c3f2021-02-25 10:35:49 -0500497 AutoProgramConfig autoConfig(fContext, &config);
John Stiles270cec22021-02-17 12:59:36 -0500498
John Stilesd1204642021-02-17 16:30:02 -0500499 // Reset the Inliner.
John Stiles10d39d92021-05-04 16:13:14 -0400500 fInliner.reset();
John Stiles270cec22021-02-17 12:59:36 -0500501
502 std::unique_ptr<ProgramUsage> usage = Analysis::GetUsage(module);
Brian Osman0006ad02020-11-18 15:38:39 -0500503
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -0400504 while (this->errorCount() == 0) {
Brian Osman0006ad02020-11-18 15:38:39 -0500505 // Perform inline-candidate analysis and inline any functions deemed suitable.
John Stiles3ff77f42021-09-06 22:17:58 -0400506 if (!this->runInliner(module.fElements, module.fSymbols, usage.get())) {
Brian Osman0006ad02020-11-18 15:38:39 -0500507 break;
508 }
509 }
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -0400510 return this->errorCount() == 0;
Brian Osman0006ad02020-11-18 15:38:39 -0500511}
512
John Stiles0bfeae62021-03-11 09:09:42 -0500513bool Compiler::removeDeadFunctions(Program& program, ProgramUsage* usage) {
514 bool madeChanges = false;
515
516 if (program.fConfig->fSettings.fRemoveDeadFunctions) {
517 auto isDeadFunction = [&](const ProgramElement* element) {
518 if (!element->is<FunctionDefinition>()) {
519 return false;
520 }
521 const FunctionDefinition& fn = element->as<FunctionDefinition>();
John Stilese8da4d22021-03-24 09:19:45 -0400522 if (fn.declaration().isMain() || usage->get(fn.declaration()) > 0) {
John Stiles0bfeae62021-03-11 09:09:42 -0500523 return false;
524 }
525 usage->remove(*element);
526 madeChanges = true;
527 return true;
528 };
529
530 program.fElements.erase(std::remove_if(program.fElements.begin(),
531 program.fElements.end(),
532 [&](const std::unique_ptr<ProgramElement>& element) {
533 return isDeadFunction(element.get());
534 }),
535 program.fElements.end());
536 program.fSharedElements.erase(std::remove_if(program.fSharedElements.begin(),
537 program.fSharedElements.end(),
538 isDeadFunction),
539 program.fSharedElements.end());
540 }
541 return madeChanges;
542}
543
544bool Compiler::removeDeadGlobalVariables(Program& program, ProgramUsage* usage) {
545 bool madeChanges = false;
546
547 if (program.fConfig->fSettings.fRemoveDeadVariables) {
548 auto isDeadVariable = [&](const ProgramElement* element) {
549 if (!element->is<GlobalVarDeclaration>()) {
550 return false;
551 }
552 const GlobalVarDeclaration& global = element->as<GlobalVarDeclaration>();
553 const VarDeclaration& varDecl = global.declaration()->as<VarDeclaration>();
554 if (!usage->isDead(varDecl.var())) {
555 return false;
556 }
557 madeChanges = true;
558 return true;
559 };
560
561 program.fElements.erase(std::remove_if(program.fElements.begin(),
562 program.fElements.end(),
563 [&](const std::unique_ptr<ProgramElement>& element) {
564 return isDeadVariable(element.get());
565 }),
566 program.fElements.end());
567 program.fSharedElements.erase(std::remove_if(program.fSharedElements.begin(),
568 program.fSharedElements.end(),
569 isDeadVariable),
570 program.fSharedElements.end());
571 }
572 return madeChanges;
573}
574
John Stiles26541872021-03-16 12:19:54 -0400575bool Compiler::removeDeadLocalVariables(Program& program, ProgramUsage* usage) {
576 class DeadLocalVariableEliminator : public ProgramWriter {
577 public:
578 DeadLocalVariableEliminator(const Context& context, ProgramUsage* usage)
579 : fContext(context)
580 , fUsage(usage) {}
581
582 using ProgramWriter::visitProgramElement;
583
584 bool visitExpressionPtr(std::unique_ptr<Expression>& expr) override {
585 // We don't need to look inside expressions at all.
586 return false;
587 }
588
589 bool visitStatementPtr(std::unique_ptr<Statement>& stmt) override {
590 if (stmt->is<VarDeclaration>()) {
591 VarDeclaration& varDecl = stmt->as<VarDeclaration>();
592 const Variable* var = &varDecl.var();
593 ProgramUsage::VariableCounts* counts = fUsage->fVariableCounts.find(var);
594 SkASSERT(counts);
595 SkASSERT(counts->fDeclared);
596 if (CanEliminate(var, *counts)) {
597 if (var->initialValue()) {
598 // The variable has an initial-value expression, which might have side
599 // effects. ExpressionStatement::Make will preserve side effects, but
600 // replaces pure expressions with Nop.
601 fUsage->remove(stmt.get());
602 stmt = ExpressionStatement::Make(fContext, std::move(varDecl.value()));
603 fUsage->add(stmt.get());
604 } else {
605 // The variable has no initial-value and can be cleanly eliminated.
606 fUsage->remove(stmt.get());
607 stmt = std::make_unique<Nop>();
608 }
609 fMadeChanges = true;
610 }
611 return false;
612 }
613 return INHERITED::visitStatementPtr(stmt);
614 }
615
616 static bool CanEliminate(const Variable* var, const ProgramUsage::VariableCounts& counts) {
617 if (!counts.fDeclared || counts.fRead || var->storage() != VariableStorage::kLocal) {
618 return false;
619 }
620 if (var->initialValue()) {
621 SkASSERT(counts.fWrite >= 1);
622 return counts.fWrite == 1;
623 } else {
624 return counts.fWrite == 0;
625 }
626 }
627
628 bool fMadeChanges = false;
629 const Context& fContext;
630 ProgramUsage* fUsage;
631
632 using INHERITED = ProgramWriter;
633 };
634
635 DeadLocalVariableEliminator visitor{*fContext, usage};
636
637 if (program.fConfig->fSettings.fRemoveDeadVariables) {
638 for (auto& [var, counts] : usage->fVariableCounts) {
639 if (DeadLocalVariableEliminator::CanEliminate(var, counts)) {
640 // This program contains at least one dead local variable.
641 // Scan the program for any dead local variables and eliminate them all.
642 for (std::unique_ptr<ProgramElement>& pe : program.ownedElements()) {
643 if (pe->is<FunctionDefinition>()) {
644 visitor.visitProgramElement(*pe);
645 }
646 }
647 break;
648 }
649 }
650 }
651
652 return visitor.fMadeChanges;
653}
654
John Stiles25be58e2021-05-20 14:38:40 -0400655void Compiler::removeUnreachableCode(Program& program, ProgramUsage* usage) {
John Stiles25be58e2021-05-20 14:38:40 -0400656 for (std::unique_ptr<ProgramElement>& pe : program.ownedElements()) {
657 if (pe->is<FunctionDefinition>()) {
John Stiles49b1a422021-09-22 09:35:39 -0400658 Analysis::EliminateUnreachableCode(pe->as<FunctionDefinition>().body(), usage);
John Stiles25be58e2021-05-20 14:38:40 -0400659 }
660 }
661}
662
Ethan Nicholas00543112018-07-31 09:44:36 -0400663bool Compiler::optimize(Program& program) {
John Stiles7247b482021-03-08 10:40:35 -0500664 // The optimizer only needs to run when it is enabled.
665 if (!program.fConfig->fSettings.fOptimize) {
666 return true;
667 }
668
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -0400669 SkASSERT(!this->errorCount());
Brian Osman010ce6a2020-10-19 16:34:10 -0400670 ProgramUsage* usage = program.fUsage.get();
John Stiles7954d6c2020-09-01 10:53:02 -0400671
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -0400672 if (this->errorCount() == 0) {
John Stiles87fc6572021-04-01 14:56:34 +0000673 // Run the inliner only once; it is expensive! Multiple passes can occasionally shake out
674 // more wins, but it's diminishing returns.
John Stiles3ff77f42021-09-06 22:17:58 -0400675 this->runInliner(program.ownedElements(), program.fSymbols, usage);
Ethan Nicholas34b19c52020-09-14 11:33:47 -0400676
John Stiles80970762021-09-18 12:42:10 -0400677 // Unreachable code can confuse some drivers, so it's worth removing. (skia:12012)
678 this->removeUnreachableCode(program, usage);
679
John Stilesb6664582021-03-19 09:46:00 -0400680 while (this->removeDeadFunctions(program, usage)) {
681 // Removing dead functions may cause more functions to become unreferenced. Try again.
Ethan Nicholas34b19c52020-09-14 11:33:47 -0400682 }
John Stilesb6664582021-03-19 09:46:00 -0400683 while (this->removeDeadLocalVariables(program, usage)) {
684 // Removing dead variables may cause more variables to become unreferenced. Try again.
685 }
John Stiles25be58e2021-05-20 14:38:40 -0400686
Brian Osman8c264792021-07-01 16:41:27 -0400687 this->removeDeadGlobalVariables(program, usage);
Ethan Nicholas00543112018-07-31 09:44:36 -0400688 }
John Stilesbb1505f2021-02-12 09:17:53 -0500689
John Stiles2ecc5952021-09-01 14:41:36 -0400690 return this->errorCount() == 0;
691}
692
John Stiles3ff77f42021-09-06 22:17:58 -0400693bool Compiler::runInliner(const std::vector<std::unique_ptr<ProgramElement>>& elements,
694 std::shared_ptr<SymbolTable> symbols,
695 ProgramUsage* usage) {
696 // The program's SymbolTable was taken out of the IRGenerator when the program was bundled, but
697 // the inliner relies (indirectly) on having a valid SymbolTable in the IRGenerator.
698 // In particular, inlining can turn a non-optimizable expression like `normalize(myVec)` into
699 // `normalize(vec2(7))`, which is now optimizable. The optimizer can use DSL to simplify this
700 // expression--e.g., in the case of normalize, using DSL's Length(). The DSL relies on
701 // irGenerator.convertIdentifier() to look up `length`. convertIdentifier() needs a valid symbol
702 // table to find the declaration of `length`. To allow this chain of events to succeed, we
703 // re-insert the program's symbol table back into the IRGenerator temporarily.
704 SkASSERT(!fIRGenerator->fSymbolTable);
705 fIRGenerator->fSymbolTable = symbols;
706
707 bool result = fInliner.analyze(elements, symbols, usage);
708
709 fIRGenerator->fSymbolTable = nullptr;
710 return result;
711}
712
John Stiles2ecc5952021-09-01 14:41:36 -0400713bool Compiler::finalize(Program& program) {
714 // Do a pass looking for @if/@switch statements that didn't optimize away, or dangling
715 // FunctionReference or TypeReference expressions. Report these as errors.
716 Analysis::VerifyStaticTestsAndExpressions(program);
717
John Stiles9d82e612021-09-03 08:39:54 -0400718 // Verify that the program conforms to ES2 limitations.
John Stiles2ecc5952021-09-01 14:41:36 -0400719 if (fContext->fConfig->strictES2Mode() && this->errorCount() == 0) {
John Stiles9d82e612021-09-03 08:39:54 -0400720 // Enforce Appendix A, Section 5 of the GLSL ES 1.00 spec -- Indexing. This logic assumes
721 // that all loops meet the criteria of Section 4, and if they don't, could crash.
John Stiles2ecc5952021-09-01 14:41:36 -0400722 for (const auto& pe : program.ownedElements()) {
723 Analysis::ValidateIndexingForES2(*pe, this->errorReporter());
724 }
John Stiles9d82e612021-09-03 08:39:54 -0400725 // Verify that the program size is reasonable after unrolling and inlining. This also
726 // issues errors for static recursion and overly-deep function-call chains.
John Stiles61e5e202021-09-02 09:56:31 -0400727 Analysis::CheckProgramUnrolledSize(program);
John Stilesbb1505f2021-02-12 09:17:53 -0500728 }
729
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -0400730 return this->errorCount() == 0;
Ethan Nicholas00543112018-07-31 09:44:36 -0400731}
732
Brian Osmanfb32ddf2019-06-18 10:14:20 -0400733#if defined(SKSL_STANDALONE) || SK_SUPPORT_GPU
734
Ethan Nicholas00543112018-07-31 09:44:36 -0400735bool Compiler::toSPIRV(Program& program, OutputStream& out) {
Brian Osman7a20b5c2021-03-15 16:23:33 -0400736 TRACE_EVENT0("skia.shaders", "SkSL::Compiler::toSPIRV");
Ethan Nicholasb449fff2021-08-04 15:06:37 -0400737 AutoSource as(this, program.fSource->c_str());
Brian Salomond8d85b92021-07-07 09:41:17 -0400738 ProgramSettings settings;
739 settings.fDSLUseMemoryPool = false;
740 dsl::Start(this, program.fConfig->fKind, settings);
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -0400741 dsl::SetErrorReporter(&fErrorReporter);
Brian Salomond8d85b92021-07-07 09:41:17 -0400742 dsl::DSLWriter::IRGenerator().fSymbolTable = program.fSymbols;
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -0400743#ifdef SK_ENABLE_SPIRV_VALIDATION
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400744 StringStream buffer;
Ethan Nicholas3abc6c62021-08-13 11:20:09 -0400745 SPIRVCodeGenerator cg(fContext.get(), &program, &buffer);
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -0400746 bool result = cg.generateCode();
John Stiles270cec22021-02-17 12:59:36 -0500747 if (result && program.fConfig->fSettings.fValidateSPIRV) {
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -0400748 spvtools::SpirvTools tools(SPV_ENV_VULKAN_1_0);
Ethan Nicholas762466e2017-06-29 10:03:38 -0400749 const String& data = buffer.str();
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400750 SkASSERT(0 == data.size() % 4);
Brian Osman8d09d4a2020-11-24 15:51:06 -0500751 String errors;
752 auto dumpmsg = [&errors](spv_message_level_t, const char*, const spv_position_t&,
753 const char* m) {
754 errors.appendf("SPIR-V validation error: %s\n", m);
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -0400755 };
756 tools.SetMessageConsumer(dumpmsg);
Brian Osman8d09d4a2020-11-24 15:51:06 -0500757
758 // Verify that the SPIR-V we produced is valid. At runtime, we will abort() with a message
759 // explaining the error. In standalone mode (skslc), we will send the message, plus the
760 // entire disassembled SPIR-V (for easier context & debugging) as *our* error message.
761 result = tools.Validate((const uint32_t*) data.c_str(), data.size() / 4);
762
763 if (!result) {
764#if defined(SKSL_STANDALONE)
765 // Convert the string-stream to a SPIR-V disassembly.
766 std::string disassembly;
767 if (tools.Disassemble((const uint32_t*)data.data(), data.size() / 4, &disassembly)) {
768 errors.append(disassembly);
769 }
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -0400770 this->errorReporter().error(-1, errors);
Ethan Nicholasc973d262021-09-17 16:10:29 -0400771 this->errorReporter().reportPendingErrors(PositionInfo());
Brian Osman8d09d4a2020-11-24 15:51:06 -0500772#else
773 SkDEBUGFAILF("%s", errors.c_str());
774#endif
775 }
Ethan Nicholas762466e2017-06-29 10:03:38 -0400776 out.write(data.c_str(), data.size());
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -0400777 }
778#else
Ethan Nicholas3abc6c62021-08-13 11:20:09 -0400779 SPIRVCodeGenerator cg(fContext.get(), &program, &out);
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500780 bool result = cg.generateCode();
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -0400781#endif
Brian Salomond8d85b92021-07-07 09:41:17 -0400782 dsl::End();
Ethan Nicholasce33f102016-12-09 17:22:59 -0500783 return result;
784}
785
Ethan Nicholas00543112018-07-31 09:44:36 -0400786bool Compiler::toSPIRV(Program& program, String* out) {
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400787 StringStream buffer;
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500788 bool result = this->toSPIRV(program, buffer);
789 if (result) {
Ethan Nicholas762466e2017-06-29 10:03:38 -0400790 *out = buffer.str();
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500791 }
792 return result;
793}
794
Ethan Nicholas00543112018-07-31 09:44:36 -0400795bool Compiler::toGLSL(Program& program, OutputStream& out) {
Brian Osman7a20b5c2021-03-15 16:23:33 -0400796 TRACE_EVENT0("skia.shaders", "SkSL::Compiler::toGLSL");
Ethan Nicholasb449fff2021-08-04 15:06:37 -0400797 AutoSource as(this, program.fSource->c_str());
Ethan Nicholas3abc6c62021-08-13 11:20:09 -0400798 GLSLCodeGenerator cg(fContext.get(), &program, &out);
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500799 bool result = cg.generateCode();
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500800 return result;
801}
802
Ethan Nicholas00543112018-07-31 09:44:36 -0400803bool Compiler::toGLSL(Program& program, String* out) {
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400804 StringStream buffer;
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500805 bool result = this->toGLSL(program, buffer);
806 if (result) {
Ethan Nicholas762466e2017-06-29 10:03:38 -0400807 *out = buffer.str();
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500808 }
809 return result;
810}
811
Brian Osmanc0243912020-02-19 15:35:26 -0500812bool Compiler::toHLSL(Program& program, String* out) {
813 String spirv;
814 if (!this->toSPIRV(program, &spirv)) {
815 return false;
816 }
817
818 return SPIRVtoHLSL(spirv, out);
819}
820
Ethan Nicholas00543112018-07-31 09:44:36 -0400821bool Compiler::toMetal(Program& program, OutputStream& out) {
Brian Osman7a20b5c2021-03-15 16:23:33 -0400822 TRACE_EVENT0("skia.shaders", "SkSL::Compiler::toMetal");
Ethan Nicholasb449fff2021-08-04 15:06:37 -0400823 AutoSource as(this, program.fSource->c_str());
Ethan Nicholas3abc6c62021-08-13 11:20:09 -0400824 MetalCodeGenerator cg(fContext.get(), &program, &out);
Ethan Nicholascc305772017-10-13 16:17:45 -0400825 bool result = cg.generateCode();
Ethan Nicholascc305772017-10-13 16:17:45 -0400826 return result;
827}
828
Ethan Nicholas00543112018-07-31 09:44:36 -0400829bool Compiler::toMetal(Program& program, String* out) {
Timothy Liangb8eeb802018-07-23 16:46:16 -0400830 StringStream buffer;
831 bool result = this->toMetal(program, buffer);
832 if (result) {
833 *out = buffer.str();
834 }
835 return result;
836}
837
Ethan Nicholas2a479a52020-08-18 16:29:45 -0400838#endif // defined(SKSL_STANDALONE) || SK_SUPPORT_GPU
Brian Osman2e29ab52019-09-20 12:19:11 -0400839
Ethan Nicholas32724122021-09-07 13:49:07 -0400840void Compiler::handleError(skstd::string_view msg, PositionInfo pos) {
Ethan Nicholasa40ddcd2021-08-06 09:17:18 -0400841 fErrorText += "error: " + (pos.line() >= 1 ? to_string(pos.line()) + ": " : "") + msg + "\n";
ethannicholasb3058bd2016-07-01 08:22:01 -0700842}
843
Ethan Nicholas95046142021-01-07 10:57:27 -0500844String Compiler::errorText(bool showCount) {
845 if (showCount) {
846 this->writeErrorCount();
847 }
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400848 String result = fErrorText;
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -0400849 this->resetErrors();
ethannicholasb3058bd2016-07-01 08:22:01 -0700850 return result;
851}
852
853void Compiler::writeErrorCount() {
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -0400854 int count = this->errorCount();
855 if (count) {
856 fErrorText += to_string(count) + " error";
857 if (count > 1) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700858 fErrorText += "s";
859 }
860 fErrorText += "\n";
861 }
862}
863
John Stilesa6841be2020-08-06 14:11:56 -0400864} // namespace SkSL