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
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
use crate::wasm_stream::pipeline::{StreamPass, par_process_code_section};
use eyre::Result;
use wasm_encoder::{Function, Instruction, Module, RawSection};
use wasmparser::{Parser, Payload, TypeRef};
const LOWERING_HELPERS_SECTION: &str = "wvl.multi_memory_lowering.helpers.v1";
#[derive(Debug, Default)]
pub struct MultiMemoryLoweringStreamPass {
pub threads: bool,
}
impl MultiMemoryLoweringStreamPass {
pub fn new(threads: bool) -> Self {
Self { threads }
}
}
impl StreamPass for MultiMemoryLoweringStreamPass {
fn run(&mut self, input_wasm: &[u8]) -> Result<Vec<u8>> {
let mut memory_count = 0;
let mut total_initial = 0;
let mut max_pages = None;
let mut is_shared = false;
let mut lock_acquire_fn = None;
let mut lock_release_fn = None;
let mut lock_write_acquire_fn = None;
let mut lock_write_release_fn = None;
let mut func_types = Vec::new();
let mut types = Vec::new();
let mut imported_funcs = 0;
let mut global_count = 0;
let mut memory_initials = Vec::new();
let mut data_count = 0;
for payload in Parser::new(0).parse_all(input_wasm) {
match payload? {
Payload::TypeSection(s) => {
for t in s {
for sub_ty in t?.into_types() {
types.push(sub_ty);
}
}
}
Payload::ImportSection(s) => {
for group in s {
for i in group?.into_iter() {
let (_, i) = i?;
match i.ty {
TypeRef::Func(_) | TypeRef::FuncExact(_) => imported_funcs += 1,
TypeRef::Global(_) => global_count += 1,
TypeRef::Memory(m) => {
memory_count += 1;
memory_initials.push(m.initial);
total_initial += m.initial;
if let Some(max) = m.maximum {
let cur_max = max_pages.unwrap_or(0);
max_pages = Some(std::cmp::min(cur_max + max, 65536));
}
if memory_count == 1 {
is_shared = m.shared;
}
}
_ => {}
}
}
}
}
Payload::FunctionSection(s) => {
for f in s {
func_types.push(f?);
}
}
Payload::GlobalSection(s) => {
for g in s {
let _ = g?;
global_count += 1;
}
}
Payload::MemorySection(s) => {
for mem in s {
let mem = mem?;
memory_count += 1;
memory_initials.push(mem.initial);
total_initial += mem.initial;
if let Some(max) = mem.maximum {
let cur_max = max_pages.unwrap_or(0);
max_pages = Some(std::cmp::min(cur_max + max, 65536));
}
if memory_count == 1 {
is_shared = mem.shared;
}
}
}
Payload::DataSection(s) => {
data_count = s.count();
}
Payload::ExportSection(s) => {
for export in s {
let export = export?;
if let wasmparser::ExternalKind::Func = export.kind {
match export.name {
"__wasip1_vfs_memory_lock_read_acquire" => {
lock_acquire_fn = Some(export.index)
}
"__wasip1_vfs_memory_lock_read_release" => {
lock_release_fn = Some(export.index)
}
"__wasip1_vfs_memory_lock_write_acquire" => {
lock_write_acquire_fn = Some(export.index)
}
"__wasip1_vfs_memory_lock_write_release" => {
lock_write_release_fn = Some(export.index)
}
_ => {}
}
}
}
}
_ => {}
}
}
if memory_count <= 1 {
return Ok(input_wasm.to_vec());
}
let mut size_type_idx = None;
let mut grow_type_idx = None;
for (i, t) in types.iter().enumerate() {
if let wasmparser::CompositeInnerType::Func(f) = &t.composite_type.inner {
if f.params().is_empty()
&& f.results().len() == 1
&& f.results()[0] == wasmparser::ValType::I32
{
size_type_idx = Some(i as u32);
}
if f.params().len() == 1
&& f.params()[0] == wasmparser::ValType::I32
&& f.results().len() == 1
&& f.results()[0] == wasmparser::ValType::I32
{
grow_type_idx = Some(i as u32);
}
}
}
let mut encoder = Module::new();
let threads = self.threads;
let mut current_offset = 0;
let mut memory_offsets = Vec::new();
for initial in &memory_initials {
memory_offsets.push(current_offset);
current_offset += initial;
}
let orig_global_count = global_count;
let orig_func_count = imported_funcs + func_types.len() as u32;
let final_size_type_idx = size_type_idx.unwrap_or(types.len() as u32);
let final_grow_type_idx = grow_type_idx.unwrap_or(if size_type_idx.is_none() {
types.len() as u32 + 1
} else {
types.len() as u32
});
let mut emitted_memory = false;
for payload in Parser::new(0).parse_all(input_wasm) {
let payload = payload?;
match payload {
Payload::TypeSection(s) => {
let mut type_sec = wasm_encoder::TypeSection::new();
// We must re-encode types to append
for t in s {
let t = t?;
if t.is_explicit_rec_group() {
let rec_types = t
.into_types()
.map(|sub_ty| {
crate::wasm_stream::translator::translate_sub_type(
&sub_ty,
&crate::wasm_stream::translator::DefaultRebinder,
)
})
.collect::<Vec<_>>();
type_sec.ty().rec(rec_types);
} else {
for sub_ty in t.into_types() {
type_sec.ty().subtype(
&crate::wasm_stream::translator::translate_sub_type(
&sub_ty,
&crate::wasm_stream::translator::DefaultRebinder,
),
);
}
}
}
if size_type_idx.is_none() {
type_sec.ty().function([], [wasm_encoder::ValType::I32]);
}
if grow_type_idx.is_none() {
type_sec
.ty()
.function([wasm_encoder::ValType::I32], [wasm_encoder::ValType::I32]);
}
encoder.section(&type_sec);
}
Payload::ImportSection(s) => {
let mut imports = wasm_encoder::ImportSection::new();
for group in s {
for i in group?.into_iter() {
let (_, i) = i?;
match i.ty {
TypeRef::Func(_)
| TypeRef::FuncExact(_)
| TypeRef::Global(_)
| TypeRef::Table(_)
| TypeRef::Tag(_) => {
let entity = match i.ty {
TypeRef::Func(idx) | TypeRef::FuncExact(idx) => {
wasm_encoder::EntityType::Function(idx)
}
TypeRef::Table(t) => wasm_encoder::EntityType::Table(
crate::wasm_stream::translator::translate_table_type(
t,
&crate::wasm_stream::translator::DefaultRebinder,
),
),
TypeRef::Global(g) => wasm_encoder::EntityType::Global(
crate::wasm_stream::translator::translate_global_type(
g,
&crate::wasm_stream::translator::DefaultRebinder,
),
),
TypeRef::Tag(t) => wasm_encoder::EntityType::Tag(
crate::wasm_stream::translator::translate_tag_type(t),
),
_ => unreachable!(),
};
imports.import(i.module, i.name, entity);
}
TypeRef::Memory(_) => {
// Drop memory imports (they are merged into locally defined memory)
}
}
}
}
if !imports.is_empty() {
encoder.section(&imports);
}
}
Payload::MemorySection(_) => {
if !emitted_memory {
emitted_memory = true;
let mut mem_section = wasm_encoder::MemorySection::new();
mem_section.memory(wasm_encoder::MemoryType {
minimum: total_initial,
maximum: max_pages,
memory64: false,
shared: is_shared,
page_size_log2: None,
});
encoder.section(&mem_section);
}
}
Payload::GlobalSection(s) => {
if !emitted_memory {
emitted_memory = true;
let mut mem_section = wasm_encoder::MemorySection::new();
mem_section.memory(wasm_encoder::MemoryType {
minimum: total_initial,
maximum: max_pages,
memory64: false,
shared: is_shared,
page_size_log2: None,
});
encoder.section(&mem_section);
}
let mut global_sec = wasm_encoder::GlobalSection::new();
for item in s {
let g = item?;
let ty = wasm_encoder::GlobalType {
val_type: crate::wasm_stream::translator::translate_val_type(
g.ty.content_type,
&crate::wasm_stream::translator::DefaultRebinder,
),
mutable: g.ty.mutable,
shared: g.ty.shared,
};
let expr = crate::wasm_stream::translator::translate_const_expr(
&g.init_expr,
&crate::wasm_stream::translator::DefaultRebinder,
)?;
global_sec.global(ty, &expr);
}
// Append offset globals
for offset in memory_offsets.iter().skip(1) {
global_sec.global(
wasm_encoder::GlobalType {
val_type: wasm_encoder::ValType::I32,
mutable: true,
shared: false,
},
&wasm_encoder::ConstExpr::i32_const((*offset * 65536) as i32),
);
}
encoder.section(&global_sec);
}
Payload::FunctionSection(s) => {
let mut func_sec = wasm_encoder::FunctionSection::new();
for f in s {
func_sec.function(f?);
}
// size fns
for _ in 0..memory_count {
func_sec.function(final_size_type_idx);
}
// grow fns
for _ in 0..memory_count {
func_sec.function(final_grow_type_idx);
}
encoder.section(&func_sec);
}
Payload::ExportSection(s) => {
let mut exp_sec = wasm_encoder::ExportSection::new();
for e in s {
let e = e?;
let kind = match e.kind {
wasmparser::ExternalKind::Func => wasm_encoder::ExportKind::Func,
wasmparser::ExternalKind::FuncExact => wasm_encoder::ExportKind::Func,
wasmparser::ExternalKind::Table => wasm_encoder::ExportKind::Table,
wasmparser::ExternalKind::Memory => wasm_encoder::ExportKind::Memory,
wasmparser::ExternalKind::Global => wasm_encoder::ExportKind::Global,
wasmparser::ExternalKind::Tag => wasm_encoder::ExportKind::Tag,
};
// Note: If an export is memory and memory > 0, we could remap to 0.
// But combined memory is 0.
let idx = if e.kind == wasmparser::ExternalKind::Memory {
0
} else {
e.index
};
exp_sec.export(e.name, kind, idx);
}
encoder.section(&exp_sec);
}
Payload::DataSection(s) => {
let mut data_sec = wasm_encoder::DataSection::new();
for d in s {
let d = d?;
match d.kind {
wasmparser::DataKind::Active {
memory_index,
offset_expr,
} => {
let mem_idx = memory_index as usize;
let mut expr =
crate::wasm_stream::translator::translate_const_expr(
&offset_expr,
&crate::wasm_stream::translator::DefaultRebinder,
)?;
if mem_idx > 0 {
// Replace `expr` by adding the initial offset
// Actually, we can just use the global
let gid = orig_global_count + mem_idx as u32 - 1;
let _new_expr = wasm_encoder::ConstExpr::global_get(gid);
// Wasm-encoder doesn't allow complex const expressions yet?
// Wait! ConstExpr in wasm-encoder is limited!
// Actually, DataKind::Active offset can just be i32_const(val + offset * 65536)
// if the original is just i32_const.
// Let's assume it's just i32_const because multi-memory lowering runs at build time.
let op = offset_expr.get_operators_reader().read()?;
if let wasmparser::Operator::I32Const { value } = op {
let new_val =
value + (memory_offsets[mem_idx] * 65536) as i32;
expr = wasm_encoder::ConstExpr::i32_const(new_val);
} else {
panic!("Data segment offset is not i32.const");
}
}
data_sec.active(0, &expr, d.data.iter().copied());
}
wasmparser::DataKind::Passive => {
data_sec.passive(d.data.iter().copied());
}
}
}
encoder.section(&data_sec);
}
Payload::CodeSectionStart {
count: _,
range,
size: _,
} => {
let reader = wasmparser::BinaryReader::new(
&input_wasm[range.start..range.end],
range.start,
);
let s = wasmparser::CodeSectionReader::new(reader)?;
let mut new_code_sec = par_process_code_section(s, |i, func_body| {
let func_type_idx = func_types[i] as usize;
let func_type = match &types[func_type_idx].composite_type.inner {
wasmparser::CompositeInnerType::Func(f) => f,
_ => unreachable!(),
};
let num_params = func_type.params().len() as u32;
let mut locals = Vec::new();
let mut locals_reader = func_body.get_locals_reader()?;
let mut original_locals_count = 0;
for _ in 0..locals_reader.get_count() {
let (count, ty) = locals_reader.read()?;
original_locals_count += count;
let enc_ty = crate::wasm_stream::translator::translate_val_type(
ty,
&crate::wasm_stream::translator::DefaultRebinder,
);
locals.push((count, enc_ty));
}
let tmp_base = num_params + original_locals_count;
let tmp_addr = tmp_base;
let tmp_i32 = tmp_base + 1;
let tmp_i32_2 = tmp_base + 2;
let tmp_i64 = tmp_base + 3;
let tmp_f32 = tmp_base + 4;
let tmp_f64 = tmp_base + 5;
let tmp_v128 = tmp_base + 6;
let tmp_i64_2 = tmp_base + 7;
locals.push((1, wasm_encoder::ValType::I32)); // tmp_addr
locals.push((1, wasm_encoder::ValType::I32)); // tmp_i32
locals.push((1, wasm_encoder::ValType::I32)); // tmp_i32_2
locals.push((1, wasm_encoder::ValType::I64)); // tmp_i64
locals.push((1, wasm_encoder::ValType::F32)); // tmp_f32
locals.push((1, wasm_encoder::ValType::F64)); // tmp_f64
locals.push((1, wasm_encoder::ValType::V128)); // tmp_v128
locals.push((1, wasm_encoder::ValType::I64)); // tmp_i64_2
let mut func = Function::new(locals);
let mut reader = func_body.get_operators_reader()?;
while !reader.eof() {
let op = reader.read()?;
match op {
wasmparser::Operator::MemorySize { mem, .. } => {
func.instruction(&wasm_encoder::Instruction::Call(
orig_func_count + mem,
));
}
wasmparser::Operator::MemoryGrow { mem, .. } => {
func.instruction(&wasm_encoder::Instruction::Call(
orig_func_count + memory_count + mem,
));
}
wasmparser::Operator::MemoryCopy { dst_mem, src_mem } => {
let d_idx = dst_mem as u32;
let s_idx = src_mem as u32;
if d_idx > 0 || s_idx > 0 {
func.instruction(&wasm_encoder::Instruction::LocalSet(
tmp_addr,
)); // len
func.instruction(&wasm_encoder::Instruction::LocalSet(
tmp_i32,
)); // src
func.instruction(&wasm_encoder::Instruction::LocalSet(
tmp_i32_2,
)); // dst
// Acquire read lock if threaded
if threads {
if let Some(acq) = lock_acquire_fn {
func.instruction(&wasm_encoder::Instruction::Call(
acq,
));
}
}
func.instruction(&wasm_encoder::Instruction::LocalGet(
tmp_i32_2,
));
if d_idx > 0 {
func.instruction(
&wasm_encoder::Instruction::GlobalGet(
orig_global_count + d_idx - 1,
),
);
func.instruction(&wasm_encoder::Instruction::I32Add);
}
func.instruction(&wasm_encoder::Instruction::LocalGet(
tmp_i32,
));
if s_idx > 0 {
func.instruction(
&wasm_encoder::Instruction::GlobalGet(
orig_global_count + s_idx - 1,
),
);
func.instruction(&wasm_encoder::Instruction::I32Add);
}
func.instruction(&wasm_encoder::Instruction::LocalGet(
tmp_addr,
));
func.instruction(&wasm_encoder::Instruction::MemoryCopy {
dst_mem: 0,
src_mem: 0,
});
// Release read lock if threaded
if threads {
if let Some(rel) = lock_release_fn {
func.instruction(&wasm_encoder::Instruction::Call(
rel,
));
}
}
} else {
func.instruction(&wasm_encoder::Instruction::MemoryCopy {
dst_mem: 0,
src_mem: 0,
});
}
}
wasmparser::Operator::MemoryFill { mem } => {
let idx = mem as u32;
if idx > 0 {
func.instruction(&wasm_encoder::Instruction::LocalSet(
tmp_addr,
)); // len
func.instruction(&wasm_encoder::Instruction::LocalSet(
tmp_i32,
)); // val
func.instruction(&wasm_encoder::Instruction::LocalSet(
tmp_i32_2,
)); // dst
// Acquire read lock if threaded
if threads {
if let Some(acq) = lock_acquire_fn {
func.instruction(&wasm_encoder::Instruction::Call(
acq,
));
}
}
func.instruction(&wasm_encoder::Instruction::LocalGet(
tmp_i32_2,
));
func.instruction(&wasm_encoder::Instruction::GlobalGet(
orig_global_count + idx - 1,
));
func.instruction(&wasm_encoder::Instruction::I32Add);
func.instruction(&wasm_encoder::Instruction::LocalGet(
tmp_i32,
));
func.instruction(&wasm_encoder::Instruction::LocalGet(
tmp_addr,
));
func.instruction(&wasm_encoder::Instruction::MemoryFill(0));
// Release read lock if threaded
if threads {
if let Some(rel) = lock_release_fn {
func.instruction(&wasm_encoder::Instruction::Call(
rel,
));
}
}
} else {
func.instruction(&wasm_encoder::Instruction::MemoryFill(0));
}
}
wasmparser::Operator::MemoryInit { data_index, mem } => {
let idx = mem as u32;
if idx > 0 {
func.instruction(&wasm_encoder::Instruction::LocalSet(
tmp_addr,
)); // len
func.instruction(&wasm_encoder::Instruction::LocalSet(
tmp_i32,
)); // src
func.instruction(&wasm_encoder::Instruction::LocalSet(
tmp_i32_2,
)); // dst
// Acquire read lock if threaded
if threads {
if let Some(acq) = lock_acquire_fn {
func.instruction(&wasm_encoder::Instruction::Call(
acq,
));
}
}
func.instruction(&wasm_encoder::Instruction::LocalGet(
tmp_i32_2,
));
func.instruction(&wasm_encoder::Instruction::GlobalGet(
orig_global_count + idx - 1,
));
func.instruction(&wasm_encoder::Instruction::I32Add);
func.instruction(&wasm_encoder::Instruction::LocalGet(
tmp_i32,
));
func.instruction(&wasm_encoder::Instruction::LocalGet(
tmp_addr,
));
func.instruction(&wasm_encoder::Instruction::MemoryInit {
data_index,
mem: 0,
});
// Release read lock if threaded
if threads {
if let Some(rel) = lock_release_fn {
func.instruction(&wasm_encoder::Instruction::Call(
rel,
));
}
}
} else {
func.instruction(&wasm_encoder::Instruction::MemoryInit {
data_index,
mem: 0,
});
}
}
_ => {
if let Some(info) =
crate::wasm_stream::mem_info::memory_op_info(&op)
{
if info.memory > 0 {
let offset_idx = orig_global_count + info.memory - 1;
// Helper closure-like mapping for temp locals.
// For two-operand cases we need distinct temp slots
// per type. The "second slot" indices:
// i32 -> tmp_i32_2, i64 -> tmp_i64_2
// (f32/f64/v128 never appear as second operand in
// practice, but we panic if they do.)
let tmp_for = |ty: wasm_encoder::ValType, secondary: bool| -> u32 {
if !secondary {
match ty {
wasm_encoder::ValType::I32 => tmp_i32,
wasm_encoder::ValType::I64 => tmp_i64,
wasm_encoder::ValType::F32 => tmp_f32,
wasm_encoder::ValType::F64 => tmp_f64,
wasm_encoder::ValType::V128 => tmp_v128,
_ => unreachable!(),
}
} else {
match ty {
wasm_encoder::ValType::I32 => tmp_i32_2,
wasm_encoder::ValType::I64 => tmp_i64_2,
_ => unreachable!("secondary temp for {:?}", ty),
}
}
};
// Save value operands (top-of-stack first, i.e.
// in reverse order of value_operands).
// Stack before: [... addr val0 val1]
// LocalSet(tmp_for(val1, secondary=true))
// LocalSet(tmp_for(val0, secondary=false))
// LocalSet(tmp_addr)
let _n = info.value_operands.len();
for (i, ty) in
info.value_operands.iter().enumerate().rev()
{
let secondary = i > 0; // first operand uses primary, rest use secondary
func.instruction(
&wasm_encoder::Instruction::LocalSet(tmp_for(
*ty, secondary,
)),
);
}
func.instruction(&wasm_encoder::Instruction::LocalSet(
tmp_addr,
));
// Acquire lock if threaded
if threads {
if let Some(acq) = lock_acquire_fn {
func.instruction(
&wasm_encoder::Instruction::Call(acq),
);
}
}
// Push adjusted address
func.instruction(&wasm_encoder::Instruction::LocalGet(
tmp_addr,
));
func.instruction(
&wasm_encoder::Instruction::GlobalGet(offset_idx),
);
func.instruction(&wasm_encoder::Instruction::I32Add);
// Restore value operands in original order
for (i, ty) in info.value_operands.iter().enumerate() {
let secondary = i > 0;
func.instruction(
&wasm_encoder::Instruction::LocalGet(tmp_for(
*ty, secondary,
)),
);
}
// Emit the instruction with memory index 0
let mut enc_op = crate::wasm_stream::translator::translate(&op, &crate::wasm_stream::translator::DefaultRebinder);
crate::wasm_stream::mem_info::clear_memory_index(
&mut enc_op,
);
func.instruction(&enc_op);
// Release lock if threaded
if threads {
if let Some(rel) = lock_release_fn {
// If there's a result, save it, release, restore
if let Some(res_ty) = info.result_type {
let tmp_res = tmp_for(res_ty, false);
func.instruction(
&wasm_encoder::Instruction::LocalSet(
tmp_res,
),
);
func.instruction(
&wasm_encoder::Instruction::Call(rel),
);
func.instruction(
&wasm_encoder::Instruction::LocalGet(
tmp_res,
),
);
} else {
func.instruction(
&wasm_encoder::Instruction::Call(rel),
);
}
}
}
continue;
}
}
let mut enc_op = crate::wasm_stream::translator::translate(
&op,
&crate::wasm_stream::translator::DefaultRebinder,
);
if crate::wasm_stream::mem_info::memory_op_info(&op).is_some() {
crate::wasm_stream::mem_info::clear_memory_index(
&mut enc_op,
);
}
func.instruction(&enc_op);
}
}
}
Ok(func)
})?;
// Add the size and grow wrappers
for idx in 0..memory_count {
let mut func = Function::new(Vec::new());
if memory_count == 1 {
func.instruction(&Instruction::MemorySize(0));
} else if idx == 0 {
let next_gid = orig_global_count; // first offset global
func.instruction(&Instruction::GlobalGet(next_gid));
func.instruction(&Instruction::I32Const(16));
func.instruction(&Instruction::I32ShrU);
} else if idx == memory_count - 1 {
let this_gid = orig_global_count + idx - 1;
func.instruction(&Instruction::MemorySize(0));
func.instruction(&Instruction::GlobalGet(this_gid));
func.instruction(&Instruction::I32Const(16));
func.instruction(&Instruction::I32ShrU);
func.instruction(&Instruction::I32Sub);
} else {
let this_gid = orig_global_count + idx - 1;
let next_gid = orig_global_count + idx;
func.instruction(&Instruction::GlobalGet(next_gid));
func.instruction(&Instruction::GlobalGet(this_gid));
func.instruction(&Instruction::I32Sub);
func.instruction(&Instruction::I32Const(16));
func.instruction(&Instruction::I32ShrU);
}
func.instruction(&Instruction::End);
new_code_sec.function(&func);
}
for idx in 0..memory_count {
let mut func = Function::new(vec![
(1, wasm_encoder::ValType::I32), // return_size
(1, wasm_encoder::ValType::I32), // combined_size
(1, wasm_encoder::ValType::I32), // shift_bytes
]);
let page_delta = 0;
let return_size = 1;
let combined_size = 2;
let shift_bytes = 3;
// return_size = memory_size_i()
func.instruction(&Instruction::Call(orig_func_count + idx));
func.instruction(&Instruction::LocalSet(return_size));
if threads {
if let Some(acq) = lock_write_acquire_fn {
func.instruction(&Instruction::Call(acq));
}
}
func.instruction(&Instruction::MemorySize(0));
func.instruction(&Instruction::LocalSet(combined_size));
func.instruction(&Instruction::LocalGet(page_delta));
func.instruction(&Instruction::MemoryGrow(0));
func.instruction(&Instruction::I32Const(-1));
func.instruction(&Instruction::I32Eq);
func.instruction(&Instruction::If(wasm_encoder::BlockType::Empty));
if threads {
if let Some(rel) = lock_write_release_fn {
func.instruction(&Instruction::Call(rel));
}
}
func.instruction(&Instruction::I32Const(-1));
func.instruction(&Instruction::Return);
func.instruction(&Instruction::End); // end if
let next_offset_global = if idx + 1 < memory_count {
Some(orig_global_count + idx)
} else {
None
};
if let Some(next_gid) = next_offset_global {
func.instruction(&Instruction::LocalGet(page_delta));
func.instruction(&Instruction::I32Const(16));
func.instruction(&Instruction::I32Shl);
func.instruction(&Instruction::LocalSet(shift_bytes));
// dst
func.instruction(&Instruction::GlobalGet(next_gid));
func.instruction(&Instruction::LocalGet(shift_bytes));
func.instruction(&Instruction::I32Add);
// src
func.instruction(&Instruction::GlobalGet(next_gid));
// len
func.instruction(&Instruction::LocalGet(combined_size));
func.instruction(&Instruction::I32Const(16));
func.instruction(&Instruction::I32Shl);
func.instruction(&Instruction::GlobalGet(next_gid));
func.instruction(&Instruction::I32Sub);
func.instruction(&Instruction::MemoryCopy {
dst_mem: 0,
src_mem: 0,
});
let globals_to_update = (idx + 1)..memory_count;
for update_idx in globals_to_update {
let gid = orig_global_count + update_idx - 1;
func.instruction(&Instruction::GlobalGet(gid));
func.instruction(&Instruction::LocalGet(shift_bytes));
func.instruction(&Instruction::I32Add);
func.instruction(&Instruction::GlobalSet(gid));
}
}
if threads {
if let Some(rel) = lock_write_release_fn {
func.instruction(&Instruction::Call(rel));
}
}
func.instruction(&Instruction::LocalGet(return_size));
func.instruction(&Instruction::End);
new_code_sec.function(&func);
}
if threads {
let mut data = Vec::with_capacity(8);
data.extend_from_slice(&orig_func_count.to_le_bytes());
data.extend_from_slice(&memory_count.to_le_bytes());
encoder.section(&wasm_encoder::CustomSection {
name: LOWERING_HELPERS_SECTION.into(),
data: std::borrow::Cow::Owned(data),
});
}
encoder.section(&new_code_sec);
}
Payload::CustomSection(c) => {
encoder.section(&wasm_encoder::CustomSection {
name: c.name().into(),
data: std::borrow::Cow::Borrowed(c.data()),
});
}
_ => {
if let Some((id, range)) = payload.as_section() {
encoder.section(&RawSection {
id,
data: &input_wasm[range.clone()],
});
}
}
}
}
Ok(encoder.finish())
}
}