Skip to main content

cranelift_codegen/machinst/
lower.rs

1//! This module implements lowering (instruction selection) from Cranelift IR
2//! to machine instructions with virtual registers. This is *almost* the final
3//! machine code, except for register allocation.
4
5// TODO: separate the IR-query core of `Lower` from the lowering logic built on
6// top of it, e.g. the side-effect/coloring analysis and the scan support.
7
8use crate::entity::SecondaryMap;
9use crate::inst_predicates::{
10    has_lowering_side_effect, is_constant_64bit, must_lower_even_if_unused,
11};
12use crate::ir::{
13    ArgumentPurpose, Block, BlockArg, Constant, ConstantData, DataFlowGraph, ExternalName,
14    Function, GlobalValue, GlobalValueData, Immediate, Inst, InstructionData, RelSourceLoc, SigRef,
15    Signature, Type, Value, ValueDef, ValueLabelAssignments, ValueLabelStart,
16};
17use crate::machinst::valueregs::InvalidSentinel;
18use crate::machinst::{
19    ABIMachineSpec, BackwardsInsnIndex, BlockIndex, BlockLoweringOrder, CallArgList, CallInfo,
20    CallRetList, Callee, InsnIndex, LoweredBlock, MachLabel, MachMemFlags, Reg, Sig, SigSet,
21    TryCallInfo, VCode, VCodeBuilder, VCodeConstant, VCodeConstantData, VCodeConstants, VCodeInst,
22    ValueRegs, Writable, writable_value_regs,
23};
24use crate::settings::Flags;
25use crate::{CodegenError, CodegenResult, trace};
26use crate::{FxHashMap, FxHashSet};
27use alloc::vec::Vec;
28use core::fmt::Debug;
29use cranelift_control::ControlPlane;
30use smallvec::{SmallVec, smallvec};
31
32use super::{VCodeBuildDirection, VRegAllocator};
33
34/// A vector of ValueRegs, used to represent the outputs of an instruction.
35pub type InstOutput = SmallVec<[ValueRegs<Reg>; 2]>;
36
37/// An "instruction color" partitions CLIF instructions by side-effecting ops.
38/// All instructions with the same "color" are guaranteed not to be separated by
39/// any side-effecting op (for this purpose, loads are also considered
40/// side-effecting, to avoid subtle questions w.r.t. the memory model), and
41/// furthermore, it is guaranteed that for any two instructions A and B such
42/// that color(A) == color(B), either A dominates B and B postdominates A, or
43/// vice-versa. (For now, in practice, only ops in the same basic block can ever
44/// have the same color, trivially providing the second condition.) Intuitively,
45/// this means that the ops of the same color must always execute "together", as
46/// part of one atomic contiguous section of the dynamic execution trace, and
47/// they can be freely permuted (modulo true dataflow dependencies) without
48/// affecting program behavior.
49#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
50struct InstColor(u32);
51impl InstColor {
52    fn new(n: u32) -> InstColor {
53        InstColor(n)
54    }
55
56    /// Get an arbitrary index representing this color. The index is unique
57    /// *within a single function compilation*, but indices may be reused across
58    /// functions.
59    pub fn get(self) -> u32 {
60        self.0
61    }
62}
63
64/// A representation of all of the ways in which a value is available, aside
65/// from as a direct register.
66///
67/// - An instruction, if it would be allowed to occur at the current location
68///   instead (see [Lower::get_input_as_source_or_const()] for more details).
69///
70/// - A constant, if the value is known to be a constant.
71#[derive(Clone, Copy, Debug)]
72pub struct NonRegInput {
73    /// An instruction produces this value (as the given output), and its
74    /// computation (and side-effect if applicable) could occur at the
75    /// current instruction's location instead.
76    ///
77    /// If this instruction's operation is merged into the current instruction,
78    /// the backend must call [Lower::sink_inst()].
79    ///
80    /// This enum indicates whether this use of the source instruction
81    /// is unique or not.
82    pub inst: InputSourceInst,
83    /// The value is a known constant.
84    pub constant: Option<u64>,
85}
86
87/// When examining an input to an instruction, this enum provides one
88/// of several options: there is or isn't a single instruction (that
89/// we can see and merge with) that produces that input's value, and
90/// we are or aren't the single user of that instruction.
91#[derive(Clone, Copy, Debug)]
92pub enum InputSourceInst {
93    /// The input in question is the single, unique use of the given
94    /// instruction and output index, and it can be sunk to the
95    /// location of this input.
96    UniqueUse(Inst, usize),
97    /// The input in question is one of multiple uses of the given
98    /// instruction. It can still be sunk to the location of this
99    /// input.
100    Use(Inst, usize),
101    /// We cannot determine which instruction produced the input, or
102    /// it is one of several instructions (e.g., due to a control-flow
103    /// merge and blockparam), or the source instruction cannot be
104    /// allowed to sink to the current location due to side-effects.
105    None,
106}
107
108impl InputSourceInst {
109    /// Get the instruction and output index for this source, whether
110    /// we are its single or one of many users.
111    pub fn as_inst(&self) -> Option<(Inst, usize)> {
112        match self {
113            &InputSourceInst::UniqueUse(inst, output_idx)
114            | &InputSourceInst::Use(inst, output_idx) => Some((inst, output_idx)),
115            &InputSourceInst::None => None,
116        }
117    }
118}
119
120/// A machine backend.
121pub trait LowerBackend {
122    /// The machine instruction type.
123    type MInst: VCodeInst;
124
125    /// Lower a single instruction.
126    ///
127    /// For a branch, this function should not generate the actual branch
128    /// instruction. However, it must force any values it needs for the branch
129    /// edge (block-param actuals) into registers, because the actual branch
130    /// generation (`lower_branch()`) happens *after* any possible merged
131    /// out-edge.
132    ///
133    /// Returns `None` if no lowering for the instruction was found.
134    fn lower(&self, ctx: &mut Lower<Self::MInst>, inst: Inst) -> Option<InstOutput>;
135
136    /// Lower a block-terminating group of branches (which together can be seen
137    /// as one N-way branch), given a vcode MachLabel for each target.
138    ///
139    /// Returns `None` if no lowering for the branch was found.
140    fn lower_branch(
141        &self,
142        ctx: &mut Lower<Self::MInst>,
143        inst: Inst,
144        targets: &[MachLabel],
145    ) -> Option<()>;
146
147    /// A bit of a hack: give a fixed register that always holds the result of a
148    /// `get_pinned_reg` instruction, if known.  This allows elision of moves
149    /// into the associated vreg, instead using the real reg directly.
150    fn maybe_pinned_reg(&self) -> Option<Reg> {
151        None
152    }
153}
154
155/// Machine-independent lowering driver / machine-instruction container. Maintains a correspondence
156/// from original Inst to MachInsts.
157pub struct Lower<'func, I: VCodeInst> {
158    /// The function to lower.
159    pub(crate) f: &'func Function,
160
161    /// Lowered machine instructions.
162    vcode: VCodeBuilder<I>,
163
164    /// VReg allocation context, given to the vcode field at build time to finalize the vcode.
165    vregs: VRegAllocator<I>,
166
167    /// Mapping from `Value` (SSA value in IR) to virtual register.
168    value_regs: SecondaryMap<Value, ValueRegs<Reg>>,
169
170    /// sret registers, if needed.
171    sret_reg: Option<ValueRegs<Reg>>,
172
173    /// Instruction colors at block exits. From this map, we can recover all
174    /// instruction colors by scanning backward from the block end and
175    /// decrementing on any color-changing (side-effecting) instruction.
176    block_end_colors: SecondaryMap<Block, InstColor>,
177
178    /// Instruction colors at side-effecting ops. This is the *entry* color,
179    /// i.e., the version of global state that exists before an instruction
180    /// executes.  For each side-effecting instruction, the *exit* color is its
181    /// entry color plus one.
182    ///
183    /// The current color is incremented to at least 1 before any instruction is
184    /// processed, so every side-effecting instruction has a color `>= 1`, and
185    /// the default `InstColor::new(0)` serves as a "not side-effecting"
186    /// sentinel.
187    side_effect_inst_entry_colors: SecondaryMap<Inst, InstColor>,
188
189    /// Current color as we scan during lowering. While we are lowering an
190    /// instruction, this is equal to the color *at entry to* the instruction.
191    cur_scan_entry_color: Option<InstColor>,
192
193    /// Current instruction as we scan during lowering.
194    cur_inst: Option<Inst>,
195
196    /// Use-counts per SSA value, as counted in the input IR. These
197    /// are "coarsened", in the abstract-interpretation sense: we only
198    /// care about "0, 1, many" states, as this is all we need and
199    /// this lets us do an efficient fixpoint analysis.
200    ///
201    /// See doc comment on `ValueUseState` for more details.
202    value_ir_uses: SecondaryMap<Value, ValueUseState>,
203
204    /// Actual uses of each SSA value so far, incremented while lowering.
205    value_lowered_uses: SecondaryMap<Value, u32>,
206
207    /// "Opportunistic defs" of values: when lowering an instruction that
208    /// incidentally computes another value (e.g., a branch that directly
209    /// consumes the flags of an `uadd_overflow` also computes the sum), we
210    /// record that value here, along with the regs it was computed into and
211    /// the use-count at the time of registration.
212    ///
213    /// When the scan reaches the actual definition of such a value, if its
214    /// use-count has not grown (i.e., no further uses were found while
215    /// scanning up), then the definition can be skipped and the value can be
216    /// aliased to the opportunistically-computed regs instead.
217    ///
218    /// The key is (block, value): the opportunistic def is only usable when
219    /// the actual definition is in the same block as the registration site,
220    /// further up in the scan.
221    opportunistic_defs: FxHashMap<(Block, Value), (ValueRegs<Reg>, u32)>,
222
223    /// Effectful instructions that have been sunk; they are not codegen'd at
224    /// their original locations.
225    inst_sunk: FxHashSet<Inst>,
226
227    /// Instructions collected for the CLIF inst in progress, in forward order.
228    ir_insts: Vec<I>,
229
230    /// Try-call block arg normal-return values, indexed by instruction.
231    try_call_rets: FxHashMap<Inst, SmallVec<[ValueRegs<Writable<Reg>>; 2]>>,
232
233    /// Try-call block arg exceptional-return payloads, indexed by
234    /// instruction. Payloads are carried in registers per the ABI and
235    /// can only be one register each.
236    try_call_payloads: FxHashMap<Inst, SmallVec<[Writable<Reg>; 2]>>,
237
238    /// The register to use for GetPinnedReg, if any, on this architecture.
239    pinned_reg: Option<Reg>,
240
241    /// Compilation flags.
242    flags: Flags,
243}
244
245/// How is a value used in the IR?
246///
247/// This can be seen as a coarsening of an integer count. We only need
248/// distinct states for zero, one, or many.
249///
250/// This analysis deserves further explanation. The basic idea is that
251/// we want to allow instruction lowering to know whether a value that
252/// an instruction references is *only* referenced by that one use, or
253/// by others as well. This is necessary to know when we might want to
254/// move a side-effect: we cannot, for example, duplicate a load, so
255/// we cannot let instruction lowering match a load as part of a
256/// subpattern and potentially incorporate it.
257///
258/// Note that a lot of subtlety comes into play once we have
259/// *indirect* uses. The classical example of this in our development
260/// history was the x86 compare instruction, which is incorporated
261/// into flags users (e.g. `selectif`, `trueif`, branches) and can
262/// subsequently incorporate loads, or at least we would like it
263/// to. However, danger awaits: the compare might be the only user of
264/// a load, so we might think we can just move the load (and nothing
265/// is duplicated -- success!), except that the compare itself is
266/// codegen'd in multiple places, where it is incorporated as a
267/// subpattern itself.
268///
269/// So we really want a notion of "unique all the way along the
270/// matching path". Rust's `&T` and `&mut T` offer a partial analogy
271/// to the semantics that we want here: we want to know when we've
272/// matched a unique use of an instruction, and that instruction's
273/// unique use of another instruction, etc, just as `&mut T` can only
274/// be obtained by going through a chain of `&mut T`. If one has a
275/// `&T` to a struct containing `&mut T` (one of several uses of an
276/// instruction that itself has a unique use of an instruction), one
277/// can only get a `&T` (one can only get a "I am one of several users
278/// of this instruction" result).
279///
280/// We could track these paths, either dynamically as one "looks up the operand
281/// tree" or precomputed. But the former requires state and means that the
282/// `Lower` API carries that state implicitly, which we'd like to avoid if we
283/// can. And the latter implies O(n^2) storage: it is an all-pairs property (is
284/// inst `i` unique from the point of view of `j`).
285///
286/// To make matters even a little more complex still, a value that is
287/// not uniquely used when initially viewing the IR can *become*
288/// uniquely used, at least as a root allowing further unique uses of
289/// e.g. loads to merge, if no other instruction actually merges
290/// it. To be more concrete, if we have `v1 := load; v2 := op v1; v3
291/// := op v2; v4 := op v2` then `v2` is non-uniquely used, so from the
292/// point of view of lowering `v4` or `v3`, we cannot merge the load
293/// at `v1`. But if we decide just to use the assigned register for
294/// `v2` at both `v3` and `v4`, then we only actually codegen `v2`
295/// once, so it *is* a unique root at that point and we *can* merge
296/// the load.
297///
298/// Note also that the color scheme is not sufficient to give us this
299/// information, for various reasons: reasoning about side-effects
300/// does not tell us about potential duplication of uses through pure
301/// ops.
302///
303/// To keep things simple and avoid error-prone lowering APIs that
304/// would extract more information about whether instruction merging
305/// happens or not (we don't have that info now, and it would be
306/// difficult to refactor to get it and make that refactor 100%
307/// correct), we give up on the above "can become unique if not
308/// actually merged" point. Instead, we compute a
309/// transitive-uniqueness. That is what this enum represents.
310///
311/// There is one final caveat as well to the result of this analysis.  Notably,
312/// we define some instructions to be "root" instructions, which means that we
313/// assume they will always be codegen'd at the root of a matching tree, and not
314/// matched. (This comes with the caveat that we actually enforce this property
315/// by making them "opaque" to subtree matching in
316/// `get_value_as_source_or_const`). Because they will always be codegen'd once,
317/// they in some sense "reset" multiplicity: these root instructions can be used
318/// many times, but because their result(s) are only computed once, they only
319/// use their inputs once.
320///
321/// We currently define all multi-result instructions to be "root" instructions,
322/// because it is too complex to reason about matching through them, and they
323/// cause too-coarse-grained approximation of multiplicity otherwise: the
324/// analysis would have to assume (as it used to!) that they are always
325/// multiply-used, simply because they have multiple outputs even if those
326/// outputs are used only once.
327///
328/// In the future we could define other instructions to be "root" instructions
329/// as well, if we make the corresponding change to get_value_as_source_or_const
330/// as well.
331///
332/// To define `ValueUseState` more plainly: a value is `Unused` if no references
333/// exist to it; `Once` if only one other op refers to it, *and* that other op
334/// is `Unused` or `Once`; and `Multiple` otherwise. In other words, `Multiple`
335/// is contagious (except through root instructions): even if an op's result
336/// value is directly used only once in the CLIF, that value is `Multiple` if
337/// the op that uses it is itself used multiple times (hence could be codegen'd
338/// multiple times). In brief, this analysis tells us whether, if every op
339/// merged all of its operand tree, a given op could be codegen'd in more than
340/// one place.
341///
342/// To compute this, we first consider direct uses. At this point
343/// `Unused` answers are correct, `Multiple` answers are correct, but
344/// some `Once`s may change to `Multiple`s. Then we propagate
345/// `Multiple` transitively using a workqueue/fixpoint algorithm.
346#[derive(Clone, Copy, Debug, PartialEq, Eq)]
347enum ValueUseState {
348    /// Not used at all.
349    Unused,
350    /// Used exactly once.
351    Once,
352    /// Used multiple times.
353    Multiple,
354}
355
356impl ValueUseState {
357    /// Add one use.
358    fn inc(&mut self) {
359        let new = match self {
360            Self::Unused => Self::Once,
361            Self::Once | Self::Multiple => Self::Multiple,
362        };
363        *self = new;
364    }
365}
366
367/// Notion of "relocation distance". This gives an estimate of how far away a symbol will be from a
368/// reference.
369#[derive(Clone, Copy, Debug, PartialEq, Eq)]
370pub enum RelocDistance {
371    /// Target of relocation is "nearby". The threshold for this is fuzzy but should be interpreted
372    /// as approximately "within the compiled output of one module"; e.g., within AArch64's +/-
373    /// 128MB offset. If unsure, use `Far` instead.
374    Near,
375    /// Target of relocation could be anywhere in the address space.
376    Far,
377}
378
379impl<'func, I: VCodeInst> Lower<'func, I> {
380    /// Prepare a new lowering context for the given IR function.
381    pub fn new(
382        f: &'func Function,
383        abi: Callee<I::ABIMachineSpec>,
384        emit_info: I::Info,
385        block_order: BlockLoweringOrder,
386        sigs: SigSet,
387        flags: Flags,
388    ) -> CodegenResult<Self> {
389        let constants = VCodeConstants::with_capacity(f.dfg.constants.len());
390        let vcode = VCodeBuilder::new(
391            sigs,
392            abi,
393            emit_info,
394            block_order,
395            constants,
396            VCodeBuildDirection::Backward,
397            flags.log2_min_function_alignment(),
398        );
399
400        // We usually need two VRegs per instruction result, plus extras for
401        // various temporaries, but two per Value is a good starting point.
402        let mut vregs = VRegAllocator::with_capacity(f.dfg.num_values() * 2);
403
404        let mut value_regs = SecondaryMap::with_default(ValueRegs::invalid());
405        let mut try_call_rets = FxHashMap::default();
406        let mut try_call_payloads = FxHashMap::default();
407
408        // Assign a vreg to each block param, each inst result, and
409        // each edge-defined block-call arg.
410        for bb in f.layout.blocks() {
411            for &param in f.dfg.block_params(bb) {
412                let ty = f.dfg.value_type(param);
413                if value_regs[param].is_invalid() {
414                    let regs = vregs.alloc(ty)?;
415                    value_regs[param] = regs;
416                    trace!("bb {} param {}: regs {:?}", bb, param, regs);
417                }
418            }
419            for inst in f.layout.block_insts(bb) {
420                for &result in f.dfg.inst_results(inst) {
421                    let ty = f.dfg.value_type(result);
422                    if value_regs[result].is_invalid() && !ty.is_invalid() {
423                        let regs = vregs.alloc(ty)?;
424                        value_regs[result] = regs;
425                        trace!(
426                            "bb {} inst {} ({:?}): result {} regs {:?}",
427                            bb, inst, f.dfg.insts[inst], result, regs,
428                        );
429                    }
430                }
431
432                if let Some(et) = f.dfg.insts[inst].exception_table() {
433                    let exdata = &f.dfg.exception_tables[et];
434                    let sig = &f.dfg.signatures[exdata.signature()];
435
436                    let mut rets = smallvec![];
437                    for ty in sig.returns.iter().map(|ret| ret.value_type) {
438                        rets.push(vregs.alloc(ty)?.map(|r| Writable::from_reg(r)));
439                    }
440                    try_call_rets.insert(inst, rets);
441
442                    let mut payloads = smallvec![];
443                    // Note that this is intentionally using the calling
444                    // convention of the callee to determine what payload types
445                    // are available. The callee defines that, not the calling
446                    // convention of the caller.
447                    for &ty in sig
448                        .call_conv
449                        .exception_payload_types(I::ABIMachineSpec::word_type())
450                    {
451                        payloads.push(Writable::from_reg(vregs.alloc(ty)?.only_reg().unwrap()));
452                    }
453                    try_call_payloads.insert(inst, payloads);
454                }
455            }
456        }
457
458        // Find the sret register, if it's used.
459        let mut sret_param = None;
460        for ret in vcode.abi().signature().returns.iter() {
461            if ret.purpose == ArgumentPurpose::StructReturn {
462                let entry_bb = f.stencil.layout.entry_block().unwrap();
463                for (&param, sig_param) in f
464                    .dfg
465                    .block_params(entry_bb)
466                    .iter()
467                    .zip(vcode.abi().signature().params.iter())
468                {
469                    if sig_param.purpose == ArgumentPurpose::StructReturn {
470                        assert!(sret_param.is_none());
471                        sret_param = Some(param);
472                    }
473                }
474
475                assert!(sret_param.is_some());
476            }
477        }
478
479        let sret_reg = sret_param.map(|param| {
480            let regs = value_regs[param];
481            assert!(regs.len() == 1);
482            regs
483        });
484
485        // Compute instruction colors and find instructions with side-effects.
486        let mut cur_color = 0;
487        let mut block_end_colors = SecondaryMap::with_default(InstColor::new(0));
488        let mut side_effect_inst_entry_colors = SecondaryMap::with_default(InstColor::new(0));
489        for bb in f.layout.blocks() {
490            cur_color += 1;
491            for inst in f.layout.block_insts(bb) {
492                let side_effect = has_lowering_side_effect(f, inst);
493
494                trace!("bb {} inst {} has color {}", bb, inst, cur_color);
495                if side_effect {
496                    side_effect_inst_entry_colors[inst] = InstColor::new(cur_color);
497                    trace!(" -> side-effecting; incrementing color for next inst");
498                    cur_color += 1;
499                }
500            }
501
502            block_end_colors[bb] = InstColor::new(cur_color);
503        }
504
505        let value_ir_uses = compute_use_states(f, sret_param);
506
507        Ok(Lower {
508            f,
509            vcode,
510            vregs,
511            value_regs,
512            sret_reg,
513            block_end_colors,
514            side_effect_inst_entry_colors,
515            value_ir_uses,
516            value_lowered_uses: SecondaryMap::default(),
517            opportunistic_defs: FxHashMap::default(),
518            inst_sunk: FxHashSet::default(),
519            cur_scan_entry_color: None,
520            cur_inst: None,
521            ir_insts: vec![],
522            try_call_rets,
523            try_call_payloads,
524            pinned_reg: None,
525            flags,
526        })
527    }
528
529    pub fn sigs(&self) -> &SigSet {
530        self.vcode.sigs()
531    }
532
533    pub fn sigs_mut(&mut self) -> &mut SigSet {
534        self.vcode.sigs_mut()
535    }
536
537    fn gen_arg_setup(&mut self) {
538        if let Some(entry_bb) = self.f.layout.entry_block() {
539            trace!(
540                "gen_arg_setup: entry BB {} args are:\n{:?}",
541                entry_bb,
542                self.f.dfg.block_params(entry_bb)
543            );
544
545            for (i, param) in self.f.dfg.block_params(entry_bb).iter().enumerate() {
546                if self.value_ir_uses[*param] == ValueUseState::Unused {
547                    continue;
548                }
549                let regs = writable_value_regs(self.value_regs[*param]);
550                for insn in self
551                    .vcode
552                    .vcode
553                    .abi
554                    .gen_copy_arg_to_regs(&self.vcode.vcode.sigs, i, regs, &mut self.vregs)
555                    .into_iter()
556                {
557                    self.emit(insn);
558                }
559            }
560            if let Some(insn) = self
561                .vcode
562                .vcode
563                .abi
564                .gen_retval_area_setup(&self.vcode.vcode.sigs, &mut self.vregs)
565            {
566                self.emit(insn);
567            }
568
569            // The `args` instruction below must come first. Finish
570            // the current "IR inst" (with a default source location,
571            // as for other special instructions inserted during
572            // lowering) and continue the scan backward.
573            self.finish_ir_inst(Default::default());
574
575            if let Some(insn) = self.vcode.vcode.abi.take_args() {
576                self.emit(insn);
577            }
578        }
579    }
580
581    /// Generate the return instruction.
582    pub fn gen_return(&mut self, rets: &[ValueRegs<Reg>]) {
583        let mut out_rets = vec![];
584
585        let mut rets = rets.into_iter();
586        for (i, ret) in self
587            .abi()
588            .signature()
589            .returns
590            .clone()
591            .into_iter()
592            .enumerate()
593        {
594            let regs = if ret.purpose == ArgumentPurpose::StructReturn {
595                self.sret_reg.unwrap()
596            } else {
597                *rets.next().unwrap()
598            };
599
600            let (regs, insns) = self.vcode.abi().gen_copy_regs_to_retval(
601                self.vcode.sigs(),
602                i,
603                regs,
604                &mut self.vregs,
605            );
606            out_rets.extend(regs);
607            for insn in insns {
608                self.emit(insn);
609            }
610        }
611
612        // Hack: generate a virtual instruction that uses vmctx in
613        // order to keep it alive for the duration of the function,
614        // for the benefit of debuginfo.
615        if self.f.dfg.values_labels.is_some() {
616            if let Some(vmctx_val) = self.f.special_param(ArgumentPurpose::VMContext) {
617                if self.value_ir_uses[vmctx_val] != ValueUseState::Unused {
618                    let vmctx_reg = self.value_regs[vmctx_val].only_reg().unwrap();
619                    self.emit(I::gen_dummy_use(vmctx_reg));
620                }
621            }
622        }
623
624        let inst = self.abi().gen_rets(out_rets);
625        self.emit(inst);
626    }
627
628    /// Generate list of registers to hold the output of a call with
629    /// signature `sig`.
630    pub fn gen_call_output(&mut self, sig: &Signature) -> InstOutput {
631        let mut rets = smallvec![];
632        for ty in sig.returns.iter().map(|ret| ret.value_type) {
633            rets.push(self.vregs.alloc_with_deferred_error(ty));
634        }
635        rets
636    }
637
638    /// Likewise, but for a `SigRef` instead.
639    pub fn gen_call_output_from_sig_ref(&mut self, sig_ref: SigRef) -> InstOutput {
640        self.gen_call_output(&self.f.dfg.signatures[sig_ref])
641    }
642
643    /// Set up arguments values `args` for a call with signature `sig`.
644    pub fn gen_call_args(&mut self, sig: Sig, args: &[ValueRegs<Reg>]) -> CallArgList {
645        let (uses, insts) = self.vcode.abi().gen_call_args(
646            self.vcode.sigs(),
647            sig,
648            args,
649            /* is_tail_call */ false,
650            &self.flags,
651            &mut self.vregs,
652        );
653        for insn in insts {
654            self.emit(insn);
655        }
656        uses
657    }
658
659    /// Likewise, but for a `return_call`.
660    pub fn gen_return_call_args(&mut self, sig: Sig, args: &[ValueRegs<Reg>]) -> CallArgList {
661        let (uses, insts) = self.vcode.abi().gen_call_args(
662            self.vcode.sigs(),
663            sig,
664            args,
665            /* is_tail_call */ true,
666            &self.flags,
667            &mut self.vregs,
668        );
669        for insn in insts {
670            self.emit(insn);
671        }
672        uses
673    }
674
675    /// Set up return values `outputs` for a call with signature `sig`.
676    pub fn gen_call_rets(&mut self, sig: Sig, outputs: &[ValueRegs<Reg>]) -> CallRetList {
677        self.vcode
678            .abi()
679            .gen_call_rets(self.vcode.sigs(), sig, outputs, None, &mut self.vregs)
680    }
681
682    /// Likewise, but for a `try_call`.
683    pub fn gen_try_call_rets(&mut self, sig: Sig) -> CallRetList {
684        let ir_inst = self.cur_inst.unwrap();
685        let mut outputs: SmallVec<[ValueRegs<Reg>; 2]> = smallvec![];
686        for return_def in self.try_call_rets.get(&ir_inst).unwrap() {
687            outputs.push(return_def.map(|r| r.to_reg()));
688        }
689        let payloads = Some(&self.try_call_payloads.get(&ir_inst).unwrap()[..]);
690
691        self.vcode
692            .abi()
693            .gen_call_rets(self.vcode.sigs(), sig, &outputs, payloads, &mut self.vregs)
694    }
695
696    /// Populate a `CallInfo` for a call with signature `sig`.
697    pub fn gen_call_info<T>(
698        &mut self,
699        sig: Sig,
700        dest: T,
701        uses: CallArgList,
702        defs: CallRetList,
703        try_call_info: Option<TryCallInfo>,
704        patchable: bool,
705    ) -> CallInfo<T> {
706        self.vcode.abi().gen_call_info(
707            self.vcode.sigs(),
708            sig,
709            dest,
710            uses,
711            defs,
712            try_call_info,
713            patchable,
714        )
715    }
716
717    /// Has this instruction been sunk to a use-site (i.e., away from its
718    /// original location)?
719    fn is_inst_sunk(&self, inst: Inst) -> bool {
720        self.inst_sunk.contains(&inst)
721    }
722
723    // Is any result of this instruction needed?
724    fn is_any_inst_result_needed(&self, inst: Inst) -> bool {
725        self.f
726            .dfg
727            .inst_results(inst)
728            .iter()
729            .any(|&result| self.value_lowered_uses[result] > 0)
730    }
731
732    /// Record an "opportunistic def" of `val` into `regs` at the current scan
733    /// position.
734    ///
735    /// The lowering that is currently being generated (e.g., a branch that
736    /// directly consumes the flags produced by an `uadd_overflow`) also
737    /// computes `val`'s value as a byproduct, and does so in `regs`. If, when
738    /// the scan reaches the actual definition of `val` (which must be in the
739    /// current block, further up), no further uses of `val` are found (i.e.,
740    /// the use-count matches the one recorded here), then that definition can
741    /// be skipped entirely and `val` can be aliased to `regs` instead.
742    ///
743    /// If further uses *are* found, then this opportunistic def is discarded
744    /// and the actual definition is lowered as usual (this is safe because
745    /// the value is still computed by the current lowering, just unused).
746    pub fn opportunistic_def(&mut self, val: Value, regs: ValueRegs<Reg>) {
747        trace!("opportunistic_def: val {val} regs {regs:?}");
748
749        if self.value_lowered_uses[val] == 0 {
750            trace!(" -> no uses so far; ignoring");
751            return;
752        }
753
754        // The actual definition of `val` must be in the same block as the
755        // current scan position, further up. Otherwise the regs computed here
756        // cannot possibly dominate all uses of `val` (and in particular the
757        // use-count check below is meaningless across blocks), so ignore.
758        let cur_block = match self
759            .cur_inst
760            .and_then(|inst| self.f.layout.inst_block(inst))
761        {
762            Some(block) => block,
763            None => {
764                trace!(" -> no current inst/block; ignoring");
765                return;
766            }
767        };
768        let def_block = match self.f.dfg.value_def(val) {
769            ValueDef::Result(src_inst, _) => self.f.layout.inst_block(src_inst),
770            _ => None,
771        };
772        if def_block != Some(cur_block) {
773            trace!(" -> def not in current block; ignoring");
774            return;
775        }
776
777        let uses = self.value_lowered_uses[val];
778        // Note that a later registration for the same (block, value)
779        // overwrites an earlier one: the later one is higher in the block
780        // (closer to the definition), so its defs dominate those of the
781        // earlier one, and it is strictly more useful.
782        self.opportunistic_defs
783            .insert((cur_block, val), (regs, uses));
784        trace!(" -> recorded with {uses} uses so far");
785    }
786
787    /// Attempt to commit to the opportunistic defs recorded for the results
788    /// of `inst` (whose definition is at the current scan position in
789    /// `block`).
790    ///
791    /// Returns `true` if we were able to use the opportunistic defs
792    /// and can skip this lowering.
793    fn try_use_opportunistic_defs(&mut self, block: Block, inst: Inst) -> bool {
794        let results = self.f.dfg.inst_results(inst);
795
796        // To skip the lowering and use the opportunistic defs, every
797        // result of `inst` that has uses must have a registered
798        // opportunistic def whose recorded use-count matches the
799        // current one.
800        for &result in results {
801            if self.value_lowered_uses[result] == 0 {
802                continue;
803            }
804            match self.opportunistic_defs.get(&(block, result)) {
805                Some(&(_, recorded_uses)) if recorded_uses == self.value_lowered_uses[result] => {}
806                _ => {
807                    trace!(
808                        "opportunistic defs: not committing for inst {inst}: \
809                         result {result} has {} uses but no matching opportunistic def",
810                        self.value_lowered_uses[result]
811                    );
812                    return false;
813                }
814            }
815        }
816
817        // Commit: set aliases for every result that has an opportunistic def
818        // (by the check above, this is exactly the set of results with uses),
819        // and clear the entries.
820        for &result in results {
821            if let Some(&(regs, _)) = self.opportunistic_defs.get(&(block, result)) {
822                let dsts = self.value_regs[result];
823                debug_assert_eq!(dsts.len(), regs.len());
824                for (&dst, &src) in dsts.regs().iter().zip(regs.regs().iter()) {
825                    trace!(
826                        "set vreg alias (opportunistic def): {result:?} = {dst:?}, \
827                         lowering = {src:?}"
828                    );
829                    self.vregs.set_vreg_alias(dst, src);
830                }
831                self.opportunistic_defs.remove(&(block, result));
832            }
833        }
834
835        true
836    }
837
838    fn lower_clif_block<B: LowerBackend<MInst = I>>(
839        &mut self,
840        backend: &B,
841        block: Block,
842        ctrl_plane: &mut ControlPlane,
843    ) -> CodegenResult<()> {
844        self.cur_scan_entry_color = Some(self.block_end_colors[block]);
845        // Lowering loop:
846        // - For each non-branch instruction, in reverse order:
847        //   - If side-effecting (load, store, branch/call/return,
848        //     possible trap), or if used outside of this block, or if
849        //     demanded by another inst, then lower.
850        //
851        // That's it! Lowering of side-effecting ops will force all *needed*
852        // (live) non-side-effecting ops to be lowered at the right places, via
853        // the `use_input_reg()` callback on the `Lower` (that's us). That's
854        // because `use_input_reg()` sets the eager/demand bit for any insts
855        // whose result registers are used.
856        //
857        // We set the VCodeBuilder to "backward" mode, so we emit
858        // blocks in reverse order wrt the BlockIndex sequence, and
859        // emit instructions in reverse order within blocks.  Because
860        // the machine backend calls `ctx.emit()` in forward order, we
861        // collect per-IR-inst lowered instructions in `ir_insts`,
862        // then reverse these and append to the VCode at the end of
863        // each IR instruction.
864        for inst in self.f.layout.block_insts(block).rev() {
865            let data = &self.f.dfg.insts[inst];
866            // A non-zero entry color marks a side-effecting instruction (see the
867            // field's doc comment).
868            let entry_color = self.side_effect_inst_entry_colors[inst];
869            let has_side_effect = entry_color.get() != 0;
870
871            // If  inst has been sunk to another location, skip it.
872            if self.is_inst_sunk(inst) {
873                continue;
874            }
875
876            // Are any outputs used at least once?
877            let value_needed = self.is_any_inst_result_needed(inst);
878
879            // Do we have to emit this instruction even though nothing uses its
880            // results? Note that this is not the same question as
881            // `has_side_effect` above: loads are colored as side-effecting so
882            // that load merging cannot move one across a store, but a load that
883            // is defined not to trap can simply be dropped when it is dead.
884            let must_lower = must_lower_even_if_unused(self.f, inst);
885
886            trace!(
887                "lower_clif_block: {block}, {inst}, ({data:?}), is_branch {}, \
888                 has_side_effect {has_side_effect}, must_lower {must_lower}, \
889                 value_needed {value_needed}",
890                data.opcode().is_branch(),
891            );
892
893            // Update scan state to color prior to this inst (as we are scanning
894            // backward).
895            self.cur_inst = Some(inst);
896            if has_side_effect {
897                self.cur_scan_entry_color = Some(entry_color);
898            }
899
900            // Skip lowering branches; these are handled separately
901            // (see `lower_clif_branches()` below).
902            if self.f.dfg.insts[inst].opcode().is_branch() {
903                continue;
904            }
905
906            // Value defined by "inst" becomes live after it in normal
907            // order, and therefore **before** in reversed order.
908            // Only emit value label aliases if the instruction will be lowered
909            // (otherwise we want to keep using the earlier label instead).
910            self.emit_value_label_live_range_start_for_inst(inst, must_lower || value_needed);
911
912            // Normal instruction: codegen if the instruction is side-effecting
913            // or any of its outputs is used.
914            if must_lower || value_needed {
915                if !has_side_effect && !must_lower && self.try_use_opportunistic_defs(block, inst) {
916                    trace!(
917                        "lowering: inst {}: {}: using opportunistic defs; skipping",
918                        inst,
919                        self.f.dfg.display_inst(inst)
920                    );
921                    continue;
922                }
923
924                trace!("lowering: inst {}: {}", inst, self.f.dfg.display_inst(inst));
925                let temp_regs = match backend.lower(self, inst) {
926                    Some(regs) => regs,
927                    None => {
928                        let ty = if self.num_outputs(inst) > 0 {
929                            Some(self.output_ty(inst, 0))
930                        } else {
931                            None
932                        };
933                        return Err(CodegenError::Unsupported(format!(
934                            "should be implemented in ISLE: inst = `{}`, type = `{:?}`",
935                            self.f.dfg.display_inst(inst),
936                            ty
937                        )));
938                    }
939                };
940
941                // The ISLE generated code emits its own registers to define
942                // the instruction's lowered values in. However, other
943                // instructions that use this SSA value will be lowered
944                // assuming that the value is generated into a
945                // pre-assigned, different, register.
946                //
947                // To connect the two, we set up "aliases" in the
948                // VCodeBuilder that apply when it is building the Operand
949                // table for the regalloc to use. These aliases effectively
950                // rewrite any use of the pre-assigned register to the
951                // register that was returned by the ISLE lowering logic.
952                let results = self.f.dfg.inst_results(inst);
953                debug_assert_eq!(temp_regs.len(), results.len());
954                for (regs, &result) in temp_regs.iter().zip(results) {
955                    let dsts = self.value_regs[result];
956                    let mut regs = regs.regs().iter();
957                    for &dst in dsts.regs().iter() {
958                        let temp = regs.next().copied().unwrap_or(Reg::invalid_sentinel());
959                        trace!("set vreg alias: {result:?} = {dst:?}, lowering = {temp:?}");
960                        self.vregs.set_vreg_alias(dst, temp);
961                    }
962                }
963            }
964
965            let start = self.vcode.vcode.num_insts();
966            let loc = self.srcloc(inst);
967            self.finish_ir_inst(loc);
968
969            // If the instruction had a user stack map, forward it from the CLIF
970            // to the vcode.
971            if let Some(entries) = self.f.dfg.user_stack_map_entries(inst) {
972                let end = self.vcode.vcode.num_insts();
973                debug_assert!(end > start);
974                debug_assert_eq!(
975                    (start..end)
976                        .filter(|i| self.vcode.vcode[InsnIndex::new(*i)].is_safepoint())
977                        .count(),
978                    1
979                );
980                for i in start..end {
981                    let iix = InsnIndex::new(i);
982                    if self.vcode.vcode[iix].is_safepoint() {
983                        trace!(
984                            "Adding user stack map from clif\n\n\
985                                 {inst:?} `{}`\n\n\
986                             to vcode\n\n\
987                                 {iix:?} `{}`",
988                            self.f.dfg.display_inst(inst),
989                            &self.vcode.vcode[iix].pretty_print_inst(&mut Default::default()),
990                        );
991                        self.vcode
992                            .add_user_stack_map(BackwardsInsnIndex::new(iix.index()), entries);
993                        break;
994                    }
995                }
996            }
997
998            // If the CLIF instruction had debug tags, copy them to
999            // the VCode. Place on all VCode instructions lowered from
1000            // this CLIF instruction.
1001            let debug_tags = self.f.debug_tags.get(inst);
1002            if !debug_tags.is_empty() && self.vcode.vcode.num_insts() > 0 {
1003                let end = self.vcode.vcode.num_insts();
1004                for i in start..end {
1005                    let backwards_index = BackwardsInsnIndex::new(i);
1006                    log::trace!(
1007                        "debug tags on {inst}; associating {debug_tags:?} with {backwards_index:?}"
1008                    );
1009                    self.vcode.add_debug_tags(backwards_index, debug_tags);
1010                }
1011            }
1012
1013            // maybe insert random instruction
1014            if ctrl_plane.get_decision() {
1015                if ctrl_plane.get_decision() {
1016                    let imm: u64 = ctrl_plane.get_arbitrary();
1017                    let reg = self.alloc_tmp(crate::ir::types::I64).regs()[0];
1018                    I::gen_imm_u64(imm, reg).map(|inst| self.emit(inst));
1019                } else {
1020                    let imm: f64 = ctrl_plane.get_arbitrary();
1021                    let tmp = self.alloc_tmp(crate::ir::types::I64).regs()[0];
1022                    let reg = self.alloc_tmp(crate::ir::types::F64).regs()[0];
1023                    for inst in I::gen_imm_f64(imm, tmp, reg) {
1024                        self.emit(inst);
1025                    }
1026                }
1027            }
1028        }
1029
1030        // Add the block params to this block.
1031        self.add_block_params(block)?;
1032
1033        self.cur_scan_entry_color = None;
1034        Ok(())
1035    }
1036
1037    fn add_block_params(&mut self, block: Block) -> CodegenResult<()> {
1038        for &param in self.f.dfg.block_params(block) {
1039            for &reg in self.value_regs[param].regs() {
1040                let vreg = reg.to_virtual_reg().unwrap();
1041                self.vcode.add_block_param(vreg);
1042            }
1043        }
1044        Ok(())
1045    }
1046
1047    fn get_value_labels<'a>(&'a self, val: Value, depth: usize) -> Option<&'a [ValueLabelStart]> {
1048        if let Some(ref values_labels) = self.f.dfg.values_labels {
1049            debug_assert!(self.f.dfg.value_is_real(val));
1050            trace!(
1051                "get_value_labels: val {} -> {:?}",
1052                val,
1053                values_labels.get(&val)
1054            );
1055            match values_labels.get(&val) {
1056                Some(&ValueLabelAssignments::Starts(ref list)) => Some(&list[..]),
1057                Some(&ValueLabelAssignments::Alias { value, .. }) if depth < 10 => {
1058                    self.get_value_labels(value, depth + 1)
1059                }
1060                _ => None,
1061            }
1062        } else {
1063            None
1064        }
1065    }
1066
1067    fn emit_value_label_marks_for_value(&mut self, val: Value, allow_alias: bool) {
1068        let regs = self.value_regs[val];
1069        if regs.len() > 1 {
1070            return;
1071        }
1072        let reg = regs.only_reg().unwrap();
1073
1074        if let Some(label_starts) = self.get_value_labels(val, if allow_alias { 0 } else { !0 }) {
1075            let labels = label_starts
1076                .iter()
1077                .map(|&ValueLabelStart { label, .. }| label)
1078                .collect::<FxHashSet<_>>();
1079            for label in labels {
1080                trace!(
1081                    "value labeling: defines val {:?} -> reg {:?} -> label {:?}",
1082                    val, reg, label,
1083                );
1084                self.vcode.add_value_label(reg, label);
1085            }
1086        }
1087    }
1088
1089    fn emit_value_label_live_range_start_for_inst(&mut self, inst: Inst, allow_alias: bool) {
1090        if self.f.dfg.values_labels.is_none() {
1091            return;
1092        }
1093
1094        trace!(
1095            "value labeling: srcloc {}: inst {}",
1096            self.srcloc(inst),
1097            inst
1098        );
1099        for &val in self.f.dfg.inst_results(inst) {
1100            self.emit_value_label_marks_for_value(val, allow_alias);
1101        }
1102    }
1103
1104    fn emit_value_label_live_range_start_for_block_args(&mut self, block: Block) {
1105        if self.f.dfg.values_labels.is_none() {
1106            return;
1107        }
1108
1109        trace!("value labeling: block {}", block);
1110        for &arg in self.f.dfg.block_params(block) {
1111            self.emit_value_label_marks_for_value(arg, true);
1112        }
1113        self.finish_ir_inst(Default::default());
1114    }
1115
1116    fn finish_ir_inst(&mut self, loc: RelSourceLoc) {
1117        // The VCodeBuilder builds in reverse order (and reverses at
1118        // the end), but `ir_insts` is in forward order, so reverse
1119        // it.
1120        for inst in self.ir_insts.drain(..).rev() {
1121            self.vcode.push(inst, loc);
1122        }
1123    }
1124
1125    fn finish_bb(&mut self) {
1126        self.vcode.end_bb();
1127    }
1128
1129    fn lower_clif_branch<B: LowerBackend<MInst = I>>(
1130        &mut self,
1131        backend: &B,
1132        // Lowered block index:
1133        bindex: BlockIndex,
1134        // Original CLIF block:
1135        block: Block,
1136        branch: Inst,
1137        targets: &[MachLabel],
1138    ) -> CodegenResult<()> {
1139        trace!(
1140            "lower_clif_branch: block {} branch {:?} targets {:?}",
1141            block, branch, targets,
1142        );
1143        // When considering code-motion opportunities, consider the current
1144        // program point to be this branch.
1145        self.cur_inst = Some(branch);
1146
1147        // Lower the branch in ISLE.
1148        backend
1149            .lower_branch(self, branch, targets)
1150            .unwrap_or_else(|| {
1151                panic!(
1152                    "should be implemented in ISLE: branch = `{}`",
1153                    self.f.dfg.display_inst(branch),
1154                )
1155            });
1156        let loc = self.srcloc(branch);
1157        self.finish_ir_inst(loc);
1158        // Add block param outputs for current block.
1159        self.lower_branch_blockparam_args(bindex);
1160        Ok(())
1161    }
1162
1163    fn lower_branch_blockparam_args(&mut self, block: BlockIndex) {
1164        let mut branch_arg_vregs: SmallVec<[Reg; 16]> = smallvec![];
1165
1166        // TODO: why not make `block_order` public?
1167        for succ_idx in 0..self.vcode.block_order().succ_indices(block).1.len() {
1168            branch_arg_vregs.clear();
1169            let (succ, args) = self.collect_block_call(block, succ_idx, &mut branch_arg_vregs);
1170            self.vcode.add_succ(succ, args);
1171        }
1172    }
1173
1174    fn collect_branch_and_targets(
1175        &self,
1176        bindex: BlockIndex,
1177        _bb: Block,
1178        targets: &mut SmallVec<[MachLabel; 2]>,
1179    ) -> Option<Inst> {
1180        targets.clear();
1181        let (opt_inst, succs) = self.vcode.block_order().succ_indices(bindex);
1182        targets.extend(succs.iter().map(|succ| MachLabel::from_block(*succ)));
1183        opt_inst
1184    }
1185
1186    /// Collect the outgoing block-call arguments for a given edge out
1187    /// of a lowered block.
1188    fn collect_block_call<'a>(
1189        &mut self,
1190        block: BlockIndex,
1191        succ_idx: usize,
1192        buffer: &'a mut SmallVec<[Reg; 16]>,
1193    ) -> (BlockIndex, &'a [Reg]) {
1194        let block_order = self.vcode.block_order();
1195        let (_, succs) = block_order.succ_indices(block);
1196        let succ = succs[succ_idx];
1197        let this_lb = block_order.lowered_order()[block.index()];
1198        let succ_lb = block_order.lowered_order()[succ.index()];
1199
1200        let (branch_inst, succ_idx) = match (this_lb, succ_lb) {
1201            (_, LoweredBlock::CriticalEdge { .. }) => {
1202                // The successor is a split-critical-edge block. In this
1203                // case, this block-call has no arguments, and the
1204                // arguments go on the critical edge block's unconditional
1205                // branch instead.
1206                return (succ, &[]);
1207            }
1208            (LoweredBlock::CriticalEdge { pred, succ_idx, .. }, _) => {
1209                // This is a split-critical-edge block. In this case, our
1210                // block-call has the arguments that in the CLIF appear in
1211                // the predecessor's branch to this edge.
1212                let branch_inst = self.f.layout.last_inst(pred).unwrap();
1213                (branch_inst, succ_idx as usize)
1214            }
1215
1216            (this, _) => {
1217                let block = this.orig_block().unwrap();
1218                // Ordinary block, with an ordinary block as
1219                // successor. Take the arguments from the branch.
1220                let branch_inst = self.f.layout.last_inst(block).unwrap();
1221                (branch_inst, succ_idx)
1222            }
1223        };
1224
1225        let block_call = self.f.dfg.insts[branch_inst]
1226            .branch_destination(&self.f.dfg.jump_tables, &self.f.dfg.exception_tables)[succ_idx];
1227        for arg in block_call.args(&self.f.dfg.value_lists) {
1228            match arg {
1229                BlockArg::Value(arg) => {
1230                    debug_assert!(self.f.dfg.value_is_real(arg));
1231                    let regs = self.put_value_in_regs(arg);
1232                    buffer.extend_from_slice(regs.regs());
1233                }
1234                BlockArg::TryCallRet(i) => {
1235                    let regs = self.try_call_rets.get(&branch_inst).unwrap()[i as usize]
1236                        .map(|r| r.to_reg());
1237                    buffer.extend_from_slice(regs.regs());
1238                }
1239                BlockArg::TryCallExn(i) => {
1240                    let reg =
1241                        self.try_call_payloads.get(&branch_inst).unwrap()[i as usize].to_reg();
1242                    buffer.push(reg);
1243                }
1244            }
1245        }
1246        (succ, &buffer[..])
1247    }
1248
1249    /// Lower the function.
1250    pub fn lower<B: LowerBackend<MInst = I>>(
1251        mut self,
1252        backend: &B,
1253        ctrl_plane: &mut ControlPlane,
1254    ) -> CodegenResult<VCode<I>> {
1255        trace!("about to lower function: {:?}", self.f);
1256
1257        self.vcode.init_retval_area(&mut self.vregs)?;
1258
1259        // Get the pinned reg here (we only parameterize this function on `B`,
1260        // not the whole `Lower` impl).
1261        self.pinned_reg = backend.maybe_pinned_reg();
1262
1263        self.vcode.set_entry(BlockIndex::new(0));
1264
1265        // Reused vectors for branch lowering.
1266        let mut targets: SmallVec<[MachLabel; 2]> = SmallVec::new();
1267
1268        // Main lowering loop over lowered blocks.
1269        let num_blocks = self.vcode.block_order().lowered_order().len();
1270        for i in (0..num_blocks).rev() {
1271            // We index into the (immutable) lowered order one block at a time,
1272            // copying the block out, so that the immutable borrow of
1273            // `self.vcode` ends immediately and leaves `&mut self` free for
1274            // lowering below.
1275            let bindex = BlockIndex::new(i);
1276            let lb = self.vcode.block_order().lowered_order()[i];
1277
1278            // Lower the block body in reverse order (see comment in
1279            // `lower_clif_block()` for rationale).
1280
1281            // End branch.
1282            if let Some(bb) = lb.orig_block() {
1283                if let Some(branch) = self.collect_branch_and_targets(bindex, bb, &mut targets) {
1284                    let branch_start = self.vcode.vcode.num_insts();
1285                    self.lower_clif_branch(backend, bindex, bb, branch, &targets)?;
1286                    self.finish_ir_inst(self.srcloc(branch));
1287
1288                    // Branch instructions like try_call can also be safepoints
1289                    // that need stack maps. Forward the stack map from the CLIF
1290                    // branch to the VCode safepoint, just like we do for
1291                    // non-branch instructions in `lower_clif_block`.
1292                    if let Some(entries) = self.f.dfg.user_stack_map_entries(branch) {
1293                        let branch_end = self.vcode.vcode.num_insts();
1294                        for i in branch_start..branch_end {
1295                            let iix = InsnIndex::new(i);
1296                            if self.vcode.vcode[iix].is_safepoint() {
1297                                self.vcode.add_user_stack_map(
1298                                    BackwardsInsnIndex::new(iix.index()),
1299                                    entries,
1300                                );
1301                                break;
1302                            }
1303                        }
1304                    }
1305                }
1306            } else {
1307                // If no orig block, this must be a pure edge block;
1308                // get the successor and emit a jump. This block has
1309                // no block params; and this jump's block-call args
1310                // will be filled in by
1311                // `lower_branch_blockparam_args`.
1312                let succ = self.vcode.block_order().succ_indices(bindex).1[0];
1313                self.emit(I::gen_jump(MachLabel::from_block(succ)));
1314                self.finish_ir_inst(Default::default());
1315                self.lower_branch_blockparam_args(bindex);
1316            }
1317
1318            // Original block body.
1319            if let Some(bb) = lb.orig_block() {
1320                self.lower_clif_block(backend, bb, ctrl_plane)?;
1321                self.emit_value_label_live_range_start_for_block_args(bb);
1322            }
1323
1324            if bindex.index() == 0 {
1325                // Set up the function with arg vreg inits.
1326                self.gen_arg_setup();
1327                self.finish_ir_inst(Default::default());
1328            }
1329
1330            self.finish_bb();
1331
1332            // Check for any deferred vreg-temp allocation errors, and
1333            // bubble one up at this time if it exists.
1334            if let Some(e) = self.vregs.take_deferred_error() {
1335                return Err(e);
1336            }
1337        }
1338
1339        // Now that we've emitted all instructions into the
1340        // VCodeBuilder, let's build the VCode.
1341        trace!(
1342            "built vcode:\n{:?}Backwards {:?}",
1343            &self.vregs, &self.vcode.vcode
1344        );
1345        let vcode = self.vcode.build(self.vregs);
1346
1347        Ok(vcode)
1348    }
1349
1350    pub fn value_is_unused(&self, val: Value) -> bool {
1351        match self.value_ir_uses[val] {
1352            ValueUseState::Unused => true,
1353            _ => false,
1354        }
1355    }
1356
1357    /// Does this value still have uses to serve at the current point in the
1358    /// lowering scan? If not, a lowering may be elided.
1359    pub(crate) fn value_lowered_used(&self, val: Value) -> bool {
1360        self.value_lowered_uses[val] > 0
1361    }
1362
1363    pub fn block_successor_label(&self, block: Block, succ: usize) -> MachLabel {
1364        trace!("block_successor_label: block {block} succ {succ}");
1365        let lowered = self
1366            .vcode
1367            .block_order()
1368            .lowered_index_for_block(block)
1369            .expect("Unreachable block");
1370        trace!(" -> lowered block {lowered:?}");
1371        let (_, succs) = self.vcode.block_order().succ_indices(lowered);
1372        trace!(" -> succs {succs:?}");
1373        let succ_block = *succs.get(succ).expect("Successor index out of range");
1374        MachLabel::from_block(succ_block)
1375    }
1376}
1377
1378/// Pre-analysis: compute `value_ir_uses`. See comment on
1379/// `ValueUseState` for a description of what this analysis
1380/// computes.
1381fn compute_use_states(
1382    f: &Function,
1383    sret_param: Option<Value>,
1384) -> SecondaryMap<Value, ValueUseState> {
1385    // We perform the analysis without recursion, so we don't
1386    // overflow the stack on long chains of ops in the input.
1387    //
1388    // This is sort of a hybrid of a "shallow use-count" pass and
1389    // a DFS. We iterate over all instructions and mark their args
1390    // as used. However when we increment a use-count to
1391    // "Multiple" we push its args onto the stack and do a DFS,
1392    // immediately marking the whole dependency tree as
1393    // Multiple. Doing both (shallow use-counting over all insts,
1394    // and deep Multiple propagation) lets us trim both
1395    // traversals, stopping recursion when a node is already at
1396    // the appropriate state.
1397    //
1398    // In particular, note that the *coarsening* into {Unused,
1399    // Once, Multiple} is part of what makes this pass more
1400    // efficient than a full indirect-use-counting pass.
1401
1402    let mut value_ir_uses = SecondaryMap::with_default(ValueUseState::Unused);
1403
1404    if let Some(sret_param) = sret_param {
1405        // There's an implicit use of the struct-return parameter in each
1406        // copy of the function epilogue, which we count here.
1407        value_ir_uses[sret_param] = ValueUseState::Multiple;
1408    }
1409
1410    // Stack of iterators over Values as we do DFS to mark
1411    // Multiple-state subtrees. The iterator type is whatever is
1412    // returned by `uses` below.
1413    let mut stack: SmallVec<[_; 16]> = smallvec![];
1414
1415    // Find the args for the inst corresponding to the given value.
1416    //
1417    // Note that "root" instructions are skipped here. This means that multiple
1418    // uses of any result of a multi-result instruction are not considered
1419    // multiple uses of the operands of a multi-result instruction. This
1420    // requires tight coupling with `get_value_as_source_or_const` above which
1421    // is the consumer of the map that this function is producing.
1422    let uses = |value| {
1423        trace!(" -> pushing args for {} onto stack", value);
1424        if let ValueDef::Result(src_inst, _) = f.dfg.value_def(value) {
1425            Some(f.dfg.inst_values(src_inst))
1426        } else {
1427            None
1428        }
1429    };
1430
1431    // Do a DFS through `value_ir_uses` to mark a subtree as
1432    // Multiple.
1433    for inst in f
1434        .layout
1435        .blocks()
1436        .flat_map(|block| f.layout.block_insts(block))
1437    {
1438        // Iterate over all values used by all instructions, noting an
1439        // additional use on each operand.
1440        for arg in f.dfg.inst_values(inst) {
1441            debug_assert!(f.dfg.value_is_real(arg));
1442            let old = value_ir_uses[arg];
1443            value_ir_uses[arg].inc();
1444            let new = value_ir_uses[arg];
1445            trace!("arg {} used, old state {:?}, new {:?}", arg, old, new);
1446
1447            // On transition to Multiple, do DFS.
1448            if old == ValueUseState::Multiple || new != ValueUseState::Multiple {
1449                continue;
1450            }
1451            if let Some(iter) = uses(arg) {
1452                stack.push(iter);
1453            }
1454            while let Some(iter) = stack.last_mut() {
1455                if let Some(value) = iter.next() {
1456                    debug_assert!(f.dfg.value_is_real(value));
1457                    trace!(" -> DFS reaches {}", value);
1458                    if value_ir_uses[value] == ValueUseState::Multiple {
1459                        // Truncate DFS here: no need to go further,
1460                        // as whole subtree must already be Multiple.
1461                        // With debug asserts, check one level of
1462                        // that invariant at least.
1463                        debug_assert!(uses(value).into_iter().flatten().all(|arg| {
1464                            debug_assert!(f.dfg.value_is_real(arg));
1465                            value_ir_uses[arg] == ValueUseState::Multiple
1466                        }));
1467                        continue;
1468                    }
1469                    value_ir_uses[value] = ValueUseState::Multiple;
1470                    trace!(" -> became Multiple");
1471                    if let Some(iter) = uses(value) {
1472                        stack.push(iter);
1473                    }
1474                } else {
1475                    // Empty iterator, discard.
1476                    stack.pop();
1477                }
1478            }
1479        }
1480    }
1481
1482    value_ir_uses
1483}
1484
1485/// Function-level queries.
1486impl<'func, I: VCodeInst> Lower<'func, I> {
1487    pub fn dfg(&self) -> &DataFlowGraph {
1488        &self.f.dfg
1489    }
1490
1491    /// Get the `Callee`.
1492    pub fn abi(&self) -> &Callee<I::ABIMachineSpec> {
1493        self.vcode.abi()
1494    }
1495
1496    /// Get the `Callee`.
1497    pub fn abi_mut(&mut self) -> &mut Callee<I::ABIMachineSpec> {
1498        self.vcode.abi_mut()
1499    }
1500}
1501
1502/// Instruction input/output queries.
1503impl<'func, I: VCodeInst> Lower<'func, I> {
1504    /// Get the instdata for a given IR instruction.
1505    pub fn data(&self, ir_inst: Inst) -> &InstructionData {
1506        &self.f.dfg.insts[ir_inst]
1507    }
1508
1509    /// Likewise, but starting with a GlobalValue identifier.
1510    pub fn symbol_value_data<'b>(
1511        &'b self,
1512        global_value: GlobalValue,
1513    ) -> Option<(&'b ExternalName, RelocDistance, i64)> {
1514        let gvdata = &self.f.global_values[global_value];
1515        match gvdata {
1516            &GlobalValueData::Symbol {
1517                ref name,
1518                ref offset,
1519                colocated,
1520                ..
1521            } => {
1522                let offset = offset.bits();
1523                let dist = if colocated {
1524                    RelocDistance::Near
1525                } else {
1526                    RelocDistance::Far
1527                };
1528                Some((name, dist, offset))
1529            }
1530            _ => None,
1531        }
1532    }
1533
1534    /// Returns the memory flags of a given memory access.
1535    pub fn memflags(&self, ir_inst: Inst) -> Option<MachMemFlags> {
1536        match &self.f.dfg.insts[ir_inst] {
1537            &InstructionData::AtomicCas { flags, .. } => Some(self.f.dfg.mem_flags[flags].into()),
1538            &InstructionData::AtomicRmw { flags, .. } => Some(self.f.dfg.mem_flags[flags].into()),
1539            &InstructionData::Load { flags, .. }
1540            | &InstructionData::LoadNoOffset { flags, .. }
1541            | &InstructionData::Store { flags, .. } => Some(self.f.dfg.mem_flags[flags].into()),
1542            &InstructionData::StoreNoOffset { flags, .. } => {
1543                Some(self.f.dfg.mem_flags[flags].into())
1544            }
1545            _ => None,
1546        }
1547    }
1548
1549    /// Get the source location for a given instruction.
1550    pub fn srcloc(&self, ir_inst: Inst) -> RelSourceLoc {
1551        self.f.rel_srclocs()[ir_inst]
1552    }
1553
1554    /// Get the number of inputs to the given IR instruction. This is a count only of the Value
1555    /// arguments to the instruction: block arguments will not be included in this count.
1556    pub fn num_inputs(&self, ir_inst: Inst) -> usize {
1557        self.f.dfg.inst_args(ir_inst).len()
1558    }
1559
1560    /// Get the number of outputs to the given IR instruction.
1561    pub fn num_outputs(&self, ir_inst: Inst) -> usize {
1562        self.f.dfg.inst_results(ir_inst).len()
1563    }
1564
1565    /// Get the type for an instruction's input.
1566    pub fn input_ty(&self, ir_inst: Inst, idx: usize) -> Type {
1567        self.value_ty(self.input_as_value(ir_inst, idx))
1568    }
1569
1570    /// Get the type for a value.
1571    pub fn value_ty(&self, val: Value) -> Type {
1572        self.f.dfg.value_type(val)
1573    }
1574
1575    /// Get the type for an instruction's output.
1576    pub fn output_ty(&self, ir_inst: Inst, idx: usize) -> Type {
1577        self.f.dfg.value_type(self.f.dfg.inst_results(ir_inst)[idx])
1578    }
1579
1580    /// Get the value of a constant instruction (`iconst`, etc.) as a 64-bit
1581    /// value, if possible.
1582    pub fn get_constant(&self, ir_inst: Inst) -> Option<u64> {
1583        let c = is_constant_64bit(self.f, ir_inst)?;
1584
1585        // The upper bits must be zero, enforced during legalization and by
1586        // the CLIF verifier.
1587        debug_assert_eq!(c, {
1588            let input_size = self.output_ty(ir_inst, 0).bits() as u64;
1589            let shift = 64 - input_size;
1590            (c << shift) >> shift
1591        });
1592
1593        Some(c)
1594    }
1595
1596    /// Get the input as one of two options other than a direct register:
1597    ///
1598    /// - An instruction, given that it is effect-free or able to sink its
1599    ///   effect to the current instruction being lowered, and given it has only
1600    ///   one output, and if effect-ful, given that this is the only use;
1601    /// - A constant, if the value is a constant.
1602    ///
1603    /// The instruction input may be available in either of these forms.  It may
1604    /// be available in neither form, if the conditions are not met; if so, use
1605    /// `put_input_in_regs()` instead to get it in a register.
1606    ///
1607    /// If the backend merges the effect of a side-effecting instruction, it
1608    /// must call `sink_inst()`. When this is called, it indicates that the
1609    /// effect has been sunk to the current scan location. The sunk
1610    /// instruction's result(s) must have *no* uses remaining, because it will
1611    /// not be codegen'd (it has been integrated into the current instruction).
1612    pub fn input_as_value(&self, ir_inst: Inst, idx: usize) -> Value {
1613        let val = self.f.dfg.inst_args(ir_inst)[idx];
1614        debug_assert!(self.f.dfg.value_is_real(val));
1615        val
1616    }
1617
1618    /// Resolves a particular input of an instruction to the `Value` that it is
1619    /// represented with.
1620    ///
1621    /// For more information see [`Lower::get_value_as_source_or_const`].
1622    pub fn get_input_as_source_or_const(&self, ir_inst: Inst, idx: usize) -> NonRegInput {
1623        let val = self.input_as_value(ir_inst, idx);
1624        self.get_value_as_source_or_const(val)
1625    }
1626
1627    /// Resolves a `Value` definition to the source instruction it came from
1628    /// plus whether it's a unique-use of that instruction.
1629    ///
1630    /// This function is the workhorse of pattern-matching in ISLE which enables
1631    /// combining multiple instructions together. This is used implicitly in
1632    /// patterns such as `(iadd x (iconst y))` where this function is used to
1633    /// extract the `(iconst y)` operand.
1634    ///
1635    /// At its core this function is a wrapper around
1636    /// [`DataFlowGraph::value_def`]. This function applies a filter on top of
1637    /// that, however, to determine when it is actually safe to "look through"
1638    /// the `val` definition here and view the underlying instruction. This
1639    /// protects against duplicating side effects, such as loads, for example.
1640    ///
1641    /// Internally this uses the data computed from `compute_use_states` along
1642    /// with other instruction properties to know what to return.
1643    pub fn get_value_as_source_or_const(&self, val: Value) -> NonRegInput {
1644        trace!(
1645            "get_input_for_val: val {} at cur_inst {:?} cur_scan_entry_color {:?}",
1646            val, self.cur_inst, self.cur_scan_entry_color,
1647        );
1648        let inst = match self.f.dfg.value_def(val) {
1649            // OK to merge source instruction if we have a source
1650            // instruction, and one of these two conditions hold:
1651            //
1652            // - It has no side-effects and this instruction is not a "value-use
1653            //   root" instruction. Instructions which are considered "roots"
1654            //   for value-use calculations do not have accurate information
1655            //   known about the `ValueUseState` of their operands. This is
1656            //   currently done for multi-result instructions to prevent a use
1657            //   of each result from forcing all operands of the multi-result
1658            //   instruction to also be `Multiple`. This in turn means that the
1659            //   `ValueUseState` for operands of a "root" instruction to be a
1660            //   lie if pattern matching were to look through the multi-result
1661            //   instruction. As a result the "look through this instruction"
1662            //   logic only succeeds if it's not a root instruction.
1663            //
1664            // - It has a side-effect, has one output value, that one
1665            //   output has only one use, directly or indirectly (so
1666            //   cannot be duplicated -- see comment on
1667            //   `ValueUseState`), and the instruction's color is *one
1668            //   less than* the current scan color.
1669            //
1670            //   This latter set of conditions is testing whether a
1671            //   side-effecting instruction can sink to the current scan
1672            //   location; this is possible if the in-color of this inst is
1673            //   equal to the out-color of the producing inst, so no other
1674            //   side-effecting ops occur between them (which will only be true
1675            //   if they are in the same BB, because color increments at each BB
1676            //   start).
1677            //
1678            //   If it is actually sunk, then in `merge_inst()`, we update the
1679            //   scan color so that as we scan over the range past which the
1680            //   instruction was sunk, we allow other instructions (that came
1681            //   prior to the sunk instruction) to sink.
1682            ValueDef::Result(src_inst, result_idx) => {
1683                // A non-zero entry color marks a side-effecting instruction (see
1684                // the field's doc comment).
1685                let src_entry_color = self.side_effect_inst_entry_colors[src_inst];
1686                let src_side_effect = src_entry_color.get() != 0;
1687                trace!(" -> src inst {}", self.f.dfg.display_inst(src_inst));
1688                trace!(" -> has lowering side effect: {}", src_side_effect);
1689                if !src_side_effect {
1690                    // Otherwise if this instruction has no side effects and the
1691                    // value is used only once then we can look through it with
1692                    // a "unique" tag. A non-unique `Use` can be shown for other
1693                    // values ensuring consumers know how it's computed but that
1694                    // it's not available to omit.
1695                    if self.value_ir_uses[val] == ValueUseState::Once {
1696                        InputSourceInst::UniqueUse(src_inst, result_idx)
1697                    } else {
1698                        InputSourceInst::Use(src_inst, result_idx)
1699                    }
1700                } else {
1701                    // Side-effect: test whether this is the only use of the
1702                    // only result of the instruction, and whether colors allow
1703                    // the code-motion.
1704                    trace!(
1705                        " -> side-effecting op {} for val {}: use state {:?}",
1706                        src_inst, val, self.value_ir_uses[val]
1707                    );
1708                    if self.cur_scan_entry_color.is_some()
1709                        && self.value_ir_uses[val] == ValueUseState::Once
1710                        && self.num_outputs(src_inst) == 1
1711                        && src_entry_color.get() + 1 == self.cur_scan_entry_color.unwrap().get()
1712                    {
1713                        InputSourceInst::UniqueUse(src_inst, 0)
1714                    } else {
1715                        InputSourceInst::None
1716                    }
1717                }
1718            }
1719            _ => InputSourceInst::None,
1720        };
1721        let constant = inst.as_inst().and_then(|(inst, _)| self.get_constant(inst));
1722
1723        NonRegInput { inst, constant }
1724    }
1725
1726    /// Increment the reference count for the Value, ensuring that it gets lowered.
1727    #[cfg(any(
1728        feature = "x86",
1729        feature = "arm64",
1730        feature = "riscv64",
1731        feature = "s390x",
1732        feature = "pulley"
1733    ))]
1734    pub fn increment_lowered_uses(&mut self, val: Value) {
1735        self.value_lowered_uses[val] += 1
1736    }
1737
1738    /// Put the `idx`th input into register(s) and return the assigned register.
1739    pub fn put_input_in_regs(&mut self, ir_inst: Inst, idx: usize) -> ValueRegs<Reg> {
1740        let val = self.f.dfg.inst_args(ir_inst)[idx];
1741        self.put_value_in_regs(val)
1742    }
1743
1744    /// Put the given value into register(s) and return the assigned register.
1745    pub fn put_value_in_regs(&mut self, val: Value) -> ValueRegs<Reg> {
1746        debug_assert!(self.f.dfg.value_is_real(val));
1747        trace!("put_value_in_regs: val {}", val);
1748
1749        if let Some(inst) = self.f.dfg.value_def(val).inst() {
1750            assert!(!self.inst_sunk.contains(&inst));
1751        }
1752
1753        let regs = self.value_regs[val];
1754        trace!(" -> regs {:?}", regs);
1755        assert!(regs.is_valid());
1756
1757        self.value_lowered_uses[val] += 1;
1758
1759        regs
1760    }
1761}
1762
1763/// Codegen primitives: allocate temps, emit instructions, set result registers,
1764/// ask for an input to be gen'd into a register.
1765impl<'func, I: VCodeInst> Lower<'func, I> {
1766    /// Get a new temp.
1767    pub fn alloc_tmp(&mut self, ty: Type) -> ValueRegs<Writable<Reg>> {
1768        writable_value_regs(self.vregs.alloc_with_deferred_error(ty))
1769    }
1770
1771    /// Emit a machine instruction.
1772    pub fn emit(&mut self, mach_inst: I) {
1773        trace!("emit: {:?}", mach_inst);
1774        self.ir_insts.push(mach_inst);
1775    }
1776
1777    /// Indicate that the side-effect of an instruction has been sunk to the
1778    /// current scan location. This should only be done with the instruction's
1779    /// original results are not used (i.e., `put_input_in_regs` is not invoked
1780    /// for the input produced by the sunk instruction), otherwise the
1781    /// side-effect will occur twice.
1782    pub fn sink_inst(&mut self, ir_inst: Inst) {
1783        assert!(has_lowering_side_effect(self.f, ir_inst));
1784        assert!(self.cur_scan_entry_color.is_some());
1785
1786        for result in self.dfg().inst_results(ir_inst) {
1787            assert!(self.value_lowered_uses[*result] == 0);
1788        }
1789
1790        let sunk_inst_entry_color = self.side_effect_inst_entry_colors[ir_inst];
1791        let sunk_inst_exit_color = InstColor::new(sunk_inst_entry_color.get() + 1);
1792        assert!(sunk_inst_exit_color == self.cur_scan_entry_color.unwrap());
1793        self.cur_scan_entry_color = Some(sunk_inst_entry_color);
1794        self.inst_sunk.insert(ir_inst);
1795    }
1796
1797    /// Retrieve immediate data given a handle.
1798    pub fn get_immediate_data(&self, imm: Immediate) -> &ConstantData {
1799        self.f.dfg.immediates.get(imm).unwrap()
1800    }
1801
1802    /// Retrieve constant data given a handle.
1803    pub fn get_constant_data(&self, constant_handle: Constant) -> &ConstantData {
1804        self.f.dfg.constants.get(constant_handle)
1805    }
1806
1807    /// Indicate that a constant should be emitted.
1808    pub fn use_constant(&mut self, constant: VCodeConstantData) -> VCodeConstant {
1809        self.vcode.constants().insert(constant)
1810    }
1811}
1812
1813#[cfg(test)]
1814mod tests {
1815    use super::ValueUseState;
1816    use crate::cursor::{Cursor, FuncCursor};
1817    use crate::ir::types;
1818    use crate::ir::{Function, InstBuilder};
1819
1820    #[test]
1821    fn multi_result_use_once() {
1822        let mut func = Function::new();
1823        let block0 = func.dfg.make_block();
1824        let mut pos = FuncCursor::new(&mut func);
1825        pos.insert_block(block0);
1826        let v1 = pos.ins().iconst(types::I64, 0);
1827        let v2 = pos.ins().iconst(types::I64, 1);
1828        let v3 = pos.ins().iconcat(v1, v2);
1829        let (v4, v5) = pos.ins().isplit(v3);
1830        pos.ins().return_(&[v4, v5]);
1831        let func = pos.func;
1832
1833        let uses = super::compute_use_states(&func, None);
1834        assert_eq!(uses[v1], ValueUseState::Once);
1835        assert_eq!(uses[v2], ValueUseState::Once);
1836        assert_eq!(uses[v3], ValueUseState::Once);
1837        assert_eq!(uses[v4], ValueUseState::Once);
1838        assert_eq!(uses[v5], ValueUseState::Once);
1839    }
1840}