blob: f031ad82ae3101218c195c18d5ad7667a71bf3e4 [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
John Stiles270cec22021-02-17 12:59:36 -050013#include "src/core/SkScopeExit.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"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050017#include "src/sksl/SkSLIRGenerator.h"
Brian Osman00185012021-02-04 16:07:11 -050018#include "src/sksl/SkSLOperators.h"
John Stiles270cec22021-02-17 12:59:36 -050019#include "src/sksl/SkSLProgramSettings.h"
Ethan Nicholasc18bb512020-07-28 14:46:53 -040020#include "src/sksl/SkSLRehydrator.h"
John Stiles3738ef52021-04-13 10:41:57 -040021#include "src/sksl/codegen/SkSLCPPCodeGenerator.h"
John Stiles82ab3402021-04-13 17:13:03 -040022#include "src/sksl/codegen/SkSLDSLCPPCodeGenerator.h"
John Stiles3738ef52021-04-13 10:41:57 -040023#include "src/sksl/codegen/SkSLGLSLCodeGenerator.h"
24#include "src/sksl/codegen/SkSLHCodeGenerator.h"
25#include "src/sksl/codegen/SkSLMetalCodeGenerator.h"
26#include "src/sksl/codegen/SkSLSPIRVCodeGenerator.h"
27#include "src/sksl/codegen/SkSLSPIRVtoHLSL.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050028#include "src/sksl/ir/SkSLEnum.h"
29#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_fp.dehydrated.sksl"
62#include "src/sksl/generated/sksl_frag.dehydrated.sksl"
63#include "src/sksl/generated/sksl_geom.dehydrated.sksl"
64#include "src/sksl/generated/sksl_gpu.dehydrated.sksl"
Brian Osmanb06301e2020-11-06 11:45:36 -050065#include "src/sksl/generated/sksl_public.dehydrated.sksl"
Brian Osmancbb60bd2021-04-12 09:49:20 -040066#include "src/sksl/generated/sksl_rt_colorfilter.dehydrated.sksl"
67#include "src/sksl/generated/sksl_rt_shader.dehydrated.sksl"
Ethan Nicholasc18bb512020-07-28 14:46:53 -040068#include "src/sksl/generated/sksl_vert.dehydrated.sksl"
69
Brian Osman3d87e9f2020-10-08 11:50:22 -040070#define MODULE_DATA(name) MakeModuleData(SKSL_INCLUDE_sksl_##name,\
71 SKSL_INCLUDE_sksl_##name##_LENGTH)
Ethan Nicholasc18bb512020-07-28 14:46:53 -040072
73#endif
Ethan Nicholas0d997662019-04-08 09:46:01 -040074
ethannicholasb3058bd2016-07-01 08:22:01 -070075namespace SkSL {
76
John Stiles7247b482021-03-08 10:40:35 -050077// These flags allow tools like Viewer or Nanobench to override the compiler's ProgramSettings.
John Stiles2ee4d7a2021-03-30 10:30:47 -040078Compiler::OverrideFlag Compiler::sOptimizer = OverrideFlag::kDefault;
79Compiler::OverrideFlag Compiler::sInliner = OverrideFlag::kDefault;
John Stiles8ef4d6c2021-03-05 16:01:45 -050080
John Stiles47c0a742021-02-09 09:30:35 -050081using RefKind = VariableReference::RefKind;
82
Brian Osman88cda172020-10-09 12:05:16 -040083class AutoSource {
84public:
85 AutoSource(Compiler* compiler, const String* source)
John Stilesa289ac22021-05-06 07:35:35 -040086 : fCompiler(compiler) {
87 SkASSERT(!fCompiler->fSource);
Brian Osman88cda172020-10-09 12:05:16 -040088 fCompiler->fSource = source;
89 }
90
John Stilesa289ac22021-05-06 07:35:35 -040091 ~AutoSource() {
92 fCompiler->fSource = nullptr;
93 }
Brian Osman88cda172020-10-09 12:05:16 -040094
95 Compiler* fCompiler;
Brian Osman88cda172020-10-09 12:05:16 -040096};
97
John Stilesa935c3f2021-02-25 10:35:49 -050098class AutoProgramConfig {
99public:
100 AutoProgramConfig(std::shared_ptr<Context>& context, ProgramConfig* config)
101 : fContext(context.get()) {
102 SkASSERT(!fContext->fConfig);
103 fContext->fConfig = config;
104 }
105
106 ~AutoProgramConfig() {
107 fContext->fConfig = nullptr;
108 }
109
110 Context* fContext;
111};
112
John Stiles10d39d92021-05-04 16:13:14 -0400113class AutoModifiersPool {
114public:
115 AutoModifiersPool(std::shared_ptr<Context>& context, ModifiersPool* modifiersPool)
116 : fContext(context.get()) {
117 SkASSERT(!fContext->fModifiersPool);
118 fContext->fModifiersPool = modifiersPool;
119 }
120
121 ~AutoModifiersPool() {
122 fContext->fModifiersPool = nullptr;
123 }
124
125 Context* fContext;
126};
127
John Stilesd6a5f4492021-02-11 15:46:11 -0500128Compiler::Compiler(const ShaderCapsClass* caps)
John Stilesc1a98b82021-02-24 13:35:02 -0500129 : fContext(std::make_shared<Context>(/*errors=*/*this, *caps))
John Stilesa47b3512021-05-04 16:15:00 -0400130 , fInliner(fContext.get()) {
John Stilesc1a98b82021-02-24 13:35:02 -0500131 SkASSERT(caps);
John Stiles7c3515b2020-10-16 18:38:39 -0400132 fRootSymbolTable = std::make_shared<SymbolTable>(this, /*builtin=*/true);
Brian Osmanb06301e2020-11-06 11:45:36 -0500133 fPrivateSymbolTable = std::make_shared<SymbolTable>(fRootSymbolTable, /*builtin=*/true);
John Stilesc1a98b82021-02-24 13:35:02 -0500134 fIRGenerator = std::make_unique<IRGenerator>(fContext.get());
ethannicholasb3058bd2016-07-01 08:22:01 -0700135
John Stiles54e7c052021-01-11 14:22:36 -0500136#define TYPE(t) fContext->fTypes.f ## t .get()
ethannicholasb3058bd2016-07-01 08:22:01 -0700137
Brian Osmanb06301e2020-11-06 11:45:36 -0500138 const SkSL::Symbol* rootTypes[] = {
139 TYPE(Void),
Brian Salomonbf7b6202016-11-11 16:08:03 -0500140
Brian Osmanb06301e2020-11-06 11:45:36 -0500141 TYPE( Float), TYPE( Float2), TYPE( Float3), TYPE( Float4),
142 TYPE( Half), TYPE( Half2), TYPE( Half3), TYPE( Half4),
143 TYPE( Int), TYPE( Int2), TYPE( Int3), TYPE( Int4),
Brian Osmanb06301e2020-11-06 11:45:36 -0500144 TYPE( Bool), TYPE( Bool2), TYPE( Bool3), TYPE( Bool4),
Brian Salomon2a51de82016-11-16 12:06:01 -0500145
Brian Osmanc0f2b642020-12-22 13:35:55 -0500146 TYPE(Float2x2), TYPE(Float3x3), TYPE(Float4x4),
Brian Osmanc63f4312020-12-23 11:44:14 -0500147 TYPE( Half2x2), TYPE( Half3x3), TYPE(Half4x4),
Greg Daniel64773e62016-11-22 09:44:03 -0500148
Brian Osmanc63f4312020-12-23 11:44:14 -0500149 TYPE(SquareMat), TYPE(SquareHMat),
ethannicholasb3058bd2016-07-01 08:22:01 -0700150
Brian Osman20fad322020-12-23 12:42:33 -0500151 TYPE(GenType), TYPE(GenHType), TYPE(GenIType), TYPE(GenBType),
152 TYPE(Vec), TYPE(HVec), TYPE(IVec), TYPE(BVec),
Brian Osmanb06301e2020-11-06 11:45:36 -0500153
Brian Osman14d00962021-04-02 17:04:35 -0400154 TYPE(ColorFilter),
155 TYPE(Shader),
Brian Osmanb06301e2020-11-06 11:45:36 -0500156 };
157
158 const SkSL::Symbol* privateTypes[] = {
Brian Osman20fad322020-12-23 12:42:33 -0500159 TYPE( UInt), TYPE( UInt2), TYPE( UInt3), TYPE( UInt4),
160 TYPE( Short), TYPE( Short2), TYPE( Short3), TYPE( Short4),
161 TYPE(UShort), TYPE(UShort2), TYPE(UShort3), TYPE(UShort4),
Brian Osman20fad322020-12-23 12:42:33 -0500162
163 TYPE(GenUType), TYPE(UVec),
Ethan Nicholas722c83e2021-05-04 11:39:30 -0400164 TYPE(SVec), TYPE(USVec),
Brian Osman20fad322020-12-23 12:42:33 -0500165
Brian Osmanc0f2b642020-12-22 13:35:55 -0500166 TYPE(Float2x3), TYPE(Float2x4),
167 TYPE(Float3x2), TYPE(Float3x4),
168 TYPE(Float4x2), TYPE(Float4x3),
169
Brian Osmanc63f4312020-12-23 11:44:14 -0500170 TYPE(Half2x3), TYPE(Half2x4),
171 TYPE(Half3x2), TYPE(Half3x4),
172 TYPE(Half4x2), TYPE(Half4x3),
173
Brian Osmanc0f2b642020-12-22 13:35:55 -0500174 TYPE(Mat), TYPE(HMat),
175
Brian Osmanb06301e2020-11-06 11:45:36 -0500176 TYPE(Sampler1D), TYPE(Sampler2D), TYPE(Sampler3D),
177 TYPE(SamplerExternalOES),
Brian Osmanb06301e2020-11-06 11:45:36 -0500178 TYPE(Sampler2DRect),
Brian Osmanb06301e2020-11-06 11:45:36 -0500179
180 TYPE(ISampler2D),
Brian Osmanb06301e2020-11-06 11:45:36 -0500181 TYPE(SubpassInput), TYPE(SubpassInputMS),
182
Brian Osmanb06301e2020-11-06 11:45:36 -0500183 TYPE(Sampler),
184 TYPE(Texture2D),
Brian Osman14d00962021-04-02 17:04:35 -0400185
186 TYPE(FragmentProcessor),
Brian Osmanb06301e2020-11-06 11:45:36 -0500187 };
188
189 for (const SkSL::Symbol* type : rootTypes) {
190 fRootSymbolTable->addWithoutOwnership(type);
191 }
192 for (const SkSL::Symbol* type : privateTypes) {
193 fPrivateSymbolTable->addWithoutOwnership(type);
194 }
195
196#undef TYPE
ethannicholasb3058bd2016-07-01 08:22:01 -0700197
Brian Osman3887a012020-09-30 13:22:27 -0400198 // sk_Caps is "builtin", but all references to it are resolved to Settings, so we don't need to
199 // treat it as builtin (ie, no need to clone it into the Program).
John Stiles10d39d92021-05-04 16:13:14 -0400200 fPrivateSymbolTable->add(std::make_unique<Variable>(/*offset=*/-1,
John Stilesa47b3512021-05-04 16:15:00 -0400201 fCoreModifiers.add(Modifiers{}),
John Stiles10d39d92021-05-04 16:13:14 -0400202 "sk_Caps",
203 fContext->fTypes.fSkCaps.get(),
204 /*builtin=*/false,
205 Variable::Storage::kGlobal));
Ethan Nicholas3605ace2016-11-21 15:59:48 -0500206
Brian Osman3d87e9f2020-10-08 11:50:22 -0400207 fRootModule = {fRootSymbolTable, /*fIntrinsics=*/nullptr};
Brian Osmanb06301e2020-11-06 11:45:36 -0500208 fPrivateModule = {fPrivateSymbolTable, /*fIntrinsics=*/nullptr};
ethannicholasb3058bd2016-07-01 08:22:01 -0700209}
210
John Stilesdd13dba2020-10-29 10:45:34 -0400211Compiler::~Compiler() {}
ethannicholasb3058bd2016-07-01 08:22:01 -0700212
Brian Osman56269982020-11-20 12:38:07 -0500213const ParsedModule& Compiler::loadGPUModule() {
214 if (!fGPUModule.fSymbols) {
John Stilesdbd4e6f2021-02-16 13:29:15 -0500215 fGPUModule = this->parseModule(ProgramKind::kFragment, MODULE_DATA(gpu), fPrivateModule);
Brian Osman56269982020-11-20 12:38:07 -0500216 }
217 return fGPUModule;
218}
219
220const ParsedModule& Compiler::loadFragmentModule() {
221 if (!fFragmentModule.fSymbols) {
John Stilesdbd4e6f2021-02-16 13:29:15 -0500222 fFragmentModule = this->parseModule(ProgramKind::kFragment, MODULE_DATA(frag),
Brian Osman56269982020-11-20 12:38:07 -0500223 this->loadGPUModule());
224 }
225 return fFragmentModule;
226}
227
228const ParsedModule& Compiler::loadVertexModule() {
229 if (!fVertexModule.fSymbols) {
John Stilesdbd4e6f2021-02-16 13:29:15 -0500230 fVertexModule = this->parseModule(ProgramKind::kVertex, MODULE_DATA(vert),
Brian Osman56269982020-11-20 12:38:07 -0500231 this->loadGPUModule());
232 }
233 return fVertexModule;
234}
235
Brian Osman88cda172020-10-09 12:05:16 -0400236const ParsedModule& Compiler::loadGeometryModule() {
Brian Osman3d87e9f2020-10-08 11:50:22 -0400237 if (!fGeometryModule.fSymbols) {
John Stilesdbd4e6f2021-02-16 13:29:15 -0500238 fGeometryModule = this->parseModule(ProgramKind::kGeometry, MODULE_DATA(geom),
Brian Osman56269982020-11-20 12:38:07 -0500239 this->loadGPUModule());
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400240 }
Brian Osman88cda172020-10-09 12:05:16 -0400241 return fGeometryModule;
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400242}
243
Brian Osman88cda172020-10-09 12:05:16 -0400244const ParsedModule& Compiler::loadFPModule() {
Brian Osman3d87e9f2020-10-08 11:50:22 -0400245 if (!fFPModule.fSymbols) {
John Stilesdbd4e6f2021-02-16 13:29:15 -0500246 fFPModule = this->parseModule(ProgramKind::kFragmentProcessor, MODULE_DATA(fp),
Brian Osman56269982020-11-20 12:38:07 -0500247 this->loadGPUModule());
Brian Osman8e2ef022020-09-30 13:26:43 -0400248 }
Brian Osman88cda172020-10-09 12:05:16 -0400249 return fFPModule;
Brian Osman8e2ef022020-09-30 13:26:43 -0400250}
251
Brian Osmanb06301e2020-11-06 11:45:36 -0500252const ParsedModule& Compiler::loadPublicModule() {
253 if (!fPublicModule.fSymbols) {
John Stilesdbd4e6f2021-02-16 13:29:15 -0500254 fPublicModule = this->parseModule(ProgramKind::kGeneric, MODULE_DATA(public), fRootModule);
Brian Osmanb06301e2020-11-06 11:45:36 -0500255 }
256 return fPublicModule;
257}
258
Brian Osmancbb60bd2021-04-12 09:49:20 -0400259static void add_glsl_type_aliases(SkSL::SymbolTable* symbols, const SkSL::BuiltinTypes& types) {
260 // Add some aliases to the runtime effect modules so that it's friendlier, and more like GLSL
261 symbols->addAlias("vec2", types.fFloat2.get());
262 symbols->addAlias("vec3", types.fFloat3.get());
263 symbols->addAlias("vec4", types.fFloat4.get());
264
265 symbols->addAlias("ivec2", types.fInt2.get());
266 symbols->addAlias("ivec3", types.fInt3.get());
267 symbols->addAlias("ivec4", types.fInt4.get());
268
269 symbols->addAlias("bvec2", types.fBool2.get());
270 symbols->addAlias("bvec3", types.fBool3.get());
271 symbols->addAlias("bvec4", types.fBool4.get());
272
273 symbols->addAlias("mat2", types.fFloat2x2.get());
274 symbols->addAlias("mat3", types.fFloat3x3.get());
275 symbols->addAlias("mat4", types.fFloat4x4.get());
276}
277
Brian Osmancbb60bd2021-04-12 09:49:20 -0400278const ParsedModule& Compiler::loadRuntimeColorFilterModule() {
279 if (!fRuntimeColorFilterModule.fSymbols) {
280 fRuntimeColorFilterModule = this->parseModule(ProgramKind::kRuntimeColorFilter,
281 MODULE_DATA(rt_colorfilter),
282 this->loadPublicModule());
283 add_glsl_type_aliases(fRuntimeColorFilterModule.fSymbols.get(), fContext->fTypes);
284 }
285 return fRuntimeColorFilterModule;
286}
287
288const ParsedModule& Compiler::loadRuntimeShaderModule() {
289 if (!fRuntimeShaderModule.fSymbols) {
290 fRuntimeShaderModule = this->parseModule(
291 ProgramKind::kRuntimeShader, MODULE_DATA(rt_shader), this->loadPublicModule());
292 add_glsl_type_aliases(fRuntimeShaderModule.fSymbols.get(), fContext->fTypes);
293 }
294 return fRuntimeShaderModule;
295}
296
John Stilesdbd4e6f2021-02-16 13:29:15 -0500297const ParsedModule& Compiler::moduleForProgramKind(ProgramKind kind) {
Brian Osman88cda172020-10-09 12:05:16 -0400298 switch (kind) {
Brian Osmancbb60bd2021-04-12 09:49:20 -0400299 case ProgramKind::kVertex: return this->loadVertexModule(); break;
300 case ProgramKind::kFragment: return this->loadFragmentModule(); break;
301 case ProgramKind::kGeometry: return this->loadGeometryModule(); break;
302 case ProgramKind::kFragmentProcessor: return this->loadFPModule(); break;
Brian Osmancbb60bd2021-04-12 09:49:20 -0400303 case ProgramKind::kRuntimeColorFilter: return this->loadRuntimeColorFilterModule(); break;
304 case ProgramKind::kRuntimeShader: return this->loadRuntimeShaderModule(); break;
305 case ProgramKind::kGeneric: return this->loadPublicModule(); break;
Brian Osman88cda172020-10-09 12:05:16 -0400306 }
307 SkUNREACHABLE;
Ethan Nicholasc18bb512020-07-28 14:46:53 -0400308}
309
John Stilesdbd4e6f2021-02-16 13:29:15 -0500310LoadedModule Compiler::loadModule(ProgramKind kind,
Brian Osman3d87e9f2020-10-08 11:50:22 -0400311 ModuleData data,
John Stilesa935c3f2021-02-25 10:35:49 -0500312 std::shared_ptr<SymbolTable> base,
313 bool dehydrate) {
314 if (dehydrate) {
315 // NOTE: This is a workaround. When dehydrating includes, skslc doesn't know which module
316 // it's preparing, nor what the correct base module is. We can't use 'Root', because many
317 // GPU intrinsics reference private types, like samplers or textures. Today, 'Private' does
318 // contain the union of all known types, so this is safe. If we ever have types that only
319 // exist in 'Public' (for example), this logic needs to be smarter (by choosing the correct
320 // base for the module we're compiling).
Brian Osmanb06301e2020-11-06 11:45:36 -0500321 base = fPrivateSymbolTable;
Brian Osman3d87e9f2020-10-08 11:50:22 -0400322 }
John Stilesa935c3f2021-02-25 10:35:49 -0500323 SkASSERT(base);
324
John Stilesa47b3512021-05-04 16:15:00 -0400325 // Put the core-module modifier pool into the context.
326 AutoModifiersPool autoPool(fContext, &fCoreModifiers);
John Stiles10d39d92021-05-04 16:13:14 -0400327
John Stilesa935c3f2021-02-25 10:35:49 -0500328 // Built-in modules always use default program settings.
329 ProgramConfig config;
330 config.fKind = kind;
331 config.fSettings.fReplaceSettings = !dehydrate;
332 AutoProgramConfig autoConfig(fContext, &config);
Brian Osman3d87e9f2020-10-08 11:50:22 -0400333
334#if defined(SKSL_STANDALONE)
335 SkASSERT(data.fPath);
336 std::ifstream in(data.fPath);
John Stilesd51c9792021-03-18 11:40:14 -0400337 String text{std::istreambuf_iterator<char>(in), std::istreambuf_iterator<char>()};
Ethan Nicholasb33fa3f2020-08-06 13:00:19 -0400338 if (in.rdstate()) {
Brian Osman3d87e9f2020-10-08 11:50:22 -0400339 printf("error reading %s\n", data.fPath);
Ethan Nicholasb33fa3f2020-08-06 13:00:19 -0400340 abort();
341 }
Brian Osmane498b3c2020-09-23 14:42:11 -0400342 const String* source = fRootSymbolTable->takeOwnershipOfString(std::move(text));
Brian Osman88cda172020-10-09 12:05:16 -0400343 AutoSource as(this, source);
John Stilesd1204642021-02-17 16:30:02 -0500344
Brian Osman88cda172020-10-09 12:05:16 -0400345 ParsedModule baseModule = {base, /*fIntrinsics=*/nullptr};
John Stilesd1204642021-02-17 16:30:02 -0500346 IRGenerator::IRBundle ir = fIRGenerator->convertProgram(baseModule, /*isBuiltinCode=*/true,
347 source->c_str(), source->length(),
348 /*externalFunctions=*/nullptr);
Brian Osman133724c2020-10-28 14:14:39 -0400349 SkASSERT(ir.fSharedElements.empty());
Brian Osman0006ad02020-11-18 15:38:39 -0500350 LoadedModule module = { kind, std::move(ir.fSymbolTable), std::move(ir.fElements) };
Ethan Nicholas8da1e652019-05-24 11:01:59 -0400351 if (this->fErrorCount) {
352 printf("Unexpected errors: %s\n", this->fErrorText.c_str());
Brian Osman3d87e9f2020-10-08 11:50:22 -0400353 SkDEBUGFAILF("%s %s\n", data.fPath, this->fErrorText.c_str());
Ethan Nicholas8da1e652019-05-24 11:01:59 -0400354 }
Brian Osman3d87e9f2020-10-08 11:50:22 -0400355#else
356 SkASSERT(data.fData && (data.fSize != 0));
John Stiles10d39d92021-05-04 16:13:14 -0400357 Rehydrator rehydrator(fContext.get(), base, data.fData, data.fSize);
Brian Osman0006ad02020-11-18 15:38:39 -0500358 LoadedModule module = { kind, rehydrator.symbolTable(), rehydrator.elements() };
Brian Osman3d87e9f2020-10-08 11:50:22 -0400359#endif
360
361 return module;
362}
363
John Stilesdbd4e6f2021-02-16 13:29:15 -0500364ParsedModule Compiler::parseModule(ProgramKind kind, ModuleData data, const ParsedModule& base) {
John Stilesa935c3f2021-02-25 10:35:49 -0500365 LoadedModule module = this->loadModule(kind, data, base.fSymbols, /*dehydrate=*/false);
Brian Osman0006ad02020-11-18 15:38:39 -0500366 this->optimize(module);
Brian Osman3d87e9f2020-10-08 11:50:22 -0400367
368 // For modules that just declare (but don't define) intrinsic functions, there will be no new
369 // program elements. In that case, we can share our parent's intrinsic map:
Brian Osman0006ad02020-11-18 15:38:39 -0500370 if (module.fElements.empty()) {
John Stiles10d39d92021-05-04 16:13:14 -0400371 return ParsedModule{module.fSymbols, base.fIntrinsics};
Brian Osman3d87e9f2020-10-08 11:50:22 -0400372 }
373
374 auto intrinsics = std::make_shared<IRIntrinsicMap>(base.fIntrinsics.get());
375
376 // Now, transfer all of the program elements to an intrinsic map. This maps certain types of
377 // global objects to the declaring ProgramElement.
Brian Osman0006ad02020-11-18 15:38:39 -0500378 for (std::unique_ptr<ProgramElement>& element : module.fElements) {
Brian Osman3d87e9f2020-10-08 11:50:22 -0400379 switch (element->kind()) {
380 case ProgramElement::Kind::kFunction: {
381 const FunctionDefinition& f = element->as<FunctionDefinition>();
Ethan Nicholas0a5d0962020-10-14 13:33:18 -0400382 SkASSERT(f.declaration().isBuiltin());
383 intrinsics->insertOrDie(f.declaration().description(), std::move(element));
Brian Osman3d87e9f2020-10-08 11:50:22 -0400384 break;
385 }
John Stiles569249b2020-11-03 12:18:22 -0500386 case ProgramElement::Kind::kFunctionPrototype: {
387 // These are already in the symbol table.
388 break;
389 }
Brian Osman3d87e9f2020-10-08 11:50:22 -0400390 case ProgramElement::Kind::kEnum: {
391 const Enum& e = element->as<Enum>();
392 SkASSERT(e.isBuiltin());
393 intrinsics->insertOrDie(e.typeName(), std::move(element));
394 break;
395 }
396 case ProgramElement::Kind::kGlobalVar: {
Ethan Nicholasc51f33e2020-10-13 13:49:44 -0400397 const GlobalVarDeclaration& global = element->as<GlobalVarDeclaration>();
398 const Variable& var = global.declaration()->as<VarDeclaration>().var();
399 SkASSERT(var.isBuiltin());
400 intrinsics->insertOrDie(var.name(), std::move(element));
Brian Osman3d87e9f2020-10-08 11:50:22 -0400401 break;
402 }
403 case ProgramElement::Kind::kInterfaceBlock: {
Ethan Nicholaseaf47882020-10-15 10:10:08 -0400404 const Variable& var = element->as<InterfaceBlock>().variable();
405 SkASSERT(var.isBuiltin());
406 intrinsics->insertOrDie(var.name(), std::move(element));
Brian Osman3d87e9f2020-10-08 11:50:22 -0400407 break;
408 }
409 default:
410 printf("Unsupported element: %s\n", element->description().c_str());
411 SkASSERT(false);
412 break;
413 }
414 }
415
John Stiles10d39d92021-05-04 16:13:14 -0400416 return ParsedModule{module.fSymbols, std::move(intrinsics)};
Ethan Nicholas8da1e652019-05-24 11:01:59 -0400417}
418
Brian Osman32d53552020-09-23 13:55:20 -0400419std::unique_ptr<Program> Compiler::convertProgram(
John Stilesdbd4e6f2021-02-16 13:29:15 -0500420 ProgramKind kind,
Brian Osman32d53552020-09-23 13:55:20 -0400421 String text,
422 const Program::Settings& settings,
Brian Osmanbe0b3b72021-01-06 14:27:35 -0500423 const std::vector<std::unique_ptr<ExternalFunction>>* externalFunctions) {
Brian Osman7a20b5c2021-03-15 16:23:33 -0400424 TRACE_EVENT0("skia.shaders", "SkSL::Compiler::convertProgram");
Leon Scrogginsb66214e2021-02-11 17:14:18 -0500425
John Stilesdbd4e6f2021-02-16 13:29:15 -0500426 SkASSERT(!externalFunctions || (kind == ProgramKind::kGeneric));
Ethan Nicholas91164d12019-05-15 15:29:54 -0400427
Brian Osman0006ad02020-11-18 15:38:39 -0500428 // Loading and optimizing our base module might reset the inliner, so do that first,
429 // *then* configure the inliner with the settings for this program.
430 const ParsedModule& baseModule = this->moduleForProgramKind(kind);
431
John Stiles10d39d92021-05-04 16:13:14 -0400432 // Put a fresh modifier pool into the context.
433 auto modifiersPool = std::make_unique<ModifiersPool>();
434 AutoModifiersPool autoPool(fContext, modifiersPool.get());
435
John Stiles270cec22021-02-17 12:59:36 -0500436 // Update our context to point to the program configuration for the duration of compilation.
437 auto config = std::make_unique<ProgramConfig>(ProgramConfig{kind, settings});
John Stilesa935c3f2021-02-25 10:35:49 -0500438 AutoProgramConfig autoConfig(fContext, config.get());
John Stiles270cec22021-02-17 12:59:36 -0500439
John Stiles2ee4d7a2021-03-30 10:30:47 -0400440 // Honor our optimization-override flags.
441 switch (sOptimizer) {
442 case OverrideFlag::kDefault:
443 break;
444 case OverrideFlag::kOff:
445 config->fSettings.fOptimize = false;
446 break;
447 case OverrideFlag::kOn:
448 config->fSettings.fOptimize = true;
449 break;
450 }
451
452 switch (sInliner) {
453 case OverrideFlag::kDefault:
454 break;
455 case OverrideFlag::kOff:
456 config->fSettings.fInlineThreshold = 0;
457 break;
458 case OverrideFlag::kOn:
459 if (config->fSettings.fInlineThreshold == 0) {
460 config->fSettings.fInlineThreshold = kDefaultInlineThreshold;
461 }
462 break;
463 }
John Stiles7247b482021-03-08 10:40:35 -0500464
465 // Disable optimization settings that depend on a parent setting which has been disabled.
John Stiles7247b482021-03-08 10:40:35 -0500466 config->fSettings.fInlineThreshold *= (int)config->fSettings.fOptimize;
John Stiles0bfeae62021-03-11 09:09:42 -0500467 config->fSettings.fRemoveDeadFunctions &= config->fSettings.fOptimize;
468 config->fSettings.fRemoveDeadVariables &= config->fSettings.fOptimize;
John Stiles7247b482021-03-08 10:40:35 -0500469
ethannicholasb3058bd2016-07-01 08:22:01 -0700470 fErrorText = "";
471 fErrorCount = 0;
John Stiles10d39d92021-05-04 16:13:14 -0400472 fInliner.reset();
Brian Osman88cda172020-10-09 12:05:16 -0400473
John Stiles10d39d92021-05-04 16:13:14 -0400474 auto textPtr = std::make_unique<String>(std::move(text));
John Stilesa289ac22021-05-06 07:35:35 -0400475 AutoSource as(this, textPtr.get());
Brian Osman88cda172020-10-09 12:05:16 -0400476
John Stiles5c7bb322020-10-22 11:09:15 -0400477 // Enable node pooling while converting and optimizing the program for a performance boost.
478 // The Program will take ownership of the pool.
Brian Osman28f702c2021-02-02 11:52:07 -0500479 std::unique_ptr<Pool> pool;
John Stilesc1a98b82021-02-24 13:35:02 -0500480 if (fContext->fCaps.useNodePools()) {
Brian Osman28f702c2021-02-02 11:52:07 -0500481 pool = Pool::Create();
482 pool->attachToThread();
483 }
John Stilesd1204642021-02-17 16:30:02 -0500484 IRGenerator::IRBundle ir = fIRGenerator->convertProgram(baseModule, /*isBuiltinCode=*/false,
485 textPtr->c_str(), textPtr->size(),
486 externalFunctions);
John Stiles270cec22021-02-17 12:59:36 -0500487 auto program = std::make_unique<Program>(std::move(textPtr),
488 std::move(config),
John Stiles5c7bb322020-10-22 11:09:15 -0400489 fContext,
490 std::move(ir.fElements),
Brian Osman133724c2020-10-28 14:14:39 -0400491 std::move(ir.fSharedElements),
John Stiles10d39d92021-05-04 16:13:14 -0400492 std::move(modifiersPool),
John Stiles5c7bb322020-10-22 11:09:15 -0400493 std::move(ir.fSymbolTable),
494 std::move(pool),
495 ir.fInputs);
496 bool success = false;
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500497 if (fErrorCount) {
John Stiles5c7bb322020-10-22 11:09:15 -0400498 // Do not return programs that failed to compile.
John Stiles7247b482021-03-08 10:40:35 -0500499 } else if (!this->optimize(*program)) {
John Stiles5c7bb322020-10-22 11:09:15 -0400500 // Do not return programs that failed to optimize.
501 } else {
502 // We have a successful program!
503 success = true;
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500504 }
John Stiles5c7bb322020-10-22 11:09:15 -0400505
Brian Osman28f702c2021-02-02 11:52:07 -0500506 if (program->fPool) {
507 program->fPool->detachFromThread();
508 }
John Stiles5c7bb322020-10-22 11:09:15 -0400509 return success ? std::move(program) : nullptr;
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500510}
511
John Stilesbb1505f2021-02-12 09:17:53 -0500512void Compiler::verifyStaticTests(const Program& program) {
513 class StaticTestVerifier : public ProgramVisitor {
514 public:
515 StaticTestVerifier(ErrorReporter* r) : fReporter(r) {}
516
517 using ProgramVisitor::visitProgramElement;
518
519 bool visitStatement(const Statement& stmt) override {
520 switch (stmt.kind()) {
521 case Statement::Kind::kIf:
522 if (stmt.as<IfStatement>().isStatic()) {
523 fReporter->error(stmt.fOffset, "static if has non-static test");
524 }
525 break;
526
527 case Statement::Kind::kSwitch:
528 if (stmt.as<SwitchStatement>().isStatic()) {
529 fReporter->error(stmt.fOffset, "static switch has non-static test");
530 }
531 break;
532
533 default:
534 break;
535 }
536 return INHERITED::visitStatement(stmt);
537 }
538
John Stiles59e34562021-02-12 16:56:39 -0500539 bool visitExpression(const Expression&) override {
540 // We aren't looking for anything inside an Expression, so skip them entirely.
541 return false;
542 }
543
John Stilesbb1505f2021-02-12 09:17:53 -0500544 private:
545 using INHERITED = ProgramVisitor;
546 ErrorReporter* fReporter;
547 };
548
549 // If invalid static tests are permitted, we don't need to check anything.
John Stilesd1204642021-02-17 16:30:02 -0500550 if (fContext->fConfig->fSettings.fPermitInvalidStaticTests) {
John Stilesbb1505f2021-02-12 09:17:53 -0500551 return;
552 }
553
554 // Check all of the program's owned elements. (Built-in elements are assumed to be valid.)
555 StaticTestVerifier visitor{this};
556 for (const std::unique_ptr<ProgramElement>& element : program.ownedElements()) {
557 if (element->is<FunctionDefinition>()) {
558 visitor.visitProgramElement(*element);
559 }
560 }
561}
562
Brian Osman0006ad02020-11-18 15:38:39 -0500563bool Compiler::optimize(LoadedModule& module) {
564 SkASSERT(!fErrorCount);
Brian Osman0006ad02020-11-18 15:38:39 -0500565
John Stiles270cec22021-02-17 12:59:36 -0500566 // Create a temporary program configuration with default settings.
567 ProgramConfig config;
568 config.fKind = module.fKind;
John Stilesa935c3f2021-02-25 10:35:49 -0500569 AutoProgramConfig autoConfig(fContext, &config);
John Stiles270cec22021-02-17 12:59:36 -0500570
John Stilesd1204642021-02-17 16:30:02 -0500571 // Reset the Inliner.
John Stiles10d39d92021-05-04 16:13:14 -0400572 fInliner.reset();
John Stiles270cec22021-02-17 12:59:36 -0500573
574 std::unique_ptr<ProgramUsage> usage = Analysis::GetUsage(module);
Brian Osman0006ad02020-11-18 15:38:39 -0500575
576 while (fErrorCount == 0) {
Brian Osman0006ad02020-11-18 15:38:39 -0500577 // Perform inline-candidate analysis and inline any functions deemed suitable.
John Stilesf3a28db2021-03-10 23:00:47 -0500578 if (!fInliner.analyze(module.fElements, module.fSymbols, usage.get())) {
Brian Osman0006ad02020-11-18 15:38:39 -0500579 break;
580 }
581 }
582 return fErrorCount == 0;
583}
584
John Stiles0bfeae62021-03-11 09:09:42 -0500585bool Compiler::removeDeadFunctions(Program& program, ProgramUsage* usage) {
586 bool madeChanges = false;
587
588 if (program.fConfig->fSettings.fRemoveDeadFunctions) {
589 auto isDeadFunction = [&](const ProgramElement* element) {
590 if (!element->is<FunctionDefinition>()) {
591 return false;
592 }
593 const FunctionDefinition& fn = element->as<FunctionDefinition>();
John Stilese8da4d22021-03-24 09:19:45 -0400594 if (fn.declaration().isMain() || usage->get(fn.declaration()) > 0) {
John Stiles0bfeae62021-03-11 09:09:42 -0500595 return false;
596 }
597 usage->remove(*element);
598 madeChanges = true;
599 return true;
600 };
601
602 program.fElements.erase(std::remove_if(program.fElements.begin(),
603 program.fElements.end(),
604 [&](const std::unique_ptr<ProgramElement>& element) {
605 return isDeadFunction(element.get());
606 }),
607 program.fElements.end());
608 program.fSharedElements.erase(std::remove_if(program.fSharedElements.begin(),
609 program.fSharedElements.end(),
610 isDeadFunction),
611 program.fSharedElements.end());
612 }
613 return madeChanges;
614}
615
616bool Compiler::removeDeadGlobalVariables(Program& program, ProgramUsage* usage) {
617 bool madeChanges = false;
618
619 if (program.fConfig->fSettings.fRemoveDeadVariables) {
620 auto isDeadVariable = [&](const ProgramElement* element) {
621 if (!element->is<GlobalVarDeclaration>()) {
622 return false;
623 }
624 const GlobalVarDeclaration& global = element->as<GlobalVarDeclaration>();
625 const VarDeclaration& varDecl = global.declaration()->as<VarDeclaration>();
626 if (!usage->isDead(varDecl.var())) {
627 return false;
628 }
629 madeChanges = true;
630 return true;
631 };
632
633 program.fElements.erase(std::remove_if(program.fElements.begin(),
634 program.fElements.end(),
635 [&](const std::unique_ptr<ProgramElement>& element) {
636 return isDeadVariable(element.get());
637 }),
638 program.fElements.end());
639 program.fSharedElements.erase(std::remove_if(program.fSharedElements.begin(),
640 program.fSharedElements.end(),
641 isDeadVariable),
642 program.fSharedElements.end());
643 }
644 return madeChanges;
645}
646
John Stiles26541872021-03-16 12:19:54 -0400647bool Compiler::removeDeadLocalVariables(Program& program, ProgramUsage* usage) {
648 class DeadLocalVariableEliminator : public ProgramWriter {
649 public:
650 DeadLocalVariableEliminator(const Context& context, ProgramUsage* usage)
651 : fContext(context)
652 , fUsage(usage) {}
653
654 using ProgramWriter::visitProgramElement;
655
656 bool visitExpressionPtr(std::unique_ptr<Expression>& expr) override {
657 // We don't need to look inside expressions at all.
658 return false;
659 }
660
661 bool visitStatementPtr(std::unique_ptr<Statement>& stmt) override {
662 if (stmt->is<VarDeclaration>()) {
663 VarDeclaration& varDecl = stmt->as<VarDeclaration>();
664 const Variable* var = &varDecl.var();
665 ProgramUsage::VariableCounts* counts = fUsage->fVariableCounts.find(var);
666 SkASSERT(counts);
667 SkASSERT(counts->fDeclared);
668 if (CanEliminate(var, *counts)) {
669 if (var->initialValue()) {
670 // The variable has an initial-value expression, which might have side
671 // effects. ExpressionStatement::Make will preserve side effects, but
672 // replaces pure expressions with Nop.
673 fUsage->remove(stmt.get());
674 stmt = ExpressionStatement::Make(fContext, std::move(varDecl.value()));
675 fUsage->add(stmt.get());
676 } else {
677 // The variable has no initial-value and can be cleanly eliminated.
678 fUsage->remove(stmt.get());
679 stmt = std::make_unique<Nop>();
680 }
681 fMadeChanges = true;
682 }
683 return false;
684 }
685 return INHERITED::visitStatementPtr(stmt);
686 }
687
688 static bool CanEliminate(const Variable* var, const ProgramUsage::VariableCounts& counts) {
689 if (!counts.fDeclared || counts.fRead || var->storage() != VariableStorage::kLocal) {
690 return false;
691 }
692 if (var->initialValue()) {
693 SkASSERT(counts.fWrite >= 1);
694 return counts.fWrite == 1;
695 } else {
696 return counts.fWrite == 0;
697 }
698 }
699
700 bool fMadeChanges = false;
701 const Context& fContext;
702 ProgramUsage* fUsage;
703
704 using INHERITED = ProgramWriter;
705 };
706
707 DeadLocalVariableEliminator visitor{*fContext, usage};
708
709 if (program.fConfig->fSettings.fRemoveDeadVariables) {
710 for (auto& [var, counts] : usage->fVariableCounts) {
711 if (DeadLocalVariableEliminator::CanEliminate(var, counts)) {
712 // This program contains at least one dead local variable.
713 // Scan the program for any dead local variables and eliminate them all.
714 for (std::unique_ptr<ProgramElement>& pe : program.ownedElements()) {
715 if (pe->is<FunctionDefinition>()) {
716 visitor.visitProgramElement(*pe);
717 }
718 }
719 break;
720 }
721 }
722 }
723
724 return visitor.fMadeChanges;
725}
726
Ethan Nicholas00543112018-07-31 09:44:36 -0400727bool Compiler::optimize(Program& program) {
John Stiles7247b482021-03-08 10:40:35 -0500728 // The optimizer only needs to run when it is enabled.
729 if (!program.fConfig->fSettings.fOptimize) {
730 return true;
731 }
732
Ethan Nicholas00543112018-07-31 09:44:36 -0400733 SkASSERT(!fErrorCount);
Brian Osman010ce6a2020-10-19 16:34:10 -0400734 ProgramUsage* usage = program.fUsage.get();
John Stiles7954d6c2020-09-01 10:53:02 -0400735
John Stilesb6664582021-03-19 09:46:00 -0400736 if (fErrorCount == 0) {
John Stiles87fc6572021-04-01 14:56:34 +0000737 // Run the inliner only once; it is expensive! Multiple passes can occasionally shake out
738 // more wins, but it's diminishing returns.
739 fInliner.analyze(program.ownedElements(), program.fSymbols, usage);
Ethan Nicholas34b19c52020-09-14 11:33:47 -0400740
John Stilesb6664582021-03-19 09:46:00 -0400741 while (this->removeDeadFunctions(program, usage)) {
742 // Removing dead functions may cause more functions to become unreferenced. Try again.
Ethan Nicholas34b19c52020-09-14 11:33:47 -0400743 }
John Stilesb6664582021-03-19 09:46:00 -0400744 while (this->removeDeadLocalVariables(program, usage)) {
745 // Removing dead variables may cause more variables to become unreferenced. Try again.
746 }
747 if (program.fConfig->fKind != ProgramKind::kFragmentProcessor) {
748 this->removeDeadGlobalVariables(program, usage);
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500749 }
Ethan Nicholas00543112018-07-31 09:44:36 -0400750 }
John Stilesbb1505f2021-02-12 09:17:53 -0500751
752 if (fErrorCount == 0) {
753 this->verifyStaticTests(program);
754 }
755
Ethan Nicholas00543112018-07-31 09:44:36 -0400756 return fErrorCount == 0;
757}
758
Brian Osmanfb32ddf2019-06-18 10:14:20 -0400759#if defined(SKSL_STANDALONE) || SK_SUPPORT_GPU
760
Ethan Nicholas00543112018-07-31 09:44:36 -0400761bool Compiler::toSPIRV(Program& program, OutputStream& out) {
Brian Osman7a20b5c2021-03-15 16:23:33 -0400762 TRACE_EVENT0("skia.shaders", "SkSL::Compiler::toSPIRV");
John Stilesa289ac22021-05-06 07:35:35 -0400763 AutoSource as(this, program.fSource.get());
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -0400764#ifdef SK_ENABLE_SPIRV_VALIDATION
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400765 StringStream buffer;
Brian Osman8b43dad2020-10-09 13:31:42 -0400766 SPIRVCodeGenerator cg(fContext.get(), &program, this, &buffer);
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -0400767 bool result = cg.generateCode();
John Stiles270cec22021-02-17 12:59:36 -0500768 if (result && program.fConfig->fSettings.fValidateSPIRV) {
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -0400769 spvtools::SpirvTools tools(SPV_ENV_VULKAN_1_0);
Ethan Nicholas762466e2017-06-29 10:03:38 -0400770 const String& data = buffer.str();
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400771 SkASSERT(0 == data.size() % 4);
Brian Osman8d09d4a2020-11-24 15:51:06 -0500772 String errors;
773 auto dumpmsg = [&errors](spv_message_level_t, const char*, const spv_position_t&,
774 const char* m) {
775 errors.appendf("SPIR-V validation error: %s\n", m);
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -0400776 };
777 tools.SetMessageConsumer(dumpmsg);
Brian Osman8d09d4a2020-11-24 15:51:06 -0500778
779 // Verify that the SPIR-V we produced is valid. At runtime, we will abort() with a message
780 // explaining the error. In standalone mode (skslc), we will send the message, plus the
781 // entire disassembled SPIR-V (for easier context & debugging) as *our* error message.
782 result = tools.Validate((const uint32_t*) data.c_str(), data.size() / 4);
783
784 if (!result) {
785#if defined(SKSL_STANDALONE)
786 // Convert the string-stream to a SPIR-V disassembly.
787 std::string disassembly;
788 if (tools.Disassemble((const uint32_t*)data.data(), data.size() / 4, &disassembly)) {
789 errors.append(disassembly);
790 }
791 this->error(-1, errors);
792#else
793 SkDEBUGFAILF("%s", errors.c_str());
794#endif
795 }
Ethan Nicholas762466e2017-06-29 10:03:38 -0400796 out.write(data.c_str(), data.size());
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -0400797 }
798#else
Brian Osman8b43dad2020-10-09 13:31:42 -0400799 SPIRVCodeGenerator cg(fContext.get(), &program, this, &out);
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500800 bool result = cg.generateCode();
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -0400801#endif
Ethan Nicholasce33f102016-12-09 17:22:59 -0500802 return result;
803}
804
Ethan Nicholas00543112018-07-31 09:44:36 -0400805bool Compiler::toSPIRV(Program& program, String* out) {
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400806 StringStream buffer;
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500807 bool result = this->toSPIRV(program, buffer);
808 if (result) {
Ethan Nicholas762466e2017-06-29 10:03:38 -0400809 *out = buffer.str();
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500810 }
811 return result;
812}
813
Ethan Nicholas00543112018-07-31 09:44:36 -0400814bool Compiler::toGLSL(Program& program, OutputStream& out) {
Brian Osman7a20b5c2021-03-15 16:23:33 -0400815 TRACE_EVENT0("skia.shaders", "SkSL::Compiler::toGLSL");
Brian Osman88cda172020-10-09 12:05:16 -0400816 AutoSource as(this, program.fSource.get());
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400817 GLSLCodeGenerator cg(fContext.get(), &program, this, &out);
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500818 bool result = cg.generateCode();
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500819 return result;
820}
821
Ethan Nicholas00543112018-07-31 09:44:36 -0400822bool Compiler::toGLSL(Program& program, String* out) {
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400823 StringStream buffer;
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500824 bool result = this->toGLSL(program, buffer);
825 if (result) {
Ethan Nicholas762466e2017-06-29 10:03:38 -0400826 *out = buffer.str();
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500827 }
828 return result;
829}
830
Brian Osmanc0243912020-02-19 15:35:26 -0500831bool Compiler::toHLSL(Program& program, String* out) {
832 String spirv;
833 if (!this->toSPIRV(program, &spirv)) {
834 return false;
835 }
836
837 return SPIRVtoHLSL(spirv, out);
838}
839
Ethan Nicholas00543112018-07-31 09:44:36 -0400840bool Compiler::toMetal(Program& program, OutputStream& out) {
Brian Osman7a20b5c2021-03-15 16:23:33 -0400841 TRACE_EVENT0("skia.shaders", "SkSL::Compiler::toMetal");
John Stilesa289ac22021-05-06 07:35:35 -0400842 AutoSource as(this, program.fSource.get());
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400843 MetalCodeGenerator cg(fContext.get(), &program, this, &out);
Ethan Nicholascc305772017-10-13 16:17:45 -0400844 bool result = cg.generateCode();
Ethan Nicholascc305772017-10-13 16:17:45 -0400845 return result;
846}
847
Ethan Nicholas00543112018-07-31 09:44:36 -0400848bool Compiler::toMetal(Program& program, String* out) {
Timothy Liangb8eeb802018-07-23 16:46:16 -0400849 StringStream buffer;
850 bool result = this->toMetal(program, buffer);
851 if (result) {
852 *out = buffer.str();
853 }
854 return result;
855}
856
Greg Daniela28ea672020-09-25 11:12:56 -0400857#if defined(SKSL_STANDALONE) || GR_TEST_UTILS
Ethan Nicholas00543112018-07-31 09:44:36 -0400858bool Compiler::toCPP(Program& program, String name, OutputStream& out) {
Brian Osman88cda172020-10-09 12:05:16 -0400859 AutoSource as(this, program.fSource.get());
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400860 CPPCodeGenerator cg(fContext.get(), &program, this, name, &out);
Ethan Nicholas762466e2017-06-29 10:03:38 -0400861 bool result = cg.generateCode();
Ethan Nicholas762466e2017-06-29 10:03:38 -0400862 return result;
863}
864
John Stiles82ab3402021-04-13 17:13:03 -0400865bool Compiler::toDSLCPP(Program& program, String name, OutputStream& out) {
866 AutoSource as(this, program.fSource.get());
867 DSLCPPCodeGenerator cg(fContext.get(), &program, this, name, &out);
868 bool result = cg.generateCode();
869 return result;
870}
871
Ethan Nicholas00543112018-07-31 09:44:36 -0400872bool Compiler::toH(Program& program, String name, OutputStream& out) {
Brian Osman88cda172020-10-09 12:05:16 -0400873 AutoSource as(this, program.fSource.get());
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400874 HCodeGenerator cg(fContext.get(), &program, this, name, &out);
Ethan Nicholas762466e2017-06-29 10:03:38 -0400875 bool result = cg.generateCode();
Ethan Nicholas00543112018-07-31 09:44:36 -0400876 return result;
877}
Greg Daniela28ea672020-09-25 11:12:56 -0400878#endif // defined(SKSL_STANDALONE) || GR_TEST_UTILS
Ethan Nicholas00543112018-07-31 09:44:36 -0400879
Ethan Nicholas2a479a52020-08-18 16:29:45 -0400880#endif // defined(SKSL_STANDALONE) || SK_SUPPORT_GPU
Brian Osman2e29ab52019-09-20 12:19:11 -0400881
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700882Position Compiler::position(int offset) {
Ethan Nicholas3c729892020-12-07 12:47:17 -0500883 if (fSource && offset >= 0) {
884 int line = 1;
885 int column = 1;
886 for (int i = 0; i < offset; i++) {
887 if ((*fSource)[i] == '\n') {
888 ++line;
889 column = 1;
890 }
891 else {
892 ++column;
893 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700894 }
Ethan Nicholas3c729892020-12-07 12:47:17 -0500895 return Position(line, column);
896 } else {
897 return Position(-1, -1);
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700898 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700899}
900
901void Compiler::error(int offset, String msg) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700902 fErrorCount++;
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700903 Position pos = this->position(offset);
John Stiles8d3642e2021-01-22 09:50:04 -0500904 fErrorTextLength.push_back(fErrorText.length());
Ethan Nicholas3c729892020-12-07 12:47:17 -0500905 fErrorText += "error: " + (pos.fLine >= 1 ? to_string(pos.fLine) + ": " : "") + msg + "\n";
ethannicholasb3058bd2016-07-01 08:22:01 -0700906}
907
John Stiles8d3642e2021-01-22 09:50:04 -0500908void Compiler::setErrorCount(int c) {
909 if (c < fErrorCount) {
910 fErrorText.resize(fErrorTextLength[c]);
911 fErrorTextLength.resize(c);
912 fErrorCount = c;
913 }
914}
915
Ethan Nicholas95046142021-01-07 10:57:27 -0500916String Compiler::errorText(bool showCount) {
917 if (showCount) {
918 this->writeErrorCount();
919 }
Ethan Nicholas00543112018-07-31 09:44:36 -0400920 fErrorCount = 0;
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400921 String result = fErrorText;
Ethan Nicholas95046142021-01-07 10:57:27 -0500922 fErrorText = "";
ethannicholasb3058bd2016-07-01 08:22:01 -0700923 return result;
924}
925
926void Compiler::writeErrorCount() {
927 if (fErrorCount) {
928 fErrorText += to_string(fErrorCount) + " error";
929 if (fErrorCount > 1) {
930 fErrorText += "s";
931 }
932 fErrorText += "\n";
933 }
934}
935
John Stilesa6841be2020-08-06 14:11:56 -0400936} // namespace SkSL