-
Notifications
You must be signed in to change notification settings - Fork 850
Expand file tree
/
Copy pathStringLifting.cpp
More file actions
383 lines (355 loc) · 14.9 KB
/
StringLifting.cpp
File metadata and controls
383 lines (355 loc) · 14.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
/*
* Copyright 2025 WebAssembly Community Group participants
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
//
// Lift JS string imports into wasm strings in Binaryen IR, which can then be
// fully optimized. Typically StringLowering would be run later to lower them
// back down.
//
// A pass argument allows customizing the module name for string constants:
//
// --pass-arg=string-constants-module@MODULE_NAME
//
#include "ir/utils.h"
#include "pass.h"
#include "passes/string-utils.h"
#include "support/json.h"
#include "support/string.h"
#include "wasm-builder.h"
#include "wasm.h"
namespace wasm {
struct StringLifting : public Pass {
// Maps the global name of an imported string to the actual string.
std::unordered_map<Name, Name> importedStrings;
// Imported string functions. Imports that do not exist remain null.
Name fromCharCodeArrayImport;
Name intoCharCodeArrayImport;
Name fromCodePointImport;
Name concatImport;
Name equalsImport;
Name testImport;
Name compareImport;
Name lengthImport;
Name charCodeAtImport;
Name substringImport;
// Shared imported string functions.
Name fromCharCodeArraySharedImport;
Name intoCharCodeArraySharedImport;
Name fromCodePointSharedImport;
Name concatSharedImport;
Name equalsSharedImport;
Name testSharedImport;
Name compareSharedImport;
Name lengthSharedImport;
Name charCodeAtSharedImport;
Name substringSharedImport;
void run(Module* module) override {
// Whether we found any work to do.
bool found = false;
// Imported string constants look like
//
// (import "\'" "bar" (global $string.bar.internal.name (ref extern)))
//
// That is, they are imported from module "'" and the basename is the
// actual string. Find them all so we can apply them.
Name stringConstsModule =
getArgumentOrDefault("string-constants-module", WasmStringConstsModule);
for (auto& global : module->globals) {
if (!global->imported()) {
continue;
}
if (global->module == stringConstsModule) {
// Encode from WTF-8 to WTF-16.
auto wtf8 = global->base;
std::stringstream wtf16;
bool valid = String::convertWTF8ToWTF16(wtf16, wtf8.str);
if (!valid) {
Fatal() << "Bad string to lift: " << wtf8;
}
importedStrings[global->name] = wtf16.str();
found = true;
}
}
// Imported strings may also be found in the string section.
auto stringSectionIter = std::find_if(
module->customSections.begin(),
module->customSections.end(),
[&](CustomSection& section) { return section.name == "string.consts"; });
if (stringSectionIter != module->customSections.end()) {
// We found the string consts section. Parse it.
auto& section = *stringSectionIter;
auto copy = section.data;
json::Value array;
array.parse(copy.data(), json::Value::WTF16);
if (!array.isArray()) {
Fatal() << "StringLifting: string.const section should be a JSON array";
}
// We have the array of constants from the section. Find globals that
// refer to it.
for (auto& global : module->globals) {
if (!global->imported() || global->module != "string.const") {
continue;
}
// The index in the array is the basename.
Index index = std::stoi(std::string(global->base.str));
if (index >= array.size()) {
Fatal() << "StringLifting: bad index in string.const section";
}
auto item = array[index];
if (!item->isString()) {
Fatal()
<< "StringLifting: string.const section entry is not a string";
}
if (importedStrings.count(global->name)) {
Fatal() << "StringLifting: string.const section tramples other const";
}
importedStrings[global->name] = item->getIString();
}
// Remove the custom section: After lifting it has no purpose (and could
// cause problems with repeated lifting/lowering).
module->customSections.erase(stringSectionIter);
}
auto array16 = Type(HeapTypes::getMutI16Array(), Nullable);
auto refExtern = Type(HeapType::ext, NonNullable);
auto externref = Type(HeapType::ext, Nullable);
auto i32 = Type::i32;
auto sharedArray16 = Type(HeapTypes::getSharedMutI16Array(), Nullable);
auto refSharedExtern =
Type(HeapType(HeapType::ext).getBasic(Shared), NonNullable);
auto sharedExternref =
Type(HeapType(HeapType::ext).getBasic(Shared), Nullable);
// Find imported string functions.
for (auto& func : module->functions) {
if (!func->imported() || func->module != WasmStringsModule) {
continue;
}
auto type = func->type;
if (func->base == "fromCharCodeArray") {
if (type.getHeapType() ==
Signature(Type({array16, i32, i32}), refExtern)) {
fromCharCodeArrayImport = func->name;
found = true;
} else if (type.getHeapType() ==
Signature(Type({sharedArray16, i32, i32}),
refSharedExtern)) {
fromCharCodeArraySharedImport = func->name;
found = true;
} else {
Fatal() << "StringLifting: bad type for fromCharCodeArray: " << type;
}
} else if (func->base == "fromCodePoint") {
if (type.getHeapType() == Signature(i32, refExtern)) {
fromCodePointImport = func->name;
found = true;
} else if (type.getHeapType() == Signature(i32, refSharedExtern)) {
fromCodePointSharedImport = func->name;
found = true;
} else {
Fatal() << "StringLifting: bad type for fromCodePoint: " << type;
}
} else if (func->base == "concat") {
if (type.getHeapType() ==
Signature(Type({externref, externref}), refExtern)) {
concatImport = func->name;
found = true;
} else if (type.getHeapType() ==
Signature(Type({sharedExternref, sharedExternref}),
refSharedExtern)) {
concatSharedImport = func->name;
found = true;
} else {
Fatal() << "StringLifting: bad type for concat: " << type;
}
} else if (func->base == "intoCharCodeArray") {
if (type.getHeapType() ==
Signature(Type({externref, array16, i32}), i32)) {
intoCharCodeArrayImport = func->name;
found = true;
} else if (type.getHeapType() ==
Signature(Type({sharedExternref, sharedArray16, i32}),
i32)) {
intoCharCodeArraySharedImport = func->name;
found = true;
} else {
Fatal() << "StringLifting: bad type for intoCharCodeArray: " << type;
}
} else if (func->base == "equals") {
if (type.getHeapType() ==
Signature(Type({externref, externref}), i32)) {
equalsImport = func->name;
found = true;
} else if (type.getHeapType() ==
Signature(Type({sharedExternref, sharedExternref}), i32)) {
equalsSharedImport = func->name;
found = true;
} else {
Fatal() << "StringLifting: bad type for equals: " << type;
}
} else if (func->base == "test") {
if (type.getHeapType() == Signature(Type({externref}), i32)) {
testImport = func->name;
found = true;
} else if (type.getHeapType() ==
Signature(Type({sharedExternref}), i32)) {
testSharedImport = func->name;
found = true;
} else {
Fatal() << "StringLifting: bad type for test: " << type;
}
} else if (func->base == "compare") {
if (type.getHeapType() ==
Signature(Type({externref, externref}), i32)) {
compareImport = func->name;
found = true;
} else if (type.getHeapType() ==
Signature(Type({sharedExternref, sharedExternref}), i32)) {
compareSharedImport = func->name;
found = true;
} else {
Fatal() << "StringLifting: bad type for compare: " << type;
}
} else if (func->base == "length") {
if (type.getHeapType() == Signature(Type({externref}), i32)) {
lengthImport = func->name;
found = true;
} else if (type.getHeapType() ==
Signature(Type({sharedExternref}), i32)) {
lengthSharedImport = func->name;
found = true;
} else {
Fatal() << "StringLifting: bad type for length: " << type;
}
} else if (func->base == "charCodeAt") {
if (type.getHeapType() == Signature(Type({externref, i32}), i32)) {
charCodeAtImport = func->name;
found = true;
} else if (type.getHeapType() ==
Signature(Type({sharedExternref, i32}), i32)) {
charCodeAtSharedImport = func->name;
found = true;
} else {
Fatal() << "StringLifting: bad type for charCodeAt: " << type;
}
} else if (func->base == "substring") {
if (type.getHeapType() ==
Signature(Type({externref, i32, i32}), refExtern)) {
substringImport = func->name;
found = true;
} else if (type.getHeapType() ==
Signature(Type({sharedExternref, i32, i32}),
refSharedExtern)) {
substringSharedImport = func->name;
found = true;
} else {
Fatal() << "StringLifting: bad type for substring: " << type;
}
} else {
std::cerr << "warning: unknown strings import: " << func->base << '\n';
}
}
if (!found) {
// Nothing to do.
return;
}
struct StringApplier : public WalkerPass<PostWalker<StringApplier>> {
bool isFunctionParallel() override { return true; }
const StringLifting& parent;
StringApplier(const StringLifting& parent) : parent(parent) {}
std::unique_ptr<Pass> create() override {
return std::make_unique<StringApplier>(parent);
}
bool modified = false;
void visitGlobalGet(GlobalGet* curr) {
// Replace global.gets of imported strings with string.const.
auto iter = parent.importedStrings.find(curr->name);
if (iter != parent.importedStrings.end()) {
auto wtf16 = iter->second;
replaceCurrent(Builder(*getModule()).makeStringConst(wtf16.str));
modified = true;
}
}
void visitCall(Call* curr) {
Builder builder(*getModule());
// Replace calls of imported string methods with stringref operations.
if (curr->target == parent.fromCharCodeArrayImport ||
curr->target == parent.fromCharCodeArraySharedImport) {
replaceCurrent(builder.makeStringNew(StringNewWTF16Array,
curr->operands[0],
curr->operands[1],
curr->operands[2]));
} else if (curr->target == parent.fromCodePointImport ||
curr->target == parent.fromCodePointSharedImport) {
replaceCurrent(
builder.makeStringNew(StringNewFromCodePoint, curr->operands[0]));
} else if (curr->target == parent.concatImport ||
curr->target == parent.concatSharedImport) {
replaceCurrent(
builder.makeStringConcat(curr->operands[0], curr->operands[1]));
} else if (curr->target == parent.intoCharCodeArrayImport ||
curr->target == parent.intoCharCodeArraySharedImport) {
replaceCurrent(builder.makeStringEncode(StringEncodeWTF16Array,
curr->operands[0],
curr->operands[1],
curr->operands[2]));
} else if (curr->target == parent.equalsImport ||
curr->target == parent.equalsSharedImport) {
replaceCurrent(builder.makeStringEq(
StringEqEqual, curr->operands[0], curr->operands[1]));
} else if (curr->target == parent.testImport ||
curr->target == parent.testSharedImport) {
replaceCurrent(builder.makeStringTest(curr->operands[0]));
} else if (curr->target == parent.compareImport ||
curr->target == parent.compareSharedImport) {
replaceCurrent(builder.makeStringEq(
StringEqCompare, curr->operands[0], curr->operands[1]));
} else if (curr->target == parent.lengthImport ||
curr->target == parent.lengthSharedImport) {
replaceCurrent(
builder.makeStringMeasure(StringMeasureWTF16, curr->operands[0]));
} else if (curr->target == parent.charCodeAtImport ||
curr->target == parent.charCodeAtSharedImport) {
replaceCurrent(
builder.makeStringWTF16Get(curr->operands[0], curr->operands[1]));
} else if (curr->target == parent.substringImport ||
curr->target == parent.substringSharedImport) {
replaceCurrent(builder.makeStringSliceWTF(
curr->operands[0], curr->operands[1], curr->operands[2]));
}
}
void visitFunction(Function* curr) {
// If we made modifications then we need to refinalize, as we replace
// externrefs with stringrefs, a subtype.
if (modified) {
ReFinalize().walkFunctionInModule(curr, getModule());
}
}
};
StringApplier applier(*this);
applier.run(getPassRunner(), module);
applier.walkModuleCode(module);
// TODO: Add casts. We generate new string.* instructions, and all their
// string inputs should be stringref, not externref, but we have not
// converted all externrefs to stringrefs (since some externrefs might
// be something else). It is not urgent to fix this as the validator
// accepts externrefs there atm, and since toolchains will lower
// strings out at the end anyhow (which would remove such casts). Note
// that if we add a type import for stringref then this problem would
// become a lot simpler (we'd convert that type to stringref).
// Enable the feature so the module validates.
module->features.enable(FeatureSet::Strings);
}
};
Pass* createStringLiftingPass() { return new StringLifting(); }
} // namespace wasm