forked from bytecodealliance/wasmtime
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathemit.rs
3486 lines (3247 loc) · 129 KB
/
emit.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
//! Riscv64 ISA: binary code emission.
use crate::binemit::StackMap;
use crate::ir::{self, LibCall, RelSourceLoc, TrapCode};
use crate::isa::riscv64::inst::*;
use crate::isa::riscv64::lower::isle::generated_code::{
CaOp, CbOp, CiOp, CiwOp, ClOp, CrOp, CsOp, CssOp, CsznOp, ZcbMemOp,
};
use crate::machinst::{AllocationConsumer, Reg, Writable};
use crate::trace;
use cranelift_control::ControlPlane;
use regalloc2::Allocation;
pub struct EmitInfo {
shared_flag: settings::Flags,
isa_flags: super::super::riscv_settings::Flags,
}
impl EmitInfo {
pub(crate) fn new(
shared_flag: settings::Flags,
isa_flags: super::super::riscv_settings::Flags,
) -> Self {
Self {
shared_flag,
isa_flags,
}
}
}
pub(crate) fn reg_to_gpr_num(m: Reg) -> u32 {
u32::try_from(m.to_real_reg().unwrap().hw_enc() & 31).unwrap()
}
pub(crate) fn reg_to_compressed_gpr_num(m: Reg) -> u32 {
let real_reg = m.to_real_reg().unwrap().hw_enc();
debug_assert!(real_reg >= 8 && real_reg < 16);
let compressed_reg = real_reg - 8;
u32::try_from(compressed_reg).unwrap()
}
#[derive(Clone, Debug, PartialEq, Default)]
pub enum EmitVState {
#[default]
Unknown,
Known(VState),
}
/// State carried between emissions of a sequence of instructions.
#[derive(Default, Clone, Debug)]
pub struct EmitState {
pub(crate) virtual_sp_offset: i64,
pub(crate) nominal_sp_to_fp: i64,
/// Safepoint stack map for upcoming instruction, as provided to `pre_safepoint()`.
stack_map: Option<StackMap>,
/// Current source-code location corresponding to instruction to be emitted.
cur_srcloc: RelSourceLoc,
/// Only used during fuzz-testing. Otherwise, it is a zero-sized struct and
/// optimized away at compiletime. See [cranelift_control].
ctrl_plane: ControlPlane,
/// Vector State
/// Controls the current state of the vector unit at the emission point.
vstate: EmitVState,
}
impl EmitState {
fn take_stack_map(&mut self) -> Option<StackMap> {
self.stack_map.take()
}
fn cur_srcloc(&self) -> RelSourceLoc {
self.cur_srcloc
}
}
impl MachInstEmitState<Inst> for EmitState {
fn new(
abi: &Callee<crate::isa::riscv64::abi::Riscv64MachineDeps>,
ctrl_plane: ControlPlane,
) -> Self {
EmitState {
virtual_sp_offset: 0,
nominal_sp_to_fp: abi.frame_size() as i64,
stack_map: None,
cur_srcloc: RelSourceLoc::default(),
ctrl_plane,
vstate: EmitVState::Unknown,
}
}
fn pre_safepoint(&mut self, stack_map: StackMap) {
self.stack_map = Some(stack_map);
}
fn pre_sourceloc(&mut self, srcloc: RelSourceLoc) {
self.cur_srcloc = srcloc;
}
fn ctrl_plane_mut(&mut self) -> &mut ControlPlane {
&mut self.ctrl_plane
}
fn take_ctrl_plane(self) -> ControlPlane {
self.ctrl_plane
}
fn on_new_block(&mut self) {
// Reset the vector state.
self.vstate = EmitVState::Unknown;
}
}
impl Inst {
/// Load int mask.
/// If ty is int then 0xff in rd.
pub(crate) fn load_int_mask(rd: Writable<Reg>, ty: Type) -> SmallInstVec<Inst> {
let mut insts = SmallInstVec::new();
assert!(ty.is_int() && ty.bits() <= 64);
match ty {
I64 => {
insts.push(Inst::load_imm12(rd, Imm12::from_i16(-1)));
}
I32 | I16 => {
insts.push(Inst::load_imm12(rd, Imm12::from_i16(-1)));
insts.push(Inst::Extend {
rd: rd,
rn: rd.to_reg(),
signed: false,
from_bits: ty.bits() as u8,
to_bits: 64,
});
}
I8 => {
insts.push(Inst::load_imm12(rd, Imm12::from_i16(255)));
}
_ => unreachable!("ty:{:?}", ty),
}
insts
}
/// inverse all bit
pub(crate) fn construct_bit_not(rd: Writable<Reg>, rs: Reg) -> Inst {
Inst::AluRRImm12 {
alu_op: AluOPRRI::Xori,
rd,
rs,
imm12: Imm12::from_i16(-1),
}
}
// emit a float is not a nan.
pub(crate) fn emit_not_nan(rd: Writable<Reg>, rs: Reg, ty: Type) -> Inst {
Inst::FpuRRR {
alu_op: if ty == F32 {
FpuOPRRR::FeqS
} else {
FpuOPRRR::FeqD
},
frm: FRM::RDN,
rd: rd,
rs1: rs,
rs2: rs,
}
}
pub(crate) fn emit_fabs(rd: Writable<Reg>, rs: Reg, ty: Type) -> Inst {
Inst::FpuRRR {
alu_op: if ty == F32 {
FpuOPRRR::FsgnjxS
} else {
FpuOPRRR::FsgnjxD
},
frm: FRM::RDN,
rd: rd,
rs1: rs,
rs2: rs,
}
}
/// Returns Some(VState) if this insturction is expecting a specific vector state
/// before emission.
fn expected_vstate(&self) -> Option<&VState> {
match self {
Inst::Nop0
| Inst::Nop4
| Inst::BrTable { .. }
| Inst::Auipc { .. }
| Inst::Lui { .. }
| Inst::LoadInlineConst { .. }
| Inst::AluRRR { .. }
| Inst::FpuRRR { .. }
| Inst::AluRRImm12 { .. }
| Inst::CsrReg { .. }
| Inst::CsrImm { .. }
| Inst::Load { .. }
| Inst::Store { .. }
| Inst::Args { .. }
| Inst::Rets { .. }
| Inst::Ret { .. }
| Inst::Extend { .. }
| Inst::Call { .. }
| Inst::CallInd { .. }
| Inst::ReturnCall { .. }
| Inst::ReturnCallInd { .. }
| Inst::Jal { .. }
| Inst::CondBr { .. }
| Inst::LoadExtName { .. }
| Inst::ElfTlsGetAddr { .. }
| Inst::LoadAddr { .. }
| Inst::VirtualSPOffsetAdj { .. }
| Inst::Mov { .. }
| Inst::MovFromPReg { .. }
| Inst::Fence { .. }
| Inst::EBreak
| Inst::Udf { .. }
| Inst::FpuRR { .. }
| Inst::FpuRRRR { .. }
| Inst::Jalr { .. }
| Inst::Atomic { .. }
| Inst::Select { .. }
| Inst::AtomicCas { .. }
| Inst::RawData { .. }
| Inst::AtomicStore { .. }
| Inst::AtomicLoad { .. }
| Inst::AtomicRmwLoop { .. }
| Inst::TrapIf { .. }
| Inst::Unwind { .. }
| Inst::DummyUse { .. }
| Inst::FloatRound { .. }
| Inst::Popcnt { .. }
| Inst::Cltz { .. }
| Inst::Brev8 { .. }
| Inst::StackProbeLoop { .. } => None,
// VecSetState does not expect any vstate, rather it updates it.
Inst::VecSetState { .. } => None,
// `vmv` instructions copy a set of registers and ignore vstate.
Inst::VecAluRRImm5 { op: VecAluOpRRImm5::VmvrV, .. } => None,
Inst::VecAluRR { vstate, .. } |
Inst::VecAluRRR { vstate, .. } |
Inst::VecAluRRRR { vstate, .. } |
Inst::VecAluRImm5 { vstate, .. } |
Inst::VecAluRRImm5 { vstate, .. } |
Inst::VecAluRRRImm5 { vstate, .. } |
// TODO: Unit-stride loads and stores only need the AVL to be correct, not
// the full vtype. A future optimization could be to decouple these two when
// updating vstate. This would allow us to avoid emitting a VecSetState in
// some cases.
Inst::VecLoad { vstate, .. }
| Inst::VecStore { vstate, .. } => Some(vstate),
}
}
}
impl MachInstEmit for Inst {
type State = EmitState;
type Info = EmitInfo;
fn emit(
&self,
allocs: &[Allocation],
sink: &mut MachBuffer<Inst>,
emit_info: &Self::Info,
state: &mut EmitState,
) {
// Transform this into a instruction with all the physical regs
let mut allocs = AllocationConsumer::new(allocs);
let inst = self.clone().allocate(&mut allocs);
// Check if we need to update the vector state before emitting this instruction
if let Some(expected) = inst.expected_vstate() {
if state.vstate != EmitVState::Known(expected.clone()) {
// Update the vector state.
Inst::VecSetState {
rd: writable_zero_reg(),
vstate: expected.clone(),
}
.emit(&[], sink, emit_info, state);
}
}
// N.B.: we *must* not exceed the "worst-case size" used to compute
// where to insert islands, except when islands are explicitly triggered
// (with an `EmitIsland`). We check this in debug builds. This is `mut`
// to allow disabling the check for `JTSequence`, which is always
// emitted following an `EmitIsland`.
let mut start_off = sink.cur_offset();
// First try to emit this as a compressed instruction
let res = inst.try_emit_compressed(sink, emit_info, state, &mut start_off);
if res.is_none() {
// If we can't lets emit it as a normal instruction
inst.emit_uncompressed(sink, emit_info, state, &mut start_off);
}
let end_off = sink.cur_offset();
assert!(
(end_off - start_off) <= Inst::worst_case_size(),
"Inst:{:?} length:{} worst_case_size:{}",
self,
end_off - start_off,
Inst::worst_case_size()
);
}
fn pretty_print_inst(&self, allocs: &[Allocation], state: &mut Self::State) -> String {
let mut allocs = AllocationConsumer::new(allocs);
self.print_with_state(state, &mut allocs)
}
}
impl Inst {
/// Tries to emit an instruction as compressed, if we can't return false.
fn try_emit_compressed(
&self,
sink: &mut MachBuffer<Inst>,
emit_info: &EmitInfo,
state: &mut EmitState,
start_off: &mut u32,
) -> Option<()> {
let has_m = emit_info.isa_flags.has_m();
let has_zba = emit_info.isa_flags.has_zba();
let has_zbb = emit_info.isa_flags.has_zbb();
let has_zca = emit_info.isa_flags.has_zca();
let has_zcb = emit_info.isa_flags.has_zcb();
let has_zcd = emit_info.isa_flags.has_zcd();
// Currently all compressed extensions (Zcb, Zcd, Zcmp, Zcmt, etc..) require Zca
// to be enabled, so check it early.
if !has_zca {
return None;
}
fn reg_is_compressible(r: Reg) -> bool {
r.to_real_reg()
.map(|r| r.hw_enc() >= 8 && r.hw_enc() < 16)
.unwrap_or(false)
}
match *self {
// C.ADD
Inst::AluRRR {
alu_op: AluOPRRR::Add,
rd,
rs1,
rs2,
} if (rd.to_reg() == rs1 || rd.to_reg() == rs2)
&& rs1 != zero_reg()
&& rs2 != zero_reg() =>
{
// Technically `c.add rd, rs` expands to `add rd, rd, rs`, but we can
// also swap rs1 with rs2 and we get an equivalent instruction. i.e we
// can also compress `add rd, rs, rd` into `c.add rd, rs`.
let src = if rd.to_reg() == rs1 { rs2 } else { rs1 };
sink.put2(encode_cr_type(CrOp::CAdd, rd, src));
}
// C.MV
Inst::AluRRImm12 {
alu_op: AluOPRRI::Addi | AluOPRRI::Ori,
rd,
rs,
imm12,
} if rd.to_reg() != rs
&& rd.to_reg() != zero_reg()
&& rs != zero_reg()
&& imm12.as_i16() == 0 =>
{
sink.put2(encode_cr_type(CrOp::CMv, rd, rs));
}
// CA Ops
Inst::AluRRR {
alu_op:
alu_op @ (AluOPRRR::And
| AluOPRRR::Or
| AluOPRRR::Xor
| AluOPRRR::Addw
| AluOPRRR::Mul),
rd,
rs1,
rs2,
} if (rd.to_reg() == rs1 || rd.to_reg() == rs2)
&& reg_is_compressible(rs1)
&& reg_is_compressible(rs2) =>
{
let op = match alu_op {
AluOPRRR::And => CaOp::CAnd,
AluOPRRR::Or => CaOp::COr,
AluOPRRR::Xor => CaOp::CXor,
AluOPRRR::Addw => CaOp::CAddw,
AluOPRRR::Mul if has_zcb && has_m => CaOp::CMul,
_ => return None,
};
// The canonical expansion for these instruction has `rd == rs1`, but
// these are all comutative operations, so we can swap the operands.
let src = if rd.to_reg() == rs1 { rs2 } else { rs1 };
sink.put2(encode_ca_type(op, rd, src));
}
// The sub instructions are non comutative, so we can't swap the operands.
Inst::AluRRR {
alu_op: alu_op @ (AluOPRRR::Sub | AluOPRRR::Subw),
rd,
rs1,
rs2,
} if rd.to_reg() == rs1 && reg_is_compressible(rs1) && reg_is_compressible(rs2) => {
let op = match alu_op {
AluOPRRR::Sub => CaOp::CSub,
AluOPRRR::Subw => CaOp::CSubw,
_ => return None,
};
sink.put2(encode_ca_type(op, rd, rs2));
}
// c.j
//
// We don't have a separate JAL as that is only availabile in RV32C
Inst::Jal { label } => {
sink.use_label_at_offset(*start_off, label, LabelUse::RVCJump);
sink.add_uncond_branch(*start_off, *start_off + 2, label);
sink.put2(encode_cj_type(CjOp::CJ, Imm12::ZERO));
}
// c.jr
Inst::Jalr { rd, base, offset }
if rd.to_reg() == zero_reg() && base != zero_reg() && offset.as_i16() == 0 =>
{
sink.put2(encode_cr2_type(CrOp::CJr, base));
}
// c.jalr
Inst::Jalr { rd, base, offset }
if rd.to_reg() == link_reg() && base != zero_reg() && offset.as_i16() == 0 =>
{
sink.put2(encode_cr2_type(CrOp::CJalr, base));
}
// c.ebreak
Inst::EBreak => {
sink.put2(encode_cr_type(
CrOp::CEbreak,
writable_zero_reg(),
zero_reg(),
));
}
// c.unimp
Inst::Udf { trap_code } => {
sink.add_trap(trap_code);
if let Some(s) = state.take_stack_map() {
sink.add_stack_map(StackMapExtent::UpcomingBytes(2), s);
}
sink.put2(0x0000);
}
// c.addi16sp
//
// c.addi16sp shares the opcode with c.lui, but has a destination field of x2.
// c.addi16sp adds the non-zero sign-extended 6-bit immediate to the value in the stack pointer (sp=x2),
// where the immediate is scaled to represent multiples of 16 in the range (-512,496). c.addi16sp is used
// to adjust the stack pointer in procedure prologues and epilogues. It expands into addi x2, x2, nzimm. c.addi16sp
// is only valid when nzimm≠0; the code point with nzimm=0 is reserved.
Inst::AluRRImm12 {
alu_op: AluOPRRI::Addi,
rd,
rs,
imm12,
} if rd.to_reg() == rs
&& rs == stack_reg()
&& imm12.as_i16() != 0
&& (imm12.as_i16() % 16) == 0
&& Imm6::maybe_from_i16(imm12.as_i16() / 16).is_some() =>
{
let imm6 = Imm6::maybe_from_i16(imm12.as_i16() / 16).unwrap();
sink.put2(encode_c_addi16sp(imm6));
}
// c.addi4spn
//
// c.addi4spn is a CIW-format instruction that adds a zero-extended non-zero
// immediate, scaled by 4, to the stack pointer, x2, and writes the result to
// rd. This instruction is used to generate pointers to stack-allocated variables
// and expands to addi rd, x2, nzuimm. c.addi4spn is only valid when nzuimm≠0;
// the code points with nzuimm=0 are reserved.
Inst::AluRRImm12 {
alu_op: AluOPRRI::Addi,
rd,
rs,
imm12,
} if reg_is_compressible(rd.to_reg())
&& rs == stack_reg()
&& imm12.as_i16() != 0
&& (imm12.as_i16() % 4) == 0
&& u8::try_from(imm12.as_i16() / 4).is_ok() =>
{
let imm = u8::try_from(imm12.as_i16() / 4).unwrap();
sink.put2(encode_ciw_type(CiwOp::CAddi4spn, rd, imm));
}
// c.li
Inst::AluRRImm12 {
alu_op: AluOPRRI::Addi,
rd,
rs,
imm12,
} if rd.to_reg() != zero_reg() && rs == zero_reg() => {
let imm6 = Imm6::maybe_from_imm12(imm12)?;
sink.put2(encode_ci_type(CiOp::CLi, rd, imm6));
}
// c.addi
Inst::AluRRImm12 {
alu_op: AluOPRRI::Addi,
rd,
rs,
imm12,
} if rd.to_reg() == rs && rs != zero_reg() && imm12.as_i16() != 0 => {
let imm6 = Imm6::maybe_from_imm12(imm12)?;
sink.put2(encode_ci_type(CiOp::CAddi, rd, imm6));
}
// c.addiw
Inst::AluRRImm12 {
alu_op: AluOPRRI::Addiw,
rd,
rs,
imm12,
} if rd.to_reg() == rs && rs != zero_reg() => {
let imm6 = Imm6::maybe_from_imm12(imm12)?;
sink.put2(encode_ci_type(CiOp::CAddiw, rd, imm6));
}
// c.lui
//
// c.lui loads the non-zero 6-bit immediate field into bits 17–12
// of the destination register, clears the bottom 12 bits, and
// sign-extends bit 17 into all higher bits of the destination.
Inst::Lui { rd, imm: imm20 }
if rd.to_reg() != zero_reg()
&& rd.to_reg() != stack_reg()
&& imm20.as_i32() != 0 =>
{
// Check that the top bits are sign extended
let imm = imm20.as_i32() << 14 >> 14;
if imm != imm20.as_i32() {
return None;
}
let imm6 = Imm6::maybe_from_i32(imm)?;
sink.put2(encode_ci_type(CiOp::CLui, rd, imm6));
}
// c.slli
Inst::AluRRImm12 {
alu_op: AluOPRRI::Slli,
rd,
rs,
imm12,
} if rd.to_reg() == rs && rs != zero_reg() && imm12.as_i16() != 0 => {
// The shift amount is unsigned, but we encode it as signed.
let shift = imm12.as_i16() & 0x3f;
let imm6 = Imm6::maybe_from_i16(shift << 10 >> 10).unwrap();
sink.put2(encode_ci_type(CiOp::CSlli, rd, imm6));
}
// c.srli / c.srai
Inst::AluRRImm12 {
alu_op: op @ (AluOPRRI::Srli | AluOPRRI::Srai),
rd,
rs,
imm12,
} if rd.to_reg() == rs && reg_is_compressible(rs) && imm12.as_i16() != 0 => {
let op = match op {
AluOPRRI::Srli => CbOp::CSrli,
AluOPRRI::Srai => CbOp::CSrai,
_ => unreachable!(),
};
// The shift amount is unsigned, but we encode it as signed.
let shift = imm12.as_i16() & 0x3f;
let imm6 = Imm6::maybe_from_i16(shift << 10 >> 10).unwrap();
sink.put2(encode_cb_type(op, rd, imm6));
}
// c.zextb
//
// This is an alias for `andi rd, rd, 0xff`
Inst::AluRRImm12 {
alu_op: AluOPRRI::Andi,
rd,
rs,
imm12,
} if has_zcb
&& rd.to_reg() == rs
&& reg_is_compressible(rs)
&& imm12.as_i16() == 0xff =>
{
sink.put2(encode_cszn_type(CsznOp::CZextb, rd));
}
// c.andi
Inst::AluRRImm12 {
alu_op: AluOPRRI::Andi,
rd,
rs,
imm12,
} if rd.to_reg() == rs && reg_is_compressible(rs) => {
let imm6 = Imm6::maybe_from_imm12(imm12)?;
sink.put2(encode_cb_type(CbOp::CAndi, rd, imm6));
}
// Stack Based Loads
Inst::Load {
rd,
op: op @ (LoadOP::Lw | LoadOP::Ld | LoadOP::Fld),
from,
flags,
} if from.get_base_register() == Some(stack_reg())
&& (from.get_offset_with_state(state) % op.size()) == 0 =>
{
// We encode the offset in multiples of the load size.
let offset = from.get_offset_with_state(state);
let imm6 = u8::try_from(offset / op.size())
.ok()
.and_then(Uimm6::maybe_from_u8)?;
// Some additional constraints on these instructions.
//
// Integer loads are not allowed to target x0, but floating point loads
// are, since f0 is not a special register.
//
// Floating point loads are not included in the base Zca extension
// but in a separate Zcd extension. Both of these are part of the C Extension.
let rd_is_zero = rd.to_reg() == zero_reg();
let op = match op {
LoadOP::Lw if !rd_is_zero => CiOp::CLwsp,
LoadOP::Ld if !rd_is_zero => CiOp::CLdsp,
LoadOP::Fld if has_zcd => CiOp::CFldsp,
_ => return None,
};
let srcloc = state.cur_srcloc();
if !srcloc.is_default() && !flags.notrap() {
// Register the offset at which the actual load instruction starts.
sink.add_trap(TrapCode::HeapOutOfBounds);
}
sink.put2(encode_ci_sp_load(op, rd, imm6));
}
// Regular Loads
Inst::Load {
rd,
op:
op
@ (LoadOP::Lw | LoadOP::Ld | LoadOP::Fld | LoadOP::Lbu | LoadOP::Lhu | LoadOP::Lh),
from,
flags,
} if reg_is_compressible(rd.to_reg())
&& from
.get_base_register()
.map(reg_is_compressible)
.unwrap_or(false)
&& (from.get_offset_with_state(state) % op.size()) == 0 =>
{
let base = from.get_base_register().unwrap();
// We encode the offset in multiples of the store size.
let offset = from.get_offset_with_state(state);
let offset = u8::try_from(offset / op.size()).ok()?;
// We mix two different formats here.
//
// c.lw / c.ld / c.fld instructions are available in the standard Zca
// extension using the CL format.
//
// c.lbu / c.lhu / c.lh are only available in the Zcb extension and
// are also encoded differently. Technically they each have a different
// format, but they are similar enough that we can group them.
let is_zcb_load = matches!(op, LoadOP::Lbu | LoadOP::Lhu | LoadOP::Lh);
let encoded = if is_zcb_load {
if !has_zcb {
return None;
}
let op = match op {
LoadOP::Lbu => ZcbMemOp::CLbu,
LoadOP::Lhu => ZcbMemOp::CLhu,
LoadOP::Lh => ZcbMemOp::CLh,
_ => unreachable!(),
};
// Byte stores & loads have 2 bits of immediate offset. Halfword stores
// and loads only have 1 bit.
let imm2 = Uimm2::maybe_from_u8(offset)?;
if (offset & !((1 << op.imm_bits()) - 1)) != 0 {
return None;
}
encode_zcbmem_load(op, rd, base, imm2)
} else {
// Floating point loads are not included in the base Zca extension
// but in a separate Zcd extension. Both of these are part of the C Extension.
let op = match op {
LoadOP::Lw => ClOp::CLw,
LoadOP::Ld => ClOp::CLd,
LoadOP::Fld if has_zcd => ClOp::CFld,
_ => return None,
};
let imm5 = Uimm5::maybe_from_u8(offset)?;
encode_cl_type(op, rd, base, imm5)
};
let srcloc = state.cur_srcloc();
if !srcloc.is_default() && !flags.notrap() {
// Register the offset at which the actual load instruction starts.
sink.add_trap(TrapCode::HeapOutOfBounds);
}
sink.put2(encoded);
}
// Stack Based Stores
Inst::Store {
src,
op: op @ (StoreOP::Sw | StoreOP::Sd | StoreOP::Fsd),
to,
flags,
} if to.get_base_register() == Some(stack_reg())
&& (to.get_offset_with_state(state) % op.size()) == 0 =>
{
// We encode the offset in multiples of the store size.
let offset = to.get_offset_with_state(state);
let imm6 = u8::try_from(offset / op.size())
.ok()
.and_then(Uimm6::maybe_from_u8)?;
// Floating point stores are not included in the base Zca extension
// but in a separate Zcd extension. Both of these are part of the C Extension.
let op = match op {
StoreOP::Sw => CssOp::CSwsp,
StoreOP::Sd => CssOp::CSdsp,
StoreOP::Fsd if has_zcd => CssOp::CFsdsp,
_ => return None,
};
let srcloc = state.cur_srcloc();
if !srcloc.is_default() && !flags.notrap() {
// Register the offset at which the actual load instruction starts.
sink.add_trap(TrapCode::HeapOutOfBounds);
}
sink.put2(encode_css_type(op, src, imm6));
}
// Regular Stores
Inst::Store {
src,
op: op @ (StoreOP::Sw | StoreOP::Sd | StoreOP::Fsd | StoreOP::Sh | StoreOP::Sb),
to,
flags,
} if reg_is_compressible(src)
&& to
.get_base_register()
.map(reg_is_compressible)
.unwrap_or(false)
&& (to.get_offset_with_state(state) % op.size()) == 0 =>
{
let base = to.get_base_register().unwrap();
// We encode the offset in multiples of the store size.
let offset = to.get_offset_with_state(state);
let offset = u8::try_from(offset / op.size()).ok()?;
// We mix two different formats here.
//
// c.sw / c.sd / c.fsd instructions are available in the standard Zca
// extension using the CL format.
//
// c.sb / c.sh are only available in the Zcb extension and are also
// encoded differently.
let is_zcb_store = matches!(op, StoreOP::Sh | StoreOP::Sb);
let encoded = if is_zcb_store {
if !has_zcb {
return None;
}
let op = match op {
StoreOP::Sh => ZcbMemOp::CSh,
StoreOP::Sb => ZcbMemOp::CSb,
_ => unreachable!(),
};
// Byte stores & loads have 2 bits of immediate offset. Halfword stores
// and loads only have 1 bit.
let imm2 = Uimm2::maybe_from_u8(offset)?;
if (offset & !((1 << op.imm_bits()) - 1)) != 0 {
return None;
}
encode_zcbmem_store(op, src, base, imm2)
} else {
// Floating point stores are not included in the base Zca extension
// but in a separate Zcd extension. Both of these are part of the C Extension.
let op = match op {
StoreOP::Sw => CsOp::CSw,
StoreOP::Sd => CsOp::CSd,
StoreOP::Fsd if has_zcd => CsOp::CFsd,
_ => return None,
};
let imm5 = Uimm5::maybe_from_u8(offset)?;
encode_cs_type(op, src, base, imm5)
};
let srcloc = state.cur_srcloc();
if !srcloc.is_default() && !flags.notrap() {
// Register the offset at which the actual load instruction starts.
sink.add_trap(TrapCode::HeapOutOfBounds);
}
sink.put2(encoded);
}
// c.not
//
// This is an alias for `xori rd, rd, -1`
Inst::AluRRImm12 {
alu_op: AluOPRRI::Xori,
rd,
rs,
imm12,
} if has_zcb
&& rd.to_reg() == rs
&& reg_is_compressible(rs)
&& imm12.as_i16() == -1 =>
{
sink.put2(encode_cszn_type(CsznOp::CNot, rd));
}
// c.sext.b / c.sext.h / c.zext.h
//
// These are all the extend instructions present in `Zcb`, they
// also require `Zbb` since they aren't available in the base ISA.
Inst::AluRRImm12 {
alu_op: alu_op @ (AluOPRRI::Sextb | AluOPRRI::Sexth | AluOPRRI::Zexth),
rd,
rs,
imm12,
} if has_zcb
&& has_zbb
&& rd.to_reg() == rs
&& reg_is_compressible(rs)
&& imm12.as_i16() == 0 =>
{
let op = match alu_op {
AluOPRRI::Sextb => CsznOp::CSextb,
AluOPRRI::Sexth => CsznOp::CSexth,
AluOPRRI::Zexth => CsznOp::CZexth,
_ => unreachable!(),
};
sink.put2(encode_cszn_type(op, rd));
}
// c.zext.w
//
// This is an alias for `add.uw rd, rd, zero`
Inst::AluRRR {
alu_op: AluOPRRR::Adduw,
rd,
rs1,
rs2,
} if has_zcb
&& has_zba
&& rd.to_reg() == rs1
&& reg_is_compressible(rs1)
&& rs2 == zero_reg() =>
{
sink.put2(encode_cszn_type(CsznOp::CZextw, rd));
}
_ => return None,
}
return Some(());
}
fn emit_uncompressed(
&self,
sink: &mut MachBuffer<Inst>,
emit_info: &EmitInfo,
state: &mut EmitState,
start_off: &mut u32,
) {
match self {
&Inst::Nop0 => {
// do nothing
}
// Addi x0, x0, 0
&Inst::Nop4 => {
let x = Inst::AluRRImm12 {
alu_op: AluOPRRI::Addi,
rd: Writable::from_reg(zero_reg()),
rs: zero_reg(),
imm12: Imm12::ZERO,
};
x.emit(&[], sink, emit_info, state)
}
&Inst::RawData { ref data } => {
// Right now we only put a u32 or u64 in this instruction.
// It is not very long, no need to check if need `emit_island`.
// If data is very long , this is a bug because RawData is typecial
// use to load some data and rely on some positon in the code stream.
// and we may exceed `Inst::worst_case_size`.
// for more information see https://github.com/bytecodealliance/wasmtime/pull/5612.
sink.put_data(&data[..]);
}
&Inst::Lui { rd, ref imm } => {
let x: u32 = 0b0110111 | reg_to_gpr_num(rd.to_reg()) << 7 | (imm.bits() << 12);
sink.put4(x);
}
&Inst::LoadInlineConst { rd, ty, imm } => {
let data = &imm.to_le_bytes()[..ty.bytes() as usize];
let label_data: MachLabel = sink.get_label();
let label_end: MachLabel = sink.get_label();
// Load into rd
Inst::Load {
rd,
op: LoadOP::from_type(ty),
flags: MemFlags::new(),
from: AMode::Label(label_data),
}
.emit(&[], sink, emit_info, state);
// Jump over the inline pool
Inst::gen_jump(label_end).emit(&[], sink, emit_info, state);
// Emit the inline data
sink.bind_label(label_data, &mut state.ctrl_plane);
Inst::RawData { data: data.into() }.emit(&[], sink, emit_info, state);
sink.bind_label(label_end, &mut state.ctrl_plane);
}
&Inst::FpuRR {
frm,
alu_op,
rd,
rs,
} => {
let x = alu_op.op_code()
| reg_to_gpr_num(rd.to_reg()) << 7
| frm.as_u32() << 12
| reg_to_gpr_num(rs) << 15
| alu_op.rs2_funct5() << 20
| alu_op.funct7() << 25;
let srcloc = state.cur_srcloc();
if !srcloc.is_default() && alu_op.is_convert_to_int() {
sink.add_trap(TrapCode::BadConversionToInteger);
}
sink.put4(x);
}
&Inst::FpuRRRR {
alu_op,
rd,
rs1,
rs2,
rs3,
frm,
} => {
let x = alu_op.op_code()
| reg_to_gpr_num(rd.to_reg()) << 7
| frm.as_u32() << 12
| reg_to_gpr_num(rs1) << 15
| reg_to_gpr_num(rs2) << 20
| alu_op.funct2() << 25
| reg_to_gpr_num(rs3) << 27;
sink.put4(x);
}
&Inst::FpuRRR {
alu_op,
frm,
rd,
rs1,
rs2,
} => {
let x: u32 = alu_op.op_code()
| reg_to_gpr_num(rd.to_reg()) << 7
| frm.as_u32() << 12
| reg_to_gpr_num(rs1) << 15
| reg_to_gpr_num(rs2) << 20
| alu_op.funct7() << 25;
sink.put4(x);
}
&Inst::Unwind { ref inst } => {
sink.add_unwind(inst.clone());
}
&Inst::DummyUse { .. } => {