Debian Codegraph @

src/sksl/SkSLCompiler.cpp

raw
1 /*
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 */
7
8 #include "src/sksl/SkSLCompiler.h"
9
10 #include "include/private/base/SkDebug.h"
11 #include "src/core/SkTraceEvent.h"
12 #include "src/sksl/SkSLAnalysis.h"
13 #include "src/sksl/SkSLContext.h"
14 #include "src/sksl/SkSLDefines.h"
15 #include "src/sksl/SkSLInliner.h"
16 #include "src/sksl/SkSLModule.h"
17 #include "src/sksl/SkSLModuleLoader.h"
18 #include "src/sksl/SkSLParser.h"
19 #include "src/sksl/SkSLPool.h"
20 #include "src/sksl/SkSLProgramKind.h"
21 #include "src/sksl/SkSLProgramSettings.h"
22 #include "src/sksl/analysis/SkSLProgramUsage.h"
23 #include "src/sksl/ir/SkSLProgram.h"
24 #include "src/sksl/ir/SkSLProgramElement.h" // IWYU pragma: keep
25 #include "src/sksl/ir/SkSLSymbolTable.h" // IWYU pragma: keep
26 #include "src/sksl/transform/SkSLTransform.h"
27
28 #include <cstdint>
29 #include <memory>
30 #include <utility>
31
32 #if defined(SKSL_STANDALONE)
33 #include <fstream>
34 #endif
35
36 namespace SkSL {
37
38 // These flags allow tools like Viewer or Nanobench to override the compiler's ProgramSettings.
39 Compiler::OverrideFlag Compiler::sOptimizer = OverrideFlag::kDefault;
40 Compiler::OverrideFlag Compiler::sInliner = OverrideFlag::kDefault;
41
42 class AutoProgramConfig {
43 public:
44 AutoProgramConfig(Context& context, ProgramConfig* config)
45 : fContext(context)
46 , fOldConfig(context.fConfig) {
47 fContext.fConfig = config;
48 }
49
50 ~AutoProgramConfig() {
51 fContext.fConfig = fOldConfig;
52 }
53
54 Context& fContext;
55 ProgramConfig* fOldConfig;
56 };
57
58 Compiler::Compiler() : fErrorReporter(this) {
59 auto moduleLoader = ModuleLoader::Get();
60 fContext = std::make_shared<Context>(moduleLoader.builtinTypes(), fErrorReporter);
61 }
62
63 Compiler::~Compiler() {}
64
65 const Module* Compiler::moduleForProgramKind(ProgramKind kind) {
66 auto m = ModuleLoader::Get();
67 switch (kind) {
68 case ProgramKind::kFragment: return m.loadFragmentModule(this);
69 case ProgramKind::kVertex: return m.loadVertexModule(this);
70 case ProgramKind::kCompute: return m.loadComputeModule(this);
71 case ProgramKind::kGraphiteFragment: return m.loadGraphiteFragmentModule(this);
72 case ProgramKind::kGraphiteVertex: return m.loadGraphiteVertexModule(this);
73 case ProgramKind::kPrivateRuntimeBlender:
74 case ProgramKind::kPrivateRuntimeColorFilter:
75 case ProgramKind::kPrivateRuntimeShader: return m.loadPrivateRTShaderModule(this);
76 case ProgramKind::kRuntimeColorFilter:
77 case ProgramKind::kRuntimeShader:
78 case ProgramKind::kRuntimeBlender:
79 case ProgramKind::kMeshVertex:
80 case ProgramKind::kMeshFragment: return m.loadPublicModule(this);
81 }
82 SkUNREACHABLE;
83 }
84
85 void Compiler::FinalizeSettings(ProgramSettings* settings, ProgramKind kind) {
86 // Honor our optimization-override flags.
87 switch (sOptimizer) {
88 case OverrideFlag::kDefault:
89 break;
90 case OverrideFlag::kOff:
91 settings->fOptimize = false;
92 break;
93 case OverrideFlag::kOn:
94 settings->fOptimize = true;
95 break;
96 }
97
98 switch (sInliner) {
99 case OverrideFlag::kDefault:
100 break;
101 case OverrideFlag::kOff:
102 settings->fInlineThreshold = 0;
103 break;
104 case OverrideFlag::kOn:
105 if (settings->fInlineThreshold == 0) {
106 settings->fInlineThreshold = kDefaultInlineThreshold;
107 }
108 break;
109 }
110
111 // Disable optimization settings that depend on a parent setting which has been disabled.
112 settings->fInlineThreshold *= (int)settings->fOptimize;
113 settings->fRemoveDeadFunctions &= settings->fOptimize;
114 settings->fRemoveDeadVariables &= settings->fOptimize;
115
116 // Runtime effects always allow narrowing conversions.
117 if (ProgramConfig::IsRuntimeEffect(kind)) {
118 settings->fAllowNarrowingConversions = true;
119 }
120 }
121
122 void Compiler::initializeContext(const SkSL::Module* module,
123 ProgramKind kind,
124 ProgramSettings settings,
125 std::string_view source,
126 ModuleType moduleType) {
127 SkASSERT(!fPool);
128 SkASSERT(!fConfig);
129 SkASSERT(!fContext->fSymbolTable);
130 SkASSERT(!fContext->fConfig);
131 SkASSERT(!fContext->fModule);
132
133 // Start the ErrorReporter with a clean slate.
134 this->resetErrors();
135
136 fConfig = std::make_unique<ProgramConfig>();
137 fConfig->fModuleType = moduleType;
138 fConfig->fSettings = settings;
139 fConfig->fKind = kind;
140
141 // Make sure the passed-in settings are valid.
142 FinalizeSettings(&fConfig->fSettings, kind);
143
144 if (settings.fUseMemoryPool) {
145 fPool = Pool::Create();
146 fPool->attachToThread();
147 }
148
149 fContext->fConfig = fConfig.get();
150 fContext->fModule = module;
151 fContext->fErrors->setSource(source);
152
153 // Set up a clean symbol table atop the parent module's symbols.
154 fGlobalSymbols = std::make_unique<SymbolTable>(module->fSymbols.get(),
155 moduleType != ModuleType::program);
156 fGlobalSymbols->markModuleBoundary();
157 fContext->fSymbolTable = fGlobalSymbols.get();
158 }
159
160 void Compiler::cleanupContext() {
161 // Clear out the fields we initialized above.
162 fContext->fConfig = nullptr;
163 fContext->fModule = nullptr;
164 fContext->fErrors->setSource(std::string_view());
165 fContext->fSymbolTable = nullptr;
166
167 fConfig = nullptr;
168 fGlobalSymbols = nullptr;
169
170 if (fPool) {
171 fPool->detachFromThread();
172 fPool = nullptr;
173 }
174 }
175
176 std::unique_ptr<Module> Compiler::compileModule(ProgramKind kind,
177 ModuleType moduleType,
178 std::string moduleSource,
179 const Module* parentModule,
180 bool shouldInline) {
181 SkASSERT(parentModule);
182 SkASSERT(this->errorCount() == 0);
183
184 // Wrap the program source in a pointer so it is guaranteed to be stable across moves.
185 auto sourcePtr = std::make_unique<std::string>(std::move(moduleSource));
186
187 // Compile the module from source, using default program settings (but no memory pooling).
188 ProgramSettings settings;
189 settings.fUseMemoryPool = false;
190 this->initializeContext(parentModule, kind, settings, *sourcePtr, moduleType);
191
192 std::unique_ptr<Module> module = SkSL::Parser(this, settings, kind, std::move(sourcePtr))
193 .moduleInheritingFrom(parentModule);
194
195 this->cleanupContext();
196
197 if (this->errorCount() != 0) {
198 SkDebugf("Unexpected errors compiling %s:\n\n%s\n",
199 ModuleTypeToString(moduleType),
200 this->errorText().c_str());
201 return nullptr;
202 }
203 if (shouldInline) {
204 this->optimizeModuleAfterLoading(kind, *module);
205 }
206 return module;
207 }
208
209 std::unique_ptr<Program> Compiler::convertProgram(ProgramKind kind,
210 std::string programSource,
211 const ProgramSettings& settings) {
212 TRACE_EVENT0("skia.shaders", "SkSL::Compiler::convertProgram");
213
214 // Wrap the program source in a pointer so it is guaranteed to be stable across moves.
215 auto sourcePtr = std::make_unique<std::string>(std::move(programSource));
216
217 // Load the module used by this ProgramKind.
218 const SkSL::Module* module = this->moduleForProgramKind(kind);
219
220 this->initializeContext(module, kind, settings, *sourcePtr, ModuleType::program);
221
222 std::unique_ptr<Program> program = SkSL::Parser(this, settings, kind, std::move(sourcePtr))
223 .programInheritingFrom(module);
224
225 this->cleanupContext();
226 return program;
227 }
228
229 std::unique_ptr<SkSL::Program> Compiler::releaseProgram(
230 std::unique_ptr<std::string> source,
231 std::vector<std::unique_ptr<SkSL::ProgramElement>> programElements) {
232 Pool* pool = fPool.get();
233 auto result = std::make_unique<SkSL::Program>(std::move(source),
234 std::move(fConfig),
235 fContext,
236 std::move(programElements),
237 std::move(fGlobalSymbols),
238 std::move(fPool));
239 fContext->fSymbolTable = nullptr;
240
241 bool success = this->finalize(*result) &&
242 this->optimize(*result);
243 if (pool) {
244 pool->detachFromThread();
245 }
246 return success ? std::move(result) : nullptr;
247 }
248
249 bool Compiler::optimizeModuleBeforeMinifying(ProgramKind kind, Module& module, bool shrinkSymbols) {
250 SkASSERT(this->errorCount() == 0);
251
252 auto m = SkSL::ModuleLoader::Get();
253
254 // Create a temporary program configuration with default settings.
255 ProgramConfig config;
256 config.fModuleType = module.fModuleType;
257 config.fKind = kind;
258 AutoProgramConfig autoConfig(this->context(), &config);
259
260 std::unique_ptr<ProgramUsage> usage = Analysis::GetUsage(module);
261
262 if (shrinkSymbols) {
263 // Assign shorter names to symbols as long as it won't change the external meaning of the
264 // code.
265 Transform::RenamePrivateSymbols(this->context(), module, usage.get(), kind);
266
267 // Replace constant variables with their literal values to save space.
268 Transform::ReplaceConstVarsWithLiterals(module, usage.get());
269 }
270
271 // Remove any unreachable code.
272 Transform::EliminateUnreachableCode(module, usage.get());
273
274 // We can only remove dead functions from runtime shaders, since runtime-effect helper functions
275 // are isolated from other parts of the program. In a module, an unreferenced function is
276 // intended to be called by the code that includes the module.
277 if (kind == ProgramKind::kRuntimeShader) {
278 while (Transform::EliminateDeadFunctions(this->context(), module, usage.get())) {
279 // Removing dead functions may cause more functions to become unreferenced. Try again.
280 }
281 }
282
283 while (Transform::EliminateDeadLocalVariables(this->context(), module, usage.get())) {
284 // Removing dead variables may cause more variables to become unreferenced. Try again.
285 }
286
287 // Runtime shaders are isolated from other parts of the program via name mangling, so we can
288 // eliminate public globals if they aren't referenced. Otherwise, we only eliminate private
289 // globals (prefixed with `$`) to avoid changing the meaning of the module code.
290 bool onlyPrivateGlobals = !ProgramConfig::IsRuntimeEffect(kind);
291 while (Transform::EliminateDeadGlobalVariables(this->context(), module, usage.get(),
292 onlyPrivateGlobals)) {
293 // Repeat until no changes occur.
294 }
295
296 // We eliminate empty statements to avoid runs of `;;;;;;` caused by the previous passes.
297 SkSL::Transform::EliminateEmptyStatements(module);
298
299 // We can eliminate `{}` around single-statement blocks.
300 SkSL::Transform::EliminateUnnecessaryBraces(this->context(), module);
301
302 // We can convert `float4(myFloat)` with `myFloat.xxxx` to save a few characters.
303 SkSL::Transform::ReplaceSplatCastsWithSwizzles(this->context(), module);
304
305 // Make sure that program usage is still correct after the optimization pass is complete.
306 SkASSERT(*usage == *Analysis::GetUsage(module));
307
308 return this->errorCount() == 0;
309 }
310
311 bool Compiler::optimizeModuleAfterLoading(ProgramKind kind, Module& module) {
312 SkASSERT(this->errorCount() == 0);
313
314 #ifndef SK_ENABLE_OPTIMIZE_SIZE
315 // Create a temporary program configuration with default settings.
316 ProgramConfig config;
317 config.fModuleType = module.fModuleType;
318 config.fKind = kind;
319 AutoProgramConfig autoConfig(this->context(), &config);
320
321 std::unique_ptr<ProgramUsage> usage = Analysis::GetUsage(module);
322
323 // Perform inline-candidate analysis and inline any functions deemed suitable.
324 Inliner inliner(fContext.get());
325 while (this->errorCount() == 0) {
326 if (!this->runInliner(&inliner, module.fElements, module.fSymbols.get(), usage.get())) {
327 break;
328 }
329 }
330 // Make sure that program usage is still correct after the optimization pass is complete.
331 SkASSERT(*usage == *Analysis::GetUsage(module));
332 #endif
333
334 return this->errorCount() == 0;
335 }
336
337 bool Compiler::optimize(Program& program) {
338 // The optimizer only needs to run when it is enabled.
339 if (!program.fConfig->fSettings.fOptimize) {
340 return true;
341 }
342
343 SkASSERT(!this->errorCount());
344 if (this->errorCount() == 0) {
345 #ifndef SK_ENABLE_OPTIMIZE_SIZE
346 // Run the inliner only once; it is expensive! Multiple passes can occasionally shake out
347 // more wins, but it's diminishing returns.
348 Inliner inliner(fContext.get());
349 this->runInliner(&inliner, program.fOwnedElements, program.fSymbols.get(),
350 program.fUsage.get());
351 #endif
352
353 // Unreachable code can confuse some drivers, so it's worth removing. (skbug.com/40043094)
354 Transform::EliminateUnreachableCode(program);
355
356 while (Transform::EliminateDeadFunctions(program)) {
357 // Removing dead functions may cause more functions to become unreferenced. Try again.
358 }
359 while (Transform::EliminateDeadLocalVariables(program)) {
360 // Removing dead variables may cause more variables to become unreferenced. Try again.
361 }
362 while (Transform::EliminateDeadGlobalVariables(program)) {
363 // Repeat until no changes occur.
364 }
365 // Make sure that program usage is still correct after the optimization pass is complete.
366 SkASSERT(*program.usage() == *Analysis::GetUsage(program));
367
368 // Make sure that variables are still declared in the correct symbol tables.
369 SkDEBUGCODE(Analysis::CheckSymbolTableCorrectness(program));
370 }
371
372 return this->errorCount() == 0;
373 }
374
375 void Compiler::runInliner(Program& program) {
376 #ifndef SK_ENABLE_OPTIMIZE_SIZE
377 AutoProgramConfig autoConfig(this->context(), program.fConfig.get());
378 Inliner inliner(fContext.get());
379 this->runInliner(&inliner, program.fOwnedElements, program.fSymbols.get(),
380 program.fUsage.get());
381 #endif
382 }
383
384 bool Compiler::runInliner(Inliner* inliner,
385 const std::vector<std::unique_ptr<ProgramElement>>& elements,
386 SymbolTable* symbols,
387 ProgramUsage* usage) {
388 #ifdef SK_ENABLE_OPTIMIZE_SIZE
389 return true;
390 #else
391 // The program's SymbolTable was taken out of the context when the program was bundled, but
392 // the inliner creates IR objects which may expect the context to hold a valid SymbolTable.
393 SkASSERT(!fContext->fSymbolTable);
394 fContext->fSymbolTable = symbols;
395
396 bool result = inliner->analyze(elements, symbols, usage);
397
398 fContext->fSymbolTable = nullptr;
399 return result;
400 #endif
401 }
402
403 bool Compiler::finalize(Program& program) {
404 // Copy all referenced built-in functions into the Program.
405 Transform::FindAndDeclareBuiltinFunctions(program);
406
407 // Variables defined in modules need their declaring elements added to the program.
408 Transform::FindAndDeclareBuiltinVariables(program);
409
410 // Structs from module code need to be added to the program's shared elements.
411 Transform::FindAndDeclareBuiltinStructs(program);
412
413 // Do one last correctness-check pass. This looks for dangling FunctionReference/TypeReference
414 // expressions, and reports them as errors.
415 Analysis::DoFinalizationChecks(program);
416
417 if (fContext->fConfig->strictES2Mode() && this->errorCount() == 0) {
418 // Enforce Appendix A, Section 5 of the GLSL ES 1.00 spec -- Indexing. This logic assumes
419 // that all loops meet the criteria of Section 4, and if they don't, could crash.
420 for (const auto& pe : program.fOwnedElements) {
421 Analysis::ValidateIndexingForES2(*pe, this->errorReporter());
422 }
423 }
424 if (this->errorCount() == 0) {
425 Analysis::CheckProgramStructure(program);
426
427 // Make sure that variables are declared in the symbol tables that immediately enclose them.
428 SkDEBUGCODE(Analysis::CheckSymbolTableCorrectness(program));
429 }
430
431 // Make sure that program usage is still correct after finalization is complete.
432 SkASSERT(*program.usage() == *Analysis::GetUsage(program));
433
434 return this->errorCount() == 0;
435 }
436
437 void Compiler::handleError(std::string_view msg, Position pos) {
438 fErrorText += "error: ";
439 bool printLocation = false;
440 std::string_view src = this->errorReporter().source();
441 int line = -1;
442 if (pos.valid()) {
443 line = pos.line(src);
444 printLocation = pos.startOffset() < (int)src.length();
445 fErrorText += std::to_string(line) + ": ";
446 }
447 fErrorText += std::string(msg) + "\n";
448 if (printLocation) {
449 const int kMaxSurroundingChars = 100;
450
451 // Find the beginning of the line.
452 int lineStart = pos.startOffset();
453 while (lineStart > 0) {
454 if (src[lineStart - 1] == '\n') {
455 break;
456 }
457 --lineStart;
458 }
459
460 // We don't want to show more than 100 characters surrounding the error, so push the line
461 // start forward and add a leading ellipsis if there would be more than this.
462 std::string lineText;
463 std::string caretText;
464 if ((pos.startOffset() - lineStart) > kMaxSurroundingChars) {
465 lineStart = pos.startOffset() - kMaxSurroundingChars;
466 lineText = "...";
467 caretText = " ";
468 }
469
470 // Echo the line. Again, we don't want to show more than 100 characters after the end of the
471 // error, so truncate with a trailing ellipsis if needed.
472 const char* lineSuffix = "...\n";
473 int lineStop = pos.endOffset() + kMaxSurroundingChars;
474 if (lineStop >= (int)src.length()) {
475 lineStop = src.length() - 1;
476 lineSuffix = "\n"; // no ellipsis if we reach end-of-file
477 }
478 for (int i = lineStart; i < lineStop; ++i) {
479 char c = src[i];
480 if (c == '\n') {
481 lineSuffix = "\n"; // no ellipsis if we reach end-of-line
482 break;
483 }
484 switch (c) {
485 case '\t': lineText += " "; break;
486 case '\0': lineText += " "; break;
487 default: lineText += src[i]; break;
488 }
489 }
490 fErrorText += lineText + lineSuffix;
491
492 // print the carets underneath it, pointing to the range in question
493 for (int i = lineStart; i < (int)src.length(); i++) {
494 if (i >= pos.endOffset()) {
495 break;
496 }
497 switch (src[i]) {
498 case '\t':
499 caretText += (i >= pos.startOffset()) ? "^^^^" : " ";
500 break;
501 case '\n':
502 SkASSERT(i >= pos.startOffset());
503 // use an ellipsis if the error continues past the end of the line
504 caretText += (pos.endOffset() > i + 1) ? "..." : "^";
505 i = src.length();
506 break;
507 default:
508 caretText += (i >= pos.startOffset()) ? '^' : ' ';
509 break;
510 }
511 }
512 fErrorText += caretText + '\n';
513 }
514 }
515
516 std::string Compiler::errorText(bool showCount) {
517 if (showCount) {
518 this->writeErrorCount();
519 }
520 std::string result = fErrorText;
521 this->resetErrors();
522 return result;
523 }
524
525 void Compiler::writeErrorCount() {
526 int count = this->errorCount();
527 if (count) {
528 fErrorText += std::to_string(count) +
529 ((count == 1) ? " error\n" : " errors\n");
530 }
531 }
532
533 } // namespace SkSL