Flutter Engine
The Flutter Engine
Loading...
Searching...
No Matches
SkSLMangler.cpp
Go to the documentation of this file.
1/*
2 * Copyright 2021 Google LLC.
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
9
14
15#include <algorithm>
16#include <cstring>
17#include <ctype.h>
18
19namespace SkSL {
20
21std::string Mangler::uniqueName(std::string_view baseName, SymbolTable* symbolTable) {
22 SkASSERT(symbolTable);
23
24 // Private names might begin with a $. Strip that off.
25 if (skstd::starts_with(baseName, '$')) {
26 baseName.remove_prefix(1);
27 }
28
29 // The inliner runs more than once, so the base name might already have been mangled and have a
30 // prefix like "_123_x". Let's strip that prefix off to make the generated code easier to read.
31 if (skstd::starts_with(baseName, '_')) {
32 // Determine if we have a string of digits.
33 int offset = 1;
34 while (isdigit(baseName[offset])) {
35 ++offset;
36 }
37 // If we found digits, another underscore, and anything else, that's the mangler prefix.
38 // Strip it off.
39 if (offset > 1 && baseName[offset] == '_' && baseName[offset + 1] != '\0') {
40 baseName.remove_prefix(offset + 1);
41 } else {
42 // This name doesn't contain a mangler prefix, but it does start with an underscore.
43 // OpenGL disallows two consecutive underscores anywhere in the string, and we'll be
44 // adding one as part of the mangler prefix, so strip the leading underscore.
45 baseName.remove_prefix(1);
46 }
47 }
48
49 // Append a unique numeric prefix to avoid name overlap. Check the symbol table to make sure
50 // we're not reusing an existing name. (Note that within a single compilation pass, this check
51 // isn't fully comprehensive, as code isn't always generated in top-to-bottom order.)
52
53 // This code is a performance hotspot. Assemble the string manually to save a few cycles.
54 char uniqueName[256];
55 uniqueName[0] = '_';
56 char* uniqueNameEnd = uniqueName + std::size(uniqueName);
57 for (;;) {
58 // _123
59 char* endPtr = SkStrAppendS32(uniqueName + 1, fCounter++);
60
61 // _123_
62 *endPtr++ = '_';
63
64 // _123_baseNameTruncatedToFit (no null terminator, because string_view doesn't require one)
65 int baseNameCopyLength = std::min<int>(baseName.size(), uniqueNameEnd - endPtr);
66 memcpy(endPtr, baseName.data(), baseNameCopyLength);
67 endPtr += baseNameCopyLength;
68
69 std::string_view uniqueNameView(uniqueName, endPtr - uniqueName);
70 if (symbolTable->find(uniqueNameView) == nullptr) {
71 return std::string(uniqueNameView);
72 }
73 }
74}
75
76} // namespace SkSL
#define SkASSERT(cond)
Definition SkAssert.h:116
char * SkStrAppendS32(char buffer[], int32_t)
Definition SkString.cpp:120
std::string uniqueName(std::string_view baseName, SymbolTable *symbolTable)
const Symbol * find(std::string_view name) const
constexpr bool starts_with(std::string_view str, std::string_view prefix)
Point offset