Repository navigation
Expand file tree
/
Copy pathdata_plan.rs
More file actions
396 lines (369 loc) · 13.2 KB
/
Copy pathdata_plan.rs
File metadata and controls
396 lines (369 loc) · 13.2 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
384
385
386
387
388
389
390
391
392
393
394
395
396
use std::{cell::RefCell, collections::HashMap};
use wasm_encoder::{ConstExpr, DataSection};
use crate::{
ast::{Program, SettingFileFilter, SettingKind, StateSource},
signature::parse_signature,
wasm_ir,
};
use super::memory_plan::LinearMemoryLayout;
use super::reachability::Reachability;
use super::{dependencies::BackendDependencies, runtime_helpers::float_format};
#[cfg(test)]
mod tests;
pub(super) struct StaticData {
pub strings: StringPool,
pub signatures: SignaturePool,
pub float_format: Option<FloatFormatData>,
layout: LinearMemoryLayout,
}
pub(super) struct FloatFormatData {
pub pow10_significands: i32,
bytes: Vec<u8>,
}
pub(super) struct StringPool {
base: u32,
bytes: Vec<u8>,
entries: HashMap<String, (u32, u32)>,
}
/// Passive initializer bytes for GC strings, collected only during emission.
/// These bytes never occupy linear memory or require a runtime reader helper.
#[derive(Default)]
pub(super) struct GcStringLiterals {
segment: Option<u32>,
pool: RefCell<GcStringPool>,
}
#[derive(Default)]
struct GcStringPool {
bytes: Vec<u8>,
offsets: HashMap<String, u32>,
}
impl GcStringLiterals {
pub fn enable(&mut self, segment: u32) {
self.segment = Some(segment);
}
pub fn intern(&self, value: &str) -> Option<(u32, u32)> {
let segment = self.segment?;
let mut pool = self.pool.borrow_mut();
let existing = pool.offsets.get(value).copied();
let length = u32::try_from(value.len()).expect("GC strings must fit wasm32");
let old_length = u32::try_from(pool.bytes.len()).expect("GC string data must fit wasm32");
let offset = existing.unwrap_or(old_length);
let new_length = if existing.is_some() {
old_length
} else {
old_length
.checked_add(length)
.expect("GC string data must fit wasm32")
};
// The GC opcode and array type index have the same size in both forms.
// Each fixed-array byte needs an i32.const and its signed LEB operand.
let fixed = uleb_len(length)
+ value
.bytes()
.map(|byte| 1 + sleb_len(i32::from(byte)))
.sum::<usize>();
let from_data = 2 + sleb_len(offset as i32) + sleb_len(length as i32) + uleb_len(segment);
let data_growth = if existing.is_some() {
0
} else if pool.bytes.is_empty() {
// Passive flag, byte count, DataCount section, and segment-count
// growth. Reserve four bytes for growth of the data-section size
// prefix (the full u32 LEB range), whose old size is not known here.
value.len() + 1 + uleb_len(length) + 2 + uleb_len(segment + 1) + uleb_len(segment + 1)
- uleb_len(segment)
+ 4
} else {
value.len() + uleb_len(new_length) - uleb_len(old_length) + 4
};
if from_data + data_growth >= fixed {
return None;
}
if existing.is_none() {
pool.bytes.extend_from_slice(value.as_bytes());
pool.offsets.insert(value.to_owned(), offset);
}
Some((segment, offset))
}
pub fn append_to(&self, data: &mut DataSection) -> bool {
let pool = self.pool.borrow();
if pool.bytes.is_empty() {
return false;
}
assert_eq!(self.segment, Some(data.len()));
data.passive(pool.bytes.iter().copied());
true
}
}
fn uleb_len(value: u32) -> usize {
(32 - value.leading_zeros()).max(1).div_ceil(7) as usize
}
fn sleb_len(value: i32) -> usize {
let magnitude = if value < 0 { !value } else { value } as u32;
(33 - magnitude.leading_zeros()).div_ceil(7) as usize
}
#[derive(Clone, Copy)]
pub(super) struct SignatureEntry {
pub needle: u32,
pub mask: u32,
pub len: u32,
}
#[derive(Default)]
pub(super) struct SignaturePool {
base: u32,
bytes: Vec<u8>,
entries: HashMap<String, SignatureEntry>,
}
impl StaticData {
pub fn collect(
program: &Program,
process_names: &[&str],
automatic_shape: Option<&crate::shape_selection::ShapeSelectionPlan>,
wasm_ir: &wasm_ir::Program,
reachability: &Reachability,
dependencies: &BackendDependencies,
) -> Self {
let state = program.state.as_ref().expect("checked programs have state");
let mut strings = StringPool::new();
for process in process_names {
strings.intern(process);
}
if let Some(plan) = automatic_shape {
let report = plan.failure_report(program);
for message in report.messages() {
strings.intern(message);
}
}
for field in state.all_fields() {
if let StateSource::Pointer(path) = &field.source
&& let crate::ast::PointerPathBase::Module { name, .. } = &path.base
{
strings.intern(name);
}
}
for setting in &program.settings {
strings.intern(setting.runtime_key());
strings.intern(&setting.description);
if let Some(tooltip) = &setting.tooltip {
strings.intern(tooltip);
}
match &setting.kind {
SettingKind::Text { default, .. } => {
strings.intern(default);
}
SettingKind::Choice { options, .. } => {
for option in options {
strings.intern(&option.variant);
strings.intern(&option.description);
}
}
SettingKind::File { filters, .. } => {
for filter in filters {
match filter {
SettingFileFilter::Name {
description,
pattern,
} => {
if let Some(description) = description {
strings.intern(description);
}
strings.intern(pattern);
}
SettingFileFilter::Mime { value: mime, .. } => {
strings.intern(mime);
}
}
}
}
SettingKind::Bool { .. } | SettingKind::Title { .. } => {}
}
}
for expression in wasm_ir.expressions() {
if !reachability.contains_expression(expression.id) {
continue;
}
// Ordinary literals are emitted as GC arrays. Only module queries
// pass an expression's literal directly to the linear-memory ABI.
// Interning every reachable literal also retained discarded error
// messages from Unity's fallible metadata readers.
if let wasm_ir::ExpressionKind::Call { target, arguments } = &expression.kind
&& super::resolved_intrinsic(target)
== Some(crate::stdlib::IntrinsicId::ProcessModule)
{
let wasm_ir::ExpressionKind::String(name) = &wasm_ir
.expression(arguments[0])
.expect("module name belongs to Wasm IR")
.kind
else {
unreachable!("module queries require a literal name")
};
strings.intern(name);
}
}
let dynamic_signatures = super::dependencies::dynamic_signatures(wasm_ir, reachability);
let mut signatures = SignaturePool::new();
for expression in wasm_ir.expressions() {
if !reachability.contains_expression(expression.id) {
continue;
}
if !dynamic_signatures
&& let wasm_ir::ExpressionKind::Signature(signature) = &expression.kind
{
signatures.intern(signature);
}
}
let float_format_bytes = if dependencies.uses_float_format() {
float_format::pow10_significands_bytes()
} else {
Vec::new()
};
let static_data_len = strings
.bytes
.len()
.checked_add(signatures.bytes.len())
.and_then(|length| length.checked_add(float_format_bytes.len()))
.expect("static data length must fit the host address space");
let layout = LinearMemoryLayout::plan(
static_data_len,
dependencies.scratch_requirements(signatures.maximum_len()),
);
strings.base = layout.static_data_start();
signatures.base = strings
.base
.checked_add(
u32::try_from(strings.bytes.len())
.expect("string data must fit WebAssembly linear memory"),
)
.expect("string data must fit WebAssembly linear memory");
let float_format = (!float_format_bytes.is_empty()).then(|| FloatFormatData {
pow10_significands: i32::try_from(signatures.base as usize + signatures.bytes.len())
.expect("float-format data address must fit wasm32"),
bytes: float_format_bytes,
});
Self {
strings,
signatures,
float_format,
layout,
}
}
pub fn layout(&self) -> LinearMemoryLayout {
self.layout
}
pub fn segment_count(&self) -> u32 {
u32::from(!self.strings.bytes.is_empty())
+ u32::from(!self.signatures.bytes.is_empty())
+ u32::from(self.float_format.is_some())
}
pub fn encode(&self) -> DataSection {
debug_assert_eq!(
self.layout.static_data_end(),
u64::from(self.signatures.base)
+ self.signatures.bytes.len() as u64
+ self
.float_format
.as_ref()
.map_or(0, |float_format| float_format.bytes.len() as u64)
);
let mut section = DataSection::new();
if !self.strings.bytes.is_empty() {
section.active(
0,
&ConstExpr::i32_const(self.strings.base as i32),
self.strings.bytes.iter().copied(),
);
}
if !self.signatures.bytes.is_empty() {
section.active(
0,
&ConstExpr::i32_const(self.signatures.base as i32),
self.signatures.bytes.iter().copied(),
);
}
if let Some(float_format) = &self.float_format {
section.active(
0,
&ConstExpr::i32_const(float_format.pow10_significands),
float_format.bytes.iter().copied(),
);
}
section
}
}
impl SignaturePool {
fn new() -> Self {
Self::default()
}
fn intern(&mut self, signature: &str) {
if self.entries.contains_key(signature) {
return;
}
let (needle, mask) = parse_signature(signature).expect("signatures were type checked");
let needle_ptr = self.base + self.bytes.len() as u32;
self.bytes.extend_from_slice(&needle);
let mask_ptr = self.base + self.bytes.len() as u32;
self.bytes.extend_from_slice(&mask);
self.entries.insert(
signature.to_owned(),
SignatureEntry {
needle: needle_ptr,
mask: mask_ptr,
len: needle.len() as u32,
},
);
}
pub fn get(&self, signature: &str) -> SignatureEntry {
let entry = self.entries[signature];
SignatureEntry {
needle: self
.base
.checked_add(entry.needle)
.expect("signature address must fit wasm32"),
mask: self
.base
.checked_add(entry.mask)
.expect("signature address must fit wasm32"),
len: entry.len,
}
}
fn maximum_len(&self) -> u32 {
self.entries
.values()
.map(|entry| entry.len)
.max()
.unwrap_or(0)
}
}
impl StringPool {
fn new() -> Self {
Self {
base: 0,
bytes: Vec::new(),
entries: HashMap::new(),
}
}
fn intern(&mut self, value: &str) -> (u32, u32) {
if let Some(entry) = self.entries.get(value) {
return *entry;
}
let offset = self
.base
.checked_add(
u32::try_from(self.bytes.len())
.expect("string data must fit WebAssembly linear memory"),
)
.expect("string data must fit WebAssembly linear memory");
let len = value.len() as u32;
self.bytes.extend_from_slice(value.as_bytes());
self.entries.insert(value.to_owned(), (offset, len));
(offset, len)
}
pub fn get(&self, value: &str) -> (u32, u32) {
let (offset, len) = self.entries[value];
(
self.base
.checked_add(offset)
.expect("string address must fit wasm32"),
len,
)
}
}