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