blob: 4ccbbc671c1ebad8594fdd9a3d416800b83d8b7a [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).
Ethan Nicholas89cfde12021-09-27 11:20:34 -0400206 privateSymbolTable->add(std::make_unique<Variable>(/*line=*/-1,
John Stilesb624b722021-08-13 12:16:13 -0400207 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 }
Brian Osman88cda172020-10-09 12:05:16 -0400319 ParsedModule baseModule = {base, /*fIntrinsics=*/nullptr};
Ethan Nicholas051aeb72021-09-24 16:39:19 -0400320 LoadedModule result = DSLParser(this, settings, kind,
321 std::move(text)).moduleInheritingFrom(std::move(baseModule));
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -0400322 if (this->errorCount()) {
Ethan Nicholas8da1e652019-05-24 11:01:59 -0400323 printf("Unexpected errors: %s\n", this->fErrorText.c_str());
Brian Osman3d87e9f2020-10-08 11:50:22 -0400324 SkDEBUGFAILF("%s %s\n", data.fPath, this->fErrorText.c_str());
Ethan Nicholas8da1e652019-05-24 11:01:59 -0400325 }
Brian Osman3d87e9f2020-10-08 11:50:22 -0400326#else
Ethan Nicholas55a63af2021-05-18 10:12:58 -0400327 ProgramConfig config;
328 config.fKind = kind;
329 config.fSettings = settings;
330 AutoProgramConfig autoConfig(fContext, &config);
Brian Osman3d87e9f2020-10-08 11:50:22 -0400331 SkASSERT(data.fData && (data.fSize != 0));
John Stiles10d39d92021-05-04 16:13:14 -0400332 Rehydrator rehydrator(fContext.get(), base, data.fData, data.fSize);
Ethan Nicholas051aeb72021-09-24 16:39:19 -0400333 LoadedModule result = { kind, rehydrator.symbolTable(), rehydrator.elements() };
Brian Osman3d87e9f2020-10-08 11:50:22 -0400334#endif
335
Ethan Nicholas051aeb72021-09-24 16:39:19 -0400336 return result;
Brian Osman3d87e9f2020-10-08 11:50:22 -0400337}
338
John Stilesdbd4e6f2021-02-16 13:29:15 -0500339ParsedModule Compiler::parseModule(ProgramKind kind, ModuleData data, const ParsedModule& base) {
John Stilesa935c3f2021-02-25 10:35:49 -0500340 LoadedModule module = this->loadModule(kind, data, base.fSymbols, /*dehydrate=*/false);
Brian Osman0006ad02020-11-18 15:38:39 -0500341 this->optimize(module);
Brian Osman3d87e9f2020-10-08 11:50:22 -0400342
343 // For modules that just declare (but don't define) intrinsic functions, there will be no new
344 // program elements. In that case, we can share our parent's intrinsic map:
Brian Osman0006ad02020-11-18 15:38:39 -0500345 if (module.fElements.empty()) {
John Stiles10d39d92021-05-04 16:13:14 -0400346 return ParsedModule{module.fSymbols, base.fIntrinsics};
Brian Osman3d87e9f2020-10-08 11:50:22 -0400347 }
348
349 auto intrinsics = std::make_shared<IRIntrinsicMap>(base.fIntrinsics.get());
350
351 // Now, transfer all of the program elements to an intrinsic map. This maps certain types of
352 // global objects to the declaring ProgramElement.
Brian Osman0006ad02020-11-18 15:38:39 -0500353 for (std::unique_ptr<ProgramElement>& element : module.fElements) {
Brian Osman3d87e9f2020-10-08 11:50:22 -0400354 switch (element->kind()) {
355 case ProgramElement::Kind::kFunction: {
356 const FunctionDefinition& f = element->as<FunctionDefinition>();
Ethan Nicholas0a5d0962020-10-14 13:33:18 -0400357 SkASSERT(f.declaration().isBuiltin());
358 intrinsics->insertOrDie(f.declaration().description(), std::move(element));
Brian Osman3d87e9f2020-10-08 11:50:22 -0400359 break;
360 }
John Stiles569249b2020-11-03 12:18:22 -0500361 case ProgramElement::Kind::kFunctionPrototype: {
362 // These are already in the symbol table.
363 break;
364 }
Brian Osman3d87e9f2020-10-08 11:50:22 -0400365 case ProgramElement::Kind::kGlobalVar: {
Ethan Nicholasc51f33e2020-10-13 13:49:44 -0400366 const GlobalVarDeclaration& global = element->as<GlobalVarDeclaration>();
367 const Variable& var = global.declaration()->as<VarDeclaration>().var();
368 SkASSERT(var.isBuiltin());
Ethan Nicholasd2e09602021-06-10 11:21:59 -0400369 intrinsics->insertOrDie(String(var.name()), std::move(element));
Brian Osman3d87e9f2020-10-08 11:50:22 -0400370 break;
371 }
372 case ProgramElement::Kind::kInterfaceBlock: {
Ethan Nicholaseaf47882020-10-15 10:10:08 -0400373 const Variable& var = element->as<InterfaceBlock>().variable();
374 SkASSERT(var.isBuiltin());
Ethan Nicholasd2e09602021-06-10 11:21:59 -0400375 intrinsics->insertOrDie(String(var.name()), std::move(element));
Brian Osman3d87e9f2020-10-08 11:50:22 -0400376 break;
377 }
378 default:
379 printf("Unsupported element: %s\n", element->description().c_str());
380 SkASSERT(false);
381 break;
382 }
383 }
384
John Stiles10d39d92021-05-04 16:13:14 -0400385 return ParsedModule{module.fSymbols, std::move(intrinsics)};
Ethan Nicholas8da1e652019-05-24 11:01:59 -0400386}
387
Brian Osman32d53552020-09-23 13:55:20 -0400388std::unique_ptr<Program> Compiler::convertProgram(
John Stilesdbd4e6f2021-02-16 13:29:15 -0500389 ProgramKind kind,
Brian Osman32d53552020-09-23 13:55:20 -0400390 String text,
Ethan Nicholas55a63af2021-05-18 10:12:58 -0400391 Program::Settings settings) {
Brian Osman7a20b5c2021-03-15 16:23:33 -0400392 TRACE_EVENT0("skia.shaders", "SkSL::Compiler::convertProgram");
Leon Scrogginsb66214e2021-02-11 17:14:18 -0500393
Ethan Nicholas55a63af2021-05-18 10:12:58 -0400394 SkASSERT(!settings.fExternalFunctions || (kind == ProgramKind::kGeneric));
Ethan Nicholas91164d12019-05-15 15:29:54 -0400395
John Stiles2ee4d7a2021-03-30 10:30:47 -0400396 // Honor our optimization-override flags.
397 switch (sOptimizer) {
398 case OverrideFlag::kDefault:
399 break;
400 case OverrideFlag::kOff:
Ethan Nicholas55a63af2021-05-18 10:12:58 -0400401 settings.fOptimize = false;
John Stiles2ee4d7a2021-03-30 10:30:47 -0400402 break;
403 case OverrideFlag::kOn:
Ethan Nicholas55a63af2021-05-18 10:12:58 -0400404 settings.fOptimize = true;
John Stiles2ee4d7a2021-03-30 10:30:47 -0400405 break;
406 }
407
408 switch (sInliner) {
409 case OverrideFlag::kDefault:
410 break;
411 case OverrideFlag::kOff:
Ethan Nicholas55a63af2021-05-18 10:12:58 -0400412 settings.fInlineThreshold = 0;
John Stiles2ee4d7a2021-03-30 10:30:47 -0400413 break;
414 case OverrideFlag::kOn:
Ethan Nicholas55a63af2021-05-18 10:12:58 -0400415 if (settings.fInlineThreshold == 0) {
416 settings.fInlineThreshold = kDefaultInlineThreshold;
John Stiles2ee4d7a2021-03-30 10:30:47 -0400417 }
418 break;
419 }
John Stiles7247b482021-03-08 10:40:35 -0500420
421 // Disable optimization settings that depend on a parent setting which has been disabled.
Ethan Nicholas55a63af2021-05-18 10:12:58 -0400422 settings.fInlineThreshold *= (int)settings.fOptimize;
423 settings.fRemoveDeadFunctions &= settings.fOptimize;
424 settings.fRemoveDeadVariables &= settings.fOptimize;
John Stiles7247b482021-03-08 10:40:35 -0500425
John Stilesaddccaf2021-08-02 19:03:30 -0400426 // Runtime effects always allow narrowing conversions.
427 if (ProgramConfig::IsRuntimeEffect(kind)) {
428 settings.fAllowNarrowingConversions = true;
429 }
430
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -0400431 this->resetErrors();
John Stiles10d39d92021-05-04 16:13:14 -0400432 fInliner.reset();
Brian Osman88cda172020-10-09 12:05:16 -0400433
Ethan Nicholasdd2fdea2021-07-20 15:23:04 -0400434 settings.fDSLMangling = false;
Ethan Nicholas051aeb72021-09-24 16:39:19 -0400435 return DSLParser(this, settings, kind, std::move(text)).program();
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500436}
437
Brian Osman0006ad02020-11-18 15:38:39 -0500438bool Compiler::optimize(LoadedModule& module) {
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -0400439 SkASSERT(!this->errorCount());
Brian Osman0006ad02020-11-18 15:38:39 -0500440
John Stiles270cec22021-02-17 12:59:36 -0500441 // Create a temporary program configuration with default settings.
442 ProgramConfig config;
443 config.fKind = module.fKind;
John Stilesa935c3f2021-02-25 10:35:49 -0500444 AutoProgramConfig autoConfig(fContext, &config);
John Stiles270cec22021-02-17 12:59:36 -0500445
John Stilesd1204642021-02-17 16:30:02 -0500446 // Reset the Inliner.
John Stiles10d39d92021-05-04 16:13:14 -0400447 fInliner.reset();
John Stiles270cec22021-02-17 12:59:36 -0500448
449 std::unique_ptr<ProgramUsage> usage = Analysis::GetUsage(module);
Brian Osman0006ad02020-11-18 15:38:39 -0500450
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -0400451 while (this->errorCount() == 0) {
Brian Osman0006ad02020-11-18 15:38:39 -0500452 // Perform inline-candidate analysis and inline any functions deemed suitable.
John Stiles3ff77f42021-09-06 22:17:58 -0400453 if (!this->runInliner(module.fElements, module.fSymbols, usage.get())) {
Brian Osman0006ad02020-11-18 15:38:39 -0500454 break;
455 }
456 }
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -0400457 return this->errorCount() == 0;
Brian Osman0006ad02020-11-18 15:38:39 -0500458}
459
John Stiles0bfeae62021-03-11 09:09:42 -0500460bool Compiler::removeDeadFunctions(Program& program, ProgramUsage* usage) {
461 bool madeChanges = false;
462
463 if (program.fConfig->fSettings.fRemoveDeadFunctions) {
464 auto isDeadFunction = [&](const ProgramElement* element) {
465 if (!element->is<FunctionDefinition>()) {
466 return false;
467 }
468 const FunctionDefinition& fn = element->as<FunctionDefinition>();
John Stilese8da4d22021-03-24 09:19:45 -0400469 if (fn.declaration().isMain() || usage->get(fn.declaration()) > 0) {
John Stiles0bfeae62021-03-11 09:09:42 -0500470 return false;
471 }
472 usage->remove(*element);
473 madeChanges = true;
474 return true;
475 };
476
477 program.fElements.erase(std::remove_if(program.fElements.begin(),
478 program.fElements.end(),
479 [&](const std::unique_ptr<ProgramElement>& element) {
480 return isDeadFunction(element.get());
481 }),
482 program.fElements.end());
483 program.fSharedElements.erase(std::remove_if(program.fSharedElements.begin(),
484 program.fSharedElements.end(),
485 isDeadFunction),
486 program.fSharedElements.end());
487 }
488 return madeChanges;
489}
490
491bool Compiler::removeDeadGlobalVariables(Program& program, ProgramUsage* usage) {
492 bool madeChanges = false;
493
494 if (program.fConfig->fSettings.fRemoveDeadVariables) {
495 auto isDeadVariable = [&](const ProgramElement* element) {
496 if (!element->is<GlobalVarDeclaration>()) {
497 return false;
498 }
499 const GlobalVarDeclaration& global = element->as<GlobalVarDeclaration>();
500 const VarDeclaration& varDecl = global.declaration()->as<VarDeclaration>();
501 if (!usage->isDead(varDecl.var())) {
502 return false;
503 }
504 madeChanges = true;
505 return true;
506 };
507
508 program.fElements.erase(std::remove_if(program.fElements.begin(),
509 program.fElements.end(),
510 [&](const std::unique_ptr<ProgramElement>& element) {
511 return isDeadVariable(element.get());
512 }),
513 program.fElements.end());
514 program.fSharedElements.erase(std::remove_if(program.fSharedElements.begin(),
515 program.fSharedElements.end(),
516 isDeadVariable),
517 program.fSharedElements.end());
518 }
519 return madeChanges;
520}
521
John Stiles26541872021-03-16 12:19:54 -0400522bool Compiler::removeDeadLocalVariables(Program& program, ProgramUsage* usage) {
523 class DeadLocalVariableEliminator : public ProgramWriter {
524 public:
525 DeadLocalVariableEliminator(const Context& context, ProgramUsage* usage)
526 : fContext(context)
527 , fUsage(usage) {}
528
529 using ProgramWriter::visitProgramElement;
530
531 bool visitExpressionPtr(std::unique_ptr<Expression>& expr) override {
532 // We don't need to look inside expressions at all.
533 return false;
534 }
535
536 bool visitStatementPtr(std::unique_ptr<Statement>& stmt) override {
537 if (stmt->is<VarDeclaration>()) {
538 VarDeclaration& varDecl = stmt->as<VarDeclaration>();
539 const Variable* var = &varDecl.var();
540 ProgramUsage::VariableCounts* counts = fUsage->fVariableCounts.find(var);
541 SkASSERT(counts);
542 SkASSERT(counts->fDeclared);
543 if (CanEliminate(var, *counts)) {
544 if (var->initialValue()) {
545 // The variable has an initial-value expression, which might have side
546 // effects. ExpressionStatement::Make will preserve side effects, but
547 // replaces pure expressions with Nop.
548 fUsage->remove(stmt.get());
549 stmt = ExpressionStatement::Make(fContext, std::move(varDecl.value()));
550 fUsage->add(stmt.get());
551 } else {
552 // The variable has no initial-value and can be cleanly eliminated.
553 fUsage->remove(stmt.get());
554 stmt = std::make_unique<Nop>();
555 }
556 fMadeChanges = true;
557 }
558 return false;
559 }
560 return INHERITED::visitStatementPtr(stmt);
561 }
562
563 static bool CanEliminate(const Variable* var, const ProgramUsage::VariableCounts& counts) {
564 if (!counts.fDeclared || counts.fRead || var->storage() != VariableStorage::kLocal) {
565 return false;
566 }
567 if (var->initialValue()) {
568 SkASSERT(counts.fWrite >= 1);
569 return counts.fWrite == 1;
570 } else {
571 return counts.fWrite == 0;
572 }
573 }
574
575 bool fMadeChanges = false;
576 const Context& fContext;
577 ProgramUsage* fUsage;
578
579 using INHERITED = ProgramWriter;
580 };
581
582 DeadLocalVariableEliminator visitor{*fContext, usage};
583
584 if (program.fConfig->fSettings.fRemoveDeadVariables) {
585 for (auto& [var, counts] : usage->fVariableCounts) {
586 if (DeadLocalVariableEliminator::CanEliminate(var, counts)) {
587 // This program contains at least one dead local variable.
588 // Scan the program for any dead local variables and eliminate them all.
589 for (std::unique_ptr<ProgramElement>& pe : program.ownedElements()) {
590 if (pe->is<FunctionDefinition>()) {
591 visitor.visitProgramElement(*pe);
592 }
593 }
594 break;
595 }
596 }
597 }
598
599 return visitor.fMadeChanges;
600}
601
John Stiles25be58e2021-05-20 14:38:40 -0400602void Compiler::removeUnreachableCode(Program& program, ProgramUsage* usage) {
John Stiles25be58e2021-05-20 14:38:40 -0400603 for (std::unique_ptr<ProgramElement>& pe : program.ownedElements()) {
604 if (pe->is<FunctionDefinition>()) {
John Stiles49b1a422021-09-22 09:35:39 -0400605 Analysis::EliminateUnreachableCode(pe->as<FunctionDefinition>().body(), usage);
John Stiles25be58e2021-05-20 14:38:40 -0400606 }
607 }
608}
609
Ethan Nicholas00543112018-07-31 09:44:36 -0400610bool Compiler::optimize(Program& program) {
John Stiles7247b482021-03-08 10:40:35 -0500611 // The optimizer only needs to run when it is enabled.
612 if (!program.fConfig->fSettings.fOptimize) {
613 return true;
614 }
615
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -0400616 SkASSERT(!this->errorCount());
Brian Osman010ce6a2020-10-19 16:34:10 -0400617 ProgramUsage* usage = program.fUsage.get();
John Stiles7954d6c2020-09-01 10:53:02 -0400618
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -0400619 if (this->errorCount() == 0) {
John Stiles87fc6572021-04-01 14:56:34 +0000620 // Run the inliner only once; it is expensive! Multiple passes can occasionally shake out
621 // more wins, but it's diminishing returns.
John Stiles3ff77f42021-09-06 22:17:58 -0400622 this->runInliner(program.ownedElements(), program.fSymbols, usage);
Ethan Nicholas34b19c52020-09-14 11:33:47 -0400623
John Stiles80970762021-09-18 12:42:10 -0400624 // Unreachable code can confuse some drivers, so it's worth removing. (skia:12012)
625 this->removeUnreachableCode(program, usage);
626
John Stilesb6664582021-03-19 09:46:00 -0400627 while (this->removeDeadFunctions(program, usage)) {
628 // Removing dead functions may cause more functions to become unreferenced. Try again.
Ethan Nicholas34b19c52020-09-14 11:33:47 -0400629 }
John Stilesb6664582021-03-19 09:46:00 -0400630 while (this->removeDeadLocalVariables(program, usage)) {
631 // Removing dead variables may cause more variables to become unreferenced. Try again.
632 }
John Stiles25be58e2021-05-20 14:38:40 -0400633
Brian Osman8c264792021-07-01 16:41:27 -0400634 this->removeDeadGlobalVariables(program, usage);
Ethan Nicholas00543112018-07-31 09:44:36 -0400635 }
John Stilesbb1505f2021-02-12 09:17:53 -0500636
John Stiles2ecc5952021-09-01 14:41:36 -0400637 return this->errorCount() == 0;
638}
639
John Stiles3ff77f42021-09-06 22:17:58 -0400640bool Compiler::runInliner(const std::vector<std::unique_ptr<ProgramElement>>& elements,
641 std::shared_ptr<SymbolTable> symbols,
642 ProgramUsage* usage) {
643 // The program's SymbolTable was taken out of the IRGenerator when the program was bundled, but
644 // the inliner relies (indirectly) on having a valid SymbolTable in the IRGenerator.
645 // In particular, inlining can turn a non-optimizable expression like `normalize(myVec)` into
646 // `normalize(vec2(7))`, which is now optimizable. The optimizer can use DSL to simplify this
647 // expression--e.g., in the case of normalize, using DSL's Length(). The DSL relies on
648 // irGenerator.convertIdentifier() to look up `length`. convertIdentifier() needs a valid symbol
649 // table to find the declaration of `length`. To allow this chain of events to succeed, we
650 // re-insert the program's symbol table back into the IRGenerator temporarily.
651 SkASSERT(!fIRGenerator->fSymbolTable);
652 fIRGenerator->fSymbolTable = symbols;
653
654 bool result = fInliner.analyze(elements, symbols, usage);
655
656 fIRGenerator->fSymbolTable = nullptr;
657 return result;
658}
659
John Stiles2ecc5952021-09-01 14:41:36 -0400660bool Compiler::finalize(Program& program) {
661 // Do a pass looking for @if/@switch statements that didn't optimize away, or dangling
662 // FunctionReference or TypeReference expressions. Report these as errors.
663 Analysis::VerifyStaticTestsAndExpressions(program);
664
John Stiles9d82e612021-09-03 08:39:54 -0400665 // Verify that the program conforms to ES2 limitations.
John Stiles2ecc5952021-09-01 14:41:36 -0400666 if (fContext->fConfig->strictES2Mode() && this->errorCount() == 0) {
John Stiles9d82e612021-09-03 08:39:54 -0400667 // Enforce Appendix A, Section 5 of the GLSL ES 1.00 spec -- Indexing. This logic assumes
668 // that all loops meet the criteria of Section 4, and if they don't, could crash.
John Stiles2ecc5952021-09-01 14:41:36 -0400669 for (const auto& pe : program.ownedElements()) {
670 Analysis::ValidateIndexingForES2(*pe, this->errorReporter());
671 }
John Stiles9d82e612021-09-03 08:39:54 -0400672 // Verify that the program size is reasonable after unrolling and inlining. This also
673 // issues errors for static recursion and overly-deep function-call chains.
John Stiles61e5e202021-09-02 09:56:31 -0400674 Analysis::CheckProgramUnrolledSize(program);
John Stilesbb1505f2021-02-12 09:17:53 -0500675 }
676
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -0400677 return this->errorCount() == 0;
Ethan Nicholas00543112018-07-31 09:44:36 -0400678}
679
Brian Osmanfb32ddf2019-06-18 10:14:20 -0400680#if defined(SKSL_STANDALONE) || SK_SUPPORT_GPU
681
Ethan Nicholas00543112018-07-31 09:44:36 -0400682bool Compiler::toSPIRV(Program& program, OutputStream& out) {
Brian Osman7a20b5c2021-03-15 16:23:33 -0400683 TRACE_EVENT0("skia.shaders", "SkSL::Compiler::toSPIRV");
Ethan Nicholasb449fff2021-08-04 15:06:37 -0400684 AutoSource as(this, program.fSource->c_str());
Brian Salomond8d85b92021-07-07 09:41:17 -0400685 ProgramSettings settings;
686 settings.fDSLUseMemoryPool = false;
687 dsl::Start(this, program.fConfig->fKind, settings);
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -0400688 dsl::SetErrorReporter(&fErrorReporter);
Brian Salomond8d85b92021-07-07 09:41:17 -0400689 dsl::DSLWriter::IRGenerator().fSymbolTable = program.fSymbols;
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -0400690#ifdef SK_ENABLE_SPIRV_VALIDATION
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400691 StringStream buffer;
Ethan Nicholas3abc6c62021-08-13 11:20:09 -0400692 SPIRVCodeGenerator cg(fContext.get(), &program, &buffer);
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -0400693 bool result = cg.generateCode();
John Stiles270cec22021-02-17 12:59:36 -0500694 if (result && program.fConfig->fSettings.fValidateSPIRV) {
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -0400695 spvtools::SpirvTools tools(SPV_ENV_VULKAN_1_0);
Ethan Nicholas762466e2017-06-29 10:03:38 -0400696 const String& data = buffer.str();
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400697 SkASSERT(0 == data.size() % 4);
Brian Osman8d09d4a2020-11-24 15:51:06 -0500698 String errors;
699 auto dumpmsg = [&errors](spv_message_level_t, const char*, const spv_position_t&,
700 const char* m) {
701 errors.appendf("SPIR-V validation error: %s\n", m);
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -0400702 };
703 tools.SetMessageConsumer(dumpmsg);
Brian Osman8d09d4a2020-11-24 15:51:06 -0500704
705 // Verify that the SPIR-V we produced is valid. At runtime, we will abort() with a message
706 // explaining the error. In standalone mode (skslc), we will send the message, plus the
707 // entire disassembled SPIR-V (for easier context & debugging) as *our* error message.
708 result = tools.Validate((const uint32_t*) data.c_str(), data.size() / 4);
709
710 if (!result) {
711#if defined(SKSL_STANDALONE)
712 // Convert the string-stream to a SPIR-V disassembly.
713 std::string disassembly;
714 if (tools.Disassemble((const uint32_t*)data.data(), data.size() / 4, &disassembly)) {
715 errors.append(disassembly);
716 }
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -0400717 this->errorReporter().error(-1, errors);
Ethan Nicholasc973d262021-09-17 16:10:29 -0400718 this->errorReporter().reportPendingErrors(PositionInfo());
Brian Osman8d09d4a2020-11-24 15:51:06 -0500719#else
720 SkDEBUGFAILF("%s", errors.c_str());
721#endif
722 }
Ethan Nicholas762466e2017-06-29 10:03:38 -0400723 out.write(data.c_str(), data.size());
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -0400724 }
725#else
Ethan Nicholas3abc6c62021-08-13 11:20:09 -0400726 SPIRVCodeGenerator cg(fContext.get(), &program, &out);
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500727 bool result = cg.generateCode();
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -0400728#endif
Brian Salomond8d85b92021-07-07 09:41:17 -0400729 dsl::End();
Ethan Nicholasce33f102016-12-09 17:22:59 -0500730 return result;
731}
732
Ethan Nicholas00543112018-07-31 09:44:36 -0400733bool Compiler::toSPIRV(Program& program, String* out) {
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400734 StringStream buffer;
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500735 bool result = this->toSPIRV(program, buffer);
736 if (result) {
Ethan Nicholas762466e2017-06-29 10:03:38 -0400737 *out = buffer.str();
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500738 }
739 return result;
740}
741
Ethan Nicholas00543112018-07-31 09:44:36 -0400742bool Compiler::toGLSL(Program& program, OutputStream& out) {
Brian Osman7a20b5c2021-03-15 16:23:33 -0400743 TRACE_EVENT0("skia.shaders", "SkSL::Compiler::toGLSL");
Ethan Nicholasb449fff2021-08-04 15:06:37 -0400744 AutoSource as(this, program.fSource->c_str());
Ethan Nicholas3abc6c62021-08-13 11:20:09 -0400745 GLSLCodeGenerator cg(fContext.get(), &program, &out);
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500746 bool result = cg.generateCode();
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500747 return result;
748}
749
Ethan Nicholas00543112018-07-31 09:44:36 -0400750bool Compiler::toGLSL(Program& program, String* out) {
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400751 StringStream buffer;
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500752 bool result = this->toGLSL(program, buffer);
753 if (result) {
Ethan Nicholas762466e2017-06-29 10:03:38 -0400754 *out = buffer.str();
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500755 }
756 return result;
757}
758
Brian Osmanc0243912020-02-19 15:35:26 -0500759bool Compiler::toHLSL(Program& program, String* out) {
760 String spirv;
761 if (!this->toSPIRV(program, &spirv)) {
762 return false;
763 }
764
765 return SPIRVtoHLSL(spirv, out);
766}
767
Ethan Nicholas00543112018-07-31 09:44:36 -0400768bool Compiler::toMetal(Program& program, OutputStream& out) {
Brian Osman7a20b5c2021-03-15 16:23:33 -0400769 TRACE_EVENT0("skia.shaders", "SkSL::Compiler::toMetal");
Ethan Nicholasb449fff2021-08-04 15:06:37 -0400770 AutoSource as(this, program.fSource->c_str());
Ethan Nicholas3abc6c62021-08-13 11:20:09 -0400771 MetalCodeGenerator cg(fContext.get(), &program, &out);
Ethan Nicholascc305772017-10-13 16:17:45 -0400772 bool result = cg.generateCode();
Ethan Nicholascc305772017-10-13 16:17:45 -0400773 return result;
774}
775
Ethan Nicholas00543112018-07-31 09:44:36 -0400776bool Compiler::toMetal(Program& program, String* out) {
Timothy Liangb8eeb802018-07-23 16:46:16 -0400777 StringStream buffer;
778 bool result = this->toMetal(program, buffer);
779 if (result) {
780 *out = buffer.str();
781 }
782 return result;
783}
784
Ethan Nicholas2a479a52020-08-18 16:29:45 -0400785#endif // defined(SKSL_STANDALONE) || SK_SUPPORT_GPU
Brian Osman2e29ab52019-09-20 12:19:11 -0400786
Ethan Nicholas32724122021-09-07 13:49:07 -0400787void Compiler::handleError(skstd::string_view msg, PositionInfo pos) {
Ethan Nicholasa40ddcd2021-08-06 09:17:18 -0400788 fErrorText += "error: " + (pos.line() >= 1 ? to_string(pos.line()) + ": " : "") + msg + "\n";
ethannicholasb3058bd2016-07-01 08:22:01 -0700789}
790
Ethan Nicholas95046142021-01-07 10:57:27 -0500791String Compiler::errorText(bool showCount) {
792 if (showCount) {
793 this->writeErrorCount();
794 }
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400795 String result = fErrorText;
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -0400796 this->resetErrors();
ethannicholasb3058bd2016-07-01 08:22:01 -0700797 return result;
798}
799
800void Compiler::writeErrorCount() {
Ethan Nicholas4a5e22a2021-08-13 17:29:51 -0400801 int count = this->errorCount();
802 if (count) {
803 fErrorText += to_string(count) + " error";
804 if (count > 1) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700805 fErrorText += "s";
806 }
807 fErrorText += "\n";
808 }
809}
810
John Stilesa6841be2020-08-06 14:11:56 -0400811} // namespace SkSL