blob: c2007efc7e49398a505101b32381c16309608974 [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)
86 : fCompiler(compiler), fOldSource(fCompiler->fSource) {
87 fCompiler->fSource = source;
88 }
89
90 ~AutoSource() { fCompiler->fSource = fOldSource; }
91
92 Compiler* fCompiler;
93 const String* fOldSource;
94};
95
John Stilesa935c3f2021-02-25 10:35:49 -050096class AutoProgramConfig {
97public:
98 AutoProgramConfig(std::shared_ptr<Context>& context, ProgramConfig* config)
99 : fContext(context.get()) {
100 SkASSERT(!fContext->fConfig);
101 fContext->fConfig = config;
102 }
103
104 ~AutoProgramConfig() {
105 fContext->fConfig = nullptr;
106 }
107
108 Context* fContext;
109};
110
John Stiles10d39d92021-05-04 16:13:14 -0400111class AutoModifiersPool {
112public:
113 AutoModifiersPool(std::shared_ptr<Context>& context, ModifiersPool* modifiersPool)
114 : fContext(context.get()) {
115 SkASSERT(!fContext->fModifiersPool);
116 fContext->fModifiersPool = modifiersPool;
117 }
118
119 ~AutoModifiersPool() {
120 fContext->fModifiersPool = nullptr;
121 }
122
123 Context* fContext;
124};
125
John Stilesd6a5f4492021-02-11 15:46:11 -0500126Compiler::Compiler(const ShaderCapsClass* caps)
John Stilesc1a98b82021-02-24 13:35:02 -0500127 : fContext(std::make_shared<Context>(/*errors=*/*this, *caps))
John Stiles7b920442020-12-17 10:43:41 -0500128 , fInliner(fContext.get())
Brian Osman0006ad02020-11-18 15:38:39 -0500129 , fErrorCount(0) {
John Stilesc1a98b82021-02-24 13:35:02 -0500130 SkASSERT(caps);
John Stiles7c3515b2020-10-16 18:38:39 -0400131 fRootSymbolTable = std::make_shared<SymbolTable>(this, /*builtin=*/true);
Brian Osmanb06301e2020-11-06 11:45:36 -0500132 fPrivateSymbolTable = std::make_shared<SymbolTable>(fRootSymbolTable, /*builtin=*/true);
John Stilesc1a98b82021-02-24 13:35:02 -0500133 fIRGenerator = std::make_unique<IRGenerator>(fContext.get());
ethannicholasb3058bd2016-07-01 08:22:01 -0700134
John Stiles54e7c052021-01-11 14:22:36 -0500135#define TYPE(t) fContext->fTypes.f ## t .get()
ethannicholasb3058bd2016-07-01 08:22:01 -0700136
Brian Osmanb06301e2020-11-06 11:45:36 -0500137 const SkSL::Symbol* rootTypes[] = {
138 TYPE(Void),
Brian Salomonbf7b6202016-11-11 16:08:03 -0500139
Brian Osmanb06301e2020-11-06 11:45:36 -0500140 TYPE( Float), TYPE( Float2), TYPE( Float3), TYPE( Float4),
141 TYPE( Half), TYPE( Half2), TYPE( Half3), TYPE( Half4),
142 TYPE( Int), TYPE( Int2), TYPE( Int3), TYPE( Int4),
Brian Osmanb06301e2020-11-06 11:45:36 -0500143 TYPE( Bool), TYPE( Bool2), TYPE( Bool3), TYPE( Bool4),
Brian Salomon2a51de82016-11-16 12:06:01 -0500144
Brian Osmanc0f2b642020-12-22 13:35:55 -0500145 TYPE(Float2x2), TYPE(Float3x3), TYPE(Float4x4),
Brian Osmanc63f4312020-12-23 11:44:14 -0500146 TYPE( Half2x2), TYPE( Half3x3), TYPE(Half4x4),
Greg Daniel64773e62016-11-22 09:44:03 -0500147
Brian Osmanc63f4312020-12-23 11:44:14 -0500148 TYPE(SquareMat), TYPE(SquareHMat),
ethannicholasb3058bd2016-07-01 08:22:01 -0700149
Brian Osman20fad322020-12-23 12:42:33 -0500150 TYPE(GenType), TYPE(GenHType), TYPE(GenIType), TYPE(GenBType),
151 TYPE(Vec), TYPE(HVec), TYPE(IVec), TYPE(BVec),
Brian Osmanb06301e2020-11-06 11:45:36 -0500152
Brian Osman14d00962021-04-02 17:04:35 -0400153 TYPE(ColorFilter),
154 TYPE(Shader),
Brian Osmanb06301e2020-11-06 11:45:36 -0500155 };
156
157 const SkSL::Symbol* privateTypes[] = {
Brian Osman20fad322020-12-23 12:42:33 -0500158 TYPE( UInt), TYPE( UInt2), TYPE( UInt3), TYPE( UInt4),
159 TYPE( Short), TYPE( Short2), TYPE( Short3), TYPE( Short4),
160 TYPE(UShort), TYPE(UShort2), TYPE(UShort3), TYPE(UShort4),
Brian Osman20fad322020-12-23 12:42:33 -0500161
162 TYPE(GenUType), TYPE(UVec),
Ethan Nicholas722c83e2021-05-04 11:39:30 -0400163 TYPE(SVec), TYPE(USVec),
Brian Osman20fad322020-12-23 12:42:33 -0500164
Brian Osmanc0f2b642020-12-22 13:35:55 -0500165 TYPE(Float2x3), TYPE(Float2x4),
166 TYPE(Float3x2), TYPE(Float3x4),
167 TYPE(Float4x2), TYPE(Float4x3),
168
Brian Osmanc63f4312020-12-23 11:44:14 -0500169 TYPE(Half2x3), TYPE(Half2x4),
170 TYPE(Half3x2), TYPE(Half3x4),
171 TYPE(Half4x2), TYPE(Half4x3),
172
Brian Osmanc0f2b642020-12-22 13:35:55 -0500173 TYPE(Mat), TYPE(HMat),
174
Brian Osmanb06301e2020-11-06 11:45:36 -0500175 TYPE(Sampler1D), TYPE(Sampler2D), TYPE(Sampler3D),
176 TYPE(SamplerExternalOES),
Brian Osmanb06301e2020-11-06 11:45:36 -0500177 TYPE(Sampler2DRect),
Brian Osmanb06301e2020-11-06 11:45:36 -0500178
179 TYPE(ISampler2D),
Brian Osmanb06301e2020-11-06 11:45:36 -0500180 TYPE(SubpassInput), TYPE(SubpassInputMS),
181
Brian Osmanb06301e2020-11-06 11:45:36 -0500182 TYPE(Sampler),
183 TYPE(Texture2D),
Brian Osman14d00962021-04-02 17:04:35 -0400184
185 TYPE(FragmentProcessor),
Brian Osmanb06301e2020-11-06 11:45:36 -0500186 };
187
188 for (const SkSL::Symbol* type : rootTypes) {
189 fRootSymbolTable->addWithoutOwnership(type);
190 }
191 for (const SkSL::Symbol* type : privateTypes) {
192 fPrivateSymbolTable->addWithoutOwnership(type);
193 }
194
195#undef TYPE
ethannicholasb3058bd2016-07-01 08:22:01 -0700196
Brian Osman3887a012020-09-30 13:22:27 -0400197 // sk_Caps is "builtin", but all references to it are resolved to Settings, so we don't need to
198 // treat it as builtin (ie, no need to clone it into the Program).
John Stiles10d39d92021-05-04 16:13:14 -0400199 static const Modifiers kNoModifiers{};
200 fPrivateSymbolTable->add(std::make_unique<Variable>(/*offset=*/-1,
201 &kNoModifiers,
202 "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 Stiles10d39d92021-05-04 16:13:14 -0400325 // Put a fresh modifier pool into the context.
326 auto modifiersPool = std::make_unique<ModifiersPool>();
327 AutoModifiersPool autoPool(fContext, modifiersPool.get());
328
John Stilesa935c3f2021-02-25 10:35:49 -0500329 // Built-in modules always use default program settings.
330 ProgramConfig config;
331 config.fKind = kind;
332 config.fSettings.fReplaceSettings = !dehydrate;
333 AutoProgramConfig autoConfig(fContext, &config);
Brian Osman3d87e9f2020-10-08 11:50:22 -0400334
335#if defined(SKSL_STANDALONE)
336 SkASSERT(data.fPath);
337 std::ifstream in(data.fPath);
John Stilesd51c9792021-03-18 11:40:14 -0400338 String text{std::istreambuf_iterator<char>(in), std::istreambuf_iterator<char>()};
Ethan Nicholasb33fa3f2020-08-06 13:00:19 -0400339 if (in.rdstate()) {
Brian Osman3d87e9f2020-10-08 11:50:22 -0400340 printf("error reading %s\n", data.fPath);
Ethan Nicholasb33fa3f2020-08-06 13:00:19 -0400341 abort();
342 }
Brian Osmane498b3c2020-09-23 14:42:11 -0400343 const String* source = fRootSymbolTable->takeOwnershipOfString(std::move(text));
Brian Osman88cda172020-10-09 12:05:16 -0400344 AutoSource as(this, source);
John Stilesd1204642021-02-17 16:30:02 -0500345
Brian Osman88cda172020-10-09 12:05:16 -0400346 ParsedModule baseModule = {base, /*fIntrinsics=*/nullptr};
John Stilesd1204642021-02-17 16:30:02 -0500347 IRGenerator::IRBundle ir = fIRGenerator->convertProgram(baseModule, /*isBuiltinCode=*/true,
348 source->c_str(), source->length(),
349 /*externalFunctions=*/nullptr);
Brian Osman133724c2020-10-28 14:14:39 -0400350 SkASSERT(ir.fSharedElements.empty());
Brian Osman0006ad02020-11-18 15:38:39 -0500351 LoadedModule module = { kind, std::move(ir.fSymbolTable), std::move(ir.fElements) };
Ethan Nicholas8da1e652019-05-24 11:01:59 -0400352 if (this->fErrorCount) {
353 printf("Unexpected errors: %s\n", this->fErrorText.c_str());
Brian Osman3d87e9f2020-10-08 11:50:22 -0400354 SkDEBUGFAILF("%s %s\n", data.fPath, this->fErrorText.c_str());
Ethan Nicholas8da1e652019-05-24 11:01:59 -0400355 }
John Stiles10d39d92021-05-04 16:13:14 -0400356 fModifiers.push_back(std::move(modifiersPool));
Brian Osman3d87e9f2020-10-08 11:50:22 -0400357#else
358 SkASSERT(data.fData && (data.fSize != 0));
John Stiles10d39d92021-05-04 16:13:14 -0400359 Rehydrator rehydrator(fContext.get(), base, data.fData, data.fSize);
Brian Osman0006ad02020-11-18 15:38:39 -0500360 LoadedModule module = { kind, rehydrator.symbolTable(), rehydrator.elements() };
John Stiles10d39d92021-05-04 16:13:14 -0400361 fModifiers.push_back(std::move(modifiersPool));
Brian Osman3d87e9f2020-10-08 11:50:22 -0400362#endif
363
364 return module;
365}
366
John Stilesdbd4e6f2021-02-16 13:29:15 -0500367ParsedModule Compiler::parseModule(ProgramKind kind, ModuleData data, const ParsedModule& base) {
John Stilesa935c3f2021-02-25 10:35:49 -0500368 LoadedModule module = this->loadModule(kind, data, base.fSymbols, /*dehydrate=*/false);
Brian Osman0006ad02020-11-18 15:38:39 -0500369 this->optimize(module);
Brian Osman3d87e9f2020-10-08 11:50:22 -0400370
371 // For modules that just declare (but don't define) intrinsic functions, there will be no new
372 // program elements. In that case, we can share our parent's intrinsic map:
Brian Osman0006ad02020-11-18 15:38:39 -0500373 if (module.fElements.empty()) {
John Stiles10d39d92021-05-04 16:13:14 -0400374 return ParsedModule{module.fSymbols, base.fIntrinsics};
Brian Osman3d87e9f2020-10-08 11:50:22 -0400375 }
376
377 auto intrinsics = std::make_shared<IRIntrinsicMap>(base.fIntrinsics.get());
378
379 // Now, transfer all of the program elements to an intrinsic map. This maps certain types of
380 // global objects to the declaring ProgramElement.
Brian Osman0006ad02020-11-18 15:38:39 -0500381 for (std::unique_ptr<ProgramElement>& element : module.fElements) {
Brian Osman3d87e9f2020-10-08 11:50:22 -0400382 switch (element->kind()) {
383 case ProgramElement::Kind::kFunction: {
384 const FunctionDefinition& f = element->as<FunctionDefinition>();
Ethan Nicholas0a5d0962020-10-14 13:33:18 -0400385 SkASSERT(f.declaration().isBuiltin());
386 intrinsics->insertOrDie(f.declaration().description(), std::move(element));
Brian Osman3d87e9f2020-10-08 11:50:22 -0400387 break;
388 }
John Stiles569249b2020-11-03 12:18:22 -0500389 case ProgramElement::Kind::kFunctionPrototype: {
390 // These are already in the symbol table.
391 break;
392 }
Brian Osman3d87e9f2020-10-08 11:50:22 -0400393 case ProgramElement::Kind::kEnum: {
394 const Enum& e = element->as<Enum>();
395 SkASSERT(e.isBuiltin());
396 intrinsics->insertOrDie(e.typeName(), std::move(element));
397 break;
398 }
399 case ProgramElement::Kind::kGlobalVar: {
Ethan Nicholasc51f33e2020-10-13 13:49:44 -0400400 const GlobalVarDeclaration& global = element->as<GlobalVarDeclaration>();
401 const Variable& var = global.declaration()->as<VarDeclaration>().var();
402 SkASSERT(var.isBuiltin());
403 intrinsics->insertOrDie(var.name(), std::move(element));
Brian Osman3d87e9f2020-10-08 11:50:22 -0400404 break;
405 }
406 case ProgramElement::Kind::kInterfaceBlock: {
Ethan Nicholaseaf47882020-10-15 10:10:08 -0400407 const Variable& var = element->as<InterfaceBlock>().variable();
408 SkASSERT(var.isBuiltin());
409 intrinsics->insertOrDie(var.name(), std::move(element));
Brian Osman3d87e9f2020-10-08 11:50:22 -0400410 break;
411 }
412 default:
413 printf("Unsupported element: %s\n", element->description().c_str());
414 SkASSERT(false);
415 break;
416 }
417 }
418
John Stiles10d39d92021-05-04 16:13:14 -0400419 return ParsedModule{module.fSymbols, std::move(intrinsics)};
Ethan Nicholas8da1e652019-05-24 11:01:59 -0400420}
421
Brian Osman32d53552020-09-23 13:55:20 -0400422std::unique_ptr<Program> Compiler::convertProgram(
John Stilesdbd4e6f2021-02-16 13:29:15 -0500423 ProgramKind kind,
Brian Osman32d53552020-09-23 13:55:20 -0400424 String text,
425 const Program::Settings& settings,
Brian Osmanbe0b3b72021-01-06 14:27:35 -0500426 const std::vector<std::unique_ptr<ExternalFunction>>* externalFunctions) {
Brian Osman7a20b5c2021-03-15 16:23:33 -0400427 TRACE_EVENT0("skia.shaders", "SkSL::Compiler::convertProgram");
Leon Scrogginsb66214e2021-02-11 17:14:18 -0500428
John Stilesdbd4e6f2021-02-16 13:29:15 -0500429 SkASSERT(!externalFunctions || (kind == ProgramKind::kGeneric));
Ethan Nicholas91164d12019-05-15 15:29:54 -0400430
Brian Osman0006ad02020-11-18 15:38:39 -0500431 // Loading and optimizing our base module might reset the inliner, so do that first,
432 // *then* configure the inliner with the settings for this program.
433 const ParsedModule& baseModule = this->moduleForProgramKind(kind);
434
John Stiles10d39d92021-05-04 16:13:14 -0400435 // Put a fresh modifier pool into the context.
436 auto modifiersPool = std::make_unique<ModifiersPool>();
437 AutoModifiersPool autoPool(fContext, modifiersPool.get());
438
John Stiles270cec22021-02-17 12:59:36 -0500439 // Update our context to point to the program configuration for the duration of compilation.
440 auto config = std::make_unique<ProgramConfig>(ProgramConfig{kind, settings});
John Stilesa935c3f2021-02-25 10:35:49 -0500441 AutoProgramConfig autoConfig(fContext, config.get());
John Stiles270cec22021-02-17 12:59:36 -0500442
John Stiles2ee4d7a2021-03-30 10:30:47 -0400443 // Honor our optimization-override flags.
444 switch (sOptimizer) {
445 case OverrideFlag::kDefault:
446 break;
447 case OverrideFlag::kOff:
448 config->fSettings.fOptimize = false;
449 break;
450 case OverrideFlag::kOn:
451 config->fSettings.fOptimize = true;
452 break;
453 }
454
455 switch (sInliner) {
456 case OverrideFlag::kDefault:
457 break;
458 case OverrideFlag::kOff:
459 config->fSettings.fInlineThreshold = 0;
460 break;
461 case OverrideFlag::kOn:
462 if (config->fSettings.fInlineThreshold == 0) {
463 config->fSettings.fInlineThreshold = kDefaultInlineThreshold;
464 }
465 break;
466 }
John Stiles7247b482021-03-08 10:40:35 -0500467
468 // Disable optimization settings that depend on a parent setting which has been disabled.
John Stiles7247b482021-03-08 10:40:35 -0500469 config->fSettings.fInlineThreshold *= (int)config->fSettings.fOptimize;
John Stiles0bfeae62021-03-11 09:09:42 -0500470 config->fSettings.fRemoveDeadFunctions &= config->fSettings.fOptimize;
471 config->fSettings.fRemoveDeadVariables &= config->fSettings.fOptimize;
John Stiles7247b482021-03-08 10:40:35 -0500472
ethannicholasb3058bd2016-07-01 08:22:01 -0700473 fErrorText = "";
474 fErrorCount = 0;
John Stiles10d39d92021-05-04 16:13:14 -0400475 fInliner.reset();
Brian Osman88cda172020-10-09 12:05:16 -0400476
477 // Not using AutoSource, because caller is likely to call errorText() if we fail to compile
John Stiles10d39d92021-05-04 16:13:14 -0400478 auto textPtr = std::make_unique<String>(std::move(text));
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700479 fSource = textPtr.get();
Brian Osman88cda172020-10-09 12:05:16 -0400480
John Stiles5c7bb322020-10-22 11:09:15 -0400481 // Enable node pooling while converting and optimizing the program for a performance boost.
482 // The Program will take ownership of the pool.
Brian Osman28f702c2021-02-02 11:52:07 -0500483 std::unique_ptr<Pool> pool;
John Stilesc1a98b82021-02-24 13:35:02 -0500484 if (fContext->fCaps.useNodePools()) {
Brian Osman28f702c2021-02-02 11:52:07 -0500485 pool = Pool::Create();
486 pool->attachToThread();
487 }
John Stilesd1204642021-02-17 16:30:02 -0500488 IRGenerator::IRBundle ir = fIRGenerator->convertProgram(baseModule, /*isBuiltinCode=*/false,
489 textPtr->c_str(), textPtr->size(),
490 externalFunctions);
John Stiles270cec22021-02-17 12:59:36 -0500491 auto program = std::make_unique<Program>(std::move(textPtr),
492 std::move(config),
John Stiles5c7bb322020-10-22 11:09:15 -0400493 fContext,
494 std::move(ir.fElements),
Brian Osman133724c2020-10-28 14:14:39 -0400495 std::move(ir.fSharedElements),
John Stiles10d39d92021-05-04 16:13:14 -0400496 std::move(modifiersPool),
John Stiles5c7bb322020-10-22 11:09:15 -0400497 std::move(ir.fSymbolTable),
498 std::move(pool),
499 ir.fInputs);
500 bool success = false;
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500501 if (fErrorCount) {
John Stiles5c7bb322020-10-22 11:09:15 -0400502 // Do not return programs that failed to compile.
John Stiles7247b482021-03-08 10:40:35 -0500503 } else if (!this->optimize(*program)) {
John Stiles5c7bb322020-10-22 11:09:15 -0400504 // Do not return programs that failed to optimize.
505 } else {
506 // We have a successful program!
507 success = true;
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500508 }
John Stiles5c7bb322020-10-22 11:09:15 -0400509
Brian Osman28f702c2021-02-02 11:52:07 -0500510 if (program->fPool) {
511 program->fPool->detachFromThread();
512 }
John Stiles5c7bb322020-10-22 11:09:15 -0400513 return success ? std::move(program) : nullptr;
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500514}
515
John Stilesbb1505f2021-02-12 09:17:53 -0500516void Compiler::verifyStaticTests(const Program& program) {
517 class StaticTestVerifier : public ProgramVisitor {
518 public:
519 StaticTestVerifier(ErrorReporter* r) : fReporter(r) {}
520
521 using ProgramVisitor::visitProgramElement;
522
523 bool visitStatement(const Statement& stmt) override {
524 switch (stmt.kind()) {
525 case Statement::Kind::kIf:
526 if (stmt.as<IfStatement>().isStatic()) {
527 fReporter->error(stmt.fOffset, "static if has non-static test");
528 }
529 break;
530
531 case Statement::Kind::kSwitch:
532 if (stmt.as<SwitchStatement>().isStatic()) {
533 fReporter->error(stmt.fOffset, "static switch has non-static test");
534 }
535 break;
536
537 default:
538 break;
539 }
540 return INHERITED::visitStatement(stmt);
541 }
542
John Stiles59e34562021-02-12 16:56:39 -0500543 bool visitExpression(const Expression&) override {
544 // We aren't looking for anything inside an Expression, so skip them entirely.
545 return false;
546 }
547
John Stilesbb1505f2021-02-12 09:17:53 -0500548 private:
549 using INHERITED = ProgramVisitor;
550 ErrorReporter* fReporter;
551 };
552
553 // If invalid static tests are permitted, we don't need to check anything.
John Stilesd1204642021-02-17 16:30:02 -0500554 if (fContext->fConfig->fSettings.fPermitInvalidStaticTests) {
John Stilesbb1505f2021-02-12 09:17:53 -0500555 return;
556 }
557
558 // Check all of the program's owned elements. (Built-in elements are assumed to be valid.)
559 StaticTestVerifier visitor{this};
560 for (const std::unique_ptr<ProgramElement>& element : program.ownedElements()) {
561 if (element->is<FunctionDefinition>()) {
562 visitor.visitProgramElement(*element);
563 }
564 }
565}
566
Brian Osman0006ad02020-11-18 15:38:39 -0500567bool Compiler::optimize(LoadedModule& module) {
568 SkASSERT(!fErrorCount);
Brian Osman0006ad02020-11-18 15:38:39 -0500569
John Stiles270cec22021-02-17 12:59:36 -0500570 // Create a temporary program configuration with default settings.
571 ProgramConfig config;
572 config.fKind = module.fKind;
John Stilesa935c3f2021-02-25 10:35:49 -0500573 AutoProgramConfig autoConfig(fContext, &config);
John Stiles270cec22021-02-17 12:59:36 -0500574
John Stilesd1204642021-02-17 16:30:02 -0500575 // Reset the Inliner.
John Stiles10d39d92021-05-04 16:13:14 -0400576 fInliner.reset();
John Stiles270cec22021-02-17 12:59:36 -0500577
578 std::unique_ptr<ProgramUsage> usage = Analysis::GetUsage(module);
Brian Osman0006ad02020-11-18 15:38:39 -0500579
580 while (fErrorCount == 0) {
Brian Osman0006ad02020-11-18 15:38:39 -0500581 // Perform inline-candidate analysis and inline any functions deemed suitable.
John Stilesf3a28db2021-03-10 23:00:47 -0500582 if (!fInliner.analyze(module.fElements, module.fSymbols, usage.get())) {
Brian Osman0006ad02020-11-18 15:38:39 -0500583 break;
584 }
585 }
586 return fErrorCount == 0;
587}
588
John Stiles0bfeae62021-03-11 09:09:42 -0500589bool Compiler::removeDeadFunctions(Program& program, ProgramUsage* usage) {
590 bool madeChanges = false;
591
592 if (program.fConfig->fSettings.fRemoveDeadFunctions) {
593 auto isDeadFunction = [&](const ProgramElement* element) {
594 if (!element->is<FunctionDefinition>()) {
595 return false;
596 }
597 const FunctionDefinition& fn = element->as<FunctionDefinition>();
John Stilese8da4d22021-03-24 09:19:45 -0400598 if (fn.declaration().isMain() || usage->get(fn.declaration()) > 0) {
John Stiles0bfeae62021-03-11 09:09:42 -0500599 return false;
600 }
601 usage->remove(*element);
602 madeChanges = true;
603 return true;
604 };
605
606 program.fElements.erase(std::remove_if(program.fElements.begin(),
607 program.fElements.end(),
608 [&](const std::unique_ptr<ProgramElement>& element) {
609 return isDeadFunction(element.get());
610 }),
611 program.fElements.end());
612 program.fSharedElements.erase(std::remove_if(program.fSharedElements.begin(),
613 program.fSharedElements.end(),
614 isDeadFunction),
615 program.fSharedElements.end());
616 }
617 return madeChanges;
618}
619
620bool Compiler::removeDeadGlobalVariables(Program& program, ProgramUsage* usage) {
621 bool madeChanges = false;
622
623 if (program.fConfig->fSettings.fRemoveDeadVariables) {
624 auto isDeadVariable = [&](const ProgramElement* element) {
625 if (!element->is<GlobalVarDeclaration>()) {
626 return false;
627 }
628 const GlobalVarDeclaration& global = element->as<GlobalVarDeclaration>();
629 const VarDeclaration& varDecl = global.declaration()->as<VarDeclaration>();
630 if (!usage->isDead(varDecl.var())) {
631 return false;
632 }
633 madeChanges = true;
634 return true;
635 };
636
637 program.fElements.erase(std::remove_if(program.fElements.begin(),
638 program.fElements.end(),
639 [&](const std::unique_ptr<ProgramElement>& element) {
640 return isDeadVariable(element.get());
641 }),
642 program.fElements.end());
643 program.fSharedElements.erase(std::remove_if(program.fSharedElements.begin(),
644 program.fSharedElements.end(),
645 isDeadVariable),
646 program.fSharedElements.end());
647 }
648 return madeChanges;
649}
650
John Stiles26541872021-03-16 12:19:54 -0400651bool Compiler::removeDeadLocalVariables(Program& program, ProgramUsage* usage) {
652 class DeadLocalVariableEliminator : public ProgramWriter {
653 public:
654 DeadLocalVariableEliminator(const Context& context, ProgramUsage* usage)
655 : fContext(context)
656 , fUsage(usage) {}
657
658 using ProgramWriter::visitProgramElement;
659
660 bool visitExpressionPtr(std::unique_ptr<Expression>& expr) override {
661 // We don't need to look inside expressions at all.
662 return false;
663 }
664
665 bool visitStatementPtr(std::unique_ptr<Statement>& stmt) override {
666 if (stmt->is<VarDeclaration>()) {
667 VarDeclaration& varDecl = stmt->as<VarDeclaration>();
668 const Variable* var = &varDecl.var();
669 ProgramUsage::VariableCounts* counts = fUsage->fVariableCounts.find(var);
670 SkASSERT(counts);
671 SkASSERT(counts->fDeclared);
672 if (CanEliminate(var, *counts)) {
673 if (var->initialValue()) {
674 // The variable has an initial-value expression, which might have side
675 // effects. ExpressionStatement::Make will preserve side effects, but
676 // replaces pure expressions with Nop.
677 fUsage->remove(stmt.get());
678 stmt = ExpressionStatement::Make(fContext, std::move(varDecl.value()));
679 fUsage->add(stmt.get());
680 } else {
681 // The variable has no initial-value and can be cleanly eliminated.
682 fUsage->remove(stmt.get());
683 stmt = std::make_unique<Nop>();
684 }
685 fMadeChanges = true;
686 }
687 return false;
688 }
689 return INHERITED::visitStatementPtr(stmt);
690 }
691
692 static bool CanEliminate(const Variable* var, const ProgramUsage::VariableCounts& counts) {
693 if (!counts.fDeclared || counts.fRead || var->storage() != VariableStorage::kLocal) {
694 return false;
695 }
696 if (var->initialValue()) {
697 SkASSERT(counts.fWrite >= 1);
698 return counts.fWrite == 1;
699 } else {
700 return counts.fWrite == 0;
701 }
702 }
703
704 bool fMadeChanges = false;
705 const Context& fContext;
706 ProgramUsage* fUsage;
707
708 using INHERITED = ProgramWriter;
709 };
710
711 DeadLocalVariableEliminator visitor{*fContext, usage};
712
713 if (program.fConfig->fSettings.fRemoveDeadVariables) {
714 for (auto& [var, counts] : usage->fVariableCounts) {
715 if (DeadLocalVariableEliminator::CanEliminate(var, counts)) {
716 // This program contains at least one dead local variable.
717 // Scan the program for any dead local variables and eliminate them all.
718 for (std::unique_ptr<ProgramElement>& pe : program.ownedElements()) {
719 if (pe->is<FunctionDefinition>()) {
720 visitor.visitProgramElement(*pe);
721 }
722 }
723 break;
724 }
725 }
726 }
727
728 return visitor.fMadeChanges;
729}
730
Ethan Nicholas00543112018-07-31 09:44:36 -0400731bool Compiler::optimize(Program& program) {
John Stiles7247b482021-03-08 10:40:35 -0500732 // The optimizer only needs to run when it is enabled.
733 if (!program.fConfig->fSettings.fOptimize) {
734 return true;
735 }
736
Ethan Nicholas00543112018-07-31 09:44:36 -0400737 SkASSERT(!fErrorCount);
Brian Osman010ce6a2020-10-19 16:34:10 -0400738 ProgramUsage* usage = program.fUsage.get();
John Stiles7954d6c2020-09-01 10:53:02 -0400739
John Stilesb6664582021-03-19 09:46:00 -0400740 if (fErrorCount == 0) {
John Stiles87fc6572021-04-01 14:56:34 +0000741 // Run the inliner only once; it is expensive! Multiple passes can occasionally shake out
742 // more wins, but it's diminishing returns.
743 fInliner.analyze(program.ownedElements(), program.fSymbols, usage);
Ethan Nicholas34b19c52020-09-14 11:33:47 -0400744
John Stilesb6664582021-03-19 09:46:00 -0400745 while (this->removeDeadFunctions(program, usage)) {
746 // Removing dead functions may cause more functions to become unreferenced. Try again.
Ethan Nicholas34b19c52020-09-14 11:33:47 -0400747 }
John Stilesb6664582021-03-19 09:46:00 -0400748 while (this->removeDeadLocalVariables(program, usage)) {
749 // Removing dead variables may cause more variables to become unreferenced. Try again.
750 }
751 if (program.fConfig->fKind != ProgramKind::kFragmentProcessor) {
752 this->removeDeadGlobalVariables(program, usage);
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500753 }
Ethan Nicholas00543112018-07-31 09:44:36 -0400754 }
John Stilesbb1505f2021-02-12 09:17:53 -0500755
756 if (fErrorCount == 0) {
757 this->verifyStaticTests(program);
758 }
759
Ethan Nicholas00543112018-07-31 09:44:36 -0400760 return fErrorCount == 0;
761}
762
Brian Osmanfb32ddf2019-06-18 10:14:20 -0400763#if defined(SKSL_STANDALONE) || SK_SUPPORT_GPU
764
Ethan Nicholas00543112018-07-31 09:44:36 -0400765bool Compiler::toSPIRV(Program& program, OutputStream& out) {
Brian Osman7a20b5c2021-03-15 16:23:33 -0400766 TRACE_EVENT0("skia.shaders", "SkSL::Compiler::toSPIRV");
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -0400767#ifdef SK_ENABLE_SPIRV_VALIDATION
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400768 StringStream buffer;
Brian Osman88cda172020-10-09 12:05:16 -0400769 AutoSource as(this, program.fSource.get());
Brian Osman8b43dad2020-10-09 13:31:42 -0400770 SPIRVCodeGenerator cg(fContext.get(), &program, this, &buffer);
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -0400771 bool result = cg.generateCode();
John Stiles270cec22021-02-17 12:59:36 -0500772 if (result && program.fConfig->fSettings.fValidateSPIRV) {
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -0400773 spvtools::SpirvTools tools(SPV_ENV_VULKAN_1_0);
Ethan Nicholas762466e2017-06-29 10:03:38 -0400774 const String& data = buffer.str();
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400775 SkASSERT(0 == data.size() % 4);
Brian Osman8d09d4a2020-11-24 15:51:06 -0500776 String errors;
777 auto dumpmsg = [&errors](spv_message_level_t, const char*, const spv_position_t&,
778 const char* m) {
779 errors.appendf("SPIR-V validation error: %s\n", m);
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -0400780 };
781 tools.SetMessageConsumer(dumpmsg);
Brian Osman8d09d4a2020-11-24 15:51:06 -0500782
783 // Verify that the SPIR-V we produced is valid. At runtime, we will abort() with a message
784 // explaining the error. In standalone mode (skslc), we will send the message, plus the
785 // entire disassembled SPIR-V (for easier context & debugging) as *our* error message.
786 result = tools.Validate((const uint32_t*) data.c_str(), data.size() / 4);
787
788 if (!result) {
789#if defined(SKSL_STANDALONE)
790 // Convert the string-stream to a SPIR-V disassembly.
791 std::string disassembly;
792 if (tools.Disassemble((const uint32_t*)data.data(), data.size() / 4, &disassembly)) {
793 errors.append(disassembly);
794 }
795 this->error(-1, errors);
796#else
797 SkDEBUGFAILF("%s", errors.c_str());
798#endif
799 }
Ethan Nicholas762466e2017-06-29 10:03:38 -0400800 out.write(data.c_str(), data.size());
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -0400801 }
802#else
Brian Osman88cda172020-10-09 12:05:16 -0400803 AutoSource as(this, program.fSource.get());
Brian Osman8b43dad2020-10-09 13:31:42 -0400804 SPIRVCodeGenerator cg(fContext.get(), &program, this, &out);
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500805 bool result = cg.generateCode();
Ethan Nicholasa6ae1f72017-03-16 09:56:54 -0400806#endif
Ethan Nicholasce33f102016-12-09 17:22:59 -0500807 return result;
808}
809
Ethan Nicholas00543112018-07-31 09:44:36 -0400810bool Compiler::toSPIRV(Program& program, String* out) {
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400811 StringStream buffer;
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500812 bool result = this->toSPIRV(program, buffer);
813 if (result) {
Ethan Nicholas762466e2017-06-29 10:03:38 -0400814 *out = buffer.str();
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500815 }
816 return result;
817}
818
Ethan Nicholas00543112018-07-31 09:44:36 -0400819bool Compiler::toGLSL(Program& program, OutputStream& out) {
Brian Osman7a20b5c2021-03-15 16:23:33 -0400820 TRACE_EVENT0("skia.shaders", "SkSL::Compiler::toGLSL");
Brian Osman88cda172020-10-09 12:05:16 -0400821 AutoSource as(this, program.fSource.get());
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400822 GLSLCodeGenerator cg(fContext.get(), &program, this, &out);
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500823 bool result = cg.generateCode();
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500824 return result;
825}
826
Ethan Nicholas00543112018-07-31 09:44:36 -0400827bool Compiler::toGLSL(Program& program, String* out) {
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400828 StringStream buffer;
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500829 bool result = this->toGLSL(program, buffer);
830 if (result) {
Ethan Nicholas762466e2017-06-29 10:03:38 -0400831 *out = buffer.str();
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500832 }
833 return result;
834}
835
Brian Osmanc0243912020-02-19 15:35:26 -0500836bool Compiler::toHLSL(Program& program, String* out) {
837 String spirv;
838 if (!this->toSPIRV(program, &spirv)) {
839 return false;
840 }
841
842 return SPIRVtoHLSL(spirv, out);
843}
844
Ethan Nicholas00543112018-07-31 09:44:36 -0400845bool Compiler::toMetal(Program& program, OutputStream& out) {
Brian Osman7a20b5c2021-03-15 16:23:33 -0400846 TRACE_EVENT0("skia.shaders", "SkSL::Compiler::toMetal");
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400847 MetalCodeGenerator cg(fContext.get(), &program, this, &out);
Ethan Nicholascc305772017-10-13 16:17:45 -0400848 bool result = cg.generateCode();
Ethan Nicholascc305772017-10-13 16:17:45 -0400849 return result;
850}
851
Ethan Nicholas00543112018-07-31 09:44:36 -0400852bool Compiler::toMetal(Program& program, String* out) {
Timothy Liangb8eeb802018-07-23 16:46:16 -0400853 StringStream buffer;
854 bool result = this->toMetal(program, buffer);
855 if (result) {
856 *out = buffer.str();
857 }
858 return result;
859}
860
Greg Daniela28ea672020-09-25 11:12:56 -0400861#if defined(SKSL_STANDALONE) || GR_TEST_UTILS
Ethan Nicholas00543112018-07-31 09:44:36 -0400862bool Compiler::toCPP(Program& program, String name, OutputStream& out) {
Brian Osman88cda172020-10-09 12:05:16 -0400863 AutoSource as(this, program.fSource.get());
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400864 CPPCodeGenerator cg(fContext.get(), &program, this, name, &out);
Ethan Nicholas762466e2017-06-29 10:03:38 -0400865 bool result = cg.generateCode();
Ethan Nicholas762466e2017-06-29 10:03:38 -0400866 return result;
867}
868
John Stiles82ab3402021-04-13 17:13:03 -0400869bool Compiler::toDSLCPP(Program& program, String name, OutputStream& out) {
870 AutoSource as(this, program.fSource.get());
871 DSLCPPCodeGenerator cg(fContext.get(), &program, this, name, &out);
872 bool result = cg.generateCode();
873 return result;
874}
875
Ethan Nicholas00543112018-07-31 09:44:36 -0400876bool Compiler::toH(Program& program, String name, OutputStream& out) {
Brian Osman88cda172020-10-09 12:05:16 -0400877 AutoSource as(this, program.fSource.get());
Ethan Nicholas26a9aad2018-03-27 14:10:52 -0400878 HCodeGenerator cg(fContext.get(), &program, this, name, &out);
Ethan Nicholas762466e2017-06-29 10:03:38 -0400879 bool result = cg.generateCode();
Ethan Nicholas00543112018-07-31 09:44:36 -0400880 return result;
881}
Greg Daniela28ea672020-09-25 11:12:56 -0400882#endif // defined(SKSL_STANDALONE) || GR_TEST_UTILS
Ethan Nicholas00543112018-07-31 09:44:36 -0400883
Ethan Nicholas2a479a52020-08-18 16:29:45 -0400884#endif // defined(SKSL_STANDALONE) || SK_SUPPORT_GPU
Brian Osman2e29ab52019-09-20 12:19:11 -0400885
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700886Position Compiler::position(int offset) {
Ethan Nicholas3c729892020-12-07 12:47:17 -0500887 if (fSource && offset >= 0) {
888 int line = 1;
889 int column = 1;
890 for (int i = 0; i < offset; i++) {
891 if ((*fSource)[i] == '\n') {
892 ++line;
893 column = 1;
894 }
895 else {
896 ++column;
897 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700898 }
Ethan Nicholas3c729892020-12-07 12:47:17 -0500899 return Position(line, column);
900 } else {
901 return Position(-1, -1);
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700902 }
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700903}
904
905void Compiler::error(int offset, String msg) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700906 fErrorCount++;
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700907 Position pos = this->position(offset);
John Stiles8d3642e2021-01-22 09:50:04 -0500908 fErrorTextLength.push_back(fErrorText.length());
Ethan Nicholas3c729892020-12-07 12:47:17 -0500909 fErrorText += "error: " + (pos.fLine >= 1 ? to_string(pos.fLine) + ": " : "") + msg + "\n";
ethannicholasb3058bd2016-07-01 08:22:01 -0700910}
911
John Stiles8d3642e2021-01-22 09:50:04 -0500912void Compiler::setErrorCount(int c) {
913 if (c < fErrorCount) {
914 fErrorText.resize(fErrorTextLength[c]);
915 fErrorTextLength.resize(c);
916 fErrorCount = c;
917 }
918}
919
Ethan Nicholas95046142021-01-07 10:57:27 -0500920String Compiler::errorText(bool showCount) {
921 if (showCount) {
922 this->writeErrorCount();
923 }
Ethan Nicholas00543112018-07-31 09:44:36 -0400924 fErrorCount = 0;
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400925 String result = fErrorText;
Ethan Nicholas95046142021-01-07 10:57:27 -0500926 fErrorText = "";
ethannicholasb3058bd2016-07-01 08:22:01 -0700927 return result;
928}
929
930void Compiler::writeErrorCount() {
931 if (fErrorCount) {
932 fErrorText += to_string(fErrorCount) + " error";
933 if (fErrorCount > 1) {
934 fErrorText += "s";
935 }
936 fErrorText += "\n";
937 }
938}
939
John Stilesa6841be2020-08-06 14:11:56 -0400940} // namespace SkSL