-
Notifications
You must be signed in to change notification settings - Fork 960
Expand file tree
/
Copy pathcodegen.rs
More file actions
5918 lines (5591 loc) · 234 KB
/
codegen.rs
File metadata and controls
5918 lines (5591 loc) · 234 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
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
#[cfg(feature = "unwind")]
use crate::dwarf::WriterRelocate;
use crate::{
address_map::get_function_address_map,
codegen_error,
common_decl::*,
config::Singlepass,
location::{Location, Reg},
machine::{
AssemblyComment, FinalizedAssembly, Label, Machine, NATIVE_PAGE_SIZE, UnsignedCondition,
},
unwind::UnwindFrame,
};
#[cfg(feature = "unwind")]
use gimli::write::Address;
use itertools::Itertools;
use smallvec::{SmallVec, smallvec};
use std::{cmp, collections::HashMap, iter, ops::Neg};
use target_lexicon::Architecture;
use wasmer_compiler::{
FunctionBodyData,
misc::CompiledKind,
types::{
function::{CompiledFunction, CompiledFunctionFrameInfo, FunctionBody},
relocation::{Relocation, RelocationTarget},
section::SectionIndex,
},
wasmparser::{
BlockType as WpTypeOrFuncType, HeapType as WpHeapType, Operator, RefType as WpRefType,
ValType as WpType,
},
};
#[cfg(feature = "unwind")]
use wasmer_compiler::types::unwind::CompiledFunctionUnwindInfo;
use wasmer_types::target::CallingConvention;
use wasmer_types::{
CompileError, FunctionIndex, FunctionType, GlobalIndex, LocalFunctionIndex, LocalMemoryIndex,
MemoryIndex, MemoryStyle, ModuleInfo, SignatureIndex, TableIndex, TableStyle, TrapCode, Type,
VMBuiltinFunctionIndex, VMOffsets,
entity::{EntityRef, PrimaryMap},
};
#[allow(type_alias_bounds)]
type LocationWithCanonicalization<M: Machine> = (Location<M::GPR, M::SIMD>, CanonicalizeType);
/// 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<LocationWithCanonicalization<M>>,
/// A list of frames describing the current control stack.
control_stack: Vec<ControlFrame<M>>,
/// Stack offset tracking in bytes.
stack_offset: usize,
save_area_offset: Option<usize>,
/// Low-level machine state.
machine: M,
/// Nesting level of unreachable code.
unreachable_depth: usize,
/// Index of a function defined locally inside the WebAssembly module.
local_func_index: LocalFunctionIndex,
/// Relocation information.
relocations: Vec<Relocation>,
/// A set of special labels for trapping.
special_labels: SpecialLabelSet,
/// Calling convention to use.
calling_convention: CallingConvention,
/// Name of the function.
function_name: String,
/// Assembly comments.
assembly_comments: HashMap<usize, AssemblyComment>,
}
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,
unaligned_atomic: Label,
}
/// 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)]
pub(crate) enum CanonicalizeType {
None,
F32,
F64,
}
impl CanonicalizeType {
fn to_size(self) -> Option<Size> {
match self {
CanonicalizeType::F32 => Some(Size::S32),
CanonicalizeType::F64 => Some(Size::S64),
CanonicalizeType::None => None,
}
}
fn promote(self) -> Result<Self, CompileError> {
match self {
CanonicalizeType::None => Ok(CanonicalizeType::None),
CanonicalizeType::F32 => Ok(CanonicalizeType::F64),
CanonicalizeType::F64 => codegen_error!("cannot promote F64"),
}
}
fn demote(self) -> Result<Self, CompileError> {
match self {
CanonicalizeType::None => Ok(CanonicalizeType::None),
CanonicalizeType::F32 => codegen_error!("cannot demote F64"),
CanonicalizeType::F64 => Ok(CanonicalizeType::F32),
}
}
}
trait WpTypeExt {
fn is_float(&self) -> bool;
}
impl WpTypeExt for WpType {
fn is_float(&self) -> bool {
matches!(self, WpType::F32 | WpType::F64)
}
}
#[derive(Clone)]
pub enum ControlState<M: Machine> {
Function,
Block,
Loop,
If {
label_else: Label,
// Store the input parameters for the If block, as they'll need to be
// restored when processing the Else block (if present).
inputs: SmallVec<[LocationWithCanonicalization<M>; 1]>,
},
Else,
}
#[derive(Clone)]
struct ControlFrame<M: Machine> {
pub state: ControlState<M>,
pub label: Label,
pub param_types: SmallVec<[WpType; 8]>,
pub return_types: SmallVec<[WpType; 1]>,
/// Value stack depth at the beginning of the frame (including params and results).
value_stack_depth: usize,
}
impl<M: Machine> ControlFrame<M> {
// Get value stack depth at the end of the frame.
fn value_stack_depth_after(&self) -> usize {
let mut depth: usize = self.value_stack_depth - self.param_types.len();
// For Loop, we have to use another slot for params that implements the PHI operation.
if matches!(self.state, ControlState::Loop) {
depth -= self.param_types.len();
}
depth
}
/// Returns the value stack depth at which resources should be deallocated.
/// For loops, this preserves PHI arguments by excluding them from deallocation.
fn value_stack_depth_for_release(&self) -> usize {
self.value_stack_depth - self.param_types.len()
}
}
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::Ref(WpRefType::new(true, WpHeapType::EXTERN).unwrap()),
Type::FuncRef => WpType::Ref(WpRefType::new(true, WpHeapType::FUNC).unwrap()),
Type::ExceptionRef => todo!(),
}
}
/// 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>,
}
/// Type of native call we emit.
enum NativeCallType {
IncludeVMCtxArgument,
Unreachable,
}
impl<'a, M: Machine> FuncGen<'a, M> {
/// Acquires location from the machine state.
///
/// If the returned location is used for stack value, `release_location` needs to be called on it;
/// Otherwise, if the returned locations is used for a local, `release_location` does not need to be called on it.
fn acquire_location(&mut self, ty: &WpType) -> Result<Location<M::GPR, M::SIMD>, CompileError> {
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::Ref(ty) if ty.is_extern_ref() || ty.is_func_ref() => {
self.machine.pick_gpr().map(Location::GPR)
}
_ => codegen_error!("can't acquire location for type {:?}", ty),
};
let Some(loc) = loc else {
return self.acquire_location_on_stack();
};
if let Location::GPR(x) = loc {
self.machine.reserve_gpr(x);
} else if let Location::SIMD(x) = loc {
self.machine.reserve_simd(x);
}
Ok(loc)
}
/// Acquire location that will live on the stack.
fn acquire_location_on_stack(&mut self) -> Result<Location<M::GPR, M::SIMD>, CompileError> {
self.stack_offset += 8;
let loc = self.machine.local_on_stack(self.stack_offset as i32);
self.machine
.extend_stack(self.machine.round_stack_adjust(8) as u32)?;
Ok(loc)
}
/// Releases locations used for stack value.
fn release_locations(
&mut self,
locs: &[LocationWithCanonicalization<M>],
) -> Result<(), CompileError> {
self.release_stack_locations(locs)?;
self.release_reg_locations(locs)
}
fn release_reg_locations(
&mut self,
locs: &[LocationWithCanonicalization<M>],
) -> Result<(), CompileError> {
for (loc, _) in locs.iter().rev() {
match *loc {
Location::GPR(ref x) => {
self.machine.release_gpr(*x);
}
Location::SIMD(ref x) => {
self.machine.release_simd(*x);
}
_ => {}
}
}
Ok(())
}
fn release_stack_locations(
&mut self,
locs: &[LocationWithCanonicalization<M>],
) -> Result<(), CompileError> {
for (loc, _) in locs.iter().rev() {
if let Location::Memory(..) = *loc {
self.check_location_on_stack(loc, self.stack_offset)?;
self.stack_offset -= 8;
self.machine
.truncate_stack(self.machine.round_stack_adjust(8) as u32)?;
}
}
Ok(())
}
fn release_stack_locations_keep_stack_offset(
&mut self,
stack_depth: usize,
) -> Result<(), CompileError> {
let mut stack_offset = self.stack_offset;
let locs = &self.value_stack[stack_depth..];
for (loc, _) in locs.iter().rev() {
if let Location::Memory(..) = *loc {
self.check_location_on_stack(loc, stack_offset)?;
stack_offset -= 8;
self.machine
.truncate_stack(self.machine.round_stack_adjust(8) as u32)?;
}
}
Ok(())
}
fn check_location_on_stack(
&self,
loc: &Location<M::GPR, M::SIMD>,
expected_stack_offset: usize,
) -> Result<(), CompileError> {
let Location::Memory(reg, offset) = loc else {
codegen_error!("Expected stack memory location");
};
if reg != &self.machine.local_pointer() {
codegen_error!("Expected location pointer for value on stack");
}
if *offset >= 0 {
codegen_error!("Invalid memory offset {offset}");
}
let offset = offset.neg() as usize;
if offset != expected_stack_offset {
codegen_error!("Invalid memory offset {offset}!={}", self.stack_offset);
}
Ok(())
}
/// Allocate return slots for block operands (Block, If, Loop) and swap them with
/// the corresponding input parameters on the value stack.
///
/// This method reserves memory slots that can accommodate both integer and
/// floating-point types, then swaps these slots with the last `stack_slots`
/// values on the stack to position them correctly for the block's return values.
/// that are already present at the value stack.
fn allocate_return_slots_and_swap(
&mut self,
stack_slots: usize,
return_slots: usize,
) -> Result<(), CompileError> {
// No shuffling needed.
if return_slots == 0 {
return Ok(());
}
/* To allocate N return slots, we first allocate N additional stack (memory) slots and then "shift" the
existing stack slots. This results in the layout: [value stack before frame, ret0, ret1, ret2, ..., retN, arg0, arg1, ..., argN],
where some of the argN values may reside in registers and others in memory on the stack. */
let latest_slots = self
.value_stack
.drain(self.value_stack.len() - stack_slots..)
.collect_vec();
let extra_slots = (0..return_slots)
.map(|_| self.acquire_location_on_stack())
.collect::<Result<Vec<_>, _>>()?;
let mut all_memory_slots = latest_slots
.iter()
.filter_map(|(loc, _)| {
if let Location::Memory(..) = loc {
Some(loc)
} else {
None
}
})
.chain(extra_slots.iter())
.collect_vec();
// First put the newly allocated return values to the value stack.
self.value_stack.extend(
all_memory_slots
.iter()
.take(return_slots)
.map(|loc| (**loc, CanonicalizeType::None)),
);
// Then map all memory stack slots to a new location (in reverse order).
let mut new_params_reversed = Vec::new();
for (loc, canonicalize) in latest_slots.iter().rev() {
let mapped_loc = if matches!(loc, Location::Memory(..)) {
let dest = all_memory_slots.pop().unwrap();
self.machine.emit_relaxed_mov(Size::S64, *loc, *dest)?;
*dest
} else {
*loc
};
new_params_reversed.push((mapped_loc, *canonicalize));
}
self.value_stack
.extend(new_params_reversed.into_iter().rev());
Ok(())
}
#[allow(clippy::type_complexity)]
fn init_locals(
&mut self,
n: usize,
sig: FunctionType,
calling_convention: CallingConvention,
) -> Result<Vec<Location<M::GPR, M::SIMD>>, CompileError> {
self.add_assembly_comment(AssemblyComment::InitializeLocals);
// 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);
// 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])?;
}
self.machine.extend_stack(static_area_size as _)?;
// Save callee-saved registers.
for loc in locations.iter() {
if let Location::GPR(_) = *loc {
self.stack_offset += 8;
self.machine.move_local(self.stack_offset as i32, *loc)?;
}
}
// Save the Reg use for vmctx.
self.stack_offset += 8;
self.machine.move_local(
self.stack_offset as i32,
Location::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 += 8;
self.machine.move_local(self.stack_offset as i32, *loc)?;
}
// Save the offset of register save area.
self.save_area_offset = Some(self.stack_offset);
// 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,
_ => {
codegen_error!("singlepass init_local unimplemented type: {param}")
}
};
let loc = self.machine.get_call_param_location(
sig.results().len(),
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,
Location::GPR(
self.machine
.get_simple_param_location(0, calling_convention),
),
Location::GPR(self.machine.get_vmctx_reg()),
)?;
// 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 location in locations.iter().take(n).skip(sig.params().len()) {
match location {
Location::Memory(_, _) => {
init_stack_loc_cnt += 1;
last_stack_loc = cmp::min(last_stack_loc, *location);
}
Location::GPR(_) => {
self.machine.zero_location(Size::S64, *location)?;
}
_ => codegen_error!("singlepass init_local 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 += static_area_size - callee_saved_regs_size;
Ok(locations)
}
fn finalize_locals(
&mut self,
calling_convention: CallingConvention,
) -> Result<(), CompileError> {
// Unwind stack to the "save area".
self.machine
.restore_saved_area(self.save_area_offset.unwrap() 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)?;
}
}
Ok(())
}
/// 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>, CanonicalizeType),
) -> Result<LocationWithCanonicalization<M>, CompileError> {
self.release_locations(&[loc])?;
Ok(loc)
}
fn pop_value_released(&mut self) -> Result<LocationWithCanonicalization<M>, CompileError> {
let loc = self.value_stack.pop().ok_or_else(|| {
CompileError::Codegen("pop_value_released: value stack is empty".to_owned())
})?;
self.get_location_released(loc)?;
Ok(loc)
}
/// Prepare data for binary operator with 2 inputs and 1 output.
fn i2o1_prepare(
&mut self,
ty: WpType,
canonicalize: CanonicalizeType,
) -> Result<I2O1<M::GPR, M::SIMD>, CompileError> {
let loc_b = self.pop_value_released()?.0;
let loc_a = self.pop_value_released()?.0;
let ret = self.acquire_location(&ty)?;
self.value_stack.push((ret, canonicalize));
Ok(I2O1 { loc_a, loc_b, ret })
}
/// 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>, CanonicalizeType)>,
J: Iterator<Item = WpType>,
K: Iterator<Item = WpType>,
F: FnOnce(&mut Self) -> Result<(), CompileError>,
>(
&mut self,
cb: F,
params: I,
params_type: J,
return_types: K,
call_type: NativeCallType,
) -> Result<(), CompileError> {
let params = params.collect_vec();
let stack_params = params
.iter()
.copied()
.filter(|(param, _)| {
if let Location::Memory(reg, _) = param {
debug_assert_eq!(reg, &self.machine.local_pointer());
true
} else {
false
}
})
.collect_vec();
let get_size = |param_type: WpType| match param_type {
WpType::F32 | WpType::I32 => Size::S32,
WpType::V128 => unimplemented!(),
_ => Size::S64,
};
let param_sizes = params_type.map(get_size).collect_vec();
let return_value_sizes = return_types.map(get_size).collect_vec();
/* We're going to reuse the memory param locations for the return values. Any extra needed slots will be allocated on stack. */
let used_stack_params = stack_params
.iter()
.take(return_value_sizes.len())
.copied()
.collect_vec();
let mut return_values = used_stack_params.clone();
let extra_return_values = (0..return_value_sizes.len().saturating_sub(stack_params.len()))
.map(|_| -> Result<_, CompileError> {
Ok((self.acquire_location_on_stack()?, CanonicalizeType::None))
})
.collect::<Result<Vec<_>, _>>()?;
return_values.extend(extra_return_values);
// Release the parameter slots that live in registers.
self.release_reg_locations(¶ms)?;
// 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)?;
// Save used SIMD registers.
let used_simds = self.machine.get_used_simd();
if !used_simds.is_empty() {
used_stack += self.machine.push_used_simd(&used_simds)?;
}
// mark the GPR used for Call as used
self.machine
.reserve_unused_temp_gpr(self.machine.get_gpr_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;
// Allocate space for return values relative to SP (the allocation happens in reverse order, thus start with return slots).
let mut return_args = Vec::with_capacity(return_value_sizes.len());
for i in 0..return_value_sizes.len() {
return_args.push(self.machine.get_return_value_location(
i,
&mut stack_offset,
self.calling_convention,
));
}
// Allocate space for arguments relative to SP.
let mut args = Vec::with_capacity(params.len());
for (i, param_size) in param_sizes.iter().enumerate() {
args.push(self.machine.get_param_location(
match call_type {
NativeCallType::IncludeVMCtxArgument => 1,
NativeCallType::Unreachable => 0,
} + i,
*param_size,
&mut stack_offset,
calling_convention,
));
}
// Align stack to 16 bytes.
let stack_unaligned =
(self.machine.round_stack_adjust(self.stack_offset) + used_stack + stack_offset) % 16;
if stack_unaligned != 0 {
stack_offset += 16 - stack_unaligned;
}
self.machine.extend_stack(stack_offset as u32)?;
#[allow(clippy::type_complexity)]
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(_, _) => {
self.machine
.move_location_for_native(param_sizes[i], *param, loc)?;
}
_ => {
return Err(CompileError::Codegen(
"emit_call_native loc: unreachable code".to_owned(),
));
}
}
}
// 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))?;
}
}
if matches!(call_type, NativeCallType::IncludeVMCtxArgument) {
// Put vmctx as the first parameter.
self.machine.move_location(
Size::S64,
Location::GPR(self.machine.get_vmctx_reg()),
Location::GPR(
self.machine
.get_simple_param_location(0, calling_convention),
),
)?; // vmctx
}
if stack_padding > 0 {
self.machine.extend_stack(stack_padding as u32)?;
}
// release the GPR used for call
self.machine.release_gpr(self.machine.get_gpr_for_call());
let begin = self.machine.assembler_get_offset().0;
cb(self)?;
if matches!(call_type, NativeCallType::Unreachable) {
let end = self.machine.assembler_get_offset().0;
self.machine.mark_address_range_with_trap_code(
TrapCode::UnreachableCodeReached,
begin,
end,
);
}
// Take the returned values from the fn call.
for (i, &return_type) in return_value_sizes.iter().enumerate() {
self.machine.move_location_for_native(
return_type,
return_args[i],
return_values[i].0,
)?;
}
// Restore stack.
if stack_offset + stack_padding > 0 {
self.machine
.truncate_stack((stack_offset + stack_padding) as u32)?;
}
// Restore SIMDs.
if !used_simds.is_empty() {
self.machine.pop_used_simd(&used_simds)?;
}
// Restore GPRs.
self.machine.pop_used_gpr(&used_gprs)?;
// We are re-using the params for the return values, thus release just the chunk
// we're not planning to use!
let params_to_release =
&stack_params[cmp::min(stack_params.len(), return_value_sizes.len())..];
self.release_stack_locations(params_to_release)?;
self.value_stack.extend(return_values);
Ok(())
}
/// Emits a memory operation.
fn op_memory<
F: FnOnce(&mut Self, bool, bool, i32, Label, Label) -> Result<(), CompileError>,
>(
&mut self,
cb: F,
) -> Result<(), CompileError> {
let need_check = self.config.strict_memory_boundary_checks
|| 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,
self.special_labels.unaligned_atomic,
)
}
fn emit_head(&mut self) -> Result<(), CompileError> {
self.add_assembly_comment(AssemblyComment::FunctionPrologue);
self.machine.emit_function_prolog()?;
// Initialize locals.
self.locals = self.init_locals(
self.local_types.len(),
self.signature.clone(),
self.calling_convention,
)?;
// simulate "red zone" if not supported by the platform
self.add_assembly_comment(AssemblyComment::RedZone);
self.machine.extend_stack(32)?;
let return_types: SmallVec<_> = self
.signature
.results()
.iter()
.map(type_to_wp_type)
.collect();
// Push return value slots for the function return on the stack.
self.value_stack.extend((0..return_types.len()).map(|i| {
(
self.machine
.get_call_return_value_location(i, self.calling_convention),
CanonicalizeType::None,
)
}));
self.control_stack.push(ControlFrame {
state: ControlState::Function,
label: self.machine.get_label(),
value_stack_depth: return_types.len(),
param_types: smallvec![],
return_types,
});
// TODO: Full preemption by explicit signal checking
// We insert set StackOverflow as the default trap that can happen
// anywhere in the function prologue.
self.machine.insert_stackoverflow();
self.add_assembly_comment(AssemblyComment::FunctionBody);
Ok(())
}
#[allow(clippy::too_many_arguments)]
pub fn new(
module: &'a ModuleInfo,
config: &'a Singlepass,
vmoffsets: &'a VMOffsets,
memory_styles: &'a PrimaryMap<MemoryIndex, MemoryStyle>,
_table_styles: &'a PrimaryMap<TableIndex, TableStyle>,
local_func_index: LocalFunctionIndex,
local_types_excluding_arguments: &[WpType],
machine: M,
calling_convention: CallingConvention,
) -> Result<FuncGen<'a, M>, CompileError> {
let func_index = module.func_index(local_func_index);
let sig_index = module.functions[func_index];
let signature = module.signatures[sig_index].clone();
let mut local_types: Vec<_> = signature.params().iter().map(type_to_wp_type).collect();
local_types.extend_from_slice(local_types_excluding_arguments);
let mut machine = machine;
let special_labels = SpecialLabelSet {
integer_division_by_zero: machine.get_label(),
integer_overflow: machine.get_label(),
heap_access_oob: machine.get_label(),
table_access_oob: machine.get_label(),
indirect_call_null: machine.get_label(),
bad_signature: machine.get_label(),
unaligned_atomic: machine.get_label(),
};
let function_name = module
.function_names
.get(&func_index)
.map(|fname| fname.to_string())
.unwrap_or_else(|| format!("function_{}", func_index.as_u32()));
let mut fg = FuncGen {
module,
config,
vmoffsets,
memory_styles,
// table_styles,
signature,
locals: vec![], // initialization deferred to emit_head
local_types,
value_stack: vec![],
control_stack: vec![],
stack_offset: 0,
save_area_offset: None,
machine,
unreachable_depth: 0,
local_func_index,
relocations: vec![],
special_labels,
calling_convention,
function_name,
assembly_comments: HashMap::new(),
};
fg.emit_head()?;
Ok(fg)
}
pub fn has_control_frames(&self) -> bool {
!self.control_stack.is_empty()
}
/// Moves the top `return_values` items from the value stack into the
/// preallocated return slots starting at `value_stack_depth_after`.
///
/// Used when completing Block/If/Loop constructs or returning from the
/// function. Applies NaN canonicalization when enabled and supported.
fn emit_return_values(
&mut self,
value_stack_depth_after: usize,
return_values: usize,
) -> Result<(), CompileError> {
for (i, (stack_value, canonicalize)) in self
.value_stack
.iter()
.rev()
.take(return_values)
.enumerate()
{
let dst = self.value_stack[value_stack_depth_after - i - 1].0;
if let Some(canonicalize_size) = canonicalize.to_size()
&& self.config.enable_nan_canonicalization
{
self.machine
.canonicalize_nan(canonicalize_size, *stack_value, dst)?;
} else {