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