Skip to main content

cranelift_codegen/machinst/
vcode.rs

1//! This implements the VCode container: a CFG of Insts that have been lowered.
2//!
3//! VCode is virtual-register code. An instruction in VCode is almost a machine
4//! instruction; however, its register slots can refer to virtual registers in
5//! addition to real machine registers.
6//!
7//! VCode is structured with traditional basic blocks, and
8//! each block must be terminated by an unconditional branch (one target), a
9//! conditional branch (two targets), or a return (no targets). Note that this
10//! slightly differs from the machine code of most ISAs: in most ISAs, a
11//! conditional branch has one target (and the not-taken case falls through).
12//! However, we expect that machine backends will elide branches to the following
13//! block (i.e., zero-offset jumps), and will be able to codegen a branch-cond /
14//! branch-uncond pair if *both* targets are not fallthrough. This allows us to
15//! play with layout prior to final binary emission, as well, if we want.
16//!
17//! See the main module comment in `mod.rs` for more details on the VCode-based
18//! backend pipeline.
19
20use crate::CodegenError;
21use crate::FxHashMap;
22use crate::ir::{self, Constant, ConstantData, ValueLabel, types};
23use crate::ranges::Ranges;
24use crate::timing;
25use crate::trace;
26use crate::{LabelValueLoc, ValueLocRange};
27use crate::{machinst::*, trace_log_enabled};
28use regalloc2::{
29    Edit, Function as RegallocFunction, InstOrEdit, InstPosition, InstRange, Operand,
30    OperandConstraint, OperandKind, PRegSet, ProgPoint, RegClass,
31};
32
33use crate::HashMap;
34use crate::hash_map::Entry;
35use core::cmp::Ordering;
36use core::fmt::{self, Write};
37use core::mem::take;
38use core::ops::Range;
39use cranelift_entity::{Keys, entity_impl};
40
41/// Index referring to an instruction in VCode.
42pub type InsnIndex = regalloc2::Inst;
43
44/// Extension trait for `InsnIndex` to allow conversion to a
45/// `BackwardsInsnIndex`.
46trait ToBackwardsInsnIndex {
47    fn to_backwards_insn_index(&self, num_insts: usize) -> BackwardsInsnIndex;
48}
49
50impl ToBackwardsInsnIndex for InsnIndex {
51    fn to_backwards_insn_index(&self, num_insts: usize) -> BackwardsInsnIndex {
52        BackwardsInsnIndex::new(num_insts - self.index() - 1)
53    }
54}
55
56/// An index referring to an instruction in the VCode when it is backwards,
57/// during VCode construction.
58#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
59#[cfg_attr(
60    feature = "enable-serde",
61    derive(::serde::Serialize, ::serde::Deserialize)
62)]
63pub struct BackwardsInsnIndex(InsnIndex);
64
65impl BackwardsInsnIndex {
66    pub fn new(i: usize) -> Self {
67        BackwardsInsnIndex(InsnIndex::new(i))
68    }
69}
70
71/// Index referring to a basic block in VCode.
72pub type BlockIndex = regalloc2::Block;
73
74/// VCodeInst wraps all requirements for a MachInst to be in VCode: it must be
75/// a `MachInst` and it must be able to emit itself at least to a `SizeCodeSink`.
76pub trait VCodeInst: MachInst + MachInstEmit {}
77impl<I: MachInst + MachInstEmit> VCodeInst for I {}
78
79/// A function in "VCode" (virtualized-register code) form, after
80/// lowering.  This is essentially a standard CFG of basic blocks,
81/// where each basic block consists of lowered instructions produced
82/// by the machine-specific backend.
83///
84/// Note that the VCode is immutable once produced, and is not
85/// modified by register allocation in particular. Rather, register
86/// allocation on the `VCode` produces a separate `regalloc2::Output`
87/// struct, and this can be passed to `emit`. `emit` in turn does not
88/// modify the vcode, but produces an `EmitResult`, which contains the
89/// machine code itself, and the associated disassembly and/or
90/// metadata as requested.
91pub struct VCode<I: VCodeInst> {
92    /// VReg IR-level types.
93    vreg_types: Vec<Type>,
94
95    /// Lowered machine instructions in order corresponding to the original IR.
96    insts: Vec<I>,
97
98    /// A map from backwards instruction index to the user stack map for that
99    /// instruction.
100    ///
101    /// This is a sparse side table that only has entries for instructions that
102    /// are safepoints, and only for a subset of those that have an associated
103    /// user stack map.
104    user_stack_maps: FxHashMap<BackwardsInsnIndex, ir::UserStackMap>,
105
106    /// A map from backwards instruction index to the debug tags for
107    /// that instruction. Each entry indexes a range in the
108    /// `debug_tag_pool`.
109    debug_tags: FxHashMap<BackwardsInsnIndex, Range<u32>>,
110
111    /// Pooled storage for sequences of debug tags; indexed by entries
112    /// in `debug_tags`.
113    debug_tag_pool: Vec<ir::DebugTag>,
114
115    /// Operands: pre-regalloc references to virtual registers with
116    /// constraints, in one flattened array. This allows the regalloc
117    /// to efficiently access all operands without requiring expensive
118    /// matches or method invocations on insts.
119    operands: Vec<Operand>,
120
121    /// Operand index ranges: for each instruction in `insts`, there
122    /// is a tuple here providing the range in `operands` for that
123    /// instruction's operands.
124    operand_ranges: Ranges,
125
126    /// Clobbers: a sparse map from instruction indices to clobber masks.
127    clobbers: FxHashMap<InsnIndex, PRegSet>,
128
129    /// Source locations for each instruction. (`SourceLoc` is a `u32`, so it is
130    /// reasonable to keep one of these per instruction.)
131    srclocs: Vec<RelSourceLoc>,
132
133    /// Entry block.
134    entry: BlockIndex,
135
136    /// Block instruction indices.
137    block_ranges: Ranges,
138
139    /// Block successors: index range in the `block_succs` list.
140    block_succ_range: Ranges,
141
142    /// Block successor lists, concatenated into one vec. The
143    /// `block_succ_range` list of tuples above gives (start, end)
144    /// ranges within this list that correspond to each basic block's
145    /// successors.
146    block_succs: Vec<regalloc2::Block>,
147
148    /// Block predecessors: index range in the `block_preds` list.
149    block_pred_range: Ranges,
150
151    /// Block predecessor lists, concatenated into one vec. The
152    /// `block_pred_range` list of tuples above gives (start, end)
153    /// ranges within this list that correspond to each basic block's
154    /// predecessors.
155    block_preds: Vec<regalloc2::Block>,
156
157    /// Block parameters: index range in `block_params` below.
158    block_params_range: Ranges,
159
160    /// Block parameter lists, concatenated into one vec. The
161    /// `block_params_range` list of tuples above gives (start, end)
162    /// ranges within this list that correspond to each basic block's
163    /// blockparam vregs.
164    block_params: Vec<regalloc2::VReg>,
165
166    /// Outgoing block arguments on branch instructions, concatenated
167    /// into one list.
168    ///
169    /// Note that this is conceptually a 3D array: we have a VReg list
170    /// per block, per successor. We flatten those three dimensions
171    /// into this 1D vec, then store index ranges in two levels of
172    /// indirection.
173    ///
174    /// Indexed by the indices in `branch_block_arg_succ_range`.
175    branch_block_args: Vec<regalloc2::VReg>,
176
177    /// Array of sequences of (start, end) tuples in
178    /// `branch_block_args`, one for each successor; these sequences
179    /// for each block are concatenated.
180    ///
181    /// Indexed by the indices in `branch_block_arg_succ_range`.
182    branch_block_arg_range: Ranges,
183
184    /// For a given block, indices in `branch_block_arg_range`
185    /// corresponding to all of its successors.
186    branch_block_arg_succ_range: Ranges,
187
188    /// Block-order information.
189    block_order: BlockLoweringOrder,
190
191    /// ABI object.
192    pub(crate) abi: Callee<I::ABIMachineSpec>,
193
194    /// Constant information used during code emission. This should be
195    /// immutable across function compilations within the same module.
196    emit_info: I::Info,
197
198    /// Constants.
199    pub(crate) constants: VCodeConstants,
200
201    /// Value labels for debuginfo attached to vregs.
202    debug_value_labels: Vec<(VReg, InsnIndex, InsnIndex, u32)>,
203
204    pub(crate) sigs: SigSet,
205
206    log2_min_function_alignment: u8,
207}
208
209/// The result of `VCode::emit`. Contains all information computed
210/// during emission: actual machine code, optionally a disassembly,
211/// and optionally metadata about the code layout.
212pub struct EmitResult {
213    /// The MachBuffer containing the machine code.
214    pub buffer: MachBufferFinalized,
215
216    /// The constants of the function, if the `separate_constant_pool` setting is
217    /// on and the function has any.
218    pub constants: Option<MachConstantsFinalized>,
219
220    /// Offset of each basic block, recorded during emission. Computed
221    /// only if `machine_code_cfg_info` is enabled.
222    pub bb_offsets: Vec<CodeOffset>,
223
224    /// Final basic-block edges, in terms of code offsets of
225    /// bb-starts. Computed only if `machine_code_cfg_info` is enabled.
226    pub bb_edges: Vec<(CodeOffset, CodeOffset)>,
227
228    /// The pretty-printed disassembly, if any. This uses the same
229    /// pretty-printing for MachInsts as the pre-regalloc VCode Debug
230    /// implementation, but additionally includes the prologue and
231    /// epilogue(s), and makes use of the regalloc results.
232    pub disasm: Option<String>,
233
234    /// Value-labels information (debug metadata).
235    pub value_labels_ranges: ValueLabelsRanges,
236}
237
238/// A builder for a VCode function body.
239///
240/// This builder has the ability to accept instructions in either
241/// forward or reverse order, depending on the pass direction that
242/// produces the VCode. The lowering from CLIF to VCode<MachInst>
243/// ordinarily occurs in reverse order (in order to allow instructions
244/// to be lowered only if used, and not merged) so a reversal will
245/// occur at the end of lowering to ensure the VCode is in machine
246/// order.
247///
248/// If built in reverse, block and instruction indices used once the
249/// VCode is built are relative to the final (reversed) order, not the
250/// order of construction. Note that this means we do not know the
251/// final block or instruction indices when building, so we do not
252/// hand them out. (The user is assumed to know them when appending
253/// terminator instructions with successor blocks.)
254pub struct VCodeBuilder<I: VCodeInst> {
255    /// In-progress VCode.
256    pub(crate) vcode: VCode<I>,
257
258    /// In what direction is the build occurring?
259    direction: VCodeBuildDirection,
260
261    /// Debug-value label in-progress map, keyed by label. For each
262    /// label, we keep disjoint ranges mapping to vregs. We'll flatten
263    /// this into (vreg, range, label) tuples when done.
264    debug_info: FxHashMap<ValueLabel, Vec<(InsnIndex, InsnIndex, VReg)>>,
265}
266
267/// Direction in which a VCodeBuilder builds VCode.
268#[derive(Clone, Copy, Debug, PartialEq, Eq)]
269pub enum VCodeBuildDirection {
270    // TODO: add `Forward` once we need it and can test it adequately.
271    /// Backward-build pass: we expect the producer to call `emit()`
272    /// with instructions in reverse program order within each block.
273    Backward,
274}
275
276impl<I: VCodeInst> VCodeBuilder<I> {
277    /// Create a new VCodeBuilder.
278    pub fn new(
279        sigs: SigSet,
280        abi: Callee<I::ABIMachineSpec>,
281        emit_info: I::Info,
282        block_order: BlockLoweringOrder,
283        constants: VCodeConstants,
284        direction: VCodeBuildDirection,
285        log2_min_function_alignment: u8,
286    ) -> Self {
287        let vcode = VCode::new(
288            sigs,
289            abi,
290            emit_info,
291            block_order,
292            constants,
293            log2_min_function_alignment,
294        );
295
296        VCodeBuilder {
297            vcode,
298            direction,
299            debug_info: FxHashMap::default(),
300        }
301    }
302
303    pub fn init_retval_area(&mut self, vregs: &mut VRegAllocator<I>) -> CodegenResult<()> {
304        self.vcode.abi.init_retval_area(&self.vcode.sigs, vregs)
305    }
306
307    /// Access the ABI object.
308    pub fn abi(&self) -> &Callee<I::ABIMachineSpec> {
309        &self.vcode.abi
310    }
311
312    /// Access the ABI object.
313    pub fn abi_mut(&mut self) -> &mut Callee<I::ABIMachineSpec> {
314        &mut self.vcode.abi
315    }
316
317    pub fn sigs(&self) -> &SigSet {
318        &self.vcode.sigs
319    }
320
321    pub fn sigs_mut(&mut self) -> &mut SigSet {
322        &mut self.vcode.sigs
323    }
324
325    /// Access to the BlockLoweringOrder object.
326    pub fn block_order(&self) -> &BlockLoweringOrder {
327        &self.vcode.block_order
328    }
329
330    /// Set the current block as the entry block.
331    pub fn set_entry(&mut self, block: BlockIndex) {
332        self.vcode.entry = block;
333    }
334
335    /// End the current basic block. Must be called after emitting vcode insts
336    /// for IR insts and prior to ending the function (building the VCode).
337    pub fn end_bb(&mut self) {
338        let end_idx = self.vcode.insts.len();
339        // Add the instruction index range to the list of blocks.
340        self.vcode.block_ranges.push_end(end_idx);
341        // End the successors list.
342        let succ_end = self.vcode.block_succs.len();
343        self.vcode.block_succ_range.push_end(succ_end);
344        // End the blockparams list.
345        let block_params_end = self.vcode.block_params.len();
346        self.vcode.block_params_range.push_end(block_params_end);
347        // End the branch blockparam args list.
348        let branch_block_arg_succ_end = self.vcode.branch_block_arg_range.len();
349        self.vcode
350            .branch_block_arg_succ_range
351            .push_end(branch_block_arg_succ_end);
352    }
353
354    pub fn add_block_param(&mut self, param: VirtualReg) {
355        self.vcode.block_params.push(param.into());
356    }
357
358    fn add_branch_args_for_succ(&mut self, args: &[Reg]) {
359        self.vcode
360            .branch_block_args
361            .extend(args.iter().map(|&arg| VReg::from(arg)));
362        let end = self.vcode.branch_block_args.len();
363        self.vcode.branch_block_arg_range.push_end(end);
364    }
365
366    /// Push an instruction for the current BB and current IR inst
367    /// within the BB.
368    pub fn push(&mut self, insn: I, loc: RelSourceLoc) {
369        assert!(!insn.is_low_level_branch()); // These are not meant to be in VCode.
370        self.vcode.insts.push(insn);
371        self.vcode.srclocs.push(loc);
372    }
373
374    /// Add a successor block with branch args.
375    pub fn add_succ(&mut self, block: BlockIndex, args: &[Reg]) {
376        self.vcode.block_succs.push(block);
377        self.add_branch_args_for_succ(args);
378    }
379
380    /// Add a debug value label to a register.
381    pub fn add_value_label(&mut self, reg: Reg, label: ValueLabel) {
382        // 1) In the reversed order, we consider the instructions
383        //    that define ranges in the "debug_info" array to refer
384        //    to the IP **after** them (when reversed):
385        //      IP[2]__| Inst 3 |
386        //      IP[1]__| Inst 2 |
387        //      IP[0]__| Inst 1 |
388        //             | Inst 0 |
389        //    This is so that we can represent IP[<function start>],
390        //    done at the cost of not being to represent IP[<function end>],
391        //    which is OK since no values will be live at that point.
392        // 2) The live range for "reg" begins at the current IP
393        //    and continues until the next, in execution order,
394        //    VReg that defines "label". Since the ranges are open
395        //    at the end, the subtraction of 1 cancels out:
396        //      [last..current IP] <=>
397        //      [last..last emitted inst index] <=>
398        //      [last..next_inst_index - 1] <=>
399        //      [last..next_inst_index)
400        //
401        let next_inst_index = self.vcode.insts.len();
402        if next_inst_index == 0 {
403            // This would produce a defective [0..0) range.
404            return;
405        }
406        let next_inst = InsnIndex::new(next_inst_index);
407        let labels = self.debug_info.entry(label).or_insert_with(|| vec![]);
408        let last = labels
409            .last()
410            .map(|(_start, end, _vreg)| *end)
411            .unwrap_or(InsnIndex::new(0));
412        labels.push((last, next_inst, reg.into()));
413    }
414
415    /// Access the constants.
416    pub fn constants(&mut self) -> &mut VCodeConstants {
417        &mut self.vcode.constants
418    }
419
420    fn compute_preds_from_succs(&mut self) {
421        // Do a linear-time counting sort: first determine how many
422        // times each block appears as a successor.
423        let mut starts = vec![0u32; self.vcode.num_blocks()];
424        for succ in &self.vcode.block_succs {
425            starts[succ.index()] += 1;
426        }
427
428        // Determine for each block the starting index where that
429        // block's predecessors should go. This is equivalent to the
430        // ranges we need to store in block_pred_range.
431        self.vcode.block_pred_range.reserve(starts.len());
432        let mut end = 0;
433        for count in starts.iter_mut() {
434            let start = end;
435            end += *count;
436            *count = start;
437            self.vcode.block_pred_range.push_end(end as usize);
438        }
439        let end = end as usize;
440        debug_assert_eq!(end, self.vcode.block_succs.len());
441
442        // Walk over the successors again, this time grouped by
443        // predecessor, and push the predecessor at the current
444        // starting position of each of its successors. We build
445        // each group of predecessors in whatever order Ranges::iter
446        // returns them; regalloc2 doesn't care.
447        self.vcode.block_preds.resize(end, BlockIndex::invalid());
448        for (pred, range) in self.vcode.block_succ_range.iter() {
449            let pred = BlockIndex::new(pred);
450            for succ in &self.vcode.block_succs[range] {
451                let pos = &mut starts[succ.index()];
452                self.vcode.block_preds[*pos as usize] = pred;
453                *pos += 1;
454            }
455        }
456        debug_assert!(self.vcode.block_preds.iter().all(|pred| pred.is_valid()));
457    }
458
459    /// Called once, when a build in Backward order is complete, to
460    /// perform the overall reversal (into final forward order) and
461    /// finalize metadata accordingly.
462    fn reverse_and_finalize(&mut self, vregs: &VRegAllocator<I>) {
463        let n_insts = self.vcode.insts.len();
464        if n_insts == 0 {
465            return;
466        }
467
468        // Reverse the per-block and per-inst sequences.
469        self.vcode.block_ranges.reverse_index();
470        self.vcode.block_ranges.reverse_target(n_insts);
471        // block_params_range is indexed by block (and blocks were
472        // traversed in reverse) so we reverse it; but block-param
473        // sequences in the concatenated vec can remain in reverse
474        // order (it is effectively an arena of arbitrarily-placed
475        // referenced sequences).
476        self.vcode.block_params_range.reverse_index();
477        // Likewise, we reverse block_succ_range, but the block_succ
478        // concatenated array can remain as-is.
479        self.vcode.block_succ_range.reverse_index();
480        self.vcode.insts.reverse();
481        self.vcode.srclocs.reverse();
482        // Likewise, branch_block_arg_succ_range is indexed by block
483        // so must be reversed.
484        self.vcode.branch_block_arg_succ_range.reverse_index();
485
486        // To translate an instruction index *endpoint* in reversed
487        // order to forward order, compute `n_insts - i`.
488        //
489        // Why not `n_insts - 1 - i`? That would be correct to
490        // translate an individual instruction index (for ten insts 0
491        // to 9 inclusive, inst 0 becomes 9, and inst 9 becomes
492        // 0). But for the usual inclusive-start, exclusive-end range
493        // idiom, inclusive starts become exclusive ends and
494        // vice-versa, so e.g. an (inclusive) start of 0 becomes an
495        // (exclusive) end of 10.
496        let translate = |inst: InsnIndex| InsnIndex::new(n_insts - inst.index());
497
498        // Generate debug-value labels based on per-label maps.
499        for (label, tuples) in &self.debug_info {
500            for &(start, end, vreg) in tuples {
501                let vreg = vregs.resolve_vreg_alias(vreg);
502                let fwd_start = translate(end);
503                let fwd_end = translate(start);
504                self.vcode
505                    .debug_value_labels
506                    .push((vreg, fwd_start, fwd_end, label.as_u32()));
507            }
508        }
509
510        // Now sort debug value labels by VReg, as required
511        // by regalloc2.
512        self.vcode
513            .debug_value_labels
514            .sort_unstable_by_key(|(vreg, _, _, _)| *vreg);
515    }
516
517    fn collect_operands(&mut self, vregs: &VRegAllocator<I>) {
518        let allocatable = PRegSet::from(self.vcode.abi.machine_env());
519        for (i, insn) in self.vcode.insts.iter_mut().enumerate() {
520            // Push operands from the instruction onto the operand list.
521            //
522            // We rename through the vreg alias table as we collect
523            // the operands. This is better than a separate post-pass
524            // over operands, because it has more cache locality:
525            // operands only need to pass through L1 once. This is
526            // also better than renaming instructions'
527            // operands/registers while lowering, because here we only
528            // need to do the `match` over the instruction to visit
529            // its register fields (which is slow, branchy code) once.
530
531            let mut op_collector =
532                OperandCollector::new(&mut self.vcode.operands, allocatable, |vreg| {
533                    vregs.resolve_vreg_alias(vreg)
534                });
535            insn.get_operands(&mut op_collector);
536            let (ops, clobbers) = op_collector.finish();
537            self.vcode.operand_ranges.push_end(ops);
538
539            if clobbers != PRegSet::default() {
540                self.vcode.clobbers.insert(InsnIndex::new(i), clobbers);
541            }
542
543            if let Some((dst, src)) = insn.is_move() {
544                // We should never see non-virtual registers present in move
545                // instructions.
546                assert!(
547                    src.is_virtual(),
548                    "the real register {src:?} was used as the source of a move instruction"
549                );
550                assert!(
551                    dst.to_reg().is_virtual(),
552                    "the real register {:?} was used as the destination of a move instruction",
553                    dst.to_reg()
554                );
555            }
556        }
557
558        // Translate blockparam args via the vreg aliases table as well.
559        for arg in &mut self.vcode.branch_block_args {
560            let new_arg = vregs.resolve_vreg_alias(*arg);
561            trace!("operandcollector: block arg {:?} -> {:?}", arg, new_arg);
562            *arg = new_arg;
563        }
564    }
565
566    /// Build the final VCode.
567    pub fn build(mut self, mut vregs: VRegAllocator<I>) -> VCode<I> {
568        self.vcode.vreg_types = take(&mut vregs.vreg_types);
569
570        if self.direction == VCodeBuildDirection::Backward {
571            self.reverse_and_finalize(&vregs);
572        }
573        self.collect_operands(&vregs);
574
575        self.compute_preds_from_succs();
576        self.vcode.debug_value_labels.sort_unstable();
577
578        // At this point, nothing in the vcode should mention any
579        // VReg which has been aliased. All the appropriate rewriting
580        // should have happened above. Just to be sure, let's
581        // double-check each field which has vregs.
582        // Note: can't easily check vcode.insts, resolved in collect_operands.
583        // Operands are resolved in collect_operands.
584        vregs.debug_assert_no_vreg_aliases(self.vcode.operands.iter().map(|op| op.vreg()));
585        // Currently block params are never aliased to another vreg.
586        vregs.debug_assert_no_vreg_aliases(self.vcode.block_params.iter().copied());
587        // Branch block args are resolved in collect_operands.
588        vregs.debug_assert_no_vreg_aliases(self.vcode.branch_block_args.iter().copied());
589        // Debug value labels are resolved in reverse_and_finalize.
590        vregs.debug_assert_no_vreg_aliases(
591            self.vcode.debug_value_labels.iter().map(|&(vreg, ..)| vreg),
592        );
593
594        self.vcode
595    }
596
597    /// Add a user stack map for the associated instruction.
598    pub fn add_user_stack_map(
599        &mut self,
600        inst: BackwardsInsnIndex,
601        entries: &[ir::UserStackMapEntry],
602    ) {
603        let stack_map = ir::UserStackMap::new(entries, self.vcode.abi.sized_stackslot_offsets());
604        let old_entry = self.vcode.user_stack_maps.insert(inst, stack_map);
605        debug_assert!(old_entry.is_none());
606    }
607
608    /// Add debug tags for the associated instruction.
609    pub fn add_debug_tags(&mut self, inst: BackwardsInsnIndex, entries: &[ir::DebugTag]) {
610        let start = u32::try_from(self.vcode.debug_tag_pool.len()).unwrap();
611        self.vcode.debug_tag_pool.extend(entries.iter().cloned());
612        let end = u32::try_from(self.vcode.debug_tag_pool.len()).unwrap();
613        self.vcode.debug_tags.insert(inst, start..end);
614    }
615}
616
617const NO_INST_OFFSET: CodeOffset = u32::MAX;
618
619impl<I: VCodeInst> VCode<I> {
620    /// New empty VCode.
621    fn new(
622        sigs: SigSet,
623        abi: Callee<I::ABIMachineSpec>,
624        emit_info: I::Info,
625        block_order: BlockLoweringOrder,
626        constants: VCodeConstants,
627        log2_min_function_alignment: u8,
628    ) -> Self {
629        let n_blocks = block_order.lowered_order().len();
630        VCode {
631            sigs,
632            vreg_types: vec![],
633            insts: Vec::with_capacity(10 * n_blocks),
634            user_stack_maps: FxHashMap::default(),
635            debug_tags: FxHashMap::default(),
636            debug_tag_pool: vec![],
637            operands: Vec::with_capacity(30 * n_blocks),
638            operand_ranges: Ranges::with_capacity(10 * n_blocks),
639            clobbers: FxHashMap::default(),
640            srclocs: Vec::with_capacity(10 * n_blocks),
641            entry: BlockIndex::new(0),
642            block_ranges: Ranges::with_capacity(n_blocks),
643            block_succ_range: Ranges::with_capacity(n_blocks),
644            block_succs: Vec::with_capacity(n_blocks),
645            block_pred_range: Ranges::default(),
646            block_preds: Vec::new(),
647            block_params_range: Ranges::with_capacity(n_blocks),
648            block_params: Vec::with_capacity(5 * n_blocks),
649            branch_block_args: Vec::with_capacity(10 * n_blocks),
650            branch_block_arg_range: Ranges::with_capacity(2 * n_blocks),
651            branch_block_arg_succ_range: Ranges::with_capacity(n_blocks),
652            block_order,
653            abi,
654            emit_info,
655            constants,
656            debug_value_labels: vec![],
657            log2_min_function_alignment,
658        }
659    }
660
661    /// Get the number of blocks. Block indices will be in the range `0 ..
662    /// (self.num_blocks() - 1)`.
663    pub fn num_blocks(&self) -> usize {
664        self.block_ranges.len()
665    }
666
667    /// The number of lowered instructions.
668    pub fn num_insts(&self) -> usize {
669        self.insts.len()
670    }
671
672    fn compute_clobbers_and_function_calls(
673        &self,
674        regalloc: &regalloc2::Output,
675    ) -> (Vec<Writable<RealReg>>, FunctionCalls) {
676        let mut clobbered = PRegSet::default();
677        let mut function_calls = FunctionCalls::None;
678
679        // All moves are included in clobbers.
680        for (_, Edit::Move { to, .. }) in &regalloc.edits {
681            if let Some(preg) = to.as_reg() {
682                clobbered.add(preg);
683            }
684        }
685
686        for (i, range) in self.operand_ranges.iter() {
687            let operands = &self.operands[range.clone()];
688            let allocs = &regalloc.allocs[range];
689            for (operand, alloc) in operands.iter().zip(allocs.iter()) {
690                if operand.kind() == OperandKind::Def {
691                    if let Some(preg) = alloc.as_reg() {
692                        clobbered.add(preg);
693                    }
694                }
695            }
696
697            function_calls.update(self.insts[i].call_type());
698
699            // Also add explicitly-clobbered registers.
700            //
701            // Skip merging this instruction's clobber list if not
702            // "included in clobbers" as per the MachInst. (Some
703            // backends use this to implement ABI specifics; e.g.,
704            // excluding calls of the same ABI as the current function
705            // from clobbers, because by definition everything
706            // clobbered by the call can be clobbered by this function
707            // without saving as well.
708            //
709            // This is important for a particular optimization: when
710            // some registers are "half-clobbered", e.g. vector/float
711            // registers on aarch64, we want them to be seen as
712            // clobbered by regalloc so it avoids carrying values
713            // across calls in these registers but not seen as
714            // clobbered by prologue generation here (because the
715            // actual half-clobber implied by the clobber list fits
716            // within the clobbers that we allow without
717            // clobber-saves).
718            if self.insts[i].is_included_in_clobbers() {
719                if let Some(&inst_clobbered) = self.clobbers.get(&InsnIndex::new(i)) {
720                    clobbered.union_from(inst_clobbered);
721                }
722            }
723        }
724
725        let clobbered_regs = clobbered
726            .into_iter()
727            .map(|preg| Writable::from_reg(RealReg::from(preg)))
728            .collect();
729
730        (clobbered_regs, function_calls)
731    }
732
733    /// Emit the instructions to a `MachBuffer`, containing fixed-up
734    /// code and external reloc/trap/etc. records ready for use. Takes
735    /// the regalloc results as well.
736    ///
737    /// Returns the machine code itself, and optionally metadata
738    /// and/or a disassembly, as an `EmitResult`. The `VCode` itself
739    /// is consumed by the emission process.
740    pub fn emit(
741        mut self,
742        regalloc: &regalloc2::Output,
743        want_disasm: bool,
744        flags: &settings::Flags,
745        ctrl_plane: &mut ControlPlane,
746    ) -> CodegenResult<EmitResult>
747    where
748        I: VCodeInst,
749    {
750        let _tt = timing::vcode_emit();
751        let mut text = MachBuffer::new();
752        text.set_log2_min_function_alignment(self.log2_min_function_alignment);
753        let mut bb_starts: Vec<Option<CodeOffset>> = vec![];
754
755        // The first M MachLabels are reserved for block indices.
756        text.reserve_labels_for_blocks(self.num_blocks());
757
758        // Register all allocated constants with the `MachBuffer` to ensure that
759        // any references to the constants during instructions can be handled
760        // correctly. With `separate_constant_pool` the constants go in a second
761        // buffer.
762        let mut rodata = flags.separate_constant_pool().then(MachBuffer::new);
763        match &mut rodata {
764            Some(rodata) => rodata.register_constants(&self.constants),
765            None => text.register_constants(&self.constants),
766        }
767        let mut buffer = MachBuffers::new(&mut text, rodata.as_mut());
768
769        // Construct the final order we emit code in: cold blocks at the end.
770        let mut final_order: SmallVec<[BlockIndex; 16]> = smallvec![];
771        let mut cold_blocks: SmallVec<[BlockIndex; 16]> = smallvec![];
772        for block in 0..self.num_blocks() {
773            let block = BlockIndex::new(block);
774            if self.block_order.is_cold(block) {
775                cold_blocks.push(block);
776            } else {
777                final_order.push(block);
778            }
779        }
780        final_order.extend(cold_blocks.clone());
781
782        // Compute/save info we need for the prologue: clobbers and
783        // number of spillslots.
784        //
785        // We clone `abi` here because we will mutate it as we
786        // generate the prologue and set other info, but we can't
787        // mutate `VCode`. The info it usually carries prior to
788        // setting clobbers is fairly minimal so this should be
789        // relatively cheap.
790        let (clobbers, function_calls) = self.compute_clobbers_and_function_calls(regalloc);
791        self.abi.compute_frame_layout(
792            &self.sigs,
793            regalloc.num_spillslots,
794            clobbers,
795            function_calls,
796        )?;
797
798        // Emit blocks.
799        let mut cur_srcloc = None;
800        let mut last_offset = None;
801        let mut inst_offsets = vec![];
802        let mut state = I::State::new(&self.abi, core::mem::take(ctrl_plane));
803
804        let mut disasm = String::new();
805
806        if !self.debug_value_labels.is_empty() {
807            inst_offsets.resize(self.insts.len(), NO_INST_OFFSET);
808        }
809
810        // Count edits per block ahead of time; this is needed for
811        // lookahead island emission. (We could derive it per-block
812        // with binary search in the edit list, but it's more
813        // efficient to do it in one pass here.)
814        let mut ra_edits_per_block: SmallVec<[u32; 64]> = smallvec![];
815        let mut edit_idx = 0;
816        for block in 0..self.num_blocks() {
817            let end_inst = InsnIndex::new(self.block_ranges.get(block).end);
818            let start_edit_idx = edit_idx;
819            while edit_idx < regalloc.edits.len() && regalloc.edits[edit_idx].0.inst() < end_inst {
820                edit_idx += 1;
821            }
822            let end_edit_idx = edit_idx;
823            ra_edits_per_block.push((end_edit_idx - start_edit_idx) as u32);
824        }
825
826        let is_forward_edge_cfi_enabled = self.abi.is_forward_edge_cfi_enabled();
827        let mut bb_padding = match flags.bb_padding_log2_minus_one() {
828            0 => Vec::new(),
829            n => vec![0; 1 << (n - 1)],
830        };
831        let mut total_bb_padding = 0;
832
833        for &block in final_order.iter() {
834            trace!("emitting block {:?}", block);
835
836            // Call the new block hook for state
837            state.on_new_block();
838
839            // Emit NOPs to align the block.
840            let new_offset = I::align_basic_block(buffer.cur_offset());
841            while new_offset > buffer.cur_offset() {
842                // Pad with NOPs up to the aligned block offset.
843                let nop = I::gen_nop((new_offset - buffer.cur_offset()) as usize);
844                nop.emit(&mut buffer, &self.emit_info, &mut Default::default());
845            }
846            assert_eq!(buffer.cur_offset(), new_offset);
847
848            // The buffer maintains its deadline invariant per-`MachInst`:
849            // after each instruction, ensure that the worst-case end of any
850            // island the buffer might emit lies before the soonest deadline,
851            // even after the next instruction.
852            let emit_island_if_needed = |buffer: &mut MachBuffers<I>, state: &mut I::State| {
853                let lookahead = I::worst_case_size() + I::worst_case_island_growth();
854                if buffer.island_needed(lookahead) {
855                    let jump_around = buffer.get_label();
856                    I::gen_jump(jump_around).emit(buffer, &self.emit_info, state);
857                    buffer.emit_island(0, state.ctrl_plane_mut());
858                    buffer.bind_label(jump_around, state.ctrl_plane_mut());
859                }
860            };
861            let emit_inst = |inst: &I,
862                             disasm: &mut String,
863                             buffer: &mut MachBuffers<I>,
864                             state: &mut I::State| {
865                if want_disasm && !inst.is_args() {
866                    let mut s = state.clone();
867                    writeln!(disasm, "  {}", inst.pretty_print_inst(&mut s)).unwrap();
868                }
869                inst.emit(buffer, &self.emit_info, state);
870                if inst.is_safepoint() {
871                    state.stack_map_emitter().assert_consumed();
872                }
873            };
874            let do_aux_emit = |inst: &I,
875                               disasm: &mut String,
876                               buffer: &mut MachBuffers<I>,
877                               state: &mut I::State| {
878                emit_inst(inst, disasm, buffer, state);
879                // Instructions emitted this way (prologue, epilogue,
880                // regalloc moves) never carry debug tags, but may
881                // include calls (e.g. stack probes); discard any
882                // post-call debug tag offset they recorded.
883                let _ = state.post_call_debug_tag_offset_mut().take();
884                emit_island_if_needed(buffer, state);
885            };
886
887            // Is this the first block? Emit the prologue directly if so.
888            if block == self.entry {
889                trace!(" -> entry block");
890                buffer.start_srcloc(Default::default());
891                for inst in &self.abi.gen_prologue() {
892                    do_aux_emit(&inst, &mut disasm, &mut buffer, &mut state);
893                }
894                buffer.end_srcloc();
895            }
896
897            // Now emit the regular block body.
898
899            buffer.bind_label(MachLabel::from_block(block), state.ctrl_plane_mut());
900
901            if want_disasm {
902                writeln!(&mut disasm, "block{}:", block.index()).unwrap();
903            }
904
905            if flags.machine_code_cfg_info() {
906                // Track BB starts. If we have backed up due to MachBuffer
907                // branch opts, note that the removed blocks were removed.
908                let cur_offset = buffer.cur_offset();
909                if last_offset.is_some() && cur_offset <= last_offset.unwrap() {
910                    for i in (0..bb_starts.len()).rev() {
911                        if bb_starts[i].is_some() && cur_offset > bb_starts[i].unwrap() {
912                            break;
913                        }
914                        bb_starts[i] = None;
915                    }
916                }
917                bb_starts.push(Some(cur_offset));
918                last_offset = Some(cur_offset);
919            }
920
921            // Attribute any regalloc edits preceding the block's first
922            // instruction to that instruction, rather than to whichever
923            // unrelated block happened to be emitted just before this one
924            // (e.g. when cold blocks are sunk to the end of the function).
925            let first_srcloc = self.srclocs[self.block_ranges.get(block.index()).start];
926            if cur_srcloc != Some(first_srcloc) {
927                if cur_srcloc.is_some() {
928                    buffer.end_srcloc();
929                }
930                buffer.start_srcloc(first_srcloc);
931                cur_srcloc = Some(first_srcloc);
932            }
933
934            if let Some(block_start) = I::gen_block_start(
935                self.block_order.is_indirect_branch_target(block),
936                is_forward_edge_cfi_enabled,
937            ) {
938                do_aux_emit(&block_start, &mut disasm, &mut buffer, &mut state);
939            }
940
941            for inst_or_edit in regalloc.block_insts_and_edits(&self, block) {
942                match inst_or_edit {
943                    InstOrEdit::Inst(iix) => {
944                        if !self.debug_value_labels.is_empty() {
945                            // If we need to produce debug info,
946                            // record the offset of each instruction
947                            // so that we can translate value-label
948                            // ranges to machine-code offsets.
949
950                            // Cold blocks violate monotonicity
951                            // assumptions elsewhere (that
952                            // instructions in inst-index order are in
953                            // order in machine code), so we omit
954                            // their offsets here. Value-label range
955                            // generation below will skip empty ranges
956                            // and ranges with to-offsets of zero.
957                            if !self.block_order.is_cold(block) {
958                                inst_offsets[iix.index()] = buffer.cur_offset();
959                            }
960                        }
961
962                        // Update the srcloc at this point in the buffer.
963                        let srcloc = self.srclocs[iix.index()];
964                        if cur_srcloc != Some(srcloc) {
965                            if cur_srcloc.is_some() {
966                                buffer.end_srcloc();
967                            }
968                            buffer.start_srcloc(srcloc);
969                            cur_srcloc = Some(srcloc);
970                        }
971
972                        // If this is a safepoint, compute a stack map
973                        // and pass it to the emit state.
974                        let stack_map_disasm = if self.insts[iix.index()].is_safepoint() {
975                            let (user_stack_map, user_stack_map_disasm) = {
976                                // The `user_stack_maps` is keyed by reverse
977                                // instruction index, so we must flip the
978                                // index. We can't put this into a helper method
979                                // due to borrowck issues because parts of
980                                // `self` are borrowed mutably elsewhere in this
981                                // function.
982                                let index = iix.to_backwards_insn_index(self.num_insts());
983                                let user_stack_map = self.user_stack_maps.remove(&index);
984                                let user_stack_map_disasm = if want_disasm {
985                                    user_stack_map.as_ref().map(|m| format!("  ; {m:?}"))
986                                } else {
987                                    None
988                                };
989                                (user_stack_map, user_stack_map_disasm)
990                            };
991
992                            state.stack_map_emitter().pre_safepoint(user_stack_map);
993
994                            user_stack_map_disasm
995                        } else {
996                            None
997                        };
998
999                        // Place debug tags in the emission buffer
1000                        // either at the offset prior to the
1001                        // instruction or at the return address of the
1002                        // call, depending on whether this is a call.
1003                        // See the documentation on [`MachDebugTagPos`]
1004                        // for details on why.
1005                        let mut debug_tag_disasm = None;
1006                        let mut place_debug_tags =
1007                            |this: &VCode<I>,
1008                             pos: MachDebugTagPos,
1009                             offset: CodeOffset,
1010                             buffer: &mut MachBuffer<I>| {
1011                                // As above, translate the forward instruction
1012                                // index to a backward index for the lookup.
1013                                let debug_tag_range = {
1014                                    let index = iix.to_backwards_insn_index(this.num_insts());
1015                                    this.debug_tags.get(&index)
1016                                };
1017                                if let Some(range) = debug_tag_range {
1018                                    let start = usize::try_from(range.start).unwrap();
1019                                    let end = usize::try_from(range.end).unwrap();
1020                                    let tags = &this.debug_tag_pool[start..end];
1021
1022                                    if want_disasm {
1023                                        debug_tag_disasm =
1024                                            Some(format!("  ; ^-- debug @ {pos:?}: {tags:?}"));
1025                                    }
1026                                    buffer.push_debug_tags_at(offset, pos, tags);
1027                                }
1028                            };
1029                        let debug_tag_pos =
1030                            if self.insts[iix.index()].call_type() == CallType::Regular {
1031                                MachDebugTagPos::PostCall
1032                            } else {
1033                                MachDebugTagPos::Pre
1034                            };
1035
1036                        if debug_tag_pos == MachDebugTagPos::Pre {
1037                            let offset = buffer.cur_offset();
1038                            place_debug_tags(&self, debug_tag_pos, offset, &mut buffer);
1039                        }
1040
1041                        // If the instruction we are about to emit is
1042                        // a return, place an epilogue at this point
1043                        // (and don't emit the return; the actual
1044                        // epilogue will contain it).
1045                        if self.insts[iix.index()].is_term() == MachTerminator::Ret {
1046                            log::trace!("emitting epilogue");
1047                            for inst in self.abi.gen_epilogue() {
1048                                do_aux_emit(&inst, &mut disasm, &mut buffer, &mut state);
1049                            }
1050                        } else {
1051                            // Update the operands for this inst using the
1052                            // allocations from the regalloc result.
1053                            let mut allocs = regalloc.inst_allocs(iix).iter();
1054                            self.insts[iix.index()].get_operands(
1055                                &mut |reg: &mut Reg, constraint, _kind, _pos| {
1056                                    let alloc =
1057                                        allocs.next().expect("enough allocations for all operands");
1058
1059                                    if let Some(alloc) = alloc.as_reg() {
1060                                        let alloc: Reg = alloc.into();
1061                                        if let OperandConstraint::FixedReg(rreg) = constraint {
1062                                            debug_assert_eq!(Reg::from(rreg), alloc);
1063                                        }
1064                                        *reg = alloc;
1065                                    } else if let Some(alloc) = alloc.as_stack() {
1066                                        let alloc: Reg = alloc.into();
1067                                        *reg = alloc;
1068                                    }
1069                                },
1070                            );
1071                            debug_assert!(allocs.next().is_none());
1072
1073                            log::trace!("emitting: {:?}", self.insts[iix.index()]);
1074
1075                            // Emit the instruction!
1076                            emit_inst(
1077                                &self.insts[iix.index()],
1078                                &mut disasm,
1079                                &mut buffer,
1080                                &mut state,
1081                            );
1082
1083                            // Place post-call tags at the call's return
1084                            // address, as recorded by the backend while
1085                            // emitting the call.
1086                            let post_call_offset = state.post_call_debug_tag_offset_mut().take();
1087                            if debug_tag_pos == MachDebugTagPos::PostCall {
1088                                let offset = post_call_offset.expect(
1089                                    "emission of a call instruction must record its post-call \
1090                                     debug tag offset",
1091                                );
1092                                place_debug_tags(&self, debug_tag_pos, offset, &mut buffer);
1093                            } else {
1094                                debug_assert!(
1095                                    post_call_offset.is_none(),
1096                                    "post-call debug tag offset recorded by a non-call instruction"
1097                                );
1098                            }
1099                            emit_island_if_needed(&mut buffer, &mut state);
1100
1101                            if let Some(stack_map_disasm) = stack_map_disasm {
1102                                disasm.push_str(&stack_map_disasm);
1103                                disasm.push('\n');
1104                            }
1105                            if let Some(debug_tag_disasm) = debug_tag_disasm {
1106                                disasm.push_str(&debug_tag_disasm);
1107                                disasm.push('\n');
1108                            }
1109                        }
1110                    }
1111
1112                    InstOrEdit::Edit(Edit::Move { from, to }) => {
1113                        // Create a move/spill/reload instruction and
1114                        // immediately emit it.
1115                        match (from.as_reg(), to.as_reg()) {
1116                            (Some(from), Some(to)) => {
1117                                // Reg-to-reg move.
1118                                let from_rreg = Reg::from(from);
1119                                let to_rreg = Writable::from_reg(Reg::from(to));
1120                                debug_assert_eq!(from.class(), to.class());
1121                                let ty = I::canonical_type_for_rc(from.class());
1122                                let mv = I::gen_move(to_rreg, from_rreg, ty);
1123                                do_aux_emit(&mv, &mut disasm, &mut buffer, &mut state);
1124                            }
1125                            (Some(from), None) => {
1126                                // Spill from register to spillslot.
1127                                let to = to.as_stack().unwrap();
1128                                let from_rreg = RealReg::from(from);
1129                                let spill = self.abi.gen_spill(to, from_rreg);
1130                                do_aux_emit(&spill, &mut disasm, &mut buffer, &mut state);
1131                            }
1132                            (None, Some(to)) => {
1133                                // Load from spillslot to register.
1134                                let from = from.as_stack().unwrap();
1135                                let to_rreg = Writable::from_reg(RealReg::from(to));
1136                                let reload = self.abi.gen_reload(to_rreg, from);
1137                                do_aux_emit(&reload, &mut disasm, &mut buffer, &mut state);
1138                            }
1139                            (None, None) => {
1140                                panic!("regalloc2 should have eliminated stack-to-stack moves!");
1141                            }
1142                        }
1143                    }
1144                }
1145            }
1146
1147            if cur_srcloc.is_some() {
1148                buffer.end_srcloc();
1149                cur_srcloc = None;
1150            }
1151
1152            // Insert padding, if configured, to stress the `MachBuffer`'s
1153            // relocation and island calculations.
1154            //
1155            // Padding can get quite large during fuzzing though so place a
1156            // total cap on it where when a per-function threshold is exceeded
1157            // the padding is turned back down to zero. This avoids a small-ish
1158            // test case generating a GB+ memory footprint in Cranelift for
1159            // example.
1160            if !bb_padding.is_empty() {
1161                // The padding bytes go directly into the buffer without
1162                // passing through `do_emit`, so check the deadline invariant
1163                // *before* writing them: if the padding would push the
1164                // worst-case end of an island past any pending deadline,
1165                // drain pending fixups via an island now. We're between
1166                // blocks, so no jump-around is needed.
1167                let padding_len = bb_padding.len() as u32 + I::LabelUse::ALIGN - 1;
1168                let lookahead = I::worst_case_size() + I::worst_case_island_growth();
1169                if buffer.island_needed(padding_len + lookahead) {
1170                    buffer.emit_island(padding_len + lookahead, ctrl_plane);
1171                }
1172
1173                buffer.put_data(&bb_padding);
1174                buffer.align_to(I::LabelUse::ALIGN);
1175                total_bb_padding += bb_padding.len();
1176                if total_bb_padding > (150 << 20) {
1177                    bb_padding = Vec::new();
1178                }
1179            }
1180        }
1181
1182        debug_assert!(
1183            self.user_stack_maps.is_empty(),
1184            "any stack maps should have been consumed by instruction emission, still have: {:#?}",
1185            self.user_stack_maps,
1186        );
1187
1188        // Do any optimizations on branches at tail of buffer, as if we had
1189        // bound one last label.
1190        buffer.optimize_branches(ctrl_plane);
1191
1192        // emission state is not needed anymore, move control plane back out
1193        *ctrl_plane = state.take_ctrl_plane();
1194
1195        let func_body_len = buffer.cur_offset();
1196
1197        // Create `bb_edges` and final (filtered) `bb_starts`.
1198        let mut bb_edges = vec![];
1199        let mut bb_offsets = vec![];
1200        if flags.machine_code_cfg_info() {
1201            for block in 0..self.num_blocks() {
1202                if bb_starts[block].is_none() {
1203                    // Block was deleted by MachBuffer; skip.
1204                    continue;
1205                }
1206                let from = bb_starts[block].unwrap();
1207
1208                bb_offsets.push(from);
1209                // Resolve each `succ` label and add edges.
1210                let succs = self.block_succs(BlockIndex::new(block));
1211                for &succ in succs.iter() {
1212                    let to = buffer.resolve_label_offset(MachLabel::from_block(succ));
1213                    bb_edges.push((from, to));
1214                }
1215            }
1216        }
1217
1218        self.monotonize_inst_offsets(&mut inst_offsets[..], func_body_len);
1219        let value_labels_ranges =
1220            self.compute_value_labels_ranges(regalloc, &inst_offsets[..], func_body_len);
1221
1222        // Store metadata about frame layout in the MachBuffer.
1223        buffer.set_frame_layout(self.abi.frame_slot_metadata());
1224
1225        let (offsets, refs) = buffer.finish(ctrl_plane);
1226        let constants = rodata
1227            .filter(|_| !refs.is_empty())
1228            .map(|rodata| MachConstantsFinalized {
1229                buffer: rodata.finish(&self.constants, ctrl_plane),
1230                offsets,
1231                refs,
1232            });
1233
1234        Ok(EmitResult {
1235            buffer: text.finish(&self.constants, ctrl_plane),
1236            constants,
1237            bb_offsets,
1238            bb_edges,
1239            disasm: if want_disasm { Some(disasm) } else { None },
1240            value_labels_ranges,
1241        })
1242    }
1243
1244    fn monotonize_inst_offsets(&self, inst_offsets: &mut [CodeOffset], func_body_len: u32) {
1245        if self.debug_value_labels.is_empty() {
1246            return;
1247        }
1248
1249        // During emission, branch removal can make offsets of instructions incorrect.
1250        // Consider the following sequence: [insi][jmp0][jmp1][jmp2][insj]
1251        // It will be recorded as (say):    [30]  [34]  [38]  [42]  [<would be 46>]
1252        // When the jumps get removed we are left with (in "inst_offsets"):
1253        // [insi][jmp0][jmp1][jmp2][insj][...]
1254        // [30]  [34]  [38]  [42]  [34]
1255        // Which violates the monotonicity invariant. This method sets offsets of these
1256        // removed instructions such as to make them appear zero-sized:
1257        // [insi][jmp0][jmp1][jmp2][insj][...]
1258        // [30]  [34]  [34]  [34]  [34]
1259        //
1260        let mut next_offset = func_body_len;
1261        for inst_index in (0..(inst_offsets.len() - 1)).rev() {
1262            let inst_offset = inst_offsets[inst_index];
1263
1264            // Not all instructions get their offsets recorded.
1265            if inst_offset == NO_INST_OFFSET {
1266                continue;
1267            }
1268
1269            if inst_offset > next_offset {
1270                trace!(
1271                    "Fixing code offset of the removed Inst {}: {} -> {}",
1272                    inst_index, inst_offset, next_offset
1273                );
1274                inst_offsets[inst_index] = next_offset;
1275                continue;
1276            }
1277
1278            next_offset = inst_offset;
1279        }
1280    }
1281
1282    fn compute_value_labels_ranges(
1283        &self,
1284        regalloc: &regalloc2::Output,
1285        inst_offsets: &[CodeOffset],
1286        func_body_len: u32,
1287    ) -> ValueLabelsRanges {
1288        if self.debug_value_labels.is_empty() {
1289            return ValueLabelsRanges::default();
1290        }
1291
1292        if trace_log_enabled!() {
1293            self.log_value_labels_ranges(regalloc, inst_offsets);
1294        }
1295
1296        let mut value_labels_ranges: ValueLabelsRanges = HashMap::new();
1297        for &(label, from, to, alloc) in &regalloc.debug_locations {
1298            let label = ValueLabel::from_u32(label);
1299            let ranges = value_labels_ranges.entry(label).or_insert_with(|| vec![]);
1300            let prog_point_to_inst = |prog_point: ProgPoint| {
1301                let mut inst = prog_point.inst();
1302                if prog_point.pos() == InstPosition::After {
1303                    inst = inst.next();
1304                }
1305                inst.index()
1306            };
1307            let inst_to_offset = |inst_index: usize| {
1308                // Skip over cold blocks.
1309                for offset in &inst_offsets[inst_index..] {
1310                    if *offset != NO_INST_OFFSET {
1311                        return *offset;
1312                    }
1313                }
1314                func_body_len
1315            };
1316            let from_inst_index = prog_point_to_inst(from);
1317            let to_inst_index = prog_point_to_inst(to);
1318            let from_offset = inst_to_offset(from_inst_index);
1319            let to_offset = inst_to_offset(to_inst_index);
1320
1321            // Empty ranges or unavailable offsets can happen
1322            // due to cold blocks and branch removal (see above).
1323            if from_offset == to_offset {
1324                continue;
1325            }
1326
1327            let loc = if let Some(preg) = alloc.as_reg() {
1328                LabelValueLoc::Reg(Reg::from(preg))
1329            } else {
1330                #[cfg(not(feature = "unwind"))]
1331                continue;
1332
1333                #[cfg(feature = "unwind")]
1334                {
1335                    let slot = alloc.as_stack().unwrap();
1336                    let slot_offset = self.abi.get_spillslot_offset(slot);
1337                    let slot_base_to_caller_sp_offset = self.abi.slot_base_to_caller_sp_offset();
1338                    let caller_sp_to_cfa_offset =
1339                        crate::isa::unwind::systemv::caller_sp_to_cfa_offset();
1340                    // NOTE: this is a negative offset because it's relative to the caller's SP
1341                    let cfa_to_sp_offset =
1342                        -((slot_base_to_caller_sp_offset + caller_sp_to_cfa_offset) as i64);
1343                    LabelValueLoc::CFAOffset(cfa_to_sp_offset + slot_offset)
1344                }
1345            };
1346
1347            // Coalesce adjacent ranges that for the same location
1348            // to minimize output size here and for the consumers.
1349            if let Some(last_loc_range) = ranges.last_mut() {
1350                if last_loc_range.loc == loc && last_loc_range.end == from_offset {
1351                    trace!(
1352                        "Extending debug range for {:?} in {:?} to Inst {} ({})",
1353                        label, loc, to_inst_index, to_offset
1354                    );
1355                    last_loc_range.end = to_offset;
1356                    continue;
1357                }
1358            }
1359
1360            trace!(
1361                "Recording debug range for {:?} in {:?}: [Inst {}..Inst {}) [{}..{})",
1362                label, loc, from_inst_index, to_inst_index, from_offset, to_offset
1363            );
1364
1365            ranges.push(ValueLocRange {
1366                loc,
1367                start: from_offset,
1368                end: to_offset,
1369            });
1370        }
1371
1372        value_labels_ranges
1373    }
1374
1375    fn log_value_labels_ranges(&self, regalloc: &regalloc2::Output, inst_offsets: &[CodeOffset]) {
1376        debug_assert!(trace_log_enabled!());
1377
1378        // What debug labels do we have? Note we'll skip those that have not been
1379        // allocated any location at all. They will show up as numeric gaps in the table.
1380        let mut labels = vec![];
1381        for &(label, _, _, _) in &regalloc.debug_locations {
1382            if Some(&label) == labels.last() {
1383                continue;
1384            }
1385            labels.push(label);
1386        }
1387
1388        // Reformat the data on what VRegs were the VLs assigned to by lowering, since
1389        // the array we have is sorted by VReg, and we want it sorted by VL for easy
1390        // access in the loop below.
1391        let mut vregs = vec![];
1392        for &(vreg, start, end, label) in &self.debug_value_labels {
1393            if matches!(labels.binary_search(&label), Ok(_)) {
1394                vregs.push((label, start, end, vreg));
1395            }
1396        }
1397        vregs.sort_unstable_by(
1398            |(l_label, l_start, _, _), (r_label, r_start, _, _)| match l_label.cmp(r_label) {
1399                Ordering::Equal => l_start.cmp(r_start),
1400                cmp => cmp,
1401            },
1402        );
1403
1404        #[derive(PartialEq)]
1405        enum Mode {
1406            Measure,
1407            Emit,
1408        }
1409        #[derive(PartialEq)]
1410        enum Row {
1411            Head,
1412            Line,
1413            Inst(usize, usize),
1414        }
1415
1416        let mut widths = vec![0; 3 + 2 * labels.len()];
1417        let mut row = String::new();
1418        let mut output_row = |row_kind: Row, mode: Mode| {
1419            let mut column_index = 0;
1420            row.clear();
1421
1422            macro_rules! output_cell_impl {
1423                ($fill:literal, $span:literal, $($cell_fmt:tt)*) => {
1424                    let column_start = row.len();
1425                    {
1426                        row.push('|');
1427                        write!(row, $($cell_fmt)*).unwrap();
1428                    }
1429
1430                    let next_column_index = column_index + $span;
1431                    let expected_width: usize = widths[column_index..next_column_index].iter().sum();
1432                    if mode == Mode::Measure {
1433                        let actual_width = row.len() - column_start;
1434                        if actual_width > expected_width {
1435                            widths[next_column_index - 1] += actual_width - expected_width;
1436                        }
1437                    } else {
1438                        let column_end = column_start + expected_width;
1439                        while row.len() != column_end {
1440                            row.push($fill);
1441                        }
1442                    }
1443                    column_index = next_column_index;
1444                };
1445            }
1446            macro_rules! output_cell {
1447                ($($cell_fmt:tt)*) => {
1448                    output_cell_impl!(' ', 1, $($cell_fmt)*);
1449                };
1450            }
1451
1452            match row_kind {
1453                Row::Head => {
1454                    output_cell!("BB");
1455                    output_cell!("Inst");
1456                    output_cell!("IP");
1457                    for label in &labels {
1458                        output_cell_impl!(' ', 2, "{:?}", ValueLabel::from_u32(*label));
1459                    }
1460                }
1461                Row::Line => {
1462                    debug_assert!(mode == Mode::Emit);
1463                    for _ in 0..3 {
1464                        output_cell_impl!('-', 1, "");
1465                    }
1466                    for _ in &labels {
1467                        output_cell_impl!('-', 2, "");
1468                    }
1469                }
1470                Row::Inst(block_index, inst_index) => {
1471                    debug_assert!(inst_index < self.num_insts());
1472                    if self.block_ranges.get(block_index).start == inst_index {
1473                        output_cell!("B{}", block_index);
1474                    } else {
1475                        output_cell!("");
1476                    }
1477                    output_cell!("Inst {inst_index} ");
1478                    output_cell!("{} ", inst_offsets[inst_index]);
1479
1480                    for label in &labels {
1481                        // First, the VReg.
1482                        use regalloc2::Inst;
1483                        let vreg_cmp = |inst: usize,
1484                                        vreg_label: &u32,
1485                                        range_start: &Inst,
1486                                        range_end: &Inst| {
1487                            match vreg_label.cmp(&label) {
1488                                Ordering::Equal => {
1489                                    if range_end.index() <= inst {
1490                                        Ordering::Less
1491                                    } else if range_start.index() > inst {
1492                                        Ordering::Greater
1493                                    } else {
1494                                        Ordering::Equal
1495                                    }
1496                                }
1497                                cmp => cmp,
1498                            }
1499                        };
1500                        let vreg_index =
1501                            vregs.binary_search_by(|(l, s, e, _)| vreg_cmp(inst_index, l, s, e));
1502                        if let Ok(vreg_index) = vreg_index {
1503                            let mut prev_vreg = None;
1504                            if inst_index > 0 {
1505                                let prev_vreg_index = vregs.binary_search_by(|(l, s, e, _)| {
1506                                    vreg_cmp(inst_index - 1, l, s, e)
1507                                });
1508                                if let Ok(prev_vreg_index) = prev_vreg_index {
1509                                    prev_vreg = Some(vregs[prev_vreg_index].3);
1510                                }
1511                            }
1512
1513                            let vreg = vregs[vreg_index].3;
1514                            if Some(vreg) == prev_vreg {
1515                                output_cell!("*");
1516                            } else {
1517                                output_cell!("{}", vreg);
1518                            }
1519                        } else {
1520                            output_cell!("");
1521                        }
1522
1523                        // Second, the allocated location.
1524                        let inst_prog_point = ProgPoint::before(Inst::new(inst_index));
1525                        let range_index = regalloc.debug_locations.binary_search_by(
1526                            |(range_label, range_start, range_end, _)| match range_label.cmp(label)
1527                            {
1528                                Ordering::Equal => {
1529                                    if *range_end <= inst_prog_point {
1530                                        Ordering::Less
1531                                    } else if *range_start > inst_prog_point {
1532                                        Ordering::Greater
1533                                    } else {
1534                                        Ordering::Equal
1535                                    }
1536                                }
1537                                cmp => cmp,
1538                            },
1539                        );
1540                        if let Ok(range_index) = range_index {
1541                            // Live at this instruction, print the location.
1542                            if let Some(reg) = regalloc.debug_locations[range_index].3.as_reg() {
1543                                output_cell!("{:?}", Reg::from(reg));
1544                            } else {
1545                                output_cell!("Stk");
1546                            }
1547                        } else {
1548                            // Not live at this instruction.
1549                            output_cell!("");
1550                        }
1551                    }
1552                }
1553            }
1554            row.push('|');
1555
1556            if mode == Mode::Emit {
1557                trace!("{}", row.as_str());
1558            }
1559        };
1560
1561        for block_index in 0..self.num_blocks() {
1562            for inst_index in self.block_ranges.get(block_index) {
1563                output_row(Row::Inst(block_index, inst_index), Mode::Measure);
1564            }
1565        }
1566        output_row(Row::Head, Mode::Measure);
1567
1568        output_row(Row::Head, Mode::Emit);
1569        output_row(Row::Line, Mode::Emit);
1570        for block_index in 0..self.num_blocks() {
1571            for inst_index in self.block_ranges.get(block_index) {
1572                output_row(Row::Inst(block_index, inst_index), Mode::Emit);
1573            }
1574        }
1575    }
1576
1577    /// Get the IR block for a BlockIndex, if one exists.
1578    pub fn bindex_to_bb(&self, block: BlockIndex) -> Option<ir::Block> {
1579        self.block_order.lowered_order()[block.index()].orig_block()
1580    }
1581
1582    /// Get the user stack map associated with the given forward instruction index.
1583    pub fn get_user_stack_map(&self, inst: InsnIndex) -> Option<&ir::UserStackMap> {
1584        let index = inst.to_backwards_insn_index(self.num_insts());
1585        self.user_stack_maps.get(&index)
1586    }
1587}
1588
1589impl<I: VCodeInst> core::ops::Index<InsnIndex> for VCode<I> {
1590    type Output = I;
1591    fn index(&self, idx: InsnIndex) -> &Self::Output {
1592        &self.insts[idx.index()]
1593    }
1594}
1595
1596impl<I: VCodeInst> RegallocFunction for VCode<I> {
1597    fn num_insts(&self) -> usize {
1598        self.insts.len()
1599    }
1600
1601    fn num_blocks(&self) -> usize {
1602        self.block_ranges.len()
1603    }
1604
1605    fn entry_block(&self) -> BlockIndex {
1606        self.entry
1607    }
1608
1609    fn block_insns(&self, block: BlockIndex) -> InstRange {
1610        let range = self.block_ranges.get(block.index());
1611        InstRange::new(InsnIndex::new(range.start), InsnIndex::new(range.end))
1612    }
1613
1614    fn block_succs(&self, block: BlockIndex) -> &[BlockIndex] {
1615        let range = self.block_succ_range.get(block.index());
1616        &self.block_succs[range]
1617    }
1618
1619    fn block_preds(&self, block: BlockIndex) -> &[BlockIndex] {
1620        let range = self.block_pred_range.get(block.index());
1621        &self.block_preds[range]
1622    }
1623
1624    fn block_params(&self, block: BlockIndex) -> &[VReg] {
1625        // As a special case we don't return block params for the entry block, as all the arguments
1626        // will be defined by the `Inst::Args` instruction.
1627        if block == self.entry {
1628            return &[];
1629        }
1630
1631        let range = self.block_params_range.get(block.index());
1632        &self.block_params[range]
1633    }
1634
1635    fn branch_blockparams(&self, block: BlockIndex, _insn: InsnIndex, succ_idx: usize) -> &[VReg] {
1636        let succ_range = self.branch_block_arg_succ_range.get(block.index());
1637        debug_assert!(succ_idx < succ_range.len());
1638        let branch_block_args = self.branch_block_arg_range.get(succ_range.start + succ_idx);
1639        &self.branch_block_args[branch_block_args]
1640    }
1641
1642    fn is_ret(&self, insn: InsnIndex) -> bool {
1643        match self.insts[insn.index()].is_term() {
1644            // We treat blocks terminated by an unconditional trap like a return for regalloc.
1645            MachTerminator::None => self.insts[insn.index()].is_trap(),
1646            MachTerminator::Ret | MachTerminator::RetCall => true,
1647            MachTerminator::Branch => false,
1648        }
1649    }
1650
1651    fn is_branch(&self, insn: InsnIndex) -> bool {
1652        match self.insts[insn.index()].is_term() {
1653            MachTerminator::Branch => true,
1654            _ => false,
1655        }
1656    }
1657
1658    fn inst_operands(&self, insn: InsnIndex) -> &[Operand] {
1659        let range = self.operand_ranges.get(insn.index());
1660        &self.operands[range]
1661    }
1662
1663    fn inst_clobbers(&self, insn: InsnIndex) -> PRegSet {
1664        self.clobbers.get(&insn).cloned().unwrap_or_default()
1665    }
1666
1667    fn num_vregs(&self) -> usize {
1668        self.vreg_types.len()
1669    }
1670
1671    fn debug_value_labels(&self) -> &[(VReg, InsnIndex, InsnIndex, u32)] {
1672        &self.debug_value_labels
1673    }
1674
1675    fn spillslot_size(&self, regclass: RegClass) -> usize {
1676        self.abi.get_spillslot_size(regclass) as usize
1677    }
1678
1679    fn allow_multiple_vreg_defs(&self) -> bool {
1680        // At least the s390x backend requires this, because the
1681        // `Loop` pseudo-instruction aggregates all Operands so pinned
1682        // vregs (RealRegs) may occur more than once.
1683        true
1684    }
1685
1686    fn is_block_cold(&self, block: BlockIndex) -> bool {
1687        self.block_order.is_cold(block)
1688    }
1689}
1690
1691impl<I: VCodeInst> Debug for VRegAllocator<I> {
1692    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1693        writeln!(f, "VRegAllocator {{")?;
1694
1695        let mut alias_keys = self.vreg_aliases.keys().cloned().collect::<Vec<_>>();
1696        alias_keys.sort_unstable();
1697        for key in alias_keys {
1698            let dest = self.vreg_aliases.get(&key).unwrap();
1699            writeln!(f, "  {:?} := {:?}", Reg::from(key), Reg::from(*dest))?;
1700        }
1701
1702        writeln!(f, "}}")
1703    }
1704}
1705
1706impl<I: VCodeInst> fmt::Debug for VCode<I> {
1707    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1708        writeln!(f, "VCode {{")?;
1709        writeln!(f, "  Entry block: {}", self.entry.index())?;
1710
1711        let mut state = Default::default();
1712
1713        for block in 0..self.num_blocks() {
1714            let block = BlockIndex::new(block);
1715            writeln!(
1716                f,
1717                "Block {}({:?}):",
1718                block.index(),
1719                self.block_params(block)
1720            )?;
1721            if let Some(bb) = self.bindex_to_bb(block) {
1722                writeln!(f, "    (original IR block: {bb})")?;
1723            }
1724            for (succ_idx, succ) in self.block_succs(block).iter().enumerate() {
1725                writeln!(
1726                    f,
1727                    "    (successor: Block {}({:?}))",
1728                    succ.index(),
1729                    self.branch_blockparams(block, InsnIndex::new(0) /* dummy */, succ_idx)
1730                )?;
1731            }
1732            for inst in self.block_ranges.get(block.index()) {
1733                writeln!(
1734                    f,
1735                    "  Inst {}: {}",
1736                    inst,
1737                    self.insts[inst].pretty_print_inst(&mut state)
1738                )?;
1739                if let Some(user_stack_map) = self.get_user_stack_map(InsnIndex::new(inst)) {
1740                    writeln!(f, "    {user_stack_map:?}")?;
1741                }
1742            }
1743        }
1744
1745        writeln!(f, "}}")?;
1746        Ok(())
1747    }
1748}
1749
1750/// This structure manages VReg allocation during the lifetime of the VCodeBuilder.
1751pub struct VRegAllocator<I> {
1752    /// VReg IR-level types.
1753    vreg_types: Vec<Type>,
1754
1755    /// VReg aliases. When the final VCode is built we rewrite all
1756    /// uses of the keys in this table to their replacement values.
1757    ///
1758    /// We use these aliases to rename an instruction's expected
1759    /// result vregs to the returned vregs from lowering, which are
1760    /// usually freshly-allocated temps.
1761    vreg_aliases: FxHashMap<regalloc2::VReg, regalloc2::VReg>,
1762
1763    /// A deferred error, to be bubbled up to the top level of the
1764    /// lowering algorithm. We take this approach because we cannot
1765    /// currently propagate a `Result` upward through ISLE code (the
1766    /// lowering rules) or some ABI code.
1767    deferred_error: Option<CodegenError>,
1768
1769    /// The type of instruction that this allocator makes registers for.
1770    _inst: core::marker::PhantomData<I>,
1771}
1772
1773impl<I: VCodeInst> VRegAllocator<I> {
1774    /// Make a new VRegAllocator.
1775    pub fn with_capacity(capacity: usize) -> Self {
1776        let capacity = first_user_vreg_index() + capacity;
1777        let mut vreg_types = Vec::with_capacity(capacity);
1778        vreg_types.resize(first_user_vreg_index(), types::INVALID);
1779        Self {
1780            vreg_types,
1781            vreg_aliases: FxHashMap::with_capacity_and_hasher(capacity, Default::default()),
1782            deferred_error: None,
1783            _inst: core::marker::PhantomData::default(),
1784        }
1785    }
1786
1787    /// Allocate a fresh ValueRegs.
1788    pub fn alloc(&mut self, ty: Type) -> CodegenResult<ValueRegs<Reg>> {
1789        if self.deferred_error.is_some() {
1790            return Err(CodegenError::CodeTooLarge);
1791        }
1792        let v = self.vreg_types.len();
1793        let (regclasses, tys) = I::rc_for_type(&ty)?;
1794
1795        // Check that new indices are in-bounds for regalloc2's
1796        // VReg/Operand representation.
1797        if v + regclasses.len() > VReg::MAX {
1798            return Err(CodegenError::CodeTooLarge);
1799        }
1800
1801        // Check that new indices are in-bounds for our Reg
1802        // bit-packing on top of the RA2 types, which represents
1803        // spillslots as well.
1804        let check = |vreg: regalloc2::VReg| -> CodegenResult<Reg> {
1805            Reg::from_virtual_reg_checked(vreg).ok_or(CodegenError::CodeTooLarge)
1806        };
1807
1808        let regs: ValueRegs<Reg> = match regclasses {
1809            &[rc0] => ValueRegs::one(check(VReg::new(v, rc0))?),
1810            &[rc0, rc1] => ValueRegs::two(check(VReg::new(v, rc0))?, check(VReg::new(v + 1, rc1))?),
1811            // We can extend this if/when we support 32-bit targets; e.g.,
1812            // an i128 on a 32-bit machine will need up to four machine regs
1813            // for a `Value`.
1814            _ => panic!("Value must reside in 1 or 2 registers"),
1815        };
1816        for (&reg_ty, &reg) in tys.iter().zip(regs.regs().iter()) {
1817            let vreg = reg.to_virtual_reg().unwrap();
1818            debug_assert_eq!(self.vreg_types.len(), vreg.index());
1819            self.vreg_types.push(reg_ty);
1820        }
1821
1822        Ok(regs)
1823    }
1824
1825    /// Allocate a fresh ValueRegs, deferring any out-of-vregs
1826    /// errors. This is useful in places where we cannot bubble a
1827    /// `CodegenResult` upward easily, and which are known to be
1828    /// invoked from within the lowering loop that checks the deferred
1829    /// error status below.
1830    pub fn alloc_with_deferred_error(&mut self, ty: Type) -> ValueRegs<Reg> {
1831        match self.alloc(ty) {
1832            Ok(x) => x,
1833            Err(e) => {
1834                self.deferred_error = Some(e);
1835                self.bogus_for_deferred_error(ty)
1836            }
1837        }
1838    }
1839
1840    /// Take any deferred error that was accumulated by `alloc_with_deferred_error`.
1841    pub fn take_deferred_error(&mut self) -> Option<CodegenError> {
1842        self.deferred_error.take()
1843    }
1844
1845    /// Produce an bogus VReg placeholder with the proper number of
1846    /// registers for the given type. This is meant to be used with
1847    /// deferred allocation errors (see `Lower::alloc_tmp()`).
1848    fn bogus_for_deferred_error(&self, ty: Type) -> ValueRegs<Reg> {
1849        let (regclasses, _tys) = I::rc_for_type(&ty).expect("must have valid type");
1850        match regclasses {
1851            &[rc0] => ValueRegs::one(VReg::new(0, rc0).into()),
1852            &[rc0, rc1] => ValueRegs::two(VReg::new(0, rc0).into(), VReg::new(1, rc1).into()),
1853            _ => panic!("Value must reside in 1 or 2 registers"),
1854        }
1855    }
1856
1857    /// Rewrite any mention of `from` into `to`.
1858    pub fn set_vreg_alias(&mut self, from: Reg, to: Reg) {
1859        let from = from.into();
1860        let resolved_to = self.resolve_vreg_alias(to.into());
1861        // Disallow cycles (see below).
1862        assert_ne!(resolved_to, from);
1863
1864        let old_alias = self.vreg_aliases.insert(from, resolved_to);
1865        debug_assert_eq!(old_alias, None);
1866    }
1867
1868    fn resolve_vreg_alias(&self, mut vreg: regalloc2::VReg) -> regalloc2::VReg {
1869        // We prevent cycles from existing by resolving targets of
1870        // aliases eagerly before setting them. If the target resolves
1871        // to the origin of the alias, then a cycle would be created
1872        // and the alias is disallowed. Because of the structure of
1873        // SSA code (one instruction can refer to another's defs but
1874        // not vice-versa, except indirectly through
1875        // phis/blockparams), cycles should not occur as we use
1876        // aliases to redirect vregs to the temps that actually define
1877        // them.
1878        while let Some(to) = self.vreg_aliases.get(&vreg) {
1879            vreg = *to;
1880        }
1881        vreg
1882    }
1883
1884    #[inline]
1885    fn debug_assert_no_vreg_aliases(&self, mut list: impl Iterator<Item = VReg>) {
1886        debug_assert!(list.all(|vreg| !self.vreg_aliases.contains_key(&vreg)));
1887    }
1888}
1889
1890/// This structure tracks the large constants used in VCode that will be emitted separately by the
1891/// [MachBuffer].
1892///
1893/// First, during the lowering phase, constants are inserted using
1894/// [VCodeConstants.insert]; an intermediate handle, `VCodeConstant`, tracks what constants are
1895/// used in this phase. Some deduplication is performed, when possible, as constant
1896/// values are inserted.
1897///
1898/// Secondly, during the emission phase, the [MachBuffer] assigns [MachLabel]s for each of the
1899/// constants so that instructions can refer to the value's memory location. The [MachBuffer]
1900/// then writes the constant values to the buffer.
1901#[derive(Default)]
1902pub struct VCodeConstants {
1903    constants: PrimaryMap<VCodeConstant, VCodeConstantData>,
1904    pool_uses: HashMap<Constant, VCodeConstant>,
1905    well_known_uses: HashMap<*const [u8], VCodeConstant>,
1906    u64s: HashMap<[u8; 8], VCodeConstant>,
1907}
1908impl VCodeConstants {
1909    /// Initialize the structure with the expected number of constants.
1910    pub fn with_capacity(expected_num_constants: usize) -> Self {
1911        Self {
1912            constants: PrimaryMap::with_capacity(expected_num_constants),
1913            pool_uses: HashMap::with_capacity(expected_num_constants),
1914            well_known_uses: HashMap::new(),
1915            u64s: HashMap::new(),
1916        }
1917    }
1918
1919    /// Insert a constant; using this method indicates that a constant value will be used and thus
1920    /// will be emitted to the `MachBuffer`. The current implementation can deduplicate constants
1921    /// that are [VCodeConstantData::Pool] or [VCodeConstantData::WellKnown] but not
1922    /// [VCodeConstantData::Generated].
1923    pub fn insert(&mut self, data: VCodeConstantData) -> VCodeConstant {
1924        match data {
1925            VCodeConstantData::Generated(_) => self.constants.push(data),
1926            VCodeConstantData::Pool(constant, _) => match self.pool_uses.get(&constant) {
1927                None => {
1928                    let vcode_constant = self.constants.push(data);
1929                    self.pool_uses.insert(constant, vcode_constant);
1930                    vcode_constant
1931                }
1932                Some(&vcode_constant) => vcode_constant,
1933            },
1934            VCodeConstantData::WellKnown(data_ref) => {
1935                match self.well_known_uses.entry(data_ref as *const [u8]) {
1936                    Entry::Vacant(v) => {
1937                        let vcode_constant = self.constants.push(data);
1938                        v.insert(vcode_constant);
1939                        vcode_constant
1940                    }
1941                    Entry::Occupied(o) => *o.get(),
1942                }
1943            }
1944            VCodeConstantData::U64(value) => match self.u64s.entry(value) {
1945                Entry::Vacant(v) => {
1946                    let vcode_constant = self.constants.push(data);
1947                    v.insert(vcode_constant);
1948                    vcode_constant
1949                }
1950                Entry::Occupied(o) => *o.get(),
1951            },
1952        }
1953    }
1954
1955    /// Return the number of constants inserted.
1956    pub fn len(&self) -> usize {
1957        self.constants.len()
1958    }
1959
1960    /// Iterate over the `VCodeConstant` keys inserted in this structure.
1961    pub fn keys(&self) -> Keys<VCodeConstant> {
1962        self.constants.keys()
1963    }
1964
1965    /// Iterate over the `VCodeConstant` keys and the data (as a byte slice) inserted in this
1966    /// structure.
1967    pub fn iter(&self) -> impl Iterator<Item = (VCodeConstant, &VCodeConstantData)> {
1968        self.constants.iter()
1969    }
1970
1971    /// Returns the data associated with the specified constant.
1972    pub fn get(&self, c: VCodeConstant) -> &VCodeConstantData {
1973        &self.constants[c]
1974    }
1975
1976    /// Checks if the given [VCodeConstantData] is registered as
1977    /// used by the pool.
1978    pub fn pool_uses(&self, constant: &VCodeConstantData) -> bool {
1979        match constant {
1980            VCodeConstantData::Pool(c, _) => self.pool_uses.contains_key(c),
1981            _ => false,
1982        }
1983    }
1984}
1985
1986/// A use of a constant by one or more VCode instructions; see [VCodeConstants].
1987#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1988pub struct VCodeConstant(u32);
1989entity_impl!(VCodeConstant);
1990
1991/// Identify the different types of constant that can be inserted into [VCodeConstants]. Tracking
1992/// these separately instead of as raw byte buffers allows us to avoid some duplication.
1993pub enum VCodeConstantData {
1994    /// A constant already present in the Cranelift IR
1995    /// [ConstantPool](crate::ir::constant::ConstantPool).
1996    Pool(Constant, ConstantData),
1997    /// A reference to a well-known constant value that is statically encoded within the compiler.
1998    WellKnown(&'static [u8]),
1999    /// A constant value generated during lowering; the value may depend on the instruction context
2000    /// which makes it difficult to de-duplicate--if possible, use other variants.
2001    Generated(ConstantData),
2002    /// A constant of at most 64 bits. These are deduplicated as
2003    /// well. Stored as a fixed-size array of `u8` so that we do not
2004    /// encounter endianness problems when cross-compiling.
2005    U64([u8; 8]),
2006}
2007impl VCodeConstantData {
2008    /// Retrieve the constant data as a byte slice.
2009    pub fn as_slice(&self) -> &[u8] {
2010        match self {
2011            VCodeConstantData::Pool(_, d) | VCodeConstantData::Generated(d) => d.as_slice(),
2012            VCodeConstantData::WellKnown(d) => d,
2013            VCodeConstantData::U64(value) => &value[..],
2014        }
2015    }
2016
2017    /// Calculate the alignment of the constant data.
2018    pub fn alignment(&self) -> u32 {
2019        if self.as_slice().len() <= 8 { 8 } else { 16 }
2020    }
2021}
2022
2023#[cfg(test)]
2024mod test {
2025    use super::*;
2026    use core::mem::size_of;
2027
2028    #[test]
2029    fn size_of_constant_structs() {
2030        assert_eq!(size_of::<Constant>(), 4);
2031        assert_eq!(size_of::<VCodeConstant>(), 4);
2032        assert_eq!(size_of::<ConstantData>(), 3 * size_of::<usize>());
2033        assert_eq!(size_of::<VCodeConstantData>(), 4 * size_of::<usize>());
2034        assert_eq!(
2035            size_of::<PrimaryMap<VCodeConstant, VCodeConstantData>>(),
2036            3 * size_of::<usize>()
2037        );
2038        // TODO The VCodeConstants structure's memory size could be further optimized.
2039        // With certain versions of Rust, each `HashMap` in `VCodeConstants` occupied at
2040        // least 48 bytes, making an empty `VCodeConstants` cost 120 bytes.
2041    }
2042}