/
codegen.rs
5959 lines (5624 loc) 路 240 KB
/
codegen.rs
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
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use crate::address_map::get_function_address_map;
use crate::location::{Location, Reg};
use crate::machine::{CodegenError, Label, Machine, MachineStackOffset, NATIVE_PAGE_SIZE};
use crate::{common_decl::*, config::Singlepass};
use smallvec::{smallvec, SmallVec};
use std::cmp;
use std::iter;
use wasmer_compiler::wasmparser::{Operator, Type as WpType, TypeOrFuncType as WpTypeOrFuncType};
use wasmer_compiler::{
CallingConvention, CompiledFunction, CompiledFunctionFrameInfo, FunctionBody, FunctionBodyData,
Relocation, RelocationTarget, SectionIndex,
};
use wasmer_types::{
entity::{EntityRef, PrimaryMap, SecondaryMap},
FunctionType,
};
use wasmer_types::{
FunctionIndex, GlobalIndex, LocalFunctionIndex, LocalMemoryIndex, MemoryIndex, ModuleInfo,
SignatureIndex, TableIndex, Type,
};
use wasmer_vm::{MemoryStyle, TableStyle, TrapCode, VMBuiltinFunctionIndex, VMOffsets};
/// The singlepass per-function code generator.
pub struct FuncGen<'a, M: Machine> {
// Immutable properties assigned at creation time.
/// Static module information.
module: &'a ModuleInfo,
/// ModuleInfo compilation config.
config: &'a Singlepass,
/// Offsets of vmctx fields.
vmoffsets: &'a VMOffsets,
// // Memory plans.
memory_styles: &'a PrimaryMap<MemoryIndex, MemoryStyle>,
// // Table plans.
// table_styles: &'a PrimaryMap<TableIndex, TableStyle>,
/// Function signature.
signature: FunctionType,
// Working storage.
/// Memory locations of local variables.
locals: Vec<Location<M::GPR, M::SIMD>>,
/// Types of local variables, including arguments.
local_types: Vec<WpType>,
/// Value stack.
value_stack: Vec<Location<M::GPR, M::SIMD>>,
/// Metadata about floating point values on the stack.
fp_stack: Vec<FloatValue>,
/// A list of frames describing the current control stack.
control_stack: Vec<ControlFrame>,
stack_offset: MachineStackOffset,
save_area_offset: Option<MachineStackOffset>,
state: MachineState,
track_state: bool,
/// Low-level machine state.
machine: M,
/// Nesting level of unreachable code.
unreachable_depth: usize,
/// Function state map. Not yet used in the reborn version but let's keep it.
fsm: FunctionStateMap,
/// Relocation information.
relocations: Vec<Relocation>,
/// A set of special labels for trapping.
special_labels: SpecialLabelSet,
/// Calling convention to use.
calling_convention: CallingConvention,
}
struct SpecialLabelSet {
integer_division_by_zero: Label,
integer_overflow: Label,
heap_access_oob: Label,
table_access_oob: Label,
indirect_call_null: Label,
bad_signature: Label,
}
/// Metadata about a floating-point value.
#[derive(Copy, Clone, Debug)]
struct FloatValue {
/// Do we need to canonicalize the value before its bit pattern is next observed? If so, how?
canonicalization: Option<CanonicalizeType>,
/// Corresponding depth in the main value stack.
depth: usize,
}
impl FloatValue {
fn new(depth: usize) -> Self {
FloatValue {
canonicalization: None,
depth,
}
}
fn cncl_f32(depth: usize) -> Self {
FloatValue {
canonicalization: Some(CanonicalizeType::F32),
depth,
}
}
fn cncl_f64(depth: usize) -> Self {
FloatValue {
canonicalization: Some(CanonicalizeType::F64),
depth,
}
}
fn promote(self, depth: usize) -> FloatValue {
FloatValue {
canonicalization: match self.canonicalization {
Some(CanonicalizeType::F32) => Some(CanonicalizeType::F64),
Some(CanonicalizeType::F64) => panic!("cannot promote F64"),
None => None,
},
depth,
}
}
fn demote(self, depth: usize) -> FloatValue {
FloatValue {
canonicalization: match self.canonicalization {
Some(CanonicalizeType::F64) => Some(CanonicalizeType::F32),
Some(CanonicalizeType::F32) => panic!("cannot demote F32"),
None => None,
},
depth,
}
}
}
/// Type of a pending canonicalization floating point value.
/// Sometimes we don't have the type information elsewhere and therefore we need to track it here.
#[derive(Copy, Clone, Debug)]
enum CanonicalizeType {
F32,
F64,
}
impl CanonicalizeType {
fn to_size(&self) -> Size {
match self {
CanonicalizeType::F32 => Size::S32,
CanonicalizeType::F64 => Size::S64,
}
}
}
trait PopMany<T> {
fn peek1(&self) -> Result<&T, CodegenError>;
fn pop1(&mut self) -> Result<T, CodegenError>;
fn pop2(&mut self) -> Result<(T, T), CodegenError>;
}
impl<T> PopMany<T> for Vec<T> {
fn peek1(&self) -> Result<&T, CodegenError> {
self.last().ok_or_else(|| CodegenError {
message: "peek1() expects at least 1 element".into(),
})
}
fn pop1(&mut self) -> Result<T, CodegenError> {
self.pop().ok_or_else(|| CodegenError {
message: "pop1() expects at least 1 element".into(),
})
}
fn pop2(&mut self) -> Result<(T, T), CodegenError> {
if self.len() < 2 {
return Err(CodegenError {
message: "pop2() expects at least 2 elements".into(),
});
}
let right = self.pop().unwrap();
let left = self.pop().unwrap();
Ok((left, right))
}
}
trait WpTypeExt {
fn is_float(&self) -> bool;
}
impl WpTypeExt for WpType {
fn is_float(&self) -> bool {
match self {
WpType::F32 | WpType::F64 => true,
_ => false,
}
}
}
#[derive(Debug, Clone)]
pub struct ControlFrame {
pub label: Label,
pub loop_like: bool,
pub if_else: IfElseState,
pub returns: SmallVec<[WpType; 1]>,
pub value_stack_depth: usize,
pub fp_stack_depth: usize,
pub state: MachineState,
pub state_diff_id: usize,
}
#[derive(Debug, Copy, Clone)]
pub enum IfElseState {
None,
If(Label),
Else,
}
fn type_to_wp_type(ty: Type) -> WpType {
match ty {
Type::I32 => WpType::I32,
Type::I64 => WpType::I64,
Type::F32 => WpType::F32,
Type::F64 => WpType::F64,
Type::V128 => WpType::V128,
Type::ExternRef => WpType::ExternRef,
Type::FuncRef => WpType::FuncRef, // TODO: FuncRef or Func?
}
}
/// Abstraction for a 2-input, 1-output operator. Can be an integer/floating-point
/// binop/cmpop.
struct I2O1<R: Reg, S: Reg> {
loc_a: Location<R, S>,
loc_b: Location<R, S>,
ret: Location<R, S>,
}
impl<'a, M: Machine> FuncGen<'a, M> {
fn get_stack_offset(&self) -> usize {
self.stack_offset.0
}
/// Acquires locations from the machine state.
///
/// If the returned locations are used for stack value, `release_location` needs to be called on them;
/// Otherwise, if the returned locations are used for locals, `release_location` does not need to be called on them.
fn acquire_locations(
&mut self,
tys: &[(WpType, MachineValue)],
zeroed: bool,
) -> SmallVec<[Location<M::GPR, M::SIMD>; 1]> {
let mut ret = smallvec![];
let mut delta_stack_offset: usize = 0;
for (ty, mv) in tys {
let loc = match *ty {
WpType::F32 | WpType::F64 => self.machine.pick_simd().map(Location::SIMD),
WpType::I32 | WpType::I64 => self.machine.pick_gpr().map(Location::GPR),
WpType::FuncRef | WpType::ExternRef => self.machine.pick_gpr().map(Location::GPR),
_ => unreachable!("can't acquire location for type {:?}", ty),
};
let loc = if let Some(x) = loc {
x
} else {
self.stack_offset.0 += 8;
delta_stack_offset += 8;
self.machine.local_on_stack(self.stack_offset.0 as i32)
};
if let Location::GPR(x) = loc {
self.machine.reserve_gpr(x);
self.state.register_values[self.machine.index_from_gpr(x).0] = mv.clone();
} else if let Location::SIMD(x) = loc {
self.machine.reserve_simd(x);
self.state.register_values[self.machine.index_from_simd(x).0] = mv.clone();
} else {
self.state.stack_values.push(mv.clone());
}
self.state.wasm_stack.push(WasmAbstractValue::Runtime);
ret.push(loc);
}
let delta_stack_offset = self.machine.round_stack_adjust(delta_stack_offset);
if delta_stack_offset != 0 {
self.machine.adjust_stack(delta_stack_offset as u32);
}
if zeroed {
for i in 0..tys.len() {
self.machine.zero_location(Size::S64, ret[i]);
}
}
ret
}
/// Releases locations used for stack value.
fn release_locations(&mut self, locs: &[Location<M::GPR, M::SIMD>]) {
let mut delta_stack_offset: usize = 0;
for loc in locs.iter().rev() {
match *loc {
Location::GPR(ref x) => {
self.machine.release_gpr(*x);
self.state.register_values[self.machine.index_from_gpr(*x).0] =
MachineValue::Undefined;
}
Location::SIMD(ref x) => {
self.machine.release_simd(*x);
self.state.register_values[self.machine.index_from_simd(*x).0] =
MachineValue::Undefined;
}
Location::Memory(y, x) => {
if y == self.machine.local_pointer() {
if x >= 0 {
unreachable!();
}
let offset = (-x) as usize;
if offset != self.stack_offset.0 {
unreachable!();
}
self.stack_offset.0 -= 8;
delta_stack_offset += 8;
self.state.stack_values.pop().unwrap();
}
}
_ => {}
}
self.state.wasm_stack.pop().unwrap();
}
let delta_stack_offset = self.machine.round_stack_adjust(delta_stack_offset);
if delta_stack_offset != 0 {
self.machine.restore_stack(delta_stack_offset as u32);
}
}
/// Releases locations used for stack value.
fn release_locations_value(&mut self, stack_depth: usize) {
let mut delta_stack_offset: usize = 0;
let locs: &[Location<M::GPR, M::SIMD>] = &self.value_stack[stack_depth..];
for loc in locs.iter().rev() {
match *loc {
Location::GPR(ref x) => {
self.machine.release_gpr(*x);
self.state.register_values[self.machine.index_from_gpr(*x).0] =
MachineValue::Undefined;
}
Location::SIMD(ref x) => {
self.machine.release_simd(*x);
self.state.register_values[self.machine.index_from_simd(*x).0] =
MachineValue::Undefined;
}
Location::Memory(y, x) => {
if y == self.machine.local_pointer() {
if x >= 0 {
unreachable!();
}
let offset = (-x) as usize;
if offset != self.stack_offset.0 {
unreachable!();
}
self.stack_offset.0 -= 8;
delta_stack_offset += 8;
self.state.stack_values.pop().unwrap();
}
}
_ => {}
}
self.state.wasm_stack.pop().unwrap();
}
let delta_stack_offset = self.machine.round_stack_adjust(delta_stack_offset);
if delta_stack_offset != 0 {
self.machine.adjust_stack(delta_stack_offset as u32);
}
}
fn release_locations_only_regs(&mut self, locs: &[Location<M::GPR, M::SIMD>]) {
for loc in locs.iter().rev() {
match *loc {
Location::GPR(ref x) => {
self.machine.release_gpr(*x);
self.state.register_values[self.machine.index_from_gpr(*x).0] =
MachineValue::Undefined;
}
Location::SIMD(ref x) => {
self.machine.release_simd(*x);
self.state.register_values[self.machine.index_from_simd(*x).0] =
MachineValue::Undefined;
}
_ => {}
}
// Wasm state popping is deferred to `release_locations_only_osr_state`.
}
}
fn release_locations_only_stack(&mut self, locs: &[Location<M::GPR, M::SIMD>]) {
let mut delta_stack_offset: usize = 0;
for loc in locs.iter().rev() {
if let Location::Memory(y, x) = *loc {
if y == self.machine.local_pointer() {
if x >= 0 {
unreachable!();
}
let offset = (-x) as usize;
if offset != self.stack_offset.0 {
unreachable!();
}
self.stack_offset.0 -= 8;
delta_stack_offset += 8;
self.state.stack_values.pop().unwrap();
}
}
// Wasm state popping is deferred to `release_locations_only_osr_state`.
}
let delta_stack_offset = self.machine.round_stack_adjust(delta_stack_offset);
if delta_stack_offset != 0 {
self.machine.pop_stack_locals(delta_stack_offset as u32);
}
}
fn release_locations_only_osr_state(&mut self, n: usize) {
let new_length = self
.state
.wasm_stack
.len()
.checked_sub(n)
.expect("release_locations_only_osr_state: length underflow");
self.state.wasm_stack.truncate(new_length);
}
fn release_locations_keep_state(&mut self, stack_depth: usize) {
let mut delta_stack_offset: usize = 0;
let mut stack_offset = self.stack_offset.0;
let locs = &self.value_stack[stack_depth..];
for loc in locs.iter().rev() {
if let Location::Memory(y, x) = *loc {
if y == self.machine.local_pointer() {
if x >= 0 {
unreachable!();
}
let offset = (-x) as usize;
if offset != stack_offset {
unreachable!();
}
stack_offset -= 8;
delta_stack_offset += 8;
}
}
}
let delta_stack_offset = self.machine.round_stack_adjust(delta_stack_offset);
if delta_stack_offset != 0 {
self.machine.pop_stack_locals(delta_stack_offset as u32);
}
}
fn init_locals(
&mut self,
n: usize,
sig: FunctionType,
calling_convention: CallingConvention,
) -> Vec<Location<M::GPR, M::SIMD>> {
// How many machine stack slots will all the locals use?
let num_mem_slots = (0..n)
.filter(|&x| self.machine.is_local_on_stack(x))
.count();
// Total size (in bytes) of the pre-allocated "static area" for this function's
// locals and callee-saved registers.
let mut static_area_size: usize = 0;
// Callee-saved registers used for locals.
// Keep this consistent with the "Save callee-saved registers" code below.
for i in 0..n {
// If a local is not stored on stack, then it is allocated to a callee-saved register.
if !self.machine.is_local_on_stack(i) {
static_area_size += 8;
}
}
// Callee-saved vmctx.
static_area_size += 8;
// Some ABI (like Windows) needs extrat reg save
static_area_size += 8 * self.machine.list_to_save(calling_convention).len();
// Total size of callee saved registers.
let callee_saved_regs_size = static_area_size;
// Now we can determine concrete locations for locals.
let locations: Vec<Location<M::GPR, M::SIMD>> = (0..n)
.map(|i| self.machine.get_local_location(i, callee_saved_regs_size))
.collect();
// Add size of locals on stack.
static_area_size += num_mem_slots * 8;
// Allocate save area, without actually writing to it.
static_area_size = self.machine.round_stack_adjust(static_area_size);
self.machine.adjust_stack(static_area_size as _);
// Save callee-saved registers.
for loc in locations.iter() {
if let Location::GPR(x) = *loc {
self.stack_offset.0 += 8;
self.machine.move_local(self.stack_offset.0 as i32, *loc);
self.state.stack_values.push(MachineValue::PreserveRegister(
self.machine.index_from_gpr(x),
));
}
}
// Save the Reg use for vmctx.
self.stack_offset.0 += 8;
self.machine.move_local(
self.stack_offset.0 as i32,
Location::GPR(self.machine.get_vmctx_reg()),
);
self.state.stack_values.push(MachineValue::PreserveRegister(
self.machine.index_from_gpr(self.machine.get_vmctx_reg()),
));
// Check if need to same some CallingConvention specific regs
let regs_to_save = self.machine.list_to_save(calling_convention);
for loc in regs_to_save.iter() {
self.stack_offset.0 += 8;
self.machine.move_local(self.stack_offset.0 as i32, *loc);
}
// Save the offset of register save area.
self.save_area_offset = Some(MachineStackOffset(self.stack_offset.0));
// Save location information for locals.
for (i, loc) in locations.iter().enumerate() {
match *loc {
Location::GPR(x) => {
self.state.register_values[self.machine.index_from_gpr(x).0] =
MachineValue::WasmLocal(i);
}
Location::Memory(_, _) => {
self.state.stack_values.push(MachineValue::WasmLocal(i));
}
_ => unreachable!(),
}
}
// Load in-register parameters into the allocated locations.
// Locals are allocated on the stack from higher address to lower address,
// so we won't skip the stack guard page here.
let mut stack_offset: usize = 0;
for (i, param) in sig.params().iter().enumerate() {
let sz = match *param {
Type::I32 | Type::F32 => Size::S32,
Type::I64 | Type::F64 => Size::S64,
Type::ExternRef | Type::FuncRef => Size::S64,
_ => unimplemented!(),
};
let loc = self.machine.get_call_param_location(
i + 1,
sz,
&mut stack_offset,
calling_convention,
);
self.machine
.move_location_extend(sz, false, loc, Size::S64, locations[i]);
}
// Load vmctx into it's GPR.
self.machine.move_location(
Size::S64,
self.machine
.get_simple_param_location(0, calling_convention),
Location::GPR(self.machine.get_vmctx_reg()),
);
// Stack probe.
//
// `rep stosq` writes data from low address to high address and may skip the stack guard page.
// so here we probe it explicitly when needed.
for i in (sig.params().len()..n)
.step_by(NATIVE_PAGE_SIZE / 8)
.skip(1)
{
self.machine.zero_location(Size::S64, locations[i]);
}
// Initialize all normal locals to zero.
let mut init_stack_loc_cnt = 0;
let mut last_stack_loc = Location::Memory(self.machine.local_pointer(), i32::MAX);
for i in sig.params().len()..n {
match locations[i] {
Location::Memory(_, _) => {
init_stack_loc_cnt += 1;
last_stack_loc = cmp::min(last_stack_loc, locations[i]);
}
Location::GPR(_) => {
self.machine.zero_location(Size::S64, locations[i]);
}
_ => unreachable!(),
}
}
if init_stack_loc_cnt > 0 {
self.machine
.init_stack_loc(init_stack_loc_cnt, last_stack_loc);
}
// Add the size of all locals allocated to stack.
self.stack_offset.0 += static_area_size - callee_saved_regs_size;
locations
}
fn finalize_locals(&mut self, calling_convention: CallingConvention) {
// Unwind stack to the "save area".
self.machine
.restore_saved_area(self.save_area_offset.as_ref().unwrap().0 as i32);
let regs_to_save = self.machine.list_to_save(calling_convention);
for loc in regs_to_save.iter().rev() {
self.machine.pop_location(*loc);
}
// Restore register used by vmctx.
self.machine
.pop_location(Location::GPR(self.machine.get_vmctx_reg()));
// Restore callee-saved registers.
for loc in self.locals.iter().rev() {
if let Location::GPR(_) = *loc {
self.machine.pop_location(*loc);
}
}
}
/// Set the source location of the Wasm to the given offset.
pub fn set_srcloc(&mut self, offset: u32) {
self.machine.set_srcloc(offset);
}
fn get_location_released(
&mut self,
loc: Location<M::GPR, M::SIMD>,
) -> Location<M::GPR, M::SIMD> {
self.release_locations(&[loc]);
loc
}
fn pop_value_released(&mut self) -> Location<M::GPR, M::SIMD> {
let loc = self
.value_stack
.pop()
.expect("pop_value_released: value stack is empty");
self.get_location_released(loc)
}
/// Prepare data for binary operator with 2 inputs and 1 output.
fn i2o1_prepare(&mut self, ty: WpType) -> I2O1<M::GPR, M::SIMD> {
let loc_b = self.pop_value_released();
let loc_a = self.pop_value_released();
let ret = self.acquire_locations(
&[(ty, MachineValue::WasmStack(self.value_stack.len()))],
false,
)[0];
self.value_stack.push(ret);
I2O1 { loc_a, loc_b, ret }
}
fn mark_trappable(&mut self) {
let state_diff_id = self.get_state_diff();
let offset = self.machine.assembler_get_offset().0;
self.fsm.trappable_offsets.insert(
offset,
OffsetInfo {
end_offset: offset + 1,
activate_offset: offset,
diff_id: state_diff_id,
},
);
self.fsm.wasm_offset_to_target_offset.insert(
self.state.wasm_inst_offset,
SuspendOffset::Trappable(offset),
);
}
fn mark_offset_trappable(&mut self, offset: usize) {
let state_diff_id = self.get_state_diff();
self.fsm.trappable_offsets.insert(
offset,
OffsetInfo {
end_offset: offset + 1,
activate_offset: offset,
diff_id: state_diff_id,
},
);
self.fsm.wasm_offset_to_target_offset.insert(
self.state.wasm_inst_offset,
SuspendOffset::Trappable(offset),
);
}
/// Emits a Native ABI call sequence.
///
/// The caller MUST NOT hold any temporary registers allocated by `acquire_temp_gpr` when calling
/// this function.
fn emit_call_native<
I: Iterator<Item = Location<M::GPR, M::SIMD>>,
J: Iterator<Item = WpType>,
F: FnOnce(&mut Self),
>(
&mut self,
cb: F,
params: I,
params_type: J,
) -> Result<(), CodegenError> {
// Values pushed in this function are above the shadow region.
self.state.stack_values.push(MachineValue::ExplicitShadow);
let params: Vec<_> = params.collect();
let params_size: Vec<_> = params_type
.map(|x| match x {
WpType::F32 | WpType::I32 => Size::S32,
WpType::V128 => unimplemented!(),
_ => Size::S64,
})
.collect();
// Save used GPRs. Preserve correct stack alignment
let used_gprs = self.machine.get_used_gprs();
let mut used_stack = self.machine.push_used_gpr(&used_gprs);
for r in used_gprs.iter() {
let content = self.state.register_values[self.machine.index_from_gpr(*r).0].clone();
if content == MachineValue::Undefined {
return Err(CodegenError {
message: "emit_call_native: Undefined used_gprs content".to_string(),
});
}
self.state.stack_values.push(content);
}
// Save used SIMD registers.
let used_simds = self.machine.get_used_simd();
if used_simds.len() > 0 {
used_stack += self.machine.push_used_simd(&used_simds);
for r in used_simds.iter().rev() {
let content =
self.state.register_values[self.machine.index_from_simd(*r).0].clone();
if content == MachineValue::Undefined {
return Err(CodegenError {
message: "emit_call_native: Undefined used_simds content".to_string(),
});
}
self.state.stack_values.push(content);
}
}
// mark the GPR used for Call as used
self.machine
.reserve_unused_temp_gpr(self.machine.get_grp_for_call());
let calling_convention = self.calling_convention;
let stack_padding: usize = match calling_convention {
CallingConvention::WindowsFastcall => 32,
_ => 0,
};
let mut stack_offset: usize = 0;
let mut args: Vec<Location<M::GPR, M::SIMD>> = vec![];
let mut pushed_args: usize = 0;
// Calculate stack offset.
for (i, _param) in params.iter().enumerate() {
args.push(self.machine.get_param_location(
1 + i,
params_size[i],
&mut stack_offset,
calling_convention,
));
}
// Align stack to 16 bytes.
let stack_unaligned =
(self.machine.round_stack_adjust(self.get_stack_offset()) + used_stack + stack_offset)
% 16;
if stack_unaligned != 0 {
stack_offset += 16 - stack_unaligned;
}
self.machine.adjust_stack(stack_offset as u32);
let mut call_movs: Vec<(Location<M::GPR, M::SIMD>, M::GPR)> = vec![];
// Prepare register & stack parameters.
for (i, param) in params.iter().enumerate().rev() {
let loc = args[i];
match loc {
Location::GPR(x) => {
call_movs.push((*param, x));
}
Location::Memory(_, _) => {
pushed_args += 1;
match *param {
Location::GPR(x) => {
let content = self.state.register_values
[self.machine.index_from_gpr(x).0]
.clone();
// FIXME: There might be some corner cases (release -> emit_call_native -> acquire?) that cause this assertion to fail.
// Hopefully nothing would be incorrect at runtime.
//assert!(content != MachineValue::Undefined);
self.state.stack_values.push(content);
}
Location::SIMD(x) => {
let content = self.state.register_values
[self.machine.index_from_simd(x).0]
.clone();
//assert!(content != MachineValue::Undefined);
self.state.stack_values.push(content);
}
Location::Memory(reg, offset) => {
if reg != self.machine.local_pointer() {
return Err(CodegenError {
message: "emit_call_native loc param: unreachable code"
.to_string(),
});
}
self.state
.stack_values
.push(MachineValue::CopyStackBPRelative(offset));
// TODO: Read value at this offset
}
_ => {
self.state.stack_values.push(MachineValue::Undefined);
}
}
self.machine
.move_location_for_native(params_size[i], *param, loc);
}
_ => {
return Err(CodegenError {
message: "emit_call_native loc: unreachable code".to_string(),
})
}
}
}
// Sort register moves so that register are not overwritten before read.
Self::sort_call_movs(&mut call_movs);
// Emit register moves.
for (loc, gpr) in call_movs {
if loc != Location::GPR(gpr) {
self.machine
.move_location(Size::S64, loc, Location::GPR(gpr));
}
}
// Put vmctx as the first parameter.
self.machine.move_location(
Size::S64,
Location::GPR(self.machine.get_vmctx_reg()),
self.machine
.get_simple_param_location(0, calling_convention),
); // vmctx
if stack_padding > 0 {
self.machine.adjust_stack(stack_padding as u32);
}
// release the GPR used for call
self.machine.release_gpr(self.machine.get_grp_for_call());
cb(self);
// Offset needs to be after the 'call' instruction.
// TODO: Now the state information is also inserted for internal calls (e.g. MemoryGrow). Is this expected?
{
let state_diff_id = self.get_state_diff();
let offset = self.machine.assembler_get_offset().0;
self.fsm.call_offsets.insert(
offset,
OffsetInfo {
end_offset: offset + 1,
activate_offset: offset,
diff_id: state_diff_id,
},
);
self.fsm
.wasm_offset_to_target_offset
.insert(self.state.wasm_inst_offset, SuspendOffset::Call(offset));
}
// Restore stack.
if stack_offset + stack_padding > 0 {
self.machine.restore_stack(
self.machine
.round_stack_adjust(stack_offset + stack_padding) as u32,
);
if (stack_offset % 8) != 0 {
return Err(CodegenError {
message: "emit_call_native: Bad restoring stack alignement".to_string(),
});
}
for _ in 0..pushed_args {
self.state.stack_values.pop().unwrap();
}
}
// Restore SIMDs.
if !used_simds.is_empty() {
self.machine.pop_used_simd(&used_simds);
for _ in 0..used_simds.len() {
self.state.stack_values.pop().unwrap();
}
}
// Restore GPRs.
self.machine.pop_used_gpr(&used_gprs);
for _ in used_gprs.iter().rev() {
self.state.stack_values.pop().unwrap();
}
if self.state.stack_values.pop().unwrap() != MachineValue::ExplicitShadow {
return Err(CodegenError {
message: "emit_call_native: Popped value is not ExplicitShadow".to_string(),
});
}
Ok(())
}
/// Emits a Native ABI call sequence, specialized for labels as the call target.
fn _emit_call_native_label<
I: Iterator<Item = Location<M::GPR, M::SIMD>>,
J: Iterator<Item = WpType>,
>(
&mut self,
label: Label,
params: I,
params_type: J,
) -> Result<(), CodegenError> {
self.emit_call_native(
|this| this.machine.emit_call_label(label),
params,
params_type,
)?;
Ok(())
}
/// Emits a memory operation.
fn op_memory<F: FnOnce(&mut Self, bool, bool, i32, Label)>(&mut self, cb: F) {
let need_check = match self.memory_styles[MemoryIndex::new(0)] {
MemoryStyle::Static { .. } => false,
MemoryStyle::Dynamic { .. } => true,
};
let offset = if self.module.num_imported_memories != 0 {
self.vmoffsets
.vmctx_vmmemory_import_definition(MemoryIndex::new(0))
} else {
self.vmoffsets
.vmctx_vmmemory_definition(LocalMemoryIndex::new(0))
};
cb(
self,
need_check,
self.module.num_imported_memories != 0,
offset as i32,
self.special_labels.heap_access_oob,
);
}
pub fn get_state_diff(&mut self) -> usize {
if !self.track_state {
return std::usize::MAX;
}
let last_frame = self.control_stack.last_mut().unwrap();
let mut diff = self.state.diff(&last_frame.state);
diff.last = Some(last_frame.state_diff_id);
let id = self.fsm.diffs.len();
last_frame.state = self.state.clone();
last_frame.state_diff_id = id;
self.fsm.diffs.push(diff);
id
}
fn emit_head(&mut self) -> Result<(), CodegenError> {
self.machine.emit_function_prolog();
// Initialize locals.
self.locals = self.init_locals(
self.local_types.len(),
self.signature.clone(),
self.calling_convention,