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