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