Skip to main content

cranelift_codegen/isa/riscv64/inst/
emit.rs

1//! Riscv64 ISA: binary code emission.
2
3use crate::ir::{LibCall, TrapCode};
4use crate::isa::riscv64::inst::*;
5use crate::isa::riscv64::lower::isle::generated_code::{
6    CaOp, CbOp, CiOp, CiwOp, ClOp, CrOp, CsOp, CssOp, CsznOp, FpuOPWidth, ZcbMemOp,
7};
8use cranelift_control::ControlPlane;
9
10pub struct EmitInfo {
11    #[expect(dead_code, reason = "may want to be used in the future")]
12    shared_flag: settings::Flags,
13    isa_flags: super::super::riscv_settings::Flags,
14}
15
16impl EmitInfo {
17    pub(crate) fn new(
18        shared_flag: settings::Flags,
19        isa_flags: super::super::riscv_settings::Flags,
20    ) -> Self {
21        Self {
22            shared_flag,
23            isa_flags,
24        }
25    }
26}
27
28pub(crate) fn reg_to_gpr_num(m: Reg) -> u32 {
29    u32::from(m.to_real_reg().unwrap().hw_enc() & 31)
30}
31
32pub(crate) fn reg_to_compressed_gpr_num(m: Reg) -> u32 {
33    let real_reg = m.to_real_reg().unwrap().hw_enc();
34    debug_assert!(real_reg >= 8 && real_reg < 16);
35    let compressed_reg = real_reg - 8;
36    u32::from(compressed_reg)
37}
38
39#[derive(Clone, Debug, PartialEq, Default)]
40pub enum EmitVState {
41    #[default]
42    Unknown,
43    Known(VState),
44}
45
46/// State carried between emissions of a sequence of instructions.
47#[derive(Default, Clone, Debug)]
48pub struct EmitState {
49    /// Tracks user stack maps for safepoint instructions.
50    stack_maps: StackMapEmitter<Inst>,
51
52    /// Only used during fuzz-testing. Otherwise, it is a zero-sized struct and
53    /// optimized away at compiletime. See [cranelift_control].
54    ctrl_plane: ControlPlane,
55
56    /// Vector State
57    /// Controls the current state of the vector unit at the emission point.
58    vstate: EmitVState,
59
60    frame_layout: FrameLayout,
61
62    post_call_debug_tag_offset: Option<CodeOffset>,
63}
64
65impl EmitState {
66    fn clobber_vstate(&mut self) {
67        self.vstate = EmitVState::Unknown;
68    }
69}
70
71impl MachInstEmitState<Inst> for EmitState {
72    fn new(
73        abi: &Callee<crate::isa::riscv64::abi::Riscv64MachineDeps>,
74        ctrl_plane: ControlPlane,
75    ) -> Self {
76        EmitState {
77            stack_maps: StackMapEmitter::default(),
78            ctrl_plane,
79            vstate: EmitVState::Unknown,
80            frame_layout: abi.frame_layout().clone(),
81            post_call_debug_tag_offset: None,
82        }
83    }
84
85    fn stack_map_emitter(&mut self) -> &mut StackMapEmitter<Inst> {
86        &mut self.stack_maps
87    }
88
89    fn ctrl_plane_mut(&mut self) -> &mut ControlPlane {
90        &mut self.ctrl_plane
91    }
92
93    fn take_ctrl_plane(self) -> ControlPlane {
94        self.ctrl_plane
95    }
96
97    fn on_new_block(&mut self) {
98        // Reset the vector state.
99        self.clobber_vstate();
100    }
101
102    fn frame_layout(&self) -> &FrameLayout {
103        &self.frame_layout
104    }
105
106    fn post_call_debug_tag_offset_mut(&mut self) -> &mut Option<CodeOffset> {
107        &mut self.post_call_debug_tag_offset
108    }
109}
110
111impl Inst {
112    /// Load int mask.
113    /// If ty is int then 0xff in rd.
114    pub(crate) fn load_int_mask(rd: Writable<Reg>, ty: Type) -> SmallInstVec<Inst> {
115        let mut insts = SmallInstVec::new();
116        assert!(ty.is_int() && ty.bits() <= 64);
117        match ty {
118            I64 => {
119                insts.push(Inst::load_imm12(rd, Imm12::from_i16(-1)));
120            }
121            I32 | I16 => {
122                insts.push(Inst::load_imm12(rd, Imm12::from_i16(-1)));
123                insts.push(Inst::Extend {
124                    rd,
125                    rn: rd.to_reg(),
126                    signed: false,
127                    from_bits: ty.bits() as u8,
128                    to_bits: 64,
129                });
130            }
131            I8 => {
132                insts.push(Inst::load_imm12(rd, Imm12::from_i16(255)));
133            }
134            _ => unreachable!("ty:{:?}", ty),
135        }
136        insts
137    }
138    ///  inverse all bit
139    pub(crate) fn construct_bit_not(rd: Writable<Reg>, rs: Reg) -> Inst {
140        Inst::AluRRImm12 {
141            alu_op: AluOPRRI::Xori,
142            rd,
143            rs,
144            imm12: Imm12::from_i16(-1),
145        }
146    }
147
148    /// Returns Some(VState) if this instruction is expecting a specific vector state
149    /// before emission.
150    fn expected_vstate(&self) -> Option<&VState> {
151        match self {
152            Inst::Nop0
153            | Inst::Nop4
154            | Inst::BrTable { .. }
155            | Inst::Auipc { .. }
156            | Inst::Fli { .. }
157            | Inst::Lui { .. }
158            | Inst::LoadInlineConst { .. }
159            | Inst::AluRRR { .. }
160            | Inst::FpuRRR { .. }
161            | Inst::AluRRImm12 { .. }
162            | Inst::CsrReg { .. }
163            | Inst::CsrImm { .. }
164            | Inst::Load { .. }
165            | Inst::Store { .. }
166            | Inst::Args { .. }
167            | Inst::Rets { .. }
168            | Inst::Ret { .. }
169            | Inst::Extend { .. }
170            | Inst::Call { .. }
171            | Inst::CallInd { .. }
172            | Inst::ReturnCall { .. }
173            | Inst::ReturnCallInd { .. }
174            | Inst::Jal { .. }
175            | Inst::CondBr { .. }
176            | Inst::LoadExtNameGot { .. }
177            | Inst::LoadExtNameNear { .. }
178            | Inst::LoadExtNameFar { .. }
179            | Inst::ElfTlsGetAddr { .. }
180            | Inst::LoadAddr { .. }
181            | Inst::Mov { .. }
182            | Inst::MovFromPReg { .. }
183            | Inst::Fence { .. }
184            | Inst::EBreak
185            | Inst::Udf { .. }
186            | Inst::FpuRR { .. }
187            | Inst::FpuRRRR { .. }
188            | Inst::Jalr { .. }
189            | Inst::Atomic { .. }
190            | Inst::Select { .. }
191            | Inst::AtomicCas { .. }
192            | Inst::RawData { .. }
193            | Inst::AtomicStore { .. }
194            | Inst::AtomicLoad { .. }
195            | Inst::AtomicRmwLoop { .. }
196            | Inst::TrapIf { .. }
197            | Inst::Unwind { .. }
198            | Inst::DummyUse { .. }
199            | Inst::LabelAddress { .. }
200            | Inst::SequencePoint { .. }
201            | Inst::Popcnt { .. }
202            | Inst::Cltz { .. }
203            | Inst::Brev8 { .. }
204            | Inst::StackProbeLoop { .. }
205            | Inst::StackLimitJump { .. } => None,
206
207            // VecSetState does not expect any vstate, rather it updates it.
208            Inst::VecSetState { .. } => None,
209
210            // `vmv` instructions copy a set of registers and ignore vstate.
211            Inst::VecAluRRImm5 { op: VecAluOpRRImm5::VmvrV, .. } => None,
212
213            Inst::VecAluRR { vstate, .. } |
214            Inst::VecAluRRR { vstate, .. } |
215            Inst::VecAluRRRR { vstate, .. } |
216            Inst::VecAluRImm5 { vstate, .. } |
217            Inst::VecAluRRImm5 { vstate, .. } |
218            Inst::VecAluRRRImm5 { vstate, .. } |
219            // TODO: Unit-stride loads and stores only need the AVL to be correct, not
220            // the full vtype. A future optimization could be to decouple these two when
221            // updating vstate. This would allow us to avoid emitting a VecSetState in
222            // some cases.
223            Inst::VecLoad { vstate, .. }
224            | Inst::VecStore { vstate, .. } => Some(vstate),
225            Inst::EmitIsland { .. } => None,
226        }
227    }
228}
229
230impl MachInstEmit for Inst {
231    type State = EmitState;
232    type Info = EmitInfo;
233
234    fn emit(&self, sink: &mut MachBuffers<Inst>, emit_info: &Self::Info, state: &mut EmitState) {
235        // Check if we need to update the vector state before emitting this instruction
236        if let Some(expected) = self.expected_vstate() {
237            if state.vstate != EmitVState::Known(*expected) {
238                // Update the vector state.
239                Inst::VecSetState {
240                    rd: writable_zero_reg(),
241                    vstate: *expected,
242                }
243                .emit(sink, emit_info, state);
244            }
245        }
246
247        // N.B.: we *must* not exceed the "worst-case size" used to compute
248        // where to insert islands, except when islands are explicitly triggered
249        // (with an `EmitIsland`). We check this in debug builds. This is `mut`
250        // to allow disabling the check for `JTSequence`, which is always
251        // emitted following an `EmitIsland`.
252        let mut start_off = sink.cur_offset();
253
254        // First try to emit this as a compressed instruction
255        let res = self.try_emit_compressed(sink, emit_info, state, &mut start_off);
256        if res.is_none() {
257            // If we can't lets emit it as a normal instruction
258            self.emit_uncompressed(sink, emit_info, state, &mut start_off);
259        }
260
261        // We exclude br_table, call, return_call and try_call from
262        // these checks since they emit their own islands, and thus
263        // are allowed to exceed the worst case size.
264        let emits_own_island = match self {
265            Inst::BrTable { .. }
266            | Inst::ReturnCall { .. }
267            | Inst::ReturnCallInd { .. }
268            | Inst::Call { .. }
269            | Inst::CallInd { .. }
270            | Inst::EmitIsland { .. } => true,
271            _ => false,
272        };
273        if !emits_own_island {
274            let end_off = sink.cur_offset();
275            assert!(
276                (end_off - start_off) <= Inst::worst_case_size(),
277                "Inst:{:?} length:{} worst_case_size:{}",
278                self,
279                end_off - start_off,
280                Inst::worst_case_size()
281            );
282        }
283    }
284
285    fn pretty_print_inst(&self, state: &mut Self::State) -> String {
286        self.print_with_state(state)
287    }
288}
289
290impl Inst {
291    /// Tries to emit an instruction as compressed, if we can't return false.
292    fn try_emit_compressed(
293        &self,
294        sink: &mut MachBuffer<Inst>,
295        emit_info: &EmitInfo,
296        state: &mut EmitState,
297        start_off: &mut u32,
298    ) -> Option<()> {
299        let has_m = emit_info.isa_flags.has_m();
300        let has_zba = emit_info.isa_flags.has_zba();
301        let has_zbb = emit_info.isa_flags.has_zbb();
302        let has_zca = emit_info.isa_flags.has_zca();
303        let has_zcb = emit_info.isa_flags.has_zcb();
304        let has_zcd = emit_info.isa_flags.has_zcd();
305
306        // Currently all compressed extensions (Zcb, Zcd, Zcmp, Zcmt, etc..) require Zca
307        // to be enabled, so check it early.
308        if !has_zca {
309            return None;
310        }
311
312        fn reg_is_compressible(r: Reg) -> bool {
313            r.to_real_reg()
314                .map(|r| r.hw_enc() >= 8 && r.hw_enc() < 16)
315                .unwrap_or(false)
316        }
317
318        match *self {
319            // C.ADD
320            Inst::AluRRR {
321                alu_op: AluOPRRR::Add,
322                rd,
323                rs1,
324                rs2,
325            } if (rd.to_reg() == rs1 || rd.to_reg() == rs2)
326                && rs1 != zero_reg()
327                && rs2 != zero_reg() =>
328            {
329                // Technically `c.add rd, rs` expands to `add rd, rd, rs`, but we can
330                // also swap rs1 with rs2 and we get an equivalent instruction. i.e we
331                // can also compress `add rd, rs, rd` into `c.add rd, rs`.
332                let src = if rd.to_reg() == rs1 { rs2 } else { rs1 };
333
334                sink.put2(encode_cr_type(CrOp::CAdd, rd, src));
335            }
336
337            // C.MV
338            Inst::AluRRImm12 {
339                alu_op: AluOPRRI::Addi | AluOPRRI::Ori,
340                rd,
341                rs,
342                imm12,
343            } if rd.to_reg() != rs
344                && rd.to_reg() != zero_reg()
345                && rs != zero_reg()
346                && imm12.as_i16() == 0 =>
347            {
348                sink.put2(encode_cr_type(CrOp::CMv, rd, rs));
349            }
350
351            // CA Ops
352            Inst::AluRRR {
353                alu_op:
354                    alu_op @ (AluOPRRR::And
355                    | AluOPRRR::Or
356                    | AluOPRRR::Xor
357                    | AluOPRRR::Addw
358                    | AluOPRRR::Mul),
359                rd,
360                rs1,
361                rs2,
362            } if (rd.to_reg() == rs1 || rd.to_reg() == rs2)
363                && reg_is_compressible(rs1)
364                && reg_is_compressible(rs2) =>
365            {
366                let op = match alu_op {
367                    AluOPRRR::And => CaOp::CAnd,
368                    AluOPRRR::Or => CaOp::COr,
369                    AluOPRRR::Xor => CaOp::CXor,
370                    AluOPRRR::Addw => CaOp::CAddw,
371                    AluOPRRR::Mul if has_zcb && has_m => CaOp::CMul,
372                    _ => return None,
373                };
374                // The canonical expansion for these instruction has `rd == rs1`, but
375                // these are all commutative operations, so we can swap the operands.
376                let src = if rd.to_reg() == rs1 { rs2 } else { rs1 };
377
378                sink.put2(encode_ca_type(op, rd, src));
379            }
380
381            // The sub instructions are non commutative, so we can't swap the operands.
382            Inst::AluRRR {
383                alu_op: alu_op @ (AluOPRRR::Sub | AluOPRRR::Subw),
384                rd,
385                rs1,
386                rs2,
387            } if rd.to_reg() == rs1 && reg_is_compressible(rs1) && reg_is_compressible(rs2) => {
388                let op = match alu_op {
389                    AluOPRRR::Sub => CaOp::CSub,
390                    AluOPRRR::Subw => CaOp::CSubw,
391                    _ => return None,
392                };
393                sink.put2(encode_ca_type(op, rd, rs2));
394            }
395
396            // c.j
397            //
398            // We don't have a separate JAL as that is only available in RV32C
399            Inst::Jal { label } => {
400                sink.use_label_at_offset(*start_off, label, LabelUse::RVCJump);
401                sink.add_uncond_branch(*start_off, *start_off + 2, label);
402                sink.put2(encode_cj_type(CjOp::CJ, Imm12::ZERO));
403            }
404
405            // c.jr
406            Inst::Jalr { rd, base, offset }
407                if rd.to_reg() == zero_reg() && base != zero_reg() && offset.as_i16() == 0 =>
408            {
409                sink.put2(encode_cr2_type(CrOp::CJr, base));
410                state.clobber_vstate();
411            }
412
413            // c.jalr
414            Inst::Jalr { rd, base, offset }
415                if rd.to_reg() == link_reg() && base != zero_reg() && offset.as_i16() == 0 =>
416            {
417                sink.put2(encode_cr2_type(CrOp::CJalr, base));
418                state.clobber_vstate();
419            }
420
421            // c.ebreak
422            Inst::EBreak => {
423                sink.put2(encode_cr_type(
424                    CrOp::CEbreak,
425                    writable_zero_reg(),
426                    zero_reg(),
427                ));
428            }
429
430            // c.unimp
431            Inst::Udf { trap_code } => {
432                sink.add_trap(trap_code);
433                sink.put2(0x0000);
434            }
435            // c.addi16sp
436            //
437            // c.addi16sp shares the opcode with c.lui, but has a destination field of x2.
438            // c.addi16sp adds the non-zero sign-extended 6-bit immediate to the value in the stack pointer (sp=x2),
439            // where the immediate is scaled to represent multiples of 16 in the range (-512,496). c.addi16sp is used
440            // to adjust the stack pointer in procedure prologues and epilogues. It expands into addi x2, x2, nzimm. c.addi16sp
441            // is only valid when nzimm≠0; the code point with nzimm=0 is reserved.
442            Inst::AluRRImm12 {
443                alu_op: AluOPRRI::Addi,
444                rd,
445                rs,
446                imm12,
447            } if rd.to_reg() == rs
448                && rs == stack_reg()
449                && imm12.as_i16() != 0
450                && (imm12.as_i16() % 16) == 0
451                && Imm6::maybe_from_i16(imm12.as_i16() / 16).is_some() =>
452            {
453                let imm6 = Imm6::maybe_from_i16(imm12.as_i16() / 16).unwrap();
454                sink.put2(encode_c_addi16sp(imm6));
455            }
456
457            // c.addi4spn
458            //
459            // c.addi4spn is a CIW-format instruction that adds a zero-extended non-zero
460            // immediate, scaled by 4, to the stack pointer, x2, and writes the result to
461            // rd. This instruction is used to generate pointers to stack-allocated variables
462            // and expands to addi rd, x2, nzuimm. c.addi4spn is only valid when nzuimm≠0;
463            // the code points with nzuimm=0 are reserved.
464            Inst::AluRRImm12 {
465                alu_op: AluOPRRI::Addi,
466                rd,
467                rs,
468                imm12,
469            } if reg_is_compressible(rd.to_reg())
470                && rs == stack_reg()
471                && imm12.as_i16() != 0
472                && (imm12.as_i16() % 4) == 0
473                && u8::try_from(imm12.as_i16() / 4).is_ok() =>
474            {
475                let imm = u8::try_from(imm12.as_i16() / 4).unwrap();
476                sink.put2(encode_ciw_type(CiwOp::CAddi4spn, rd, imm));
477            }
478
479            // c.li
480            Inst::AluRRImm12 {
481                alu_op: AluOPRRI::Addi,
482                rd,
483                rs,
484                imm12,
485            } if rd.to_reg() != zero_reg() && rs == zero_reg() => {
486                let imm6 = Imm6::maybe_from_imm12(imm12)?;
487                sink.put2(encode_ci_type(CiOp::CLi, rd, imm6));
488            }
489
490            // c.addi
491            Inst::AluRRImm12 {
492                alu_op: AluOPRRI::Addi,
493                rd,
494                rs,
495                imm12,
496            } if rd.to_reg() == rs && rs != zero_reg() && imm12.as_i16() != 0 => {
497                let imm6 = Imm6::maybe_from_imm12(imm12)?;
498                sink.put2(encode_ci_type(CiOp::CAddi, rd, imm6));
499            }
500
501            // c.addiw
502            Inst::AluRRImm12 {
503                alu_op: AluOPRRI::Addiw,
504                rd,
505                rs,
506                imm12,
507            } if rd.to_reg() == rs && rs != zero_reg() => {
508                let imm6 = Imm6::maybe_from_imm12(imm12)?;
509                sink.put2(encode_ci_type(CiOp::CAddiw, rd, imm6));
510            }
511
512            // c.lui
513            //
514            // c.lui loads the non-zero 6-bit immediate field into bits 17–12
515            // of the destination register, clears the bottom 12 bits, and
516            // sign-extends bit 17 into all higher bits of the destination.
517            Inst::Lui { rd, imm: imm20 }
518                if rd.to_reg() != zero_reg()
519                    && rd.to_reg() != stack_reg()
520                    && imm20.as_i32() != 0 =>
521            {
522                // Check that the top bits are sign extended
523                let imm = imm20.as_i32() << 14 >> 14;
524                if imm != imm20.as_i32() {
525                    return None;
526                }
527                let imm6 = Imm6::maybe_from_i32(imm)?;
528                sink.put2(encode_ci_type(CiOp::CLui, rd, imm6));
529            }
530
531            // c.slli
532            Inst::AluRRImm12 {
533                alu_op: AluOPRRI::Slli,
534                rd,
535                rs,
536                imm12,
537            } if rd.to_reg() == rs && rs != zero_reg() && imm12.as_i16() != 0 => {
538                // The shift amount is unsigned, but we encode it as signed.
539                let shift = imm12.as_i16() & 0x3f;
540                let imm6 = Imm6::maybe_from_i16(shift << 10 >> 10).unwrap();
541                sink.put2(encode_ci_type(CiOp::CSlli, rd, imm6));
542            }
543
544            // c.srli / c.srai
545            Inst::AluRRImm12 {
546                alu_op: op @ (AluOPRRI::Srli | AluOPRRI::Srai),
547                rd,
548                rs,
549                imm12,
550            } if rd.to_reg() == rs && reg_is_compressible(rs) && imm12.as_i16() != 0 => {
551                let op = match op {
552                    AluOPRRI::Srli => CbOp::CSrli,
553                    AluOPRRI::Srai => CbOp::CSrai,
554                    _ => unreachable!(),
555                };
556
557                // The shift amount is unsigned, but we encode it as signed.
558                let shift = imm12.as_i16() & 0x3f;
559                let imm6 = Imm6::maybe_from_i16(shift << 10 >> 10).unwrap();
560                sink.put2(encode_cb_type(op, rd, imm6));
561            }
562
563            // c.zextb
564            //
565            // This is an alias for `andi rd, rd, 0xff`
566            Inst::AluRRImm12 {
567                alu_op: AluOPRRI::Andi,
568                rd,
569                rs,
570                imm12,
571            } if has_zcb
572                && rd.to_reg() == rs
573                && reg_is_compressible(rs)
574                && imm12.as_i16() == 0xff =>
575            {
576                sink.put2(encode_cszn_type(CsznOp::CZextb, rd));
577            }
578
579            // c.andi
580            Inst::AluRRImm12 {
581                alu_op: AluOPRRI::Andi,
582                rd,
583                rs,
584                imm12,
585            } if rd.to_reg() == rs && reg_is_compressible(rs) => {
586                let imm6 = Imm6::maybe_from_imm12(imm12)?;
587                sink.put2(encode_cb_type(CbOp::CAndi, rd, imm6));
588            }
589
590            // Stack Based Loads
591            Inst::Load {
592                rd,
593                op: op @ (LoadOP::Lw | LoadOP::Ld | LoadOP::Fld),
594                from,
595                flags,
596            } if from.get_base_register() == Some(stack_reg())
597                && (from.get_offset_with_state(state) % op.size()) == 0 =>
598            {
599                // We encode the offset in multiples of the load size.
600                let offset = from.get_offset_with_state(state);
601                let imm6 = u8::try_from(offset / op.size())
602                    .ok()
603                    .and_then(Uimm6::maybe_from_u8)?;
604
605                // Some additional constraints on these instructions.
606                //
607                // Integer loads are not allowed to target x0, but floating point loads
608                // are, since f0 is not a special register.
609                //
610                // Floating point loads are not included in the base Zca extension
611                // but in a separate Zcd extension. Both of these are part of the C Extension.
612                let rd_is_zero = rd.to_reg() == zero_reg();
613                let op = match op {
614                    LoadOP::Lw if !rd_is_zero => CiOp::CLwsp,
615                    LoadOP::Ld if !rd_is_zero => CiOp::CLdsp,
616                    LoadOP::Fld if has_zcd => CiOp::CFldsp,
617                    _ => return None,
618                };
619
620                if let Some(trap_code) = flags.trap_code() {
621                    // Register the offset at which the actual load instruction starts.
622                    sink.add_trap(trap_code);
623                }
624                sink.put2(encode_ci_sp_load(op, rd, imm6));
625            }
626
627            // Regular Loads
628            Inst::Load {
629                rd,
630                op:
631                    op
632                    @ (LoadOP::Lw | LoadOP::Ld | LoadOP::Fld | LoadOP::Lbu | LoadOP::Lhu | LoadOP::Lh),
633                from,
634                flags,
635            } if reg_is_compressible(rd.to_reg())
636                && from
637                    .get_base_register()
638                    .map(reg_is_compressible)
639                    .unwrap_or(false)
640                && (from.get_offset_with_state(state) % op.size()) == 0 =>
641            {
642                let base = from.get_base_register().unwrap();
643
644                // We encode the offset in multiples of the store size.
645                let offset = from.get_offset_with_state(state);
646                let offset = u8::try_from(offset / op.size()).ok()?;
647
648                // We mix two different formats here.
649                //
650                // c.lw / c.ld / c.fld instructions are available in the standard Zca
651                // extension using the CL format.
652                //
653                // c.lbu / c.lhu / c.lh are only available in the Zcb extension and
654                // are also encoded differently. Technically they each have a different
655                // format, but they are similar enough that we can group them.
656                let is_zcb_load = matches!(op, LoadOP::Lbu | LoadOP::Lhu | LoadOP::Lh);
657                let encoded = if is_zcb_load {
658                    if !has_zcb {
659                        return None;
660                    }
661
662                    let op = match op {
663                        LoadOP::Lbu => ZcbMemOp::CLbu,
664                        LoadOP::Lhu => ZcbMemOp::CLhu,
665                        LoadOP::Lh => ZcbMemOp::CLh,
666                        _ => unreachable!(),
667                    };
668
669                    // Byte stores & loads have 2 bits of immediate offset. Halfword stores
670                    // and loads only have 1 bit.
671                    let imm2 = Uimm2::maybe_from_u8(offset)?;
672                    if (offset & !((1 << op.imm_bits()) - 1)) != 0 {
673                        return None;
674                    }
675
676                    encode_zcbmem_load(op, rd, base, imm2)
677                } else {
678                    // Floating point loads are not included in the base Zca extension
679                    // but in a separate Zcd extension. Both of these are part of the C Extension.
680                    let op = match op {
681                        LoadOP::Lw => ClOp::CLw,
682                        LoadOP::Ld => ClOp::CLd,
683                        LoadOP::Fld if has_zcd => ClOp::CFld,
684                        _ => return None,
685                    };
686                    let imm5 = Uimm5::maybe_from_u8(offset)?;
687
688                    encode_cl_type(op, rd, base, imm5)
689                };
690
691                if let Some(trap_code) = flags.trap_code() {
692                    // Register the offset at which the actual load instruction starts.
693                    sink.add_trap(trap_code);
694                }
695                sink.put2(encoded);
696            }
697
698            // Stack Based Stores
699            Inst::Store {
700                src,
701                op: op @ (StoreOP::Sw | StoreOP::Sd | StoreOP::Fsd),
702                to,
703                flags,
704            } if to.get_base_register() == Some(stack_reg())
705                && (to.get_offset_with_state(state) % op.size()) == 0 =>
706            {
707                // We encode the offset in multiples of the store size.
708                let offset = to.get_offset_with_state(state);
709                let imm6 = u8::try_from(offset / op.size())
710                    .ok()
711                    .and_then(Uimm6::maybe_from_u8)?;
712
713                // Floating point stores are not included in the base Zca extension
714                // but in a separate Zcd extension. Both of these are part of the C Extension.
715                let op = match op {
716                    StoreOP::Sw => CssOp::CSwsp,
717                    StoreOP::Sd => CssOp::CSdsp,
718                    StoreOP::Fsd if has_zcd => CssOp::CFsdsp,
719                    _ => return None,
720                };
721
722                if let Some(trap_code) = flags.trap_code() {
723                    // Register the offset at which the actual load instruction starts.
724                    sink.add_trap(trap_code);
725                }
726                sink.put2(encode_css_type(op, src, imm6));
727            }
728
729            // Regular Stores
730            Inst::Store {
731                src,
732                op: op @ (StoreOP::Sw | StoreOP::Sd | StoreOP::Fsd | StoreOP::Sh | StoreOP::Sb),
733                to,
734                flags,
735            } if reg_is_compressible(src)
736                && to
737                    .get_base_register()
738                    .map(reg_is_compressible)
739                    .unwrap_or(false)
740                && (to.get_offset_with_state(state) % op.size()) == 0 =>
741            {
742                let base = to.get_base_register().unwrap();
743
744                // We encode the offset in multiples of the store size.
745                let offset = to.get_offset_with_state(state);
746                let offset = u8::try_from(offset / op.size()).ok()?;
747
748                // We mix two different formats here.
749                //
750                // c.sw / c.sd / c.fsd instructions are available in the standard Zca
751                // extension using the CL format.
752                //
753                // c.sb / c.sh are only available in the Zcb extension and are also
754                // encoded differently.
755                let is_zcb_store = matches!(op, StoreOP::Sh | StoreOP::Sb);
756                let encoded = if is_zcb_store {
757                    if !has_zcb {
758                        return None;
759                    }
760
761                    let op = match op {
762                        StoreOP::Sh => ZcbMemOp::CSh,
763                        StoreOP::Sb => ZcbMemOp::CSb,
764                        _ => unreachable!(),
765                    };
766
767                    // Byte stores & loads have 2 bits of immediate offset. Halfword stores
768                    // and loads only have 1 bit.
769                    let imm2 = Uimm2::maybe_from_u8(offset)?;
770                    if (offset & !((1 << op.imm_bits()) - 1)) != 0 {
771                        return None;
772                    }
773
774                    encode_zcbmem_store(op, src, base, imm2)
775                } else {
776                    // Floating point stores are not included in the base Zca extension
777                    // but in a separate Zcd extension. Both of these are part of the C Extension.
778                    let op = match op {
779                        StoreOP::Sw => CsOp::CSw,
780                        StoreOP::Sd => CsOp::CSd,
781                        StoreOP::Fsd if has_zcd => CsOp::CFsd,
782                        _ => return None,
783                    };
784                    let imm5 = Uimm5::maybe_from_u8(offset)?;
785
786                    encode_cs_type(op, src, base, imm5)
787                };
788
789                if let Some(trap_code) = flags.trap_code() {
790                    // Register the offset at which the actual load instruction starts.
791                    sink.add_trap(trap_code);
792                }
793                sink.put2(encoded);
794            }
795
796            // c.not
797            //
798            // This is an alias for `xori rd, rd, -1`
799            Inst::AluRRImm12 {
800                alu_op: AluOPRRI::Xori,
801                rd,
802                rs,
803                imm12,
804            } if has_zcb
805                && rd.to_reg() == rs
806                && reg_is_compressible(rs)
807                && imm12.as_i16() == -1 =>
808            {
809                sink.put2(encode_cszn_type(CsznOp::CNot, rd));
810            }
811
812            // c.sext.b / c.sext.h / c.zext.h
813            //
814            // These are all the extend instructions present in `Zcb`, they
815            // also require `Zbb` since they aren't available in the base ISA.
816            Inst::AluRRImm12 {
817                alu_op: alu_op @ (AluOPRRI::Sextb | AluOPRRI::Sexth | AluOPRRI::Zexth),
818                rd,
819                rs,
820                imm12,
821            } if has_zcb
822                && has_zbb
823                && rd.to_reg() == rs
824                && reg_is_compressible(rs)
825                && imm12.as_i16() == 0 =>
826            {
827                let op = match alu_op {
828                    AluOPRRI::Sextb => CsznOp::CSextb,
829                    AluOPRRI::Sexth => CsznOp::CSexth,
830                    AluOPRRI::Zexth => CsznOp::CZexth,
831                    _ => unreachable!(),
832                };
833                sink.put2(encode_cszn_type(op, rd));
834            }
835
836            // c.zext.w
837            //
838            // This is an alias for `add.uw rd, rd, zero`
839            Inst::AluRRR {
840                alu_op: AluOPRRR::Adduw,
841                rd,
842                rs1,
843                rs2,
844            } if has_zcb
845                && has_zba
846                && rd.to_reg() == rs1
847                && reg_is_compressible(rs1)
848                && rs2 == zero_reg() =>
849            {
850                sink.put2(encode_cszn_type(CsznOp::CZextw, rd));
851            }
852
853            _ => return None,
854        }
855
856        return Some(());
857    }
858
859    fn emit_uncompressed(
860        &self,
861        sink: &mut MachBuffers<Inst>,
862        emit_info: &EmitInfo,
863        state: &mut EmitState,
864        start_off: &mut u32,
865    ) {
866        match self {
867            &Inst::Nop0 => {
868                // do nothing
869            }
870            // Addi x0, x0, 0
871            &Inst::Nop4 => {
872                let x = Inst::AluRRImm12 {
873                    alu_op: AluOPRRI::Addi,
874                    rd: Writable::from_reg(zero_reg()),
875                    rs: zero_reg(),
876                    imm12: Imm12::ZERO,
877                };
878                x.emit(sink, emit_info, state)
879            }
880            &Inst::RawData { ref data } => {
881                // Right now we only put a u32 or u64 in this instruction.
882                // It is not very long, no need to check if need `emit_island`.
883                // If data is very long , this is a bug because RawData is typically
884                // use to load some data and rely on some position in the code stream.
885                // and we may exceed `Inst::worst_case_size`.
886                // for more information see https://github.com/bytecodealliance/wasmtime/pull/5612.
887                sink.put_data(&data[..]);
888            }
889            &Inst::Lui { rd, ref imm } => {
890                let x: u32 = 0b0110111 | reg_to_gpr_num(rd.to_reg()) << 7 | (imm.bits() << 12);
891                sink.put4(x);
892            }
893            &Inst::Fli { rd, width, imm } => {
894                sink.put4(encode_fli(width, imm, rd));
895            }
896            &Inst::LoadInlineConst { rd, ty, imm } => {
897                let data = &imm.to_le_bytes()[..ty.bytes() as usize];
898
899                let label_data: MachLabel = sink.get_label();
900                let label_end: MachLabel = sink.get_label();
901
902                // Load into rd
903                Inst::Load {
904                    rd,
905                    op: LoadOP::from_type(ty),
906                    flags: MemFlagsData::new(),
907                    from: AMode::Label(label_data),
908                }
909                .emit(sink, emit_info, state);
910
911                // Jump over the inline pool
912                Inst::gen_jump(label_end).emit(sink, emit_info, state);
913
914                // Emit the inline data
915                sink.bind_label(label_data, &mut state.ctrl_plane);
916                Inst::RawData { data: data.into() }.emit(sink, emit_info, state);
917
918                sink.bind_label(label_end, &mut state.ctrl_plane);
919            }
920            &Inst::FpuRR {
921                alu_op,
922                width,
923                frm,
924                rd,
925                rs,
926            } => {
927                if alu_op.is_convert_to_int() {
928                    sink.add_trap(TrapCode::BAD_CONVERSION_TO_INTEGER);
929                }
930                sink.put4(encode_fp_rr(alu_op, width, frm, rd, rs));
931            }
932            &Inst::FpuRRRR {
933                alu_op,
934                rd,
935                rs1,
936                rs2,
937                rs3,
938                frm,
939                width,
940            } => {
941                sink.put4(encode_fp_rrrr(alu_op, width, frm, rd, rs1, rs2, rs3));
942            }
943            &Inst::FpuRRR {
944                alu_op,
945                width,
946                frm,
947                rd,
948                rs1,
949                rs2,
950            } => {
951                sink.put4(encode_fp_rrr(alu_op, width, frm, rd, rs1, rs2));
952            }
953            &Inst::Unwind { ref inst } => {
954                sink.add_unwind(inst.clone());
955            }
956            &Inst::DummyUse { .. } => {
957                // This has already been handled by Inst::allocate.
958            }
959            &Inst::AluRRR {
960                alu_op,
961                rd,
962                rs1,
963                rs2,
964            } => {
965                let (rs1, rs2) = if alu_op.reverse_rs() {
966                    (rs2, rs1)
967                } else {
968                    (rs1, rs2)
969                };
970
971                sink.put4(encode_r_type(
972                    alu_op.op_code(),
973                    rd,
974                    alu_op.funct3(),
975                    rs1,
976                    rs2,
977                    alu_op.funct7(),
978                ));
979            }
980            &Inst::AluRRImm12 {
981                alu_op,
982                rd,
983                rs,
984                imm12,
985            } => {
986                let x = alu_op.op_code()
987                    | reg_to_gpr_num(rd.to_reg()) << 7
988                    | alu_op.funct3() << 12
989                    | reg_to_gpr_num(rs) << 15
990                    | alu_op.imm12(imm12) << 20;
991                sink.put4(x);
992            }
993            &Inst::CsrReg { op, rd, rs, csr } => {
994                sink.put4(encode_csr_reg(op, rd, rs, csr));
995            }
996            &Inst::CsrImm { op, rd, csr, imm } => {
997                sink.put4(encode_csr_imm(op, rd, csr, imm));
998            }
999            &Inst::Load {
1000                rd,
1001                op: LoadOP::Flh,
1002                from,
1003                flags,
1004            } if !emit_info.isa_flags.has_zfhmin() => {
1005                // flh unavailable, use an integer load instead
1006                Inst::Load {
1007                    rd: writable_spilltmp_reg(),
1008                    op: LoadOP::Lh,
1009                    flags,
1010                    from,
1011                }
1012                .emit(sink, emit_info, state);
1013                // NaN-box the `f16` before loading it into the floating-point
1014                // register with a 32-bit `fmv`.
1015                Inst::Lui {
1016                    rd: writable_spilltmp_reg2(),
1017                    imm: Imm20::from_i32((0xffff_0000_u32 as i32) >> 12),
1018                }
1019                .emit(sink, emit_info, state);
1020                Inst::AluRRR {
1021                    alu_op: AluOPRRR::Or,
1022                    rd: writable_spilltmp_reg(),
1023                    rs1: spilltmp_reg(),
1024                    rs2: spilltmp_reg2(),
1025                }
1026                .emit(sink, emit_info, state);
1027                Inst::FpuRR {
1028                    alu_op: FpuOPRR::FmvFmtX,
1029                    width: FpuOPWidth::S,
1030                    frm: FRM::RNE,
1031                    rd,
1032                    rs: spilltmp_reg(),
1033                }
1034                .emit(sink, emit_info, state);
1035            }
1036            &Inst::Load {
1037                rd,
1038                op,
1039                from,
1040                flags,
1041            } => {
1042                let base = from.get_base_register();
1043                let offset = from.get_offset_with_state(state);
1044                let offset_imm12 = Imm12::maybe_from_i64(offset);
1045                let target = from.pc_rel_target();
1046
1047                let (addr, imm12) = match (base, offset_imm12, target) {
1048                    // When loading from a Reg+Offset, if the offset fits into an imm12 we can directly encode it.
1049                    (Some(base), Some(imm12), None) => (base, imm12),
1050
1051                    // Otherwise, if the offset does not fit into a imm12, we need to materialize it into a
1052                    // register and load from that.
1053                    (Some(base), None, None) => {
1054                        let tmp = if base == spilltmp_reg() {
1055                            writable_spilltmp_reg2()
1056                        } else {
1057                            writable_spilltmp_reg()
1058                        };
1059                        Inst::LoadAddr { rd: tmp, mem: from }.emit(sink, emit_info, state);
1060                        (tmp.to_reg(), Imm12::ZERO)
1061                    }
1062
1063                    // If the AMode contains a label we can emit an internal relocation that gets
1064                    // resolved with the correct address later.
1065                    (None, Some(imm), Some(target)) => {
1066                        debug_assert_eq!(imm.as_i16(), 0);
1067
1068                        // Get the current PC.
1069                        target.use_hi20(sink);
1070                        Inst::Auipc {
1071                            rd,
1072                            imm: Imm20::ZERO,
1073                        }
1074                        .emit_uncompressed(sink, emit_info, state, start_off);
1075
1076                        // Emit a relocation for the load. This patches the offset into the instruction.
1077                        target.use_lo12(sink);
1078
1079                        // Imm12 here is meaningless since it's going to get replaced.
1080                        (rd.to_reg(), Imm12::ZERO)
1081                    }
1082
1083                    // These cases are impossible with the current AModes that we have. We either
1084                    // always have a register, or always have a label. Never both, and never neither.
1085                    (None, None, None)
1086                    | (None, Some(_), None)
1087                    | (Some(_), None, Some(_))
1088                    | (Some(_), Some(_), Some(_))
1089                    | (None, None, Some(_)) => {
1090                        unreachable!("Invalid load address")
1091                    }
1092                };
1093
1094                if let Some(trap_code) = flags.trap_code() {
1095                    // Register the offset at which the actual load instruction starts.
1096                    sink.add_trap(trap_code);
1097                }
1098
1099                sink.put4(encode_i_type(op.op_code(), rd, op.funct3(), addr, imm12));
1100            }
1101            &Inst::Store {
1102                op: StoreOP::Fsh,
1103                src,
1104                flags,
1105                to,
1106            } if !emit_info.isa_flags.has_zfhmin() => {
1107                // fsh unavailable, use an integer store instead
1108                Inst::FpuRR {
1109                    alu_op: FpuOPRR::FmvXFmt,
1110                    width: FpuOPWidth::S,
1111                    frm: FRM::RNE,
1112                    rd: writable_spilltmp_reg(),
1113                    rs: src,
1114                }
1115                .emit(sink, emit_info, state);
1116                Inst::Store {
1117                    to,
1118                    op: StoreOP::Sh,
1119                    flags,
1120                    src: spilltmp_reg(),
1121                }
1122                .emit(sink, emit_info, state);
1123            }
1124            &Inst::Store { op, src, flags, to } => {
1125                let base = to.get_base_register();
1126                let offset = to.get_offset_with_state(state);
1127                let offset_imm12 = Imm12::maybe_from_i64(offset);
1128
1129                let (addr, imm12) = match (base, offset_imm12) {
1130                    // If the offset fits into an imm12 we can directly encode it.
1131                    (Some(base), Some(imm12)) => (base, imm12),
1132                    // Otherwise load the address into a scratch register and store to it.
1133                    _ => {
1134                        // Avoid clobbering `base` or `src` when loading a large-offset address.
1135                        // Synthesized large stores never occupy both scratch registers simultaneously.
1136                        let tmp = if base != Some(spilltmp_reg()) && src != spilltmp_reg() {
1137                            writable_spilltmp_reg()
1138                        } else {
1139                            debug_assert!(
1140                                base != Some(spilltmp_reg2()) && src != spilltmp_reg2(),
1141                                "base ({base:?}) and src ({src:?}) cannot simultaneously occupy \
1142                                 both reserved scratch registers (x30 and x31) in a store with \
1143                                 a non-immediate offset"
1144                            );
1145                            writable_spilltmp_reg2()
1146                        };
1147                        Inst::LoadAddr { rd: tmp, mem: to }.emit(sink, emit_info, state);
1148                        (tmp.to_reg(), Imm12::ZERO)
1149                    }
1150                };
1151
1152                if let Some(trap_code) = flags.trap_code() {
1153                    // Register the offset at which the actual load instruction starts.
1154                    sink.add_trap(trap_code);
1155                }
1156
1157                sink.put4(encode_s_type(op.op_code(), op.funct3(), addr, src, imm12));
1158            }
1159            &Inst::Args { .. } | &Inst::Rets { .. } => {
1160                // Nothing: this is a pseudoinstruction that serves
1161                // only to constrain registers at a certain point.
1162            }
1163            &Inst::Ret {} => {
1164                // RISC-V does not have a dedicated ret instruction, instead we emit the equivalent
1165                // `jalr x0, x1, 0` that jumps to the return address.
1166                Inst::Jalr {
1167                    rd: writable_zero_reg(),
1168                    base: link_reg(),
1169                    offset: Imm12::ZERO,
1170                }
1171                .emit(sink, emit_info, state);
1172            }
1173
1174            &Inst::Extend {
1175                rd,
1176                rn,
1177                signed,
1178                from_bits,
1179                to_bits: _to_bits,
1180            } => {
1181                let mut insts = SmallInstVec::new();
1182                let shift_bits = (64 - from_bits) as i16;
1183                let is_u8 = || from_bits == 8 && signed == false;
1184                if is_u8() {
1185                    // special for u8.
1186                    insts.push(Inst::AluRRImm12 {
1187                        alu_op: AluOPRRI::Andi,
1188                        rd,
1189                        rs: rn,
1190                        imm12: Imm12::from_i16(255),
1191                    });
1192                } else {
1193                    insts.push(Inst::AluRRImm12 {
1194                        alu_op: AluOPRRI::Slli,
1195                        rd,
1196                        rs: rn,
1197                        imm12: Imm12::from_i16(shift_bits),
1198                    });
1199                    insts.push(Inst::AluRRImm12 {
1200                        alu_op: if signed {
1201                            AluOPRRI::Srai
1202                        } else {
1203                            AluOPRRI::Srli
1204                        },
1205                        rd,
1206                        rs: rd.to_reg(),
1207                        imm12: Imm12::from_i16(shift_bits),
1208                    });
1209                }
1210                insts
1211                    .into_iter()
1212                    .for_each(|i| i.emit(sink, emit_info, state));
1213            }
1214
1215            &Inst::Call { ref info } => {
1216                sink.add_reloc(Reloc::RiscvCallPlt, &info.dest, 0);
1217
1218                let start = sink.cur_offset();
1219                Inst::construct_auipc_and_jalr(Some(writable_link_reg()), writable_link_reg(), 0)
1220                    .into_iter()
1221                    .for_each(|i| i.emit_uncompressed(sink, emit_info, state, start_off));
1222
1223                if let Some(s) = state.stack_maps.take(sink) {
1224                    let offset = sink.cur_offset();
1225                    state.stack_maps.push(sink, &state.frame_layout, offset, s);
1226                }
1227
1228                if let Some(try_call) = info.try_call_info.as_ref() {
1229                    sink.add_try_call_site(
1230                        Some(state.frame_layout.sp_to_fp()),
1231                        try_call.exception_handlers(&state.frame_layout),
1232                    );
1233                } else {
1234                    sink.add_call_site();
1235                }
1236                state.post_call_debug_tag_offset = Some(sink.cur_offset());
1237
1238                let callee_pop_size = i32::try_from(info.callee_pop_size).unwrap();
1239                if callee_pop_size > 0 {
1240                    for inst in Riscv64MachineDeps::gen_sp_reg_adjust(-callee_pop_size) {
1241                        inst.emit(sink, emit_info, state);
1242                    }
1243                }
1244
1245                if info.patchable {
1246                    let call_len = sink.cur_offset() - start;
1247                    sink.add_patchable_call_site(call_len);
1248                } else {
1249                    // Load any stack-carried return values.
1250                    info.emit_retval_loads::<Riscv64MachineDeps, _, _>(
1251                        state.frame_layout().stackslots_size,
1252                        |inst| inst.emit(sink, emit_info, state),
1253                        |needed_space| Some(Inst::EmitIsland { needed_space }),
1254                    );
1255                }
1256
1257                // If this is a try-call, jump to the continuation
1258                // (normal-return) block.
1259                if let Some(try_call) = info.try_call_info.as_ref() {
1260                    let jmp = Inst::Jal {
1261                        label: try_call.continuation,
1262                    };
1263                    jmp.emit(sink, emit_info, state);
1264                }
1265
1266                *start_off = sink.cur_offset();
1267            }
1268            &Inst::CallInd { ref info } => {
1269                Inst::Jalr {
1270                    rd: writable_link_reg(),
1271                    base: info.dest,
1272                    offset: Imm12::ZERO,
1273                }
1274                .emit(sink, emit_info, state);
1275
1276                if let Some(s) = state.stack_maps.take(sink) {
1277                    let offset = sink.cur_offset();
1278                    state.stack_maps.push(sink, &state.frame_layout, offset, s);
1279                }
1280
1281                if let Some(try_call) = info.try_call_info.as_ref() {
1282                    sink.add_try_call_site(
1283                        Some(state.frame_layout.sp_to_fp()),
1284                        try_call.exception_handlers(&state.frame_layout),
1285                    );
1286                } else {
1287                    sink.add_call_site();
1288                }
1289                state.post_call_debug_tag_offset = Some(sink.cur_offset());
1290
1291                let callee_pop_size = i32::try_from(info.callee_pop_size).unwrap();
1292                if callee_pop_size > 0 {
1293                    for inst in Riscv64MachineDeps::gen_sp_reg_adjust(-callee_pop_size) {
1294                        inst.emit(sink, emit_info, state);
1295                    }
1296                }
1297
1298                // Load any stack-carried return values.
1299                info.emit_retval_loads::<Riscv64MachineDeps, _, _>(
1300                    state.frame_layout().stackslots_size,
1301                    |inst| inst.emit(sink, emit_info, state),
1302                    |needed_space| Some(Inst::EmitIsland { needed_space }),
1303                );
1304
1305                // If this is a try-call, jump to the continuation
1306                // (normal-return) block.
1307                if let Some(try_call) = info.try_call_info.as_ref() {
1308                    let jmp = Inst::Jal {
1309                        label: try_call.continuation,
1310                    };
1311                    jmp.emit(sink, emit_info, state);
1312                }
1313
1314                *start_off = sink.cur_offset();
1315            }
1316
1317            &Inst::ReturnCall { ref info } => {
1318                emit_return_call_common_sequence(sink, emit_info, state, info);
1319
1320                sink.add_call_site();
1321                sink.add_reloc(Reloc::RiscvCallPlt, &info.dest, 0);
1322                Inst::construct_auipc_and_jalr(None, writable_spilltmp_reg(), 0)
1323                    .into_iter()
1324                    .for_each(|i| i.emit_uncompressed(sink, emit_info, state, start_off));
1325            }
1326
1327            &Inst::ReturnCallInd { ref info } => {
1328                emit_return_call_common_sequence(sink, emit_info, state, &info);
1329
1330                Inst::Jalr {
1331                    rd: writable_zero_reg(),
1332                    base: info.dest,
1333                    offset: Imm12::ZERO,
1334                }
1335                .emit(sink, emit_info, state);
1336            }
1337            &Inst::Jal { label } => {
1338                sink.use_label_at_offset(*start_off, label, LabelUse::Jal20);
1339                sink.add_uncond_branch(*start_off, *start_off + 4, label);
1340                sink.put4(0b1101111);
1341                state.clobber_vstate();
1342            }
1343            &Inst::CondBr {
1344                taken,
1345                not_taken,
1346                kind,
1347            } => {
1348                match taken {
1349                    CondBrTarget::Label(label) => {
1350                        let code = kind.emit();
1351                        let code_inverse = kind.inverse().emit().to_le_bytes();
1352                        sink.use_label_at_offset(*start_off, label, LabelUse::B12);
1353                        sink.add_cond_branch(*start_off, *start_off + 4, label, &code_inverse);
1354                        sink.put4(code);
1355                    }
1356                    CondBrTarget::Fallthrough => panic!("Cannot fallthrough in taken target"),
1357                }
1358
1359                match not_taken {
1360                    CondBrTarget::Label(label) => {
1361                        Inst::gen_jump(label).emit(sink, emit_info, state)
1362                    }
1363                    CondBrTarget::Fallthrough => {}
1364                };
1365            }
1366
1367            &Inst::Mov { rd, rm, ty } => {
1368                debug_assert_eq!(rd.to_reg().class(), rm.class());
1369                if rd.to_reg() == rm {
1370                    return;
1371                }
1372
1373                match rm.class() {
1374                    RegClass::Int => Inst::AluRRImm12 {
1375                        alu_op: AluOPRRI::Addi,
1376                        rd,
1377                        rs: rm,
1378                        imm12: Imm12::ZERO,
1379                    },
1380                    RegClass::Float => Inst::FpuRRR {
1381                        alu_op: FpuOPRRR::Fsgnj,
1382                        width: FpuOPWidth::try_from(ty).unwrap(),
1383                        frm: FRM::RNE,
1384                        rd,
1385                        rs1: rm,
1386                        rs2: rm,
1387                    },
1388                    RegClass::Vector => Inst::VecAluRRImm5 {
1389                        op: VecAluOpRRImm5::VmvrV,
1390                        vd: rd,
1391                        vs2: rm,
1392                        // Imm 0 means copy 1 register.
1393                        imm: Imm5::maybe_from_i8(0).unwrap(),
1394                        mask: VecOpMasking::Disabled,
1395                        // Vstate for this instruction is ignored.
1396                        vstate: VState::from_type(ty),
1397                    },
1398                }
1399                .emit(sink, emit_info, state);
1400            }
1401
1402            &Inst::MovFromPReg { rd, rm } => {
1403                Inst::gen_move(rd, Reg::from(rm), I64).emit(sink, emit_info, state);
1404            }
1405
1406            &Inst::BrTable {
1407                index,
1408                tmp1,
1409                tmp2,
1410                ref targets,
1411            } => {
1412                let ext_index = writable_spilltmp_reg();
1413
1414                let label_compute_target = sink.get_label();
1415
1416                // The default target is passed in as the 0th element of `targets`
1417                // separate it here for clarity.
1418                let default_target = targets[0];
1419                let targets = &targets[1..];
1420
1421                // We are going to potentially emit a large amount of instructions, so ensure that we emit an island
1422                // now if we need one.
1423                //
1424                // The worse case PC calculations are 12 instructions. And each entry in the jump table is 2 instructions.
1425                // Check if we need to emit a jump table here to support that jump.
1426                let inst_count = 12 + (targets.len() * 2);
1427                let distance = (inst_count * Inst::UNCOMPRESSED_INSTRUCTION_SIZE as usize) as u32;
1428                if sink.island_needed(distance) {
1429                    let jump_around_label = sink.get_label();
1430                    Inst::gen_jump(jump_around_label).emit(sink, emit_info, state);
1431                    sink.emit_island(distance + 4, &mut state.ctrl_plane);
1432                    sink.bind_label(jump_around_label, &mut state.ctrl_plane);
1433                }
1434
1435                // We emit a bounds check on the index, if the index is larger than the number of
1436                // jump table entries, we jump to the default block.  Otherwise we compute a jump
1437                // offset by multiplying the index by 8 (the size of each entry) and then jump to
1438                // that offset. Each jump table entry is a regular auipc+jalr which we emit sequentially.
1439                //
1440                // Build the following sequence:
1441                //
1442                // extend_index:
1443                //     zext.w  ext_index, index
1444                // bounds_check:
1445                //     li      tmp, n_labels
1446                //     bltu    ext_index, tmp, compute_target
1447                // jump_to_default_block:
1448                //     auipc   pc, 0
1449                //     jalr    zero, pc, default_block
1450                // compute_target:
1451                //     auipc   pc, 0
1452                //     slli    tmp, ext_index, 3
1453                //     add     pc, pc, tmp
1454                //     jalr    zero, pc, 0x10
1455                // jump_table:
1456                //     ; This repeats for each entry in the jumptable
1457                //     auipc   pc, 0
1458                //     jalr    zero, pc, block_target
1459
1460                // Extend the index to 64 bits.
1461                //
1462                // This prevents us branching on the top 32 bits of the index, which
1463                // are undefined.
1464                Inst::Extend {
1465                    rd: ext_index,
1466                    rn: index,
1467                    signed: false,
1468                    from_bits: 32,
1469                    to_bits: 64,
1470                }
1471                .emit(sink, emit_info, state);
1472
1473                // Bounds check.
1474                //
1475                // Check if the index passed in is larger than the number of jumptable
1476                // entries that we have. If it is, we fallthrough to a jump into the
1477                // default block.
1478                Inst::load_constant_u32(tmp2, targets.len() as u64)
1479                    .iter()
1480                    .for_each(|i| i.emit(sink, emit_info, state));
1481                Inst::CondBr {
1482                    taken: CondBrTarget::Label(label_compute_target),
1483                    not_taken: CondBrTarget::Fallthrough,
1484                    kind: IntegerCompare {
1485                        kind: IntCC::UnsignedLessThan,
1486                        rs1: ext_index.to_reg(),
1487                        rs2: tmp2.to_reg(),
1488                    },
1489                }
1490                .emit(sink, emit_info, state);
1491
1492                let use_offset = sink.cur_offset();
1493                sink.use_label_at_offset(use_offset, default_target, LabelUse::PCRel32);
1494                Inst::construct_auipc_and_jalr(None, tmp2, 0)
1495                    .iter()
1496                    .for_each(|i| i.emit_uncompressed(sink, emit_info, state, start_off));
1497
1498                // Compute the jump table offset.
1499                // We need to emit a PC relative offset,
1500                sink.bind_label(label_compute_target, &mut state.ctrl_plane);
1501
1502                // Get the current PC.
1503                Inst::Auipc {
1504                    rd: tmp1,
1505                    imm: Imm20::ZERO,
1506                }
1507                .emit_uncompressed(sink, emit_info, state, start_off);
1508
1509                // These instructions must be emitted as uncompressed since we
1510                // are manually computing the offset from the PC.
1511
1512                // Multiply the index by 8, since that is the size in
1513                // bytes of each jump table entry
1514                Inst::AluRRImm12 {
1515                    alu_op: AluOPRRI::Slli,
1516                    rd: tmp2,
1517                    rs: ext_index.to_reg(),
1518                    imm12: Imm12::from_i16(3),
1519                }
1520                .emit_uncompressed(sink, emit_info, state, start_off);
1521
1522                // Calculate the base of the jump, PC + the offset from above.
1523                Inst::AluRRR {
1524                    alu_op: AluOPRRR::Add,
1525                    rd: tmp1,
1526                    rs1: tmp1.to_reg(),
1527                    rs2: tmp2.to_reg(),
1528                }
1529                .emit_uncompressed(sink, emit_info, state, start_off);
1530
1531                // Jump to the middle of the jump table.
1532                // We add a 16 byte offset here, since we used 4 instructions
1533                // since the AUIPC that was used to get the PC.
1534                Inst::Jalr {
1535                    rd: writable_zero_reg(),
1536                    base: tmp1.to_reg(),
1537                    offset: Imm12::from_i16((4 * Inst::UNCOMPRESSED_INSTRUCTION_SIZE) as i16),
1538                }
1539                .emit_uncompressed(sink, emit_info, state, start_off);
1540
1541                // Emit the jump table.
1542                //
1543                // Each entry is a auipc + jalr to the target block. We also start with a island
1544                // if necessary.
1545
1546                // Emit the jumps back to back
1547                for target in targets.iter() {
1548                    let use_offset = sink.cur_offset();
1549                    sink.use_label_at_offset(use_offset, *target, LabelUse::PCRel32);
1550
1551                    Inst::construct_auipc_and_jalr(None, tmp2, 0)
1552                        .iter()
1553                        .for_each(|i| i.emit_uncompressed(sink, emit_info, state, start_off));
1554                }
1555
1556                // We've just emitted an island that is safe up to *here*.
1557                // Mark it as such so that we don't needlessly emit additional islands.
1558                *start_off = sink.cur_offset();
1559            }
1560
1561            &Inst::Atomic {
1562                op,
1563                rd,
1564                addr,
1565                src,
1566                amo,
1567            } => {
1568                // TODO: get flags from original CLIF atomic instruction
1569                let flags = MemFlagsData::new();
1570                if let Some(trap_code) = flags.trap_code() {
1571                    sink.add_trap(trap_code);
1572                }
1573                let x = op.op_code()
1574                    | reg_to_gpr_num(rd.to_reg()) << 7
1575                    | op.funct3() << 12
1576                    | reg_to_gpr_num(addr) << 15
1577                    | reg_to_gpr_num(src) << 20
1578                    | op.funct7(amo) << 25;
1579
1580                sink.put4(x);
1581            }
1582            &Inst::Fence { pred, succ } => {
1583                let x = 0b0001111
1584                    | 0b00000 << 7
1585                    | 0b000 << 12
1586                    | 0b00000 << 15
1587                    | (succ as u32) << 20
1588                    | (pred as u32) << 24;
1589
1590                sink.put4(x);
1591            }
1592            &Inst::Auipc { rd, imm } => {
1593                sink.put4(enc_auipc(rd, imm));
1594            }
1595
1596            &Inst::LoadAddr { rd, mem } => {
1597                let base = mem.get_base_register();
1598                let offset = mem.get_offset_with_state(state);
1599                let offset_imm12 = Imm12::maybe_from_i64(offset);
1600
1601                match (mem, base, offset_imm12) {
1602                    (_, Some(rs), Some(imm12)) => {
1603                        Inst::AluRRImm12 {
1604                            alu_op: AluOPRRI::Addi,
1605                            rd,
1606                            rs,
1607                            imm12,
1608                        }
1609                        .emit(sink, emit_info, state);
1610                    }
1611                    (_, Some(rs), None) => {
1612                        let tmp = if rs == rd.to_reg() {
1613                            if rs == spilltmp_reg() {
1614                                writable_spilltmp_reg2()
1615                            } else {
1616                                writable_spilltmp_reg()
1617                            }
1618                        } else {
1619                            rd
1620                        };
1621                        let mut insts = Inst::load_constant_u64(tmp, offset as u64);
1622                        insts.push(Inst::AluRRR {
1623                            alu_op: AluOPRRR::Add,
1624                            rd,
1625                            rs1: tmp.to_reg(),
1626                            rs2: rs,
1627                        });
1628                        insts
1629                            .into_iter()
1630                            .for_each(|inst| inst.emit(sink, emit_info, state));
1631                    }
1632                    (AMode::Const(_) | AMode::Label(_), None, _) => {
1633                        let target = mem.pc_rel_target().unwrap();
1634
1635                        // Get the current PC.
1636                        target.use_hi20(sink);
1637                        let inst = Inst::Auipc {
1638                            rd,
1639                            imm: Imm20::ZERO,
1640                        };
1641                        inst.emit_uncompressed(sink, emit_info, state, start_off);
1642
1643                        // Emit an add to the address with a relocation.
1644                        // This later gets patched up with the correct offset.
1645                        target.use_lo12(sink);
1646                        Inst::AluRRImm12 {
1647                            alu_op: AluOPRRI::Addi,
1648                            rd,
1649                            rs: rd.to_reg(),
1650                            imm12: Imm12::ZERO,
1651                        }
1652                        .emit_uncompressed(sink, emit_info, state, start_off);
1653                    }
1654                    (amode, _, _) => {
1655                        unimplemented!("LoadAddr: {:?}", amode);
1656                    }
1657                }
1658            }
1659
1660            &Inst::Select {
1661                ref dst,
1662                condition,
1663                ref x,
1664                ref y,
1665            } => {
1666                // The general form for this select is the following:
1667                //
1668                //     mv rd, x
1669                //     b{cond} rcond, label_end
1670                //     mv rd, y
1671                // label_end:
1672                //     ... etc
1673                //
1674                // This is built on the assumption that moves are cheap, but branches and jumps
1675                // are not. So with this format we always avoid one jump instruction at the expense
1676                // of an unconditional move.
1677                //
1678                // We also perform another optimization here. If the destination register is the same
1679                // as one of the input registers, we can avoid emitting the first unconditional move
1680                // and emit just the branch and the second move.
1681                //
1682                // To make sure that this happens as often as possible, we also try to invert the
1683                // condition, so that if either of the input registers are the same as the destination
1684                // we avoid that move.
1685
1686                let label_end = sink.get_label();
1687
1688                let xregs = x.regs();
1689                let yregs = y.regs();
1690                let dstregs: Vec<Reg> = dst.regs().into_iter().map(|r| r.to_reg()).collect();
1691                let condregs = condition.regs();
1692
1693                // We are going to write to the destination register before evaluating
1694                // the condition, so we need to make sure that the destination register
1695                // is not one of the condition registers.
1696                //
1697                // This should never happen, since hopefully the regalloc constraints
1698                // for this register are set up correctly.
1699                debug_assert_ne!(dstregs, condregs);
1700
1701                // Check if we can invert the condition and avoid moving the y registers into
1702                // the destination. This allows us to only emit the branch and one of the moves.
1703                let (uncond_move, cond_move, condition) = if yregs == dstregs {
1704                    (yregs, xregs, condition.inverse())
1705                } else {
1706                    (xregs, yregs, condition)
1707                };
1708
1709                // Unconditionally move one of the values to the destination register.
1710                //
1711                // These moves may not end up being emitted if the source and
1712                // destination registers are the same. That logic is built into
1713                // the emit function for `Inst::Mov`.
1714                for i in gen_moves(dst.regs(), uncond_move) {
1715                    i.emit(sink, emit_info, state);
1716                }
1717
1718                // If the condition passes we skip over the conditional move
1719                Inst::CondBr {
1720                    taken: CondBrTarget::Label(label_end),
1721                    not_taken: CondBrTarget::Fallthrough,
1722                    kind: condition,
1723                }
1724                .emit(sink, emit_info, state);
1725
1726                // Move the conditional value to the destination register.
1727                for i in gen_moves(dst.regs(), cond_move) {
1728                    i.emit(sink, emit_info, state);
1729                }
1730
1731                sink.bind_label(label_end, &mut state.ctrl_plane);
1732            }
1733            &Inst::Jalr { rd, base, offset } => {
1734                sink.put4(enc_jalr(rd, base, offset));
1735                state.clobber_vstate();
1736            }
1737            &Inst::EBreak => {
1738                sink.put4(0x00100073);
1739            }
1740            &Inst::AtomicCas {
1741                offset,
1742                t0,
1743                dst,
1744                e,
1745                addr,
1746                v,
1747                ty,
1748            } => {
1749                //     # addr holds address of memory location
1750                //     # e holds expected value
1751                //     # v holds desired value
1752                //     # dst holds return value
1753                // cas:
1754                //     lr.w dst, (addr)       # Load original value.
1755                //     bne dst, e, fail       # Doesn’t match, so fail.
1756                //     sc.w t0, v, (addr)     # Try to update.
1757                //     bnez t0 , cas          # if store not ok,retry.
1758                // fail:
1759                let fail_label = sink.get_label();
1760                let cas_lebel = sink.get_label();
1761                sink.bind_label(cas_lebel, &mut state.ctrl_plane);
1762                Inst::Atomic {
1763                    op: AtomicOP::load_op(ty),
1764                    rd: dst,
1765                    addr,
1766                    src: zero_reg(),
1767                    amo: AMO::SeqCst,
1768                }
1769                .emit(sink, emit_info, state);
1770                if ty.bits() < 32 {
1771                    AtomicOP::extract(dst, offset, dst.to_reg(), ty)
1772                        .iter()
1773                        .for_each(|i| i.emit(sink, emit_info, state));
1774                } else if ty.bits() == 32 {
1775                    Inst::Extend {
1776                        rd: dst,
1777                        rn: dst.to_reg(),
1778                        signed: false,
1779                        from_bits: 32,
1780                        to_bits: 64,
1781                    }
1782                    .emit(sink, emit_info, state);
1783                }
1784                Inst::CondBr {
1785                    taken: CondBrTarget::Label(fail_label),
1786                    not_taken: CondBrTarget::Fallthrough,
1787                    kind: IntegerCompare {
1788                        kind: IntCC::NotEqual,
1789                        rs1: e,
1790                        rs2: dst.to_reg(),
1791                    },
1792                }
1793                .emit(sink, emit_info, state);
1794                let store_value = if ty.bits() < 32 {
1795                    // reload value to t0.
1796                    Inst::Atomic {
1797                        op: AtomicOP::load_op(ty),
1798                        rd: t0,
1799                        addr,
1800                        src: zero_reg(),
1801                        amo: AMO::SeqCst,
1802                    }
1803                    .emit(sink, emit_info, state);
1804                    // set reset part.
1805                    AtomicOP::merge(t0, writable_spilltmp_reg(), offset, v, ty)
1806                        .iter()
1807                        .for_each(|i| i.emit(sink, emit_info, state));
1808                    t0.to_reg()
1809                } else {
1810                    v
1811                };
1812                Inst::Atomic {
1813                    op: AtomicOP::store_op(ty),
1814                    rd: t0,
1815                    addr,
1816                    src: store_value,
1817                    amo: AMO::SeqCst,
1818                }
1819                .emit(sink, emit_info, state);
1820                // check is our value stored.
1821                Inst::CondBr {
1822                    taken: CondBrTarget::Label(cas_lebel),
1823                    not_taken: CondBrTarget::Fallthrough,
1824                    kind: IntegerCompare {
1825                        kind: IntCC::NotEqual,
1826                        rs1: t0.to_reg(),
1827                        rs2: zero_reg(),
1828                    },
1829                }
1830                .emit(sink, emit_info, state);
1831                sink.bind_label(fail_label, &mut state.ctrl_plane);
1832            }
1833            &Inst::AtomicRmwLoop {
1834                offset,
1835                op,
1836                dst,
1837                ty,
1838                p,
1839                x,
1840                t0,
1841            } => {
1842                let retry = sink.get_label();
1843                sink.bind_label(retry, &mut state.ctrl_plane);
1844                // load old value.
1845                Inst::Atomic {
1846                    op: AtomicOP::load_op(ty),
1847                    rd: dst,
1848                    addr: p,
1849                    src: zero_reg(),
1850                    amo: AMO::SeqCst,
1851                }
1852                .emit(sink, emit_info, state);
1853                // For sub-word ops the merge step needs the original full word.
1854                // Stash it in spilltmp2 before `extract` clobbers `dst`; reusing
1855                // the value avoids a second LR that would cancel the reservation.
1856
1857                let store_value: Reg = match op {
1858                    crate::ir::AtomicRmwOp::Add
1859                    | crate::ir::AtomicRmwOp::Sub
1860                    | crate::ir::AtomicRmwOp::And
1861                    | crate::ir::AtomicRmwOp::Or
1862                    | crate::ir::AtomicRmwOp::Xor => {
1863                        Inst::gen_move(writable_spilltmp_reg2(), dst.to_reg(), I64)
1864                            .emit(sink, emit_info, state);
1865                        AtomicOP::extract(dst, offset, dst.to_reg(), ty)
1866                            .iter()
1867                            .for_each(|i| i.emit(sink, emit_info, state));
1868                        Inst::AluRRR {
1869                            alu_op: match op {
1870                                crate::ir::AtomicRmwOp::Add => AluOPRRR::Add,
1871                                crate::ir::AtomicRmwOp::Sub => AluOPRRR::Sub,
1872                                crate::ir::AtomicRmwOp::And => AluOPRRR::And,
1873                                crate::ir::AtomicRmwOp::Or => AluOPRRR::Or,
1874                                crate::ir::AtomicRmwOp::Xor => AluOPRRR::Xor,
1875                                _ => unreachable!(),
1876                            },
1877                            rd: t0,
1878                            rs1: dst.to_reg(),
1879                            rs2: x,
1880                        }
1881                        .emit(sink, emit_info, state);
1882                        AtomicOP::merge(
1883                            writable_spilltmp_reg2(),
1884                            writable_spilltmp_reg(),
1885                            offset,
1886                            t0.to_reg(),
1887                            ty,
1888                        )
1889                        .iter()
1890                        .for_each(|i| i.emit(sink, emit_info, state));
1891                        spilltmp_reg2()
1892                    }
1893                    crate::ir::AtomicRmwOp::Nand => {
1894                        if ty.bits() < 32 {
1895                            Inst::gen_move(writable_spilltmp_reg2(), dst.to_reg(), I64)
1896                                .emit(sink, emit_info, state);
1897                            AtomicOP::extract(dst, offset, dst.to_reg(), ty)
1898                                .iter()
1899                                .for_each(|i| i.emit(sink, emit_info, state));
1900                        }
1901                        Inst::AluRRR {
1902                            alu_op: AluOPRRR::And,
1903                            rd: t0,
1904                            rs1: x,
1905                            rs2: dst.to_reg(),
1906                        }
1907                        .emit(sink, emit_info, state);
1908                        Inst::construct_bit_not(t0, t0.to_reg()).emit(sink, emit_info, state);
1909                        if ty.bits() < 32 {
1910                            AtomicOP::merge(
1911                                writable_spilltmp_reg2(),
1912                                writable_spilltmp_reg(),
1913                                offset,
1914                                t0.to_reg(),
1915                                ty,
1916                            )
1917                            .iter()
1918                            .for_each(|i| i.emit(sink, emit_info, state));
1919                            spilltmp_reg2()
1920                        } else {
1921                            t0.to_reg()
1922                        }
1923                    }
1924
1925                    crate::ir::AtomicRmwOp::Umin
1926                    | crate::ir::AtomicRmwOp::Umax
1927                    | crate::ir::AtomicRmwOp::Smin
1928                    | crate::ir::AtomicRmwOp::Smax => {
1929                        let label_select_dst = sink.get_label();
1930                        let label_select_done = sink.get_label();
1931                        Inst::gen_move(writable_spilltmp_reg2(), dst.to_reg(), I64)
1932                            .emit(sink, emit_info, state);
1933                        if op == crate::ir::AtomicRmwOp::Umin || op == crate::ir::AtomicRmwOp::Umax
1934                        {
1935                            AtomicOP::extract(dst, offset, dst.to_reg(), ty)
1936                        } else {
1937                            AtomicOP::extract_sext(dst, offset, dst.to_reg(), ty)
1938                        }
1939                        .iter()
1940                        .for_each(|i| i.emit(sink, emit_info, state));
1941
1942                        Inst::CondBr {
1943                            taken: CondBrTarget::Label(label_select_dst),
1944                            not_taken: CondBrTarget::Fallthrough,
1945                            kind: IntegerCompare {
1946                                kind: match op {
1947                                    crate::ir::AtomicRmwOp::Umin => IntCC::UnsignedLessThan,
1948                                    crate::ir::AtomicRmwOp::Umax => IntCC::UnsignedGreaterThan,
1949                                    crate::ir::AtomicRmwOp::Smin => IntCC::SignedLessThan,
1950                                    crate::ir::AtomicRmwOp::Smax => IntCC::SignedGreaterThan,
1951                                    _ => unreachable!(),
1952                                },
1953                                rs1: dst.to_reg(),
1954                                rs2: x,
1955                            },
1956                        }
1957                        .emit(sink, emit_info, state);
1958                        // here we select x.
1959                        Inst::gen_move(t0, x, I64).emit(sink, emit_info, state);
1960                        Inst::gen_jump(label_select_done).emit(sink, emit_info, state);
1961                        sink.bind_label(label_select_dst, &mut state.ctrl_plane);
1962                        Inst::gen_move(t0, dst.to_reg(), I64).emit(sink, emit_info, state);
1963                        sink.bind_label(label_select_done, &mut state.ctrl_plane);
1964                        AtomicOP::merge(
1965                            writable_spilltmp_reg2(),
1966                            writable_spilltmp_reg(),
1967                            offset,
1968                            t0.to_reg(),
1969                            ty,
1970                        )
1971                        .iter()
1972                        .for_each(|i| i.emit(sink, emit_info, state));
1973                        spilltmp_reg2()
1974                    }
1975                    crate::ir::AtomicRmwOp::Xchg => {
1976                        Inst::gen_move(writable_spilltmp_reg2(), dst.to_reg(), I64)
1977                            .emit(sink, emit_info, state);
1978                        AtomicOP::extract(dst, offset, dst.to_reg(), ty)
1979                            .iter()
1980                            .for_each(|i| i.emit(sink, emit_info, state));
1981                        AtomicOP::merge(
1982                            writable_spilltmp_reg2(),
1983                            writable_spilltmp_reg(),
1984                            offset,
1985                            x,
1986                            ty,
1987                        )
1988                        .iter()
1989                        .for_each(|i| i.emit(sink, emit_info, state));
1990                        spilltmp_reg2()
1991                    }
1992                };
1993
1994                Inst::Atomic {
1995                    op: AtomicOP::store_op(ty),
1996                    rd: t0,
1997                    addr: p,
1998                    src: store_value,
1999                    amo: AMO::SeqCst,
2000                }
2001                .emit(sink, emit_info, state);
2002
2003                // if store is not ok,retry.
2004                Inst::CondBr {
2005                    taken: CondBrTarget::Label(retry),
2006                    not_taken: CondBrTarget::Fallthrough,
2007                    kind: IntegerCompare {
2008                        kind: IntCC::NotEqual,
2009                        rs1: t0.to_reg(),
2010                        rs2: zero_reg(),
2011                    },
2012                }
2013                .emit(sink, emit_info, state);
2014            }
2015
2016            &Inst::LoadExtNameGot { rd, ref name } => {
2017                // Load a PC-relative address into a register.
2018                // RISC-V does this slightly differently from other arches. We emit a relocation
2019                // with a label, instead of the symbol itself.
2020                //
2021                // See: https://github.com/riscv-non-isa/riscv-elf-psabi-doc/blob/master/riscv-elf.adoc#pc-relative-symbol-addresses
2022                //
2023                // Emit the following code:
2024                // label:
2025                //   auipc rd, 0              # R_RISCV_GOT_HI20 (symbol_name)
2026                //   ld    rd, rd, 0          # R_RISCV_PCREL_LO12_I (label)
2027
2028                // Create the label that is going to be published to the final binary object.
2029                let auipc_label = sink.get_label();
2030                sink.bind_label(auipc_label, &mut state.ctrl_plane);
2031
2032                // Get the current PC.
2033                sink.add_reloc(Reloc::RiscvGotHi20, &**name, 0);
2034                Inst::Auipc {
2035                    rd,
2036                    imm: Imm20::from_i32(0),
2037                }
2038                .emit_uncompressed(sink, emit_info, state, start_off);
2039
2040                // The `ld` here, points to the `auipc` label instead of directly to the symbol.
2041                sink.add_reloc(Reloc::RiscvPCRelLo12I, &auipc_label, 0);
2042                Inst::Load {
2043                    rd,
2044                    op: LoadOP::Ld,
2045                    flags: MemFlagsData::trusted(),
2046                    from: AMode::RegOffset(rd.to_reg(), 0),
2047                }
2048                .emit_uncompressed(sink, emit_info, state, start_off);
2049            }
2050
2051            &Inst::LoadExtNameFar {
2052                rd,
2053                ref name,
2054                offset,
2055            } => {
2056                // In the non PIC sequence we relocate the absolute address into
2057                // a preallocated space, load it into a register and jump over
2058                // it.
2059                //
2060                // Emit the following code:
2061                //   ld rd, label_data
2062                //   j label_end
2063                // label_data:
2064                //   <8 byte space>           # ABS8
2065                // label_end:
2066
2067                let label_data = sink.get_label();
2068                let label_end = sink.get_label();
2069
2070                // Load the value from a label
2071                Inst::Load {
2072                    rd,
2073                    op: LoadOP::Ld,
2074                    flags: MemFlagsData::trusted(),
2075                    from: AMode::Label(label_data),
2076                }
2077                .emit(sink, emit_info, state);
2078
2079                // Jump over the data
2080                Inst::gen_jump(label_end).emit(sink, emit_info, state);
2081
2082                sink.bind_label(label_data, &mut state.ctrl_plane);
2083                sink.add_reloc(Reloc::Abs8, name.as_ref(), offset);
2084                sink.put8(0);
2085
2086                sink.bind_label(label_end, &mut state.ctrl_plane);
2087            }
2088
2089            &Inst::LoadExtNameNear {
2090                rd,
2091                ref name,
2092                offset,
2093            } => {
2094                // Emit the following code:
2095                // label:
2096                //   auipc rd, 0              # R_RISCV_PCREL_HI20 (symbol_name)
2097                //   ld    rd, rd, 0          # R_RISCV_PCREL_LO12_I (label)
2098
2099                let auipc_label = sink.get_label();
2100                sink.bind_label(auipc_label, &mut state.ctrl_plane);
2101
2102                // Get the current PC.
2103                sink.add_reloc(Reloc::RiscvPCRelHi20, &**name, offset);
2104                Inst::Auipc {
2105                    rd,
2106                    imm: Imm20::from_i32(0),
2107                }
2108                .emit_uncompressed(sink, emit_info, state, start_off);
2109
2110                sink.add_reloc(Reloc::RiscvPCRelLo12I, &auipc_label, 0);
2111                Inst::AluRRImm12 {
2112                    alu_op: AluOPRRI::Addi,
2113                    rd,
2114                    rs: rd.to_reg(),
2115                    imm12: Imm12::ZERO,
2116                }
2117                .emit_uncompressed(sink, emit_info, state, start_off);
2118            }
2119
2120            &Inst::LabelAddress { dst, label } => {
2121                let offset = sink.cur_offset();
2122                Inst::Auipc {
2123                    rd: dst,
2124                    imm: Imm20::from_i32(0),
2125                }
2126                .emit_uncompressed(sink, emit_info, state, start_off);
2127                sink.use_label_at_offset(offset, label, LabelUse::PCRelHi20);
2128
2129                let offset = sink.cur_offset();
2130                Inst::AluRRImm12 {
2131                    alu_op: AluOPRRI::Addi,
2132                    rd: dst,
2133                    rs: dst.to_reg(),
2134                    imm12: Imm12::ZERO,
2135                }
2136                .emit_uncompressed(sink, emit_info, state, start_off);
2137                sink.use_label_at_offset(offset, label, LabelUse::PCRelLo12I);
2138            }
2139
2140            &Inst::ElfTlsGetAddr { rd, ref name } => {
2141                // RISC-V's TLS GD model is slightly different from other arches.
2142                //
2143                // We have a relocation (R_RISCV_TLS_GD_HI20) that loads the high 20 bits
2144                // of the address relative to the GOT entry. This relocation points to
2145                // the symbol as usual.
2146                //
2147                // However when loading the bottom 12bits of the address, we need to
2148                // use a label that points to the previous AUIPC instruction.
2149                //
2150                // label:
2151                //    auipc a0,0                    # R_RISCV_TLS_GD_HI20 (symbol)
2152                //    addi  a0,a0,0                 # R_RISCV_PCREL_LO12_I (label)
2153                //
2154                // https://github.com/riscv-non-isa/riscv-elf-psabi-doc/blob/master/riscv-elf.adoc#global-dynamic
2155
2156                // Create the label that is going to be published to the final binary object.
2157                let auipc_label = sink.get_label();
2158                sink.bind_label(auipc_label, &mut state.ctrl_plane);
2159
2160                // Get the current PC.
2161                sink.add_reloc(Reloc::RiscvTlsGdHi20, &**name, 0);
2162                Inst::Auipc {
2163                    rd,
2164                    imm: Imm20::from_i32(0),
2165                }
2166                .emit_uncompressed(sink, emit_info, state, start_off);
2167
2168                // The `addi` here, points to the `auipc` label instead of directly to the symbol.
2169                sink.add_reloc(Reloc::RiscvPCRelLo12I, &auipc_label, 0);
2170                Inst::AluRRImm12 {
2171                    alu_op: AluOPRRI::Addi,
2172                    rd,
2173                    rs: rd.to_reg(),
2174                    imm12: Imm12::from_i16(0),
2175                }
2176                .emit_uncompressed(sink, emit_info, state, start_off);
2177
2178                Inst::Call {
2179                    info: Box::new(CallInfo::empty(
2180                        ExternalName::LibCall(LibCall::ElfTlsGetAddr),
2181                        CallConv::SystemV,
2182                    )),
2183                }
2184                .emit_uncompressed(sink, emit_info, state, start_off);
2185            }
2186
2187            &Inst::StackLimitJump { limit, ref handler } => {
2188                // Generate the following code:
2189                //         bgeu  sp, limit, .ok    ;; no overflow
2190                //         auipc t6, handler       ;; tail call
2191                //         jalr  x0, t6
2192                // .ok:
2193                let ok = sink.get_label();
2194                Inst::CondBr {
2195                    taken: CondBrTarget::Label(ok),
2196                    not_taken: CondBrTarget::Fallthrough,
2197                    kind: IntegerCompare {
2198                        kind: IntCC::UnsignedGreaterThanOrEqual,
2199                        rs1: stack_reg(),
2200                        rs2: limit,
2201                    },
2202                }
2203                .emit(sink, emit_info, state);
2204                sink.add_reloc(Reloc::RiscvCallPlt, &**handler, 0);
2205                Inst::construct_auipc_and_jalr(None, writable_spilltmp_reg(), 0)
2206                    .into_iter()
2207                    .for_each(|i| i.emit_uncompressed(sink, emit_info, state, start_off));
2208                sink.bind_label(ok, &mut state.ctrl_plane);
2209            }
2210            &Inst::TrapIf { cmp, trap_code } => {
2211                let label_end = sink.get_label();
2212
2213                // Jump over the trap if we the condition is false.
2214                Inst::CondBr {
2215                    taken: CondBrTarget::Label(label_end),
2216                    not_taken: CondBrTarget::Fallthrough,
2217                    kind: cmp.inverse(),
2218                }
2219                .emit(sink, emit_info, state);
2220                Inst::Udf { trap_code }.emit(sink, emit_info, state);
2221
2222                sink.bind_label(label_end, &mut state.ctrl_plane);
2223            }
2224            &Inst::Udf { trap_code } => {
2225                sink.add_trap(trap_code);
2226                sink.put_data(Inst::TRAP_OPCODE);
2227            }
2228            &Inst::AtomicLoad { rd, ty, p } => {
2229                // emit the fence.
2230                Inst::Fence {
2231                    pred: Inst::FENCE_REQ_R | Inst::FENCE_REQ_W,
2232                    succ: Inst::FENCE_REQ_R | Inst::FENCE_REQ_W,
2233                }
2234                .emit(sink, emit_info, state);
2235                // load.
2236                Inst::Load {
2237                    rd,
2238                    op: LoadOP::from_type(ty),
2239                    flags: MemFlagsData::new(),
2240                    from: AMode::RegOffset(p, 0),
2241                }
2242                .emit(sink, emit_info, state);
2243                Inst::Fence {
2244                    pred: Inst::FENCE_REQ_R,
2245                    succ: Inst::FENCE_REQ_R | Inst::FENCE_REQ_W,
2246                }
2247                .emit(sink, emit_info, state);
2248            }
2249            &Inst::AtomicStore { src, ty, p } => {
2250                Inst::Fence {
2251                    pred: Inst::FENCE_REQ_R | Inst::FENCE_REQ_W,
2252                    succ: Inst::FENCE_REQ_W,
2253                }
2254                .emit(sink, emit_info, state);
2255                Inst::Store {
2256                    to: AMode::RegOffset(p, 0),
2257                    op: StoreOP::from_type(ty),
2258                    flags: MemFlagsData::new(),
2259                    src,
2260                }
2261                .emit(sink, emit_info, state);
2262            }
2263
2264            &Inst::Popcnt {
2265                sum,
2266                tmp,
2267                step,
2268                rs,
2269                ty,
2270            } => {
2271                // load 0 to sum , init.
2272                Inst::gen_move(sum, zero_reg(), I64).emit(sink, emit_info, state);
2273                // load
2274                Inst::load_imm12(step, Imm12::from_i16(ty.bits() as i16))
2275                    .emit(sink, emit_info, state);
2276                //
2277                Inst::load_imm12(tmp, Imm12::ONE).emit(sink, emit_info, state);
2278                Inst::AluRRImm12 {
2279                    alu_op: AluOPRRI::Slli,
2280                    rd: tmp,
2281                    rs: tmp.to_reg(),
2282                    imm12: Imm12::from_i16((ty.bits() - 1) as i16),
2283                }
2284                .emit(sink, emit_info, state);
2285                let label_done = sink.get_label();
2286                let label_loop = sink.get_label();
2287                sink.bind_label(label_loop, &mut state.ctrl_plane);
2288                Inst::CondBr {
2289                    taken: CondBrTarget::Label(label_done),
2290                    not_taken: CondBrTarget::Fallthrough,
2291                    kind: IntegerCompare {
2292                        kind: IntCC::SignedLessThanOrEqual,
2293                        rs1: step.to_reg(),
2294                        rs2: zero_reg(),
2295                    },
2296                }
2297                .emit(sink, emit_info, state);
2298                // test and add sum.
2299                {
2300                    Inst::AluRRR {
2301                        alu_op: AluOPRRR::And,
2302                        rd: writable_spilltmp_reg2(),
2303                        rs1: tmp.to_reg(),
2304                        rs2: rs,
2305                    }
2306                    .emit(sink, emit_info, state);
2307                    let label_over = sink.get_label();
2308                    Inst::CondBr {
2309                        taken: CondBrTarget::Label(label_over),
2310                        not_taken: CondBrTarget::Fallthrough,
2311                        kind: IntegerCompare {
2312                            kind: IntCC::Equal,
2313                            rs1: zero_reg(),
2314                            rs2: spilltmp_reg2(),
2315                        },
2316                    }
2317                    .emit(sink, emit_info, state);
2318                    Inst::AluRRImm12 {
2319                        alu_op: AluOPRRI::Addi,
2320                        rd: sum,
2321                        rs: sum.to_reg(),
2322                        imm12: Imm12::ONE,
2323                    }
2324                    .emit(sink, emit_info, state);
2325                    sink.bind_label(label_over, &mut state.ctrl_plane);
2326                }
2327                // set step and tmp.
2328                {
2329                    Inst::AluRRImm12 {
2330                        alu_op: AluOPRRI::Addi,
2331                        rd: step,
2332                        rs: step.to_reg(),
2333                        imm12: Imm12::from_i16(-1),
2334                    }
2335                    .emit(sink, emit_info, state);
2336                    Inst::AluRRImm12 {
2337                        alu_op: AluOPRRI::Srli,
2338                        rd: tmp,
2339                        rs: tmp.to_reg(),
2340                        imm12: Imm12::ONE,
2341                    }
2342                    .emit(sink, emit_info, state);
2343                    Inst::gen_jump(label_loop).emit(sink, emit_info, state);
2344                }
2345                sink.bind_label(label_done, &mut state.ctrl_plane);
2346            }
2347            &Inst::Cltz {
2348                sum,
2349                tmp,
2350                step,
2351                rs,
2352                leading,
2353                ty,
2354            } => {
2355                // load 0 to sum , init.
2356                Inst::gen_move(sum, zero_reg(), I64).emit(sink, emit_info, state);
2357                // load
2358                Inst::load_imm12(step, Imm12::from_i16(ty.bits() as i16))
2359                    .emit(sink, emit_info, state);
2360                //
2361                Inst::load_imm12(tmp, Imm12::ONE).emit(sink, emit_info, state);
2362                if leading {
2363                    Inst::AluRRImm12 {
2364                        alu_op: AluOPRRI::Slli,
2365                        rd: tmp,
2366                        rs: tmp.to_reg(),
2367                        imm12: Imm12::from_i16((ty.bits() - 1) as i16),
2368                    }
2369                    .emit(sink, emit_info, state);
2370                }
2371                let label_done = sink.get_label();
2372                let label_loop = sink.get_label();
2373                sink.bind_label(label_loop, &mut state.ctrl_plane);
2374                Inst::CondBr {
2375                    taken: CondBrTarget::Label(label_done),
2376                    not_taken: CondBrTarget::Fallthrough,
2377                    kind: IntegerCompare {
2378                        kind: IntCC::SignedLessThanOrEqual,
2379                        rs1: step.to_reg(),
2380                        rs2: zero_reg(),
2381                    },
2382                }
2383                .emit(sink, emit_info, state);
2384                // test and add sum.
2385                {
2386                    Inst::AluRRR {
2387                        alu_op: AluOPRRR::And,
2388                        rd: writable_spilltmp_reg2(),
2389                        rs1: tmp.to_reg(),
2390                        rs2: rs,
2391                    }
2392                    .emit(sink, emit_info, state);
2393                    Inst::CondBr {
2394                        taken: CondBrTarget::Label(label_done),
2395                        not_taken: CondBrTarget::Fallthrough,
2396                        kind: IntegerCompare {
2397                            kind: IntCC::NotEqual,
2398                            rs1: zero_reg(),
2399                            rs2: spilltmp_reg2(),
2400                        },
2401                    }
2402                    .emit(sink, emit_info, state);
2403                    Inst::AluRRImm12 {
2404                        alu_op: AluOPRRI::Addi,
2405                        rd: sum,
2406                        rs: sum.to_reg(),
2407                        imm12: Imm12::ONE,
2408                    }
2409                    .emit(sink, emit_info, state);
2410                }
2411                // set step and tmp.
2412                {
2413                    Inst::AluRRImm12 {
2414                        alu_op: AluOPRRI::Addi,
2415                        rd: step,
2416                        rs: step.to_reg(),
2417                        imm12: Imm12::from_i16(-1),
2418                    }
2419                    .emit(sink, emit_info, state);
2420                    Inst::AluRRImm12 {
2421                        alu_op: if leading {
2422                            AluOPRRI::Srli
2423                        } else {
2424                            AluOPRRI::Slli
2425                        },
2426                        rd: tmp,
2427                        rs: tmp.to_reg(),
2428                        imm12: Imm12::ONE,
2429                    }
2430                    .emit(sink, emit_info, state);
2431                    Inst::gen_jump(label_loop).emit(sink, emit_info, state);
2432                }
2433                sink.bind_label(label_done, &mut state.ctrl_plane);
2434            }
2435            &Inst::Brev8 {
2436                rs,
2437                ty,
2438                step,
2439                tmp,
2440                tmp2,
2441                rd,
2442            } => {
2443                Inst::gen_move(rd, zero_reg(), I64).emit(sink, emit_info, state);
2444                Inst::load_imm12(step, Imm12::from_i16(ty.bits() as i16))
2445                    .emit(sink, emit_info, state);
2446                //
2447                Inst::load_imm12(tmp, Imm12::ONE).emit(sink, emit_info, state);
2448                Inst::AluRRImm12 {
2449                    alu_op: AluOPRRI::Slli,
2450                    rd: tmp,
2451                    rs: tmp.to_reg(),
2452                    imm12: Imm12::from_i16((ty.bits() - 1) as i16),
2453                }
2454                .emit(sink, emit_info, state);
2455                Inst::load_imm12(tmp2, Imm12::ONE).emit(sink, emit_info, state);
2456                Inst::AluRRImm12 {
2457                    alu_op: AluOPRRI::Slli,
2458                    rd: tmp2,
2459                    rs: tmp2.to_reg(),
2460                    imm12: Imm12::from_i16((ty.bits() - 8) as i16),
2461                }
2462                .emit(sink, emit_info, state);
2463
2464                let label_done = sink.get_label();
2465                let label_loop = sink.get_label();
2466                sink.bind_label(label_loop, &mut state.ctrl_plane);
2467                Inst::CondBr {
2468                    taken: CondBrTarget::Label(label_done),
2469                    not_taken: CondBrTarget::Fallthrough,
2470                    kind: IntegerCompare {
2471                        kind: IntCC::SignedLessThanOrEqual,
2472                        rs1: step.to_reg(),
2473                        rs2: zero_reg(),
2474                    },
2475                }
2476                .emit(sink, emit_info, state);
2477                // test and set bit.
2478                {
2479                    Inst::AluRRR {
2480                        alu_op: AluOPRRR::And,
2481                        rd: writable_spilltmp_reg2(),
2482                        rs1: tmp.to_reg(),
2483                        rs2: rs,
2484                    }
2485                    .emit(sink, emit_info, state);
2486                    let label_over = sink.get_label();
2487                    Inst::CondBr {
2488                        taken: CondBrTarget::Label(label_over),
2489                        not_taken: CondBrTarget::Fallthrough,
2490                        kind: IntegerCompare {
2491                            kind: IntCC::Equal,
2492                            rs1: zero_reg(),
2493                            rs2: spilltmp_reg2(),
2494                        },
2495                    }
2496                    .emit(sink, emit_info, state);
2497                    Inst::AluRRR {
2498                        alu_op: AluOPRRR::Or,
2499                        rd,
2500                        rs1: rd.to_reg(),
2501                        rs2: tmp2.to_reg(),
2502                    }
2503                    .emit(sink, emit_info, state);
2504                    sink.bind_label(label_over, &mut state.ctrl_plane);
2505                }
2506                // set step and tmp.
2507                {
2508                    Inst::AluRRImm12 {
2509                        alu_op: AluOPRRI::Addi,
2510                        rd: step,
2511                        rs: step.to_reg(),
2512                        imm12: Imm12::from_i16(-1),
2513                    }
2514                    .emit(sink, emit_info, state);
2515                    Inst::AluRRImm12 {
2516                        alu_op: AluOPRRI::Srli,
2517                        rd: tmp,
2518                        rs: tmp.to_reg(),
2519                        imm12: Imm12::ONE,
2520                    }
2521                    .emit(sink, emit_info, state);
2522                    {
2523                        // reset tmp2
2524                        // if (step %=8 == 0) then tmp2 = tmp2 >> 15
2525                        // if (step %=8 != 0) then tmp2 = tmp2 << 1
2526                        let label_over = sink.get_label();
2527                        let label_sll_1 = sink.get_label();
2528                        Inst::load_imm12(writable_spilltmp_reg2(), Imm12::from_i16(8))
2529                            .emit(sink, emit_info, state);
2530                        Inst::AluRRR {
2531                            alu_op: AluOPRRR::Rem,
2532                            rd: writable_spilltmp_reg2(),
2533                            rs1: step.to_reg(),
2534                            rs2: spilltmp_reg2(),
2535                        }
2536                        .emit(sink, emit_info, state);
2537                        Inst::CondBr {
2538                            taken: CondBrTarget::Label(label_sll_1),
2539                            not_taken: CondBrTarget::Fallthrough,
2540                            kind: IntegerCompare {
2541                                kind: IntCC::NotEqual,
2542                                rs1: spilltmp_reg2(),
2543                                rs2: zero_reg(),
2544                            },
2545                        }
2546                        .emit(sink, emit_info, state);
2547                        Inst::AluRRImm12 {
2548                            alu_op: AluOPRRI::Srli,
2549                            rd: tmp2,
2550                            rs: tmp2.to_reg(),
2551                            imm12: Imm12::from_i16(15),
2552                        }
2553                        .emit(sink, emit_info, state);
2554                        Inst::gen_jump(label_over).emit(sink, emit_info, state);
2555                        sink.bind_label(label_sll_1, &mut state.ctrl_plane);
2556                        Inst::AluRRImm12 {
2557                            alu_op: AluOPRRI::Slli,
2558                            rd: tmp2,
2559                            rs: tmp2.to_reg(),
2560                            imm12: Imm12::ONE,
2561                        }
2562                        .emit(sink, emit_info, state);
2563                        sink.bind_label(label_over, &mut state.ctrl_plane);
2564                    }
2565                    Inst::gen_jump(label_loop).emit(sink, emit_info, state);
2566                }
2567                sink.bind_label(label_done, &mut state.ctrl_plane);
2568            }
2569            &Inst::StackProbeLoop {
2570                guard_size,
2571                probe_count,
2572                tmp: guard_size_tmp,
2573            } => {
2574                let step = writable_spilltmp_reg();
2575                Inst::load_constant_u64(step, (guard_size as u64) * (probe_count as u64))
2576                    .iter()
2577                    .for_each(|i| i.emit(sink, emit_info, state));
2578                Inst::load_constant_u64(guard_size_tmp, guard_size as u64)
2579                    .iter()
2580                    .for_each(|i| i.emit(sink, emit_info, state));
2581
2582                let loop_start = sink.get_label();
2583                let label_done = sink.get_label();
2584                sink.bind_label(loop_start, &mut state.ctrl_plane);
2585                Inst::CondBr {
2586                    taken: CondBrTarget::Label(label_done),
2587                    not_taken: CondBrTarget::Fallthrough,
2588                    kind: IntegerCompare {
2589                        kind: IntCC::UnsignedLessThanOrEqual,
2590                        rs1: step.to_reg(),
2591                        rs2: guard_size_tmp.to_reg(),
2592                    },
2593                }
2594                .emit(sink, emit_info, state);
2595                // compute address.
2596                Inst::AluRRR {
2597                    alu_op: AluOPRRR::Sub,
2598                    rd: writable_spilltmp_reg2(),
2599                    rs1: stack_reg(),
2600                    rs2: step.to_reg(),
2601                }
2602                .emit(sink, emit_info, state);
2603                Inst::Store {
2604                    to: AMode::RegOffset(spilltmp_reg2(), 0),
2605                    op: StoreOP::Sb,
2606                    flags: MemFlagsData::new(),
2607                    src: zero_reg(),
2608                }
2609                .emit(sink, emit_info, state);
2610                // reset step.
2611                Inst::AluRRR {
2612                    alu_op: AluOPRRR::Sub,
2613                    rd: step,
2614                    rs1: step.to_reg(),
2615                    rs2: guard_size_tmp.to_reg(),
2616                }
2617                .emit(sink, emit_info, state);
2618                Inst::gen_jump(loop_start).emit(sink, emit_info, state);
2619                sink.bind_label(label_done, &mut state.ctrl_plane);
2620            }
2621            &Inst::VecAluRRRImm5 {
2622                op,
2623                vd,
2624                vd_src,
2625                imm,
2626                vs2,
2627                ref mask,
2628                ..
2629            } => {
2630                debug_assert_eq!(vd.to_reg(), vd_src);
2631
2632                sink.put4(encode_valu_rrr_imm(op, vd, imm, vs2, *mask));
2633            }
2634            &Inst::VecAluRRRR {
2635                op,
2636                vd,
2637                vd_src,
2638                vs1,
2639                vs2,
2640                ref mask,
2641                ..
2642            } => {
2643                debug_assert_eq!(vd.to_reg(), vd_src);
2644
2645                sink.put4(encode_valu_rrrr(op, vd, vs2, vs1, *mask));
2646            }
2647            &Inst::VecAluRRR {
2648                op,
2649                vd,
2650                vs1,
2651                vs2,
2652                ref mask,
2653                ..
2654            } => {
2655                sink.put4(encode_valu(op, vd, vs1, vs2, *mask));
2656            }
2657            &Inst::VecAluRRImm5 {
2658                op,
2659                vd,
2660                imm,
2661                vs2,
2662                ref mask,
2663                ..
2664            } => {
2665                sink.put4(encode_valu_rr_imm(op, vd, imm, vs2, *mask));
2666            }
2667            &Inst::VecAluRR {
2668                op,
2669                vd,
2670                vs,
2671                ref mask,
2672                ..
2673            } => {
2674                sink.put4(encode_valu_rr(op, vd, vs, *mask));
2675            }
2676            &Inst::VecAluRImm5 {
2677                op,
2678                vd,
2679                imm,
2680                ref mask,
2681                ..
2682            } => {
2683                sink.put4(encode_valu_r_imm(op, vd, imm, *mask));
2684            }
2685            &Inst::VecSetState { rd, ref vstate } => {
2686                sink.put4(encode_vcfg_imm(
2687                    0x57,
2688                    rd.to_reg(),
2689                    vstate.avl.unwrap_static(),
2690                    &vstate.vtype,
2691                ));
2692
2693                // Update the current vector emit state.
2694                state.vstate = EmitVState::Known(*vstate);
2695            }
2696
2697            &Inst::VecLoad {
2698                eew,
2699                to,
2700                ref from,
2701                ref mask,
2702                flags,
2703                ..
2704            } => {
2705                // Vector Loads don't support immediate offsets, so we need to load it into a register.
2706                let addr = match from {
2707                    VecAMode::UnitStride { base } => {
2708                        let base_reg = base.get_base_register();
2709                        let offset = base.get_offset_with_state(state);
2710
2711                        // Reg+0 Offset can be directly encoded
2712                        if let (Some(base_reg), 0) = (base_reg, offset) {
2713                            base_reg
2714                        } else {
2715                            // Otherwise load the address it into a reg and load from it.
2716                            let tmp = writable_spilltmp_reg();
2717                            Inst::LoadAddr {
2718                                rd: tmp,
2719                                mem: *base,
2720                            }
2721                            .emit(sink, emit_info, state);
2722                            tmp.to_reg()
2723                        }
2724                    }
2725                };
2726
2727                if let Some(trap_code) = flags.trap_code() {
2728                    // Register the offset at which the actual load instruction starts.
2729                    sink.add_trap(trap_code);
2730                }
2731
2732                sink.put4(encode_vmem_load(
2733                    0x07,
2734                    to.to_reg(),
2735                    eew,
2736                    addr,
2737                    from.lumop(),
2738                    *mask,
2739                    from.mop(),
2740                    from.nf(),
2741                ));
2742            }
2743
2744            &Inst::VecStore {
2745                eew,
2746                ref to,
2747                from,
2748                ref mask,
2749                flags,
2750                ..
2751            } => {
2752                // Vector Stores don't support immediate offsets, so we need to load it into a register.
2753                let addr = match to {
2754                    VecAMode::UnitStride { base } => {
2755                        let base_reg = base.get_base_register();
2756                        let offset = base.get_offset_with_state(state);
2757
2758                        // Reg+0 Offset can be directly encoded
2759                        if let (Some(base_reg), 0) = (base_reg, offset) {
2760                            base_reg
2761                        } else {
2762                            // Otherwise load the address it into a reg and load from it.
2763                            let tmp = writable_spilltmp_reg();
2764                            Inst::LoadAddr {
2765                                rd: tmp,
2766                                mem: *base,
2767                            }
2768                            .emit(sink, emit_info, state);
2769                            tmp.to_reg()
2770                        }
2771                    }
2772                };
2773
2774                if let Some(trap_code) = flags.trap_code() {
2775                    // Register the offset at which the actual load instruction starts.
2776                    sink.add_trap(trap_code);
2777                }
2778
2779                sink.put4(encode_vmem_store(
2780                    0x27,
2781                    from,
2782                    eew,
2783                    addr,
2784                    to.sumop(),
2785                    *mask,
2786                    to.mop(),
2787                    to.nf(),
2788                ));
2789            }
2790
2791            Inst::EmitIsland { needed_space } => {
2792                if sink.island_needed(*needed_space) {
2793                    let jump_around_label = sink.get_label();
2794                    Inst::gen_jump(jump_around_label).emit(sink, emit_info, state);
2795                    sink.emit_island(needed_space + 4, &mut state.ctrl_plane);
2796                    sink.bind_label(jump_around_label, &mut state.ctrl_plane);
2797                }
2798            }
2799
2800            Inst::SequencePoint { .. } => {
2801                // Nothing.
2802            }
2803        }
2804    }
2805}
2806
2807fn emit_return_call_common_sequence<T>(
2808    sink: &mut MachBuffers<Inst>,
2809    emit_info: &EmitInfo,
2810    state: &mut EmitState,
2811    info: &ReturnCallInfo<T>,
2812) {
2813    // The return call sequence can potentially emit a lot of instructions (up to 634 bytes!)
2814    // So lets emit an island here if we need it.
2815    //
2816    // It is difficult to calculate exactly how many instructions are going to be emitted, so
2817    // we calculate it by emitting it into a disposable buffer, and then checking how many instructions
2818    // were actually emitted.
2819    let mut buffer = MachBuffer::new();
2820    let mut fake_emit_state = state.clone();
2821
2822    return_call_emit_impl(
2823        &mut MachBuffers::text_only(&mut buffer),
2824        emit_info,
2825        &mut fake_emit_state,
2826        info,
2827    );
2828
2829    // Finalize the buffer and get the number of bytes emitted.
2830    let buffer = buffer.finish(&Default::default(), &mut Default::default());
2831    let length = buffer.data().len() as u32;
2832
2833    // And now emit the island inline with this instruction.
2834    if sink.island_needed(length) {
2835        let jump_around_label = sink.get_label();
2836        Inst::gen_jump(jump_around_label).emit(sink, emit_info, state);
2837        sink.emit_island(length + 4, &mut state.ctrl_plane);
2838        sink.bind_label(jump_around_label, &mut state.ctrl_plane);
2839    }
2840
2841    // Now that we're done, emit the *actual* return sequence.
2842    return_call_emit_impl(sink, emit_info, state, info);
2843}
2844
2845/// This should not be called directly, Instead prefer to call [emit_return_call_common_sequence].
2846fn return_call_emit_impl<T>(
2847    sink: &mut MachBuffers<Inst>,
2848    emit_info: &EmitInfo,
2849    state: &mut EmitState,
2850    info: &ReturnCallInfo<T>,
2851) {
2852    let sp_to_fp_offset = {
2853        let frame_layout = state.frame_layout();
2854        i64::from(
2855            frame_layout.clobber_size
2856                + frame_layout.fixed_frame_storage_size
2857                + frame_layout.outgoing_args_size,
2858        )
2859    };
2860
2861    let mut clobber_offset = sp_to_fp_offset - 8;
2862    for reg in state.frame_layout().clobbered_callee_saves.clone() {
2863        let rreg = reg.to_reg();
2864        let ty = match rreg.class() {
2865            RegClass::Int => I64,
2866            RegClass::Float => F64,
2867            RegClass::Vector => unimplemented!("Vector Clobber Restores"),
2868        };
2869
2870        Inst::gen_load(
2871            reg.map(Reg::from),
2872            AMode::SPOffset(clobber_offset),
2873            ty,
2874            MemFlagsData::trusted(),
2875        )
2876        .emit(sink, emit_info, state);
2877
2878        clobber_offset -= 8
2879    }
2880
2881    // Restore the link register and frame pointer
2882    let setup_area_size = i64::from(state.frame_layout().setup_area_size);
2883    if setup_area_size > 0 {
2884        Inst::gen_load(
2885            writable_link_reg(),
2886            AMode::SPOffset(sp_to_fp_offset + 8),
2887            I64,
2888            MemFlagsData::trusted(),
2889        )
2890        .emit(sink, emit_info, state);
2891
2892        Inst::gen_load(
2893            writable_fp_reg(),
2894            AMode::SPOffset(sp_to_fp_offset),
2895            I64,
2896            MemFlagsData::trusted(),
2897        )
2898        .emit(sink, emit_info, state);
2899    }
2900
2901    // If we over-allocated the incoming args area in the prologue, resize down to what the callee
2902    // is expecting.
2903    let incoming_args_diff =
2904        i64::from(state.frame_layout().tail_args_size - info.new_stack_arg_size);
2905
2906    // Increment SP all at once
2907    let sp_increment = sp_to_fp_offset + setup_area_size + incoming_args_diff;
2908    if sp_increment > 0 {
2909        for inst in Riscv64MachineDeps::gen_sp_reg_adjust(i32::try_from(sp_increment).unwrap()) {
2910            inst.emit(sink, emit_info, state);
2911        }
2912    }
2913}