1d8357426SChris Fallin //! This implements the VCode container: a CFG of Insts that have been lowered. 2d8357426SChris Fallin //! 3d8357426SChris Fallin //! VCode is virtual-register code. An instruction in VCode is almost a machine 4d8357426SChris Fallin //! instruction; however, its register slots can refer to virtual registers in 5d8357426SChris Fallin //! addition to real machine registers. 6d8357426SChris Fallin //! 7d8357426SChris Fallin //! VCode is structured with traditional basic blocks, and 8d8357426SChris Fallin //! each block must be terminated by an unconditional branch (one target), a 9d8357426SChris Fallin //! conditional branch (two targets), or a return (no targets). Note that this 10d8357426SChris Fallin //! slightly differs from the machine code of most ISAs: in most ISAs, a 11d8357426SChris Fallin //! conditional branch has one target (and the not-taken case falls through). 12d8357426SChris Fallin //! However, we expect that machine backends will elide branches to the following 13d8357426SChris Fallin //! block (i.e., zero-offset jumps), and will be able to codegen a branch-cond / 14d8357426SChris Fallin //! branch-uncond pair if *both* targets are not fallthrough. This allows us to 15d8357426SChris Fallin //! play with layout prior to final binary emission, as well, if we want. 16d8357426SChris Fallin //! 17d8357426SChris Fallin //! See the main module comment in `mod.rs` for more details on the VCode-based 18d8357426SChris Fallin //! backend pipeline. 19d8357426SChris Fallin 2090ac295eSAlex Crichton use crate::CodegenError; 2176911c29SSSD use crate::FxHashMap; 22f466aa26SChris Fallin use crate::ir::pcc::*; 2390ac295eSAlex Crichton use crate::ir::{self, Constant, ConstantData, ValueLabel, types}; 242c409535SJamey Sharp use crate::ranges::Ranges; 252b9fefe8SChris Fallin use crate::timing; 268d022434SBenjamin Bouvier use crate::trace; 27729e2640Sbjorn3 use crate::{LabelValueLoc, ValueLocRange}; 2890ac295eSAlex Crichton use crate::{machinst::*, trace_log_enabled}; 29a0318f36SChris Fallin use regalloc2::{ 305ded0f4eSUlrich Weigand Edit, Function as RegallocFunction, InstOrEdit, InstPosition, InstRange, Operand, 315b63c874SSingleAccretion OperandConstraint, OperandKind, PRegSet, ProgPoint, RegClass, 32be6f060aSChris Fallin }; 33d8357426SChris Fallin 340889323aSSSD use crate::HashMap; 350889323aSSSD use crate::hash_map::Entry; 363da7fc8eSSingleAccretion use core::cmp::Ordering; 373da7fc8eSSingleAccretion use core::fmt::{self, Write}; 383aa32064SJamey Sharp use core::mem::take; 39a3d6e407SChris Fallin use core::ops::Range; 4090ac295eSAlex Crichton use cranelift_entity::{Keys, entity_impl}; 41d8357426SChris Fallin 42d8357426SChris Fallin /// Index referring to an instruction in VCode. 43a0318f36SChris Fallin pub type InsnIndex = regalloc2::Inst; 44a0318f36SChris Fallin 45e20b4244SNick Fitzgerald /// Extension trait for `InsnIndex` to allow conversion to a 46e20b4244SNick Fitzgerald /// `BackwardsInsnIndex`. 47e20b4244SNick Fitzgerald trait ToBackwardsInsnIndex { 48e20b4244SNick Fitzgerald fn to_backwards_insn_index(&self, num_insts: usize) -> BackwardsInsnIndex; 49e20b4244SNick Fitzgerald } 50e20b4244SNick Fitzgerald 51e20b4244SNick Fitzgerald impl ToBackwardsInsnIndex for InsnIndex { 52e20b4244SNick Fitzgerald fn to_backwards_insn_index(&self, num_insts: usize) -> BackwardsInsnIndex { 53e20b4244SNick Fitzgerald BackwardsInsnIndex::new(num_insts - self.index() - 1) 54e20b4244SNick Fitzgerald } 55e20b4244SNick Fitzgerald } 56e20b4244SNick Fitzgerald 57e20b4244SNick Fitzgerald /// An index referring to an instruction in the VCode when it is backwards, 58e20b4244SNick Fitzgerald /// during VCode construction. 59e20b4244SNick Fitzgerald #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] 60e20b4244SNick Fitzgerald #[cfg_attr( 61e20b4244SNick Fitzgerald feature = "enable-serde", 62e20b4244SNick Fitzgerald derive(::serde::Serialize, ::serde::Deserialize) 63e20b4244SNick Fitzgerald )] 64e20b4244SNick Fitzgerald pub struct BackwardsInsnIndex(InsnIndex); 65e20b4244SNick Fitzgerald 66e20b4244SNick Fitzgerald impl BackwardsInsnIndex { 67e20b4244SNick Fitzgerald pub fn new(i: usize) -> Self { 68e20b4244SNick Fitzgerald BackwardsInsnIndex(InsnIndex::new(i)) 69e20b4244SNick Fitzgerald } 70e20b4244SNick Fitzgerald } 71e20b4244SNick Fitzgerald 72d8357426SChris Fallin /// Index referring to a basic block in VCode. 73a0318f36SChris Fallin pub type BlockIndex = regalloc2::Block; 74d8357426SChris Fallin 75d8357426SChris Fallin /// VCodeInst wraps all requirements for a MachInst to be in VCode: it must be 76d8357426SChris Fallin /// a `MachInst` and it must be able to emit itself at least to a `SizeCodeSink`. 7772e6be93SChris Fallin pub trait VCodeInst: MachInst + MachInstEmit {} 7872e6be93SChris Fallin impl<I: MachInst + MachInstEmit> VCodeInst for I {} 79d8357426SChris Fallin 80a0318f36SChris Fallin /// A function in "VCode" (virtualized-register code) form, after 81a0318f36SChris Fallin /// lowering. This is essentially a standard CFG of basic blocks, 82a0318f36SChris Fallin /// where each basic block consists of lowered instructions produced 83a0318f36SChris Fallin /// by the machine-specific backend. 84a0318f36SChris Fallin /// 85a0318f36SChris Fallin /// Note that the VCode is immutable once produced, and is not 86a0318f36SChris Fallin /// modified by register allocation in particular. Rather, register 87a0318f36SChris Fallin /// allocation on the `VCode` produces a separate `regalloc2::Output` 88a0318f36SChris Fallin /// struct, and this can be passed to `emit`. `emit` in turn does not 89a0318f36SChris Fallin /// modify the vcode, but produces an `EmitResult`, which contains the 90a0318f36SChris Fallin /// machine code itself, and the associated disassembly and/or 91a0318f36SChris Fallin /// metadata as requested. 92d8357426SChris Fallin pub struct VCode<I: VCodeInst> { 93d8357426SChris Fallin /// VReg IR-level types. 94d8357426SChris Fallin vreg_types: Vec<Type>, 95d8357426SChris Fallin 96d8357426SChris Fallin /// Lowered machine instructions in order corresponding to the original IR. 9748cf2c2fSChris Fallin insts: Vec<I>, 98d8357426SChris Fallin 99e20b4244SNick Fitzgerald /// A map from backwards instruction index to the user stack map for that 100e20b4244SNick Fitzgerald /// instruction. 101e20b4244SNick Fitzgerald /// 102e20b4244SNick Fitzgerald /// This is a sparse side table that only has entries for instructions that 103e20b4244SNick Fitzgerald /// are safepoints, and only for a subset of those that have an associated 104e20b4244SNick Fitzgerald /// user stack map. 105e20b4244SNick Fitzgerald user_stack_maps: FxHashMap<BackwardsInsnIndex, ir::UserStackMap>, 106e20b4244SNick Fitzgerald 107a3d6e407SChris Fallin /// A map from backwards instruction index to the debug tags for 108a3d6e407SChris Fallin /// that instruction. Each entry indexes a range in the 109a3d6e407SChris Fallin /// `debug_tag_pool`. 110a3d6e407SChris Fallin debug_tags: FxHashMap<BackwardsInsnIndex, Range<u32>>, 111a3d6e407SChris Fallin 112a3d6e407SChris Fallin /// Pooled storage for sequences of debug tags; indexed by entries 113a3d6e407SChris Fallin /// in `debug_tags`. 114a3d6e407SChris Fallin debug_tag_pool: Vec<ir::DebugTag>, 115a3d6e407SChris Fallin 116a0318f36SChris Fallin /// Operands: pre-regalloc references to virtual registers with 117a0318f36SChris Fallin /// constraints, in one flattened array. This allows the regalloc 118a0318f36SChris Fallin /// to efficiently access all operands without requiring expensive 119a0318f36SChris Fallin /// matches or method invocations on insts. 120a0318f36SChris Fallin operands: Vec<Operand>, 121a0318f36SChris Fallin 122a0318f36SChris Fallin /// Operand index ranges: for each instruction in `insts`, there 123a0318f36SChris Fallin /// is a tuple here providing the range in `operands` for that 124a0318f36SChris Fallin /// instruction's operands. 1252c409535SJamey Sharp operand_ranges: Ranges, 126a0318f36SChris Fallin 127b2e28b91SChris Fallin /// Clobbers: a sparse map from instruction indices to clobber masks. 128b2e28b91SChris Fallin clobbers: FxHashMap<InsnIndex, PRegSet>, 129a0318f36SChris Fallin 130b691770fSChris Fallin /// Source locations for each instruction. (`SourceLoc` is a `u32`, so it is 131b691770fSChris Fallin /// reasonable to keep one of these per instruction.) 1328a9b1a90SBenjamin Bouvier srclocs: Vec<RelSourceLoc>, 133b691770fSChris Fallin 134d8357426SChris Fallin /// Entry block. 135d8357426SChris Fallin entry: BlockIndex, 136d8357426SChris Fallin 137d8357426SChris Fallin /// Block instruction indices. 1382c409535SJamey Sharp block_ranges: Ranges, 139d8357426SChris Fallin 1400f4c0d4aSJamey Sharp /// Block successors: index range in the `block_succs` list. 1412c409535SJamey Sharp block_succ_range: Ranges, 142d8357426SChris Fallin 1430f4c0d4aSJamey Sharp /// Block successor lists, concatenated into one vec. The 1440f4c0d4aSJamey Sharp /// `block_succ_range` list of tuples above gives (start, end) 1450f4c0d4aSJamey Sharp /// ranges within this list that correspond to each basic block's 1460f4c0d4aSJamey Sharp /// successors. 1470f4c0d4aSJamey Sharp block_succs: Vec<regalloc2::Block>, 1480f4c0d4aSJamey Sharp 1490f4c0d4aSJamey Sharp /// Block predecessors: index range in the `block_preds` list. 1502c409535SJamey Sharp block_pred_range: Ranges, 151a0318f36SChris Fallin 1520f4c0d4aSJamey Sharp /// Block predecessor lists, concatenated into one vec. The 1530f4c0d4aSJamey Sharp /// `block_pred_range` list of tuples above gives (start, end) 1540f4c0d4aSJamey Sharp /// ranges within this list that correspond to each basic block's 1550f4c0d4aSJamey Sharp /// predecessors. 1560f4c0d4aSJamey Sharp block_preds: Vec<regalloc2::Block>, 157a0318f36SChris Fallin 158a0318f36SChris Fallin /// Block parameters: index range in `block_params` below. 1592c409535SJamey Sharp block_params_range: Ranges, 160a0318f36SChris Fallin 161a0318f36SChris Fallin /// Block parameter lists, concatenated into one vec. The 162a0318f36SChris Fallin /// `block_params_range` list of tuples above gives (start, end) 163a0318f36SChris Fallin /// ranges within this list that correspond to each basic block's 164a0318f36SChris Fallin /// blockparam vregs. 165a0318f36SChris Fallin block_params: Vec<regalloc2::VReg>, 166a0318f36SChris Fallin 167a0318f36SChris Fallin /// Outgoing block arguments on branch instructions, concatenated 168a0318f36SChris Fallin /// into one list. 169a0318f36SChris Fallin /// 170a0318f36SChris Fallin /// Note that this is conceptually a 3D array: we have a VReg list 171a0318f36SChris Fallin /// per block, per successor. We flatten those three dimensions 172a0318f36SChris Fallin /// into this 1D vec, then store index ranges in two levels of 173a0318f36SChris Fallin /// indirection. 174a0318f36SChris Fallin /// 175a0318f36SChris Fallin /// Indexed by the indices in `branch_block_arg_succ_range`. 176a0318f36SChris Fallin branch_block_args: Vec<regalloc2::VReg>, 177a0318f36SChris Fallin 178a0318f36SChris Fallin /// Array of sequences of (start, end) tuples in 179a0318f36SChris Fallin /// `branch_block_args`, one for each successor; these sequences 180a0318f36SChris Fallin /// for each block are concatenated. 181a0318f36SChris Fallin /// 182a0318f36SChris Fallin /// Indexed by the indices in `branch_block_arg_succ_range`. 1832c409535SJamey Sharp branch_block_arg_range: Ranges, 184a0318f36SChris Fallin 185a0318f36SChris Fallin /// For a given block, indices in `branch_block_arg_range` 186a0318f36SChris Fallin /// corresponding to all of its successors. 1872c409535SJamey Sharp branch_block_arg_succ_range: Ranges, 188a0318f36SChris Fallin 18972e6be93SChris Fallin /// Block-order information. 19072e6be93SChris Fallin block_order: BlockLoweringOrder, 191d8357426SChris Fallin 192d8357426SChris Fallin /// ABI object. 1932986f6b0SChris Fallin pub(crate) abi: Callee<I::ABIMachineSpec>, 19408353fccSChris Fallin 195c5bbc874SBenjamin Bouvier /// Constant information used during code emission. This should be 196c5bbc874SBenjamin Bouvier /// immutable across function compilations within the same module. 197c5bbc874SBenjamin Bouvier emit_info: I::Info, 198c5bbc874SBenjamin Bouvier 19983f182b3SAndrew Brown /// Constants. 2004513d9caSChris Fallin pub(crate) constants: VCodeConstants, 201997fab55SChris Fallin 202a0318f36SChris Fallin /// Value labels for debuginfo attached to vregs. 203a0318f36SChris Fallin debug_value_labels: Vec<(VReg, InsnIndex, InsnIndex, u32)>, 204f18a1f14SNick Fitzgerald 2052986f6b0SChris Fallin pub(crate) sigs: SigSet, 206f466aa26SChris Fallin 207f466aa26SChris Fallin /// Facts on VRegs, for proof-carrying code verification. 208f466aa26SChris Fallin facts: Vec<Option<Fact>>, 2092af0a1f7Sbjorn3 2102af0a1f7Sbjorn3 log2_min_function_alignment: u8, 211d8357426SChris Fallin } 212d8357426SChris Fallin 213a0318f36SChris Fallin /// The result of `VCode::emit`. Contains all information computed 214a0318f36SChris Fallin /// during emission: actual machine code, optionally a disassembly, 215a0318f36SChris Fallin /// and optionally metadata about the code layout. 21649dd8fd7SAlex Crichton pub struct EmitResult { 217a0318f36SChris Fallin /// The MachBuffer containing the machine code. 21849dd8fd7SAlex Crichton pub buffer: MachBufferFinalized<Stencil>, 219a0318f36SChris Fallin 220a0318f36SChris Fallin /// Offset of each basic block, recorded during emission. Computed 2210854775bSbjorn3 /// only if `machine_code_cfg_info` is enabled. 222a0318f36SChris Fallin pub bb_offsets: Vec<CodeOffset>, 223a0318f36SChris Fallin 224a0318f36SChris Fallin /// Final basic-block edges, in terms of code offsets of 2250854775bSbjorn3 /// bb-starts. Computed only if `machine_code_cfg_info` is enabled. 226a0318f36SChris Fallin pub bb_edges: Vec<(CodeOffset, CodeOffset)>, 227a0318f36SChris Fallin 228a0318f36SChris Fallin /// The pretty-printed disassembly, if any. This uses the same 229a0318f36SChris Fallin /// pretty-printing for MachInsts as the pre-regalloc VCode Debug 230a0318f36SChris Fallin /// implementation, but additionally includes the prologue and 231a0318f36SChris Fallin /// epilogue(s), and makes use of the regalloc results. 232a0318f36SChris Fallin pub disasm: Option<String>, 233a0318f36SChris Fallin 234a0318f36SChris Fallin /// Value-labels information (debug metadata). 235a0318f36SChris Fallin pub value_labels_ranges: ValueLabelsRanges, 236d9d64694SChris Fallin } 237d9d64694SChris Fallin 238a0318f36SChris Fallin /// A builder for a VCode function body. 239d8357426SChris Fallin /// 240a0318f36SChris Fallin /// This builder has the ability to accept instructions in either 241a0318f36SChris Fallin /// forward or reverse order, depending on the pass direction that 242a0318f36SChris Fallin /// produces the VCode. The lowering from CLIF to VCode<MachInst> 243a0318f36SChris Fallin /// ordinarily occurs in reverse order (in order to allow instructions 244a0318f36SChris Fallin /// to be lowered only if used, and not merged) so a reversal will 245a0318f36SChris Fallin /// occur at the end of lowering to ensure the VCode is in machine 246a0318f36SChris Fallin /// order. 247a0318f36SChris Fallin /// 248a0318f36SChris Fallin /// If built in reverse, block and instruction indices used once the 249a0318f36SChris Fallin /// VCode is built are relative to the final (reversed) order, not the 250a0318f36SChris Fallin /// order of construction. Note that this means we do not know the 251a0318f36SChris Fallin /// final block or instruction indices when building, so we do not 252a0318f36SChris Fallin /// hand them out. (The user is assumed to know them when appending 253a0318f36SChris Fallin /// terminator instructions with successor blocks.) 254d8357426SChris Fallin pub struct VCodeBuilder<I: VCodeInst> { 255d8357426SChris Fallin /// In-progress VCode. 2562986f6b0SChris Fallin pub(crate) vcode: VCode<I>, 257d8357426SChris Fallin 2580e9121daSFrankReh /// In what direction is the build occurring? 259a0318f36SChris Fallin direction: VCodeBuildDirection, 26008353fccSChris Fallin 261a0318f36SChris Fallin /// Debug-value label in-progress map, keyed by label. For each 262a0318f36SChris Fallin /// label, we keep disjoint ranges mapping to vregs. We'll flatten 263a0318f36SChris Fallin /// this into (vreg, range, label) tuples when done. 264a0318f36SChris Fallin debug_info: FxHashMap<ValueLabel, Vec<(InsnIndex, InsnIndex, VReg)>>, 265a0318f36SChris Fallin } 266a0318f36SChris Fallin 267a0318f36SChris Fallin /// Direction in which a VCodeBuilder builds VCode. 268a0318f36SChris Fallin #[derive(Clone, Copy, Debug, PartialEq, Eq)] 269a0318f36SChris Fallin pub enum VCodeBuildDirection { 270a0318f36SChris Fallin // TODO: add `Forward` once we need it and can test it adequately. 271a0318f36SChris Fallin /// Backward-build pass: we expect the producer to call `emit()` 272a0318f36SChris Fallin /// with instructions in reverse program order within each block. 273a0318f36SChris Fallin Backward, 274d8357426SChris Fallin } 275d8357426SChris Fallin 276d8357426SChris Fallin impl<I: VCodeInst> VCodeBuilder<I> { 277d8357426SChris Fallin /// Create a new VCodeBuilder. 278c5bbc874SBenjamin Bouvier pub fn new( 279f18a1f14SNick Fitzgerald sigs: SigSet, 280f0c60f46SNick Fitzgerald abi: Callee<I::ABIMachineSpec>, 281c5bbc874SBenjamin Bouvier emit_info: I::Info, 282c5bbc874SBenjamin Bouvier block_order: BlockLoweringOrder, 28383f182b3SAndrew Brown constants: VCodeConstants, 284a0318f36SChris Fallin direction: VCodeBuildDirection, 2852af0a1f7Sbjorn3 log2_min_function_alignment: u8, 286e20b4244SNick Fitzgerald ) -> Self { 2872af0a1f7Sbjorn3 let vcode = VCode::new( 2882af0a1f7Sbjorn3 sigs, 2892af0a1f7Sbjorn3 abi, 2902af0a1f7Sbjorn3 emit_info, 2912af0a1f7Sbjorn3 block_order, 2922af0a1f7Sbjorn3 constants, 2932af0a1f7Sbjorn3 log2_min_function_alignment, 2942af0a1f7Sbjorn3 ); 29508353fccSChris Fallin 296d8357426SChris Fallin VCodeBuilder { 297d8357426SChris Fallin vcode, 298a0318f36SChris Fallin direction, 299a0318f36SChris Fallin debug_info: FxHashMap::default(), 300d8357426SChris Fallin } 301d8357426SChris Fallin } 302d8357426SChris Fallin 303b6e7cc38SJamey Sharp pub fn init_retval_area(&mut self, vregs: &mut VRegAllocator<I>) -> CodegenResult<()> { 304b6e7cc38SJamey Sharp self.vcode.abi.init_retval_area(&self.vcode.sigs, vregs) 305f18a1f14SNick Fitzgerald } 306f18a1f14SNick Fitzgerald 307d8357426SChris Fallin /// Access the ABI object. 308f18a1f14SNick Fitzgerald pub fn abi(&self) -> &Callee<I::ABIMachineSpec> { 309f18a1f14SNick Fitzgerald &self.vcode.abi 310f18a1f14SNick Fitzgerald } 311f18a1f14SNick Fitzgerald 312f18a1f14SNick Fitzgerald /// Access the ABI object. 313f18a1f14SNick Fitzgerald pub fn abi_mut(&mut self) -> &mut Callee<I::ABIMachineSpec> { 314f0c60f46SNick Fitzgerald &mut self.vcode.abi 315d8357426SChris Fallin } 316d8357426SChris Fallin 317f18a1f14SNick Fitzgerald pub fn sigs(&self) -> &SigSet { 318f18a1f14SNick Fitzgerald &self.vcode.sigs 319f18a1f14SNick Fitzgerald } 320f18a1f14SNick Fitzgerald 321f18a1f14SNick Fitzgerald pub fn sigs_mut(&mut self) -> &mut SigSet { 322f18a1f14SNick Fitzgerald &mut self.vcode.sigs 323f18a1f14SNick Fitzgerald } 324f18a1f14SNick Fitzgerald 32572e6be93SChris Fallin /// Access to the BlockLoweringOrder object. 32672e6be93SChris Fallin pub fn block_order(&self) -> &BlockLoweringOrder { 32772e6be93SChris Fallin &self.vcode.block_order 3281d90751bSBenjamin Bouvier } 3291d90751bSBenjamin Bouvier 330d8357426SChris Fallin /// Set the current block as the entry block. 331d8357426SChris Fallin pub fn set_entry(&mut self, block: BlockIndex) { 332d8357426SChris Fallin self.vcode.entry = block; 333d8357426SChris Fallin } 334d8357426SChris Fallin 335d8357426SChris Fallin /// End the current basic block. Must be called after emitting vcode insts 336d8357426SChris Fallin /// for IR insts and prior to ending the function (building the VCode). 33772e6be93SChris Fallin pub fn end_bb(&mut self) { 338a0318f36SChris Fallin let end_idx = self.vcode.insts.len(); 339d8357426SChris Fallin // Add the instruction index range to the list of blocks. 3402c409535SJamey Sharp self.vcode.block_ranges.push_end(end_idx); 341d8357426SChris Fallin // End the successors list. 3420f4c0d4aSJamey Sharp let succ_end = self.vcode.block_succs.len(); 3432c409535SJamey Sharp self.vcode.block_succ_range.push_end(succ_end); 344a0318f36SChris Fallin // End the blockparams list. 345a0318f36SChris Fallin let block_params_end = self.vcode.block_params.len(); 3462c409535SJamey Sharp self.vcode.block_params_range.push_end(block_params_end); 347a0318f36SChris Fallin // End the branch blockparam args list. 348a0318f36SChris Fallin let branch_block_arg_succ_end = self.vcode.branch_block_arg_range.len(); 3492c409535SJamey Sharp self.vcode 3502c409535SJamey Sharp .branch_block_arg_succ_range 3512c409535SJamey Sharp .push_end(branch_block_arg_succ_end); 352d8357426SChris Fallin } 353d8357426SChris Fallin 354d94173eaSTrevor Elliott pub fn add_block_param(&mut self, param: VirtualReg) { 355a0318f36SChris Fallin self.vcode.block_params.push(param.into()); 356a0318f36SChris Fallin } 357a0318f36SChris Fallin 3585774e068SChris Fallin fn add_branch_args_for_succ(&mut self, args: &[Reg]) { 359a0318f36SChris Fallin self.vcode 360a0318f36SChris Fallin .branch_block_args 361a0318f36SChris Fallin .extend(args.iter().map(|&arg| VReg::from(arg))); 362a0318f36SChris Fallin let end = self.vcode.branch_block_args.len(); 3632c409535SJamey Sharp self.vcode.branch_block_arg_range.push_end(end); 364a0318f36SChris Fallin } 365a0318f36SChris Fallin 366a0318f36SChris Fallin /// Push an instruction for the current BB and current IR inst 367a0318f36SChris Fallin /// within the BB. 3683e878837SJamey Sharp pub fn push(&mut self, insn: I, loc: RelSourceLoc) { 369392c7a96SChris Fallin assert!(!insn.is_low_level_branch()); // These are not meant to be in VCode. 37072e6be93SChris Fallin self.vcode.insts.push(insn); 3713e878837SJamey Sharp self.vcode.srclocs.push(loc); 37272e6be93SChris Fallin } 37372e6be93SChris Fallin 3745774e068SChris Fallin /// Add a successor block with branch args. 3755774e068SChris Fallin pub fn add_succ(&mut self, block: BlockIndex, args: &[Reg]) { 3760f4c0d4aSJamey Sharp self.vcode.block_succs.push(block); 3775774e068SChris Fallin self.add_branch_args_for_succ(args); 3785774e068SChris Fallin } 3795774e068SChris Fallin 380a0318f36SChris Fallin /// Add a debug value label to a register. 381a0318f36SChris Fallin pub fn add_value_label(&mut self, reg: Reg, label: ValueLabel) { 3825b63c874SSingleAccretion // 1) In the reversed order, we consider the instructions 3835b63c874SSingleAccretion // that define ranges in the "debug_info" array to refer 3845b63c874SSingleAccretion // to the IP **after** them (when reversed): 3855b63c874SSingleAccretion // IP[2]__| Inst 3 | 3865b63c874SSingleAccretion // IP[1]__| Inst 2 | 3875b63c874SSingleAccretion // IP[0]__| Inst 1 | 3885b63c874SSingleAccretion // | Inst 0 | 3895b63c874SSingleAccretion // This is so that we can represent IP[<function start>], 3905b63c874SSingleAccretion // done at the cost of not being to represent IP[<function end>], 3915b63c874SSingleAccretion // which is OK since no values will be live at that point. 3925b63c874SSingleAccretion // 2) The live range for "reg" begins at the current IP 3935b63c874SSingleAccretion // and continues until the next, in execution order, 3945b63c874SSingleAccretion // VReg that defines "label". Since the ranges are open 3955b63c874SSingleAccretion // at the end, the subtraction of 1 cancels out: 3965b63c874SSingleAccretion // [last..current IP] <=> 3975b63c874SSingleAccretion // [last..last emitted inst index] <=> 3985b63c874SSingleAccretion // [last..next_inst_index - 1] <=> 3995b63c874SSingleAccretion // [last..next_inst_index) 4005b63c874SSingleAccretion // 4015b63c874SSingleAccretion let next_inst_index = self.vcode.insts.len(); 4025b63c874SSingleAccretion if next_inst_index == 0 { 4035b63c874SSingleAccretion // This would produce a defective [0..0) range. 4045b63c874SSingleAccretion return; 4055b63c874SSingleAccretion } 4065b63c874SSingleAccretion let next_inst = InsnIndex::new(next_inst_index); 407a0318f36SChris Fallin let labels = self.debug_info.entry(label).or_insert_with(|| vec![]); 408a0318f36SChris Fallin let last = labels 409a0318f36SChris Fallin .last() 410a0318f36SChris Fallin .map(|(_start, end, _vreg)| *end) 411a0318f36SChris Fallin .unwrap_or(InsnIndex::new(0)); 4125b63c874SSingleAccretion labels.push((last, next_inst, reg.into())); 413a0318f36SChris Fallin } 414a0318f36SChris Fallin 41583f182b3SAndrew Brown /// Access the constants. 41683f182b3SAndrew Brown pub fn constants(&mut self) -> &mut VCodeConstants { 41783f182b3SAndrew Brown &mut self.vcode.constants 41883f182b3SAndrew Brown } 41983f182b3SAndrew Brown 420a0318f36SChris Fallin fn compute_preds_from_succs(&mut self) { 4210f4c0d4aSJamey Sharp // Do a linear-time counting sort: first determine how many 4220f4c0d4aSJamey Sharp // times each block appears as a successor. 4230f4c0d4aSJamey Sharp let mut starts = vec![0u32; self.vcode.num_blocks()]; 4240f4c0d4aSJamey Sharp for succ in &self.vcode.block_succs { 4250f4c0d4aSJamey Sharp starts[succ.index()] += 1; 4260f4c0d4aSJamey Sharp } 4270f4c0d4aSJamey Sharp 4280f4c0d4aSJamey Sharp // Determine for each block the starting index where that 4290f4c0d4aSJamey Sharp // block's predecessors should go. This is equivalent to the 4300f4c0d4aSJamey Sharp // ranges we need to store in block_pred_range. 4310f4c0d4aSJamey Sharp self.vcode.block_pred_range.reserve(starts.len()); 4320f4c0d4aSJamey Sharp let mut end = 0; 4330f4c0d4aSJamey Sharp for count in starts.iter_mut() { 4340f4c0d4aSJamey Sharp let start = end; 4350f4c0d4aSJamey Sharp end += *count; 4360f4c0d4aSJamey Sharp *count = start; 4372c409535SJamey Sharp self.vcode.block_pred_range.push_end(end as usize); 4380f4c0d4aSJamey Sharp } 4390f4c0d4aSJamey Sharp let end = end as usize; 4400f4c0d4aSJamey Sharp debug_assert_eq!(end, self.vcode.block_succs.len()); 4410f4c0d4aSJamey Sharp 4420f4c0d4aSJamey Sharp // Walk over the successors again, this time grouped by 4430f4c0d4aSJamey Sharp // predecessor, and push the predecessor at the current 4442c409535SJamey Sharp // starting position of each of its successors. We build 4452c409535SJamey Sharp // each group of predecessors in whatever order Ranges::iter 4462c409535SJamey Sharp // returns them; regalloc2 doesn't care. 4470f4c0d4aSJamey Sharp self.vcode.block_preds.resize(end, BlockIndex::invalid()); 4482c409535SJamey Sharp for (pred, range) in self.vcode.block_succ_range.iter() { 449a0318f36SChris Fallin let pred = BlockIndex::new(pred); 4502c409535SJamey Sharp for succ in &self.vcode.block_succs[range] { 4510f4c0d4aSJamey Sharp let pos = &mut starts[succ.index()]; 4520f4c0d4aSJamey Sharp self.vcode.block_preds[*pos as usize] = pred; 4530f4c0d4aSJamey Sharp *pos += 1; 454a0318f36SChris Fallin } 455a0318f36SChris Fallin } 4560f4c0d4aSJamey Sharp debug_assert!(self.vcode.block_preds.iter().all(|pred| pred.is_valid())); 457d8357426SChris Fallin } 458d8357426SChris Fallin 459a0318f36SChris Fallin /// Called once, when a build in Backward order is complete, to 460a0318f36SChris Fallin /// perform the overall reversal (into final forward order) and 461a0318f36SChris Fallin /// finalize metadata accordingly. 4623aa32064SJamey Sharp fn reverse_and_finalize(&mut self, vregs: &VRegAllocator<I>) { 463a0318f36SChris Fallin let n_insts = self.vcode.insts.len(); 464a0318f36SChris Fallin if n_insts == 0 { 465a0318f36SChris Fallin return; 466a0318f36SChris Fallin } 467a0318f36SChris Fallin 468a0318f36SChris Fallin // Reverse the per-block and per-inst sequences. 4692c409535SJamey Sharp self.vcode.block_ranges.reverse_index(); 4702c409535SJamey Sharp self.vcode.block_ranges.reverse_target(n_insts); 471a0318f36SChris Fallin // block_params_range is indexed by block (and blocks were 472a0318f36SChris Fallin // traversed in reverse) so we reverse it; but block-param 473a0318f36SChris Fallin // sequences in the concatenated vec can remain in reverse 474a0318f36SChris Fallin // order (it is effectively an arena of arbitrarily-placed 475a0318f36SChris Fallin // referenced sequences). 4762c409535SJamey Sharp self.vcode.block_params_range.reverse_index(); 477a0318f36SChris Fallin // Likewise, we reverse block_succ_range, but the block_succ 478a0318f36SChris Fallin // concatenated array can remain as-is. 4792c409535SJamey Sharp self.vcode.block_succ_range.reverse_index(); 480a0318f36SChris Fallin self.vcode.insts.reverse(); 481a0318f36SChris Fallin self.vcode.srclocs.reverse(); 482a0318f36SChris Fallin // Likewise, branch_block_arg_succ_range is indexed by block 483a0318f36SChris Fallin // so must be reversed. 4842c409535SJamey Sharp self.vcode.branch_block_arg_succ_range.reverse_index(); 485a0318f36SChris Fallin 486a0318f36SChris Fallin // To translate an instruction index *endpoint* in reversed 487a0318f36SChris Fallin // order to forward order, compute `n_insts - i`. 488a0318f36SChris Fallin // 489a0318f36SChris Fallin // Why not `n_insts - 1 - i`? That would be correct to 490a0318f36SChris Fallin // translate an individual instruction index (for ten insts 0 491a0318f36SChris Fallin // to 9 inclusive, inst 0 becomes 9, and inst 9 becomes 492a0318f36SChris Fallin // 0). But for the usual inclusive-start, exclusive-end range 493a0318f36SChris Fallin // idiom, inclusive starts become exclusive ends and 494a0318f36SChris Fallin // vice-versa, so e.g. an (inclusive) start of 0 becomes an 495a0318f36SChris Fallin // (exclusive) end of 10. 496a0318f36SChris Fallin let translate = |inst: InsnIndex| InsnIndex::new(n_insts - inst.index()); 497a0318f36SChris Fallin 498a0318f36SChris Fallin // Generate debug-value labels based on per-label maps. 499a0318f36SChris Fallin for (label, tuples) in &self.debug_info { 500a0318f36SChris Fallin for &(start, end, vreg) in tuples { 5013aa32064SJamey Sharp let vreg = vregs.resolve_vreg_alias(vreg); 502a0318f36SChris Fallin let fwd_start = translate(end); 503a0318f36SChris Fallin let fwd_end = translate(start); 504a0318f36SChris Fallin self.vcode 505a0318f36SChris Fallin .debug_value_labels 506a0318f36SChris Fallin .push((vreg, fwd_start, fwd_end, label.as_u32())); 507a0318f36SChris Fallin } 508a0318f36SChris Fallin } 509a0318f36SChris Fallin 510a0318f36SChris Fallin // Now sort debug value labels by VReg, as required 511a0318f36SChris Fallin // by regalloc2. 512a0318f36SChris Fallin self.vcode 513a0318f36SChris Fallin .debug_value_labels 514a0318f36SChris Fallin .sort_unstable_by_key(|(vreg, _, _, _)| *vreg); 515a0318f36SChris Fallin } 516a0318f36SChris Fallin 5173aa32064SJamey Sharp fn collect_operands(&mut self, vregs: &VRegAllocator<I>) { 5185ded0f4eSUlrich Weigand let allocatable = PRegSet::from(self.vcode.abi.machine_env()); 519d180b907SJamey Sharp for (i, insn) in self.vcode.insts.iter_mut().enumerate() { 520a0318f36SChris Fallin // Push operands from the instruction onto the operand list. 521a0318f36SChris Fallin // 522a0318f36SChris Fallin // We rename through the vreg alias table as we collect 523a0318f36SChris Fallin // the operands. This is better than a separate post-pass 524a0318f36SChris Fallin // over operands, because it has more cache locality: 525a0318f36SChris Fallin // operands only need to pass through L1 once. This is 526a0318f36SChris Fallin // also better than renaming instructions' 527a0318f36SChris Fallin // operands/registers while lowering, because here we only 528a0318f36SChris Fallin // need to do the `match` over the instruction to visit 529a0318f36SChris Fallin // its register fields (which is slow, branchy code) once. 530a0318f36SChris Fallin 531a007e02bSTrevor Elliott let mut op_collector = 532a007e02bSTrevor Elliott OperandCollector::new(&mut self.vcode.operands, allocatable, |vreg| { 5333aa32064SJamey Sharp vregs.resolve_vreg_alias(vreg) 534a0318f36SChris Fallin }); 535a0318f36SChris Fallin insn.get_operands(&mut op_collector); 536a0318f36SChris Fallin let (ops, clobbers) = op_collector.finish(); 5372c409535SJamey Sharp self.vcode.operand_ranges.push_end(ops); 538a0318f36SChris Fallin 539b2e28b91SChris Fallin if clobbers != PRegSet::default() { 540b2e28b91SChris Fallin self.vcode.clobbers.insert(InsnIndex::new(i), clobbers); 541a0318f36SChris Fallin } 542a0318f36SChris Fallin 543a0318f36SChris Fallin if let Some((dst, src)) = insn.is_move() { 544fac4a915STrevor Elliott // We should never see non-virtual registers present in move 545fac4a915STrevor Elliott // instructions. 546fac4a915STrevor Elliott assert!( 547fac4a915STrevor Elliott src.is_virtual(), 548a0442ea0SHamir Mahal "the real register {src:?} was used as the source of a move instruction" 549fac4a915STrevor Elliott ); 550fac4a915STrevor Elliott assert!( 551fac4a915STrevor Elliott dst.to_reg().is_virtual(), 552fac4a915STrevor Elliott "the real register {:?} was used as the destination of a move instruction", 553fac4a915STrevor Elliott dst.to_reg() 554fac4a915STrevor Elliott ); 555a0318f36SChris Fallin } 556a0318f36SChris Fallin } 557a0318f36SChris Fallin 558a0318f36SChris Fallin // Translate blockparam args via the vreg aliases table as well. 559a0318f36SChris Fallin for arg in &mut self.vcode.branch_block_args { 5603aa32064SJamey Sharp let new_arg = vregs.resolve_vreg_alias(*arg); 5618d022434SBenjamin Bouvier trace!("operandcollector: block arg {:?} -> {:?}", arg, new_arg); 562a0318f36SChris Fallin *arg = new_arg; 563a0318f36SChris Fallin } 564a0318f36SChris Fallin } 565a0318f36SChris Fallin 566a0318f36SChris Fallin /// Build the final VCode. 5673aa32064SJamey Sharp pub fn build(mut self, mut vregs: VRegAllocator<I>) -> VCode<I> { 5683aa32064SJamey Sharp self.vcode.vreg_types = take(&mut vregs.vreg_types); 5693aa32064SJamey Sharp self.vcode.facts = take(&mut vregs.facts); 570d94173eaSTrevor Elliott 571a0318f36SChris Fallin if self.direction == VCodeBuildDirection::Backward { 5723aa32064SJamey Sharp self.reverse_and_finalize(&vregs); 573a0318f36SChris Fallin } 5743aa32064SJamey Sharp self.collect_operands(&vregs); 5752154c63dSAlex Crichton 576a0318f36SChris Fallin self.compute_preds_from_succs(); 577a0318f36SChris Fallin self.vcode.debug_value_labels.sort_unstable(); 578d180b907SJamey Sharp 5793aa32064SJamey Sharp // At this point, nothing in the vcode should mention any 5803aa32064SJamey Sharp // VReg which has been aliased. All the appropriate rewriting 5813aa32064SJamey Sharp // should have happened above. Just to be sure, let's 5823aa32064SJamey Sharp // double-check each field which has vregs. 5833aa32064SJamey Sharp // Note: can't easily check vcode.insts, resolved in collect_operands. 5843aa32064SJamey Sharp // Operands are resolved in collect_operands. 5853aa32064SJamey Sharp vregs.debug_assert_no_vreg_aliases(self.vcode.operands.iter().map(|op| op.vreg())); 5863aa32064SJamey Sharp // Currently block params are never aliased to another vreg. 5873aa32064SJamey Sharp vregs.debug_assert_no_vreg_aliases(self.vcode.block_params.iter().copied()); 5883aa32064SJamey Sharp // Branch block args are resolved in collect_operands. 5893aa32064SJamey Sharp vregs.debug_assert_no_vreg_aliases(self.vcode.branch_block_args.iter().copied()); 5903aa32064SJamey Sharp // Debug value labels are resolved in reverse_and_finalize. 5913aa32064SJamey Sharp vregs.debug_assert_no_vreg_aliases( 5923aa32064SJamey Sharp self.vcode.debug_value_labels.iter().map(|&(vreg, ..)| vreg), 5933aa32064SJamey Sharp ); 5943aa32064SJamey Sharp // Facts are resolved eagerly during set_vreg_alias. 5953aa32064SJamey Sharp vregs.debug_assert_no_vreg_aliases( 5963aa32064SJamey Sharp self.vcode 5973aa32064SJamey Sharp .facts 5983aa32064SJamey Sharp .iter() 5993aa32064SJamey Sharp .zip(&vregs.vreg_types) 6003aa32064SJamey Sharp .enumerate() 6013aa32064SJamey Sharp .filter(|(_, (fact, _))| fact.is_some()) 6023aa32064SJamey Sharp .map(|(vreg, (_, &ty))| { 6033aa32064SJamey Sharp let (regclasses, _) = I::rc_for_type(ty).unwrap(); 6043aa32064SJamey Sharp VReg::new(vreg, regclasses[0]) 6053aa32064SJamey Sharp }), 6063aa32064SJamey Sharp ); 6073aa32064SJamey Sharp 608a0318f36SChris Fallin self.vcode 609d8357426SChris Fallin } 610e20b4244SNick Fitzgerald 611e20b4244SNick Fitzgerald /// Add a user stack map for the associated instruction. 612e20b4244SNick Fitzgerald pub fn add_user_stack_map( 613e20b4244SNick Fitzgerald &mut self, 614e20b4244SNick Fitzgerald inst: BackwardsInsnIndex, 615e20b4244SNick Fitzgerald entries: &[ir::UserStackMapEntry], 616e20b4244SNick Fitzgerald ) { 617e20b4244SNick Fitzgerald let stack_map = ir::UserStackMap::new(entries, self.vcode.abi.sized_stackslot_offsets()); 618e20b4244SNick Fitzgerald let old_entry = self.vcode.user_stack_maps.insert(inst, stack_map); 619e20b4244SNick Fitzgerald debug_assert!(old_entry.is_none()); 620e20b4244SNick Fitzgerald } 621a3d6e407SChris Fallin 622a3d6e407SChris Fallin /// Add debug tags for the associated instruction. 623a3d6e407SChris Fallin pub fn add_debug_tags(&mut self, inst: BackwardsInsnIndex, entries: &[ir::DebugTag]) { 624a3d6e407SChris Fallin let start = u32::try_from(self.vcode.debug_tag_pool.len()).unwrap(); 625a3d6e407SChris Fallin self.vcode.debug_tag_pool.extend(entries.iter().cloned()); 626a3d6e407SChris Fallin let end = u32::try_from(self.vcode.debug_tag_pool.len()).unwrap(); 627a3d6e407SChris Fallin self.vcode.debug_tags.insert(inst, start..end); 628a3d6e407SChris Fallin } 629d8357426SChris Fallin } 630d8357426SChris Fallin 631d4a4d4f9SSingleAccretion const NO_INST_OFFSET: CodeOffset = u32::MAX; 632d4a4d4f9SSingleAccretion 633d8357426SChris Fallin impl<I: VCodeInst> VCode<I> { 634d8357426SChris Fallin /// New empty VCode. 635c5bbc874SBenjamin Bouvier fn new( 636f18a1f14SNick Fitzgerald sigs: SigSet, 637f0c60f46SNick Fitzgerald abi: Callee<I::ABIMachineSpec>, 638c5bbc874SBenjamin Bouvier emit_info: I::Info, 639c5bbc874SBenjamin Bouvier block_order: BlockLoweringOrder, 64083f182b3SAndrew Brown constants: VCodeConstants, 6412af0a1f7Sbjorn3 log2_min_function_alignment: u8, 642e20b4244SNick Fitzgerald ) -> Self { 643a0318f36SChris Fallin let n_blocks = block_order.lowered_order().len(); 644d8357426SChris Fallin VCode { 645f18a1f14SNick Fitzgerald sigs, 646d8357426SChris Fallin vreg_types: vec![], 647a0318f36SChris Fallin insts: Vec::with_capacity(10 * n_blocks), 648e20b4244SNick Fitzgerald user_stack_maps: FxHashMap::default(), 649a3d6e407SChris Fallin debug_tags: FxHashMap::default(), 650a3d6e407SChris Fallin debug_tag_pool: vec![], 651a0318f36SChris Fallin operands: Vec::with_capacity(30 * n_blocks), 6522c409535SJamey Sharp operand_ranges: Ranges::with_capacity(10 * n_blocks), 653b2e28b91SChris Fallin clobbers: FxHashMap::default(), 654a0318f36SChris Fallin srclocs: Vec::with_capacity(10 * n_blocks), 655a0318f36SChris Fallin entry: BlockIndex::new(0), 6562c409535SJamey Sharp block_ranges: Ranges::with_capacity(n_blocks), 6572c409535SJamey Sharp block_succ_range: Ranges::with_capacity(n_blocks), 6580f4c0d4aSJamey Sharp block_succs: Vec::with_capacity(n_blocks), 6592c409535SJamey Sharp block_pred_range: Ranges::default(), 6600f4c0d4aSJamey Sharp block_preds: Vec::new(), 6612c409535SJamey Sharp block_params_range: Ranges::with_capacity(n_blocks), 662a0318f36SChris Fallin block_params: Vec::with_capacity(5 * n_blocks), 663a0318f36SChris Fallin branch_block_args: Vec::with_capacity(10 * n_blocks), 6642c409535SJamey Sharp branch_block_arg_range: Ranges::with_capacity(2 * n_blocks), 6652c409535SJamey Sharp branch_block_arg_succ_range: Ranges::with_capacity(n_blocks), 66672e6be93SChris Fallin block_order, 667d8357426SChris Fallin abi, 668c5bbc874SBenjamin Bouvier emit_info, 66983f182b3SAndrew Brown constants, 670a0318f36SChris Fallin debug_value_labels: vec![], 671f466aa26SChris Fallin facts: vec![], 6722af0a1f7Sbjorn3 log2_min_function_alignment, 673d8357426SChris Fallin } 674d8357426SChris Fallin } 675d8357426SChris Fallin 676d8357426SChris Fallin /// Get the number of blocks. Block indices will be in the range `0 .. 677d8357426SChris Fallin /// (self.num_blocks() - 1)`. 678d8357426SChris Fallin pub fn num_blocks(&self) -> usize { 679d8357426SChris Fallin self.block_ranges.len() 680d8357426SChris Fallin } 681d8357426SChris Fallin 6826fe69d00SNick Fitzgerald /// The number of lowered instructions. 6836fe69d00SNick Fitzgerald pub fn num_insts(&self) -> usize { 6846fe69d00SNick Fitzgerald self.insts.len() 6856fe69d00SNick Fitzgerald } 6866fe69d00SNick Fitzgerald 6873b85d838SPaul Nodet fn compute_clobbers_and_function_calls( 6883fe9c3c7SPaul Nodet &self, 6893fe9c3c7SPaul Nodet regalloc: ®alloc2::Output, 6903b85d838SPaul Nodet ) -> (Vec<Writable<RealReg>>, FunctionCalls) { 6911a17dfb5SJamey Sharp let mut clobbered = PRegSet::default(); 6923b85d838SPaul Nodet let mut function_calls = FunctionCalls::None; 693d8357426SChris Fallin 694a0318f36SChris Fallin // All moves are included in clobbers. 6951a17dfb5SJamey Sharp for (_, Edit::Move { to, .. }) in ®alloc.edits { 696a0318f36SChris Fallin if let Some(preg) = to.as_reg() { 6971a17dfb5SJamey Sharp clobbered.add(preg); 698a0318f36SChris Fallin } 699d8357426SChris Fallin } 700d8357426SChris Fallin 7012c409535SJamey Sharp for (i, range) in self.operand_ranges.iter() { 7022c409535SJamey Sharp let operands = &self.operands[range.clone()]; 7032c409535SJamey Sharp let allocs = ®alloc.allocs[range]; 704a0318f36SChris Fallin for (operand, alloc) in operands.iter().zip(allocs.iter()) { 7051a17dfb5SJamey Sharp if operand.kind() == OperandKind::Def { 706a0318f36SChris Fallin if let Some(preg) = alloc.as_reg() { 7071a17dfb5SJamey Sharp clobbered.add(preg); 708a0318f36SChris Fallin } 70908353fccSChris Fallin } 710d8357426SChris Fallin } 711d8357426SChris Fallin 7123b85d838SPaul Nodet function_calls.update(self.insts[i].call_type()); 7133fe9c3c7SPaul Nodet 714a0318f36SChris Fallin // Also add explicitly-clobbered registers. 715a62b396fSChris Fallin // 716a62b396fSChris Fallin // Skip merging this instruction's clobber list if not 717a62b396fSChris Fallin // "included in clobbers" as per the MachInst. (Some 718a62b396fSChris Fallin // backends use this to implement ABI specifics; e.g., 719a62b396fSChris Fallin // excluding calls of the same ABI as the current function 720a62b396fSChris Fallin // from clobbers, because by definition everything 721a62b396fSChris Fallin // clobbered by the call can be clobbered by this function 722a62b396fSChris Fallin // without saving as well. 723a62b396fSChris Fallin // 724a62b396fSChris Fallin // This is important for a particular optimization: when 725a62b396fSChris Fallin // some registers are "half-clobbered", e.g. vector/float 726a62b396fSChris Fallin // registers on aarch64, we want them to be seen as 727a62b396fSChris Fallin // clobbered by regalloc so it avoids carrying values 728a62b396fSChris Fallin // across calls in these registers but not seen as 729a62b396fSChris Fallin // clobbered by prologue generation here (because the 730a62b396fSChris Fallin // actual half-clobber implied by the clobber list fits 731a62b396fSChris Fallin // within the clobbers that we allow without 732a62b396fSChris Fallin // clobber-saves). 733a62b396fSChris Fallin if self.insts[i].is_included_in_clobbers() { 7341a17dfb5SJamey Sharp if let Some(&inst_clobbered) = self.clobbers.get(&InsnIndex::new(i)) { 7351a17dfb5SJamey Sharp clobbered.union_from(inst_clobbered); 736a0318f36SChris Fallin } 737a0318f36SChris Fallin } 738a62b396fSChris Fallin } 739d8357426SChris Fallin 7403fe9c3c7SPaul Nodet let clobbered_regs = clobbered 7411a17dfb5SJamey Sharp .into_iter() 7421a17dfb5SJamey Sharp .map(|preg| Writable::from_reg(RealReg::from(preg))) 7433fe9c3c7SPaul Nodet .collect(); 7443fe9c3c7SPaul Nodet 7453b85d838SPaul Nodet (clobbered_regs, function_calls) 746d8357426SChris Fallin } 747d8357426SChris Fallin 748a0318f36SChris Fallin /// Emit the instructions to a `MachBuffer`, containing fixed-up 749a0318f36SChris Fallin /// code and external reloc/trap/etc. records ready for use. Takes 750a0318f36SChris Fallin /// the regalloc results as well. 751a0318f36SChris Fallin /// 752a0318f36SChris Fallin /// Returns the machine code itself, and optionally metadata 753a0318f36SChris Fallin /// and/or a disassembly, as an `EmitResult`. The `VCode` itself 754a0318f36SChris Fallin /// is consumed by the emission process. 75511a2ef01SChris Fallin pub fn emit( 756a0318f36SChris Fallin mut self, 757a0318f36SChris Fallin regalloc: ®alloc2::Output, 758a0318f36SChris Fallin want_disasm: bool, 75949dd8fd7SAlex Crichton flags: &settings::Flags, 7607eb89140SRemo Senekowitsch ctrl_plane: &mut ControlPlane, 76149dd8fd7SAlex Crichton ) -> EmitResult 762d8357426SChris Fallin where 763f18a1f14SNick Fitzgerald I: VCodeInst, 764d8357426SChris Fallin { 7652b9fefe8SChris Fallin let _tt = timing::vcode_emit(); 76672e6be93SChris Fallin let mut buffer = MachBuffer::new(); 7672af0a1f7Sbjorn3 buffer.set_log2_min_function_alignment(self.log2_min_function_alignment); 76811a2ef01SChris Fallin let mut bb_starts: Vec<Option<CodeOffset>> = vec![]; 769d8357426SChris Fallin 77049dd8fd7SAlex Crichton // The first M MachLabels are reserved for block indices. 771a0318f36SChris Fallin buffer.reserve_labels_for_blocks(self.num_blocks()); 77249dd8fd7SAlex Crichton 77349dd8fd7SAlex Crichton // Register all allocated constants with the `MachBuffer` to ensure that 77449dd8fd7SAlex Crichton // any references to the constants during instructions can be handled 77549dd8fd7SAlex Crichton // correctly. 77649dd8fd7SAlex Crichton buffer.register_constants(&self.constants); 777d8357426SChris Fallin 778ef1b2d2fSChris Fallin // Construct the final order we emit code in: cold blocks at the end. 779ef1b2d2fSChris Fallin let mut final_order: SmallVec<[BlockIndex; 16]> = smallvec![]; 780ef1b2d2fSChris Fallin let mut cold_blocks: SmallVec<[BlockIndex; 16]> = smallvec![]; 781ef1b2d2fSChris Fallin for block in 0..self.num_blocks() { 782a0318f36SChris Fallin let block = BlockIndex::new(block); 783ef1b2d2fSChris Fallin if self.block_order.is_cold(block) { 784ef1b2d2fSChris Fallin cold_blocks.push(block); 785ef1b2d2fSChris Fallin } else { 786ef1b2d2fSChris Fallin final_order.push(block); 787ef1b2d2fSChris Fallin } 788ef1b2d2fSChris Fallin } 789d9d64694SChris Fallin final_order.extend(cold_blocks.clone()); 790ef1b2d2fSChris Fallin 791a0318f36SChris Fallin // Compute/save info we need for the prologue: clobbers and 792a0318f36SChris Fallin // number of spillslots. 793a0318f36SChris Fallin // 794a0318f36SChris Fallin // We clone `abi` here because we will mutate it as we 795a0318f36SChris Fallin // generate the prologue and set other info, but we can't 796a0318f36SChris Fallin // mutate `VCode`. The info it usually carries prior to 797a0318f36SChris Fallin // setting clobbers is fairly minimal so this should be 798a0318f36SChris Fallin // relatively cheap. 7993b85d838SPaul Nodet let (clobbers, function_calls) = self.compute_clobbers_and_function_calls(regalloc); 8003b85d838SPaul Nodet self.abi.compute_frame_layout( 8013b85d838SPaul Nodet &self.sigs, 8023b85d838SPaul Nodet regalloc.num_spillslots, 8033b85d838SPaul Nodet clobbers, 8043b85d838SPaul Nodet function_calls, 8053b85d838SPaul Nodet ); 806a0318f36SChris Fallin 807ef1b2d2fSChris Fallin // Emit blocks. 808964c6087SChris Fallin let mut cur_srcloc = None; 80911a2ef01SChris Fallin let mut last_offset = None; 810a0318f36SChris Fallin let mut inst_offsets = vec![]; 8110889323aSSSD let mut state = I::State::new(&self.abi, core::mem::take(ctrl_plane)); 812a0318f36SChris Fallin 813a0318f36SChris Fallin let mut disasm = String::new(); 814a0318f36SChris Fallin 815a0318f36SChris Fallin if !self.debug_value_labels.is_empty() { 816d4a4d4f9SSingleAccretion inst_offsets.resize(self.insts.len(), NO_INST_OFFSET); 817a0318f36SChris Fallin } 818a0318f36SChris Fallin 819863659e0SChris Fallin // Count edits per block ahead of time; this is needed for 820863659e0SChris Fallin // lookahead island emission. (We could derive it per-block 821863659e0SChris Fallin // with binary search in the edit list, but it's more 822863659e0SChris Fallin // efficient to do it in one pass here.) 823863659e0SChris Fallin let mut ra_edits_per_block: SmallVec<[u32; 64]> = smallvec![]; 824863659e0SChris Fallin let mut edit_idx = 0; 825863659e0SChris Fallin for block in 0..self.num_blocks() { 8262c409535SJamey Sharp let end_inst = InsnIndex::new(self.block_ranges.get(block).end); 827863659e0SChris Fallin let start_edit_idx = edit_idx; 828863659e0SChris Fallin while edit_idx < regalloc.edits.len() && regalloc.edits[edit_idx].0.inst() < end_inst { 829863659e0SChris Fallin edit_idx += 1; 830863659e0SChris Fallin } 831863659e0SChris Fallin let end_edit_idx = edit_idx; 832863659e0SChris Fallin ra_edits_per_block.push((end_edit_idx - start_edit_idx) as u32); 833863659e0SChris Fallin } 834863659e0SChris Fallin 835d8b29089SAnton Kirilov let is_forward_edge_cfi_enabled = self.abi.is_forward_edge_cfi_enabled(); 836475d1ba5SAlex Crichton let mut bb_padding = match flags.bb_padding_log2_minus_one() { 83749dd8fd7SAlex Crichton 0 => Vec::new(), 83849dd8fd7SAlex Crichton n => vec![0; 1 << (n - 1)], 83949dd8fd7SAlex Crichton }; 840475d1ba5SAlex Crichton let mut total_bb_padding = 0; 841d8b29089SAnton Kirilov 842863659e0SChris Fallin for (block_order_idx, &block) in final_order.iter().enumerate() { 8438d022434SBenjamin Bouvier trace!("emitting block {:?}", block); 84460e4a004SAfonso Bordado 84560e4a004SAfonso Bordado // Call the new block hook for state 84660e4a004SAfonso Bordado state.on_new_block(); 84760e4a004SAfonso Bordado 84860e4a004SAfonso Bordado // Emit NOPs to align the block. 84972e6be93SChris Fallin let new_offset = I::align_basic_block(buffer.cur_offset()); 85072e6be93SChris Fallin while new_offset > buffer.cur_offset() { 851d8357426SChris Fallin // Pad with NOPs up to the aligned block offset. 85272e6be93SChris Fallin let nop = I::gen_nop((new_offset - buffer.cur_offset()) as usize); 8537d703191SJamey Sharp nop.emit(&mut buffer, &self.emit_info, &mut Default::default()); 854d8357426SChris Fallin } 85572e6be93SChris Fallin assert_eq!(buffer.cur_offset(), new_offset); 856d8357426SChris Fallin 857a0318f36SChris Fallin let do_emit = |inst: &I, 858a0318f36SChris Fallin disasm: &mut String, 859a0318f36SChris Fallin buffer: &mut MachBuffer<I>, 860a0318f36SChris Fallin state: &mut I::State| { 8612986f6b0SChris Fallin if want_disasm && !inst.is_args() { 862a0318f36SChris Fallin let mut s = state.clone(); 8637d703191SJamey Sharp writeln!(disasm, " {}", inst.pretty_print_inst(&mut s)).unwrap(); 864a0318f36SChris Fallin } 8657d703191SJamey Sharp inst.emit(buffer, &self.emit_info, state); 866a0318f36SChris Fallin }; 867a0318f36SChris Fallin 868a0318f36SChris Fallin // Is this the first block? Emit the prologue directly if so. 869a0318f36SChris Fallin if block == self.entry { 8708d022434SBenjamin Bouvier trace!(" -> entry block"); 8718a9b1a90SBenjamin Bouvier buffer.start_srcloc(Default::default()); 87286652959SUlrich Weigand for inst in &self.abi.gen_prologue() { 8737d703191SJamey Sharp do_emit(&inst, &mut disasm, &mut buffer, &mut state); 874a0318f36SChris Fallin } 875a0318f36SChris Fallin buffer.end_srcloc(); 876d9d64694SChris Fallin } 877d9d64694SChris Fallin 878a0318f36SChris Fallin // Now emit the regular block body. 87911a2ef01SChris Fallin 8807eb89140SRemo Senekowitsch buffer.bind_label(MachLabel::from_block(block), state.ctrl_plane_mut()); 881a0318f36SChris Fallin 882a0318f36SChris Fallin if want_disasm { 883a0318f36SChris Fallin writeln!(&mut disasm, "block{}:", block.index()).unwrap(); 884a0318f36SChris Fallin } 885a0318f36SChris Fallin 88649dd8fd7SAlex Crichton if flags.machine_code_cfg_info() { 88711a2ef01SChris Fallin // Track BB starts. If we have backed up due to MachBuffer 88811a2ef01SChris Fallin // branch opts, note that the removed blocks were removed. 88911a2ef01SChris Fallin let cur_offset = buffer.cur_offset(); 89011a2ef01SChris Fallin if last_offset.is_some() && cur_offset <= last_offset.unwrap() { 89111a2ef01SChris Fallin for i in (0..bb_starts.len()).rev() { 89211a2ef01SChris Fallin if bb_starts[i].is_some() && cur_offset > bb_starts[i].unwrap() { 89311a2ef01SChris Fallin break; 89411a2ef01SChris Fallin } 89511a2ef01SChris Fallin bb_starts[i] = None; 89611a2ef01SChris Fallin } 89711a2ef01SChris Fallin } 89811a2ef01SChris Fallin bb_starts.push(Some(cur_offset)); 89911a2ef01SChris Fallin last_offset = Some(cur_offset); 900800cf25bSChris Fallin } 90111a2ef01SChris Fallin 902d8b29089SAnton Kirilov if let Some(block_start) = I::gen_block_start( 903d8b29089SAnton Kirilov self.block_order.is_indirect_branch_target(block), 904d8b29089SAnton Kirilov is_forward_edge_cfi_enabled, 905d8b29089SAnton Kirilov ) { 9067d703191SJamey Sharp do_emit(&block_start, &mut disasm, &mut buffer, &mut state); 907d8b29089SAnton Kirilov } 908d8b29089SAnton Kirilov 909a0318f36SChris Fallin for inst_or_edit in regalloc.block_insts_and_edits(&self, block) { 910a0318f36SChris Fallin match inst_or_edit { 911a0318f36SChris Fallin InstOrEdit::Inst(iix) => { 912a0318f36SChris Fallin if !self.debug_value_labels.is_empty() { 913a0318f36SChris Fallin // If we need to produce debug info, 914a0318f36SChris Fallin // record the offset of each instruction 915a0318f36SChris Fallin // so that we can translate value-label 916a0318f36SChris Fallin // ranges to machine-code offsets. 917a0318f36SChris Fallin 918a0318f36SChris Fallin // Cold blocks violate monotonicity 919a0318f36SChris Fallin // assumptions elsewhere (that 920a0318f36SChris Fallin // instructions in inst-index order are in 921a0318f36SChris Fallin // order in machine code), so we omit 922a0318f36SChris Fallin // their offsets here. Value-label range 923a0318f36SChris Fallin // generation below will skip empty ranges 924a0318f36SChris Fallin // and ranges with to-offsets of zero. 925a0318f36SChris Fallin if !self.block_order.is_cold(block) { 926a0318f36SChris Fallin inst_offsets[iix.index()] = buffer.cur_offset(); 927a0318f36SChris Fallin } 928a0318f36SChris Fallin } 929a0318f36SChris Fallin 930a0318f36SChris Fallin // Update the srcloc at this point in the buffer. 931a0318f36SChris Fallin let srcloc = self.srclocs[iix.index()]; 932964c6087SChris Fallin if cur_srcloc != Some(srcloc) { 933964c6087SChris Fallin if cur_srcloc.is_some() { 93472e6be93SChris Fallin buffer.end_srcloc(); 935b691770fSChris Fallin } 93672e6be93SChris Fallin buffer.start_srcloc(srcloc); 937964c6087SChris Fallin cur_srcloc = Some(srcloc); 938b691770fSChris Fallin } 939b691770fSChris Fallin 940a0318f36SChris Fallin // If this is a safepoint, compute a stack map 941a0318f36SChris Fallin // and pass it to the emit state. 942e20b4244SNick Fitzgerald let stack_map_disasm = if self.insts[iix.index()].is_safepoint() { 943e20b4244SNick Fitzgerald let (user_stack_map, user_stack_map_disasm) = { 944e20b4244SNick Fitzgerald // The `user_stack_maps` is keyed by reverse 945e20b4244SNick Fitzgerald // instruction index, so we must flip the 946e20b4244SNick Fitzgerald // index. We can't put this into a helper method 947e20b4244SNick Fitzgerald // due to borrowck issues because parts of 948e20b4244SNick Fitzgerald // `self` are borrowed mutably elsewhere in this 949e20b4244SNick Fitzgerald // function. 950e20b4244SNick Fitzgerald let index = iix.to_backwards_insn_index(self.num_insts()); 951e20b4244SNick Fitzgerald let user_stack_map = self.user_stack_maps.remove(&index); 952a3d6e407SChris Fallin let user_stack_map_disasm = if want_disasm { 953a3d6e407SChris Fallin user_stack_map.as_ref().map(|m| format!(" ; {m:?}")) 954a3d6e407SChris Fallin } else { 955a3d6e407SChris Fallin None 956a3d6e407SChris Fallin }; 957e20b4244SNick Fitzgerald (user_stack_map, user_stack_map_disasm) 958e20b4244SNick Fitzgerald }; 959e20b4244SNick Fitzgerald 960c0c3a68cSNick Fitzgerald state.pre_safepoint(user_stack_map); 961e20b4244SNick Fitzgerald 962e20b4244SNick Fitzgerald user_stack_map_disasm 963e20b4244SNick Fitzgerald } else { 964e20b4244SNick Fitzgerald None 965e20b4244SNick Fitzgerald }; 96608353fccSChris Fallin 967a3d6e407SChris Fallin // Place debug tags in the emission buffer 968a3d6e407SChris Fallin // either at the offset prior to the 969a3d6e407SChris Fallin // instruction or after the instruction, 970a3d6e407SChris Fallin // depending on whether this is a call. See 971a3d6e407SChris Fallin // the documentation on [`MachDebugTagPos`] 972a3d6e407SChris Fallin // for details on why. 973a3d6e407SChris Fallin let mut debug_tag_disasm = None; 974a3d6e407SChris Fallin let mut place_debug_tags = 975a3d6e407SChris Fallin |this: &VCode<I>, pos: MachDebugTagPos, buffer: &mut MachBuffer<I>| { 976a3d6e407SChris Fallin // As above, translate the forward instruction 977a3d6e407SChris Fallin // index to a backward index for the lookup. 978a3d6e407SChris Fallin let debug_tag_range = { 979a3d6e407SChris Fallin let index = iix.to_backwards_insn_index(this.num_insts()); 980a3d6e407SChris Fallin this.debug_tags.get(&index) 981a3d6e407SChris Fallin }; 982a3d6e407SChris Fallin if let Some(range) = debug_tag_range { 983a3d6e407SChris Fallin let start = usize::try_from(range.start).unwrap(); 984a3d6e407SChris Fallin let end = usize::try_from(range.end).unwrap(); 985a3d6e407SChris Fallin let tags = &this.debug_tag_pool[start..end]; 986a3d6e407SChris Fallin 987a3d6e407SChris Fallin if want_disasm { 988a3d6e407SChris Fallin debug_tag_disasm = 989a3d6e407SChris Fallin Some(format!(" ; ^-- debug @ {pos:?}: {tags:?}")); 990a3d6e407SChris Fallin } 991a3d6e407SChris Fallin buffer.push_debug_tags(pos, tags); 992a3d6e407SChris Fallin } 993a3d6e407SChris Fallin }; 994a3d6e407SChris Fallin let debug_tag_pos = 995a3d6e407SChris Fallin if self.insts[iix.index()].call_type() == CallType::Regular { 996a3d6e407SChris Fallin MachDebugTagPos::Post 997a3d6e407SChris Fallin } else { 998a3d6e407SChris Fallin MachDebugTagPos::Pre 999a3d6e407SChris Fallin }; 1000a3d6e407SChris Fallin 1001a3d6e407SChris Fallin if debug_tag_pos == MachDebugTagPos::Pre { 1002a3d6e407SChris Fallin place_debug_tags(&self, debug_tag_pos, &mut buffer); 1003a3d6e407SChris Fallin } 1004a3d6e407SChris Fallin 1005a0318f36SChris Fallin // If the instruction we are about to emit is 1006a0318f36SChris Fallin // a return, place an epilogue at this point 1007a0318f36SChris Fallin // (and don't emit the return; the actual 1008a0318f36SChris Fallin // epilogue will contain it). 1009a0318f36SChris Fallin if self.insts[iix.index()].is_term() == MachTerminator::Ret { 1010a3d6e407SChris Fallin log::trace!("emitting epilogue"); 101186652959SUlrich Weigand for inst in self.abi.gen_epilogue() { 10127d703191SJamey Sharp do_emit(&inst, &mut disasm, &mut buffer, &mut state); 1013a0318f36SChris Fallin } 1014c84d6be6SChris Fallin } else { 1015d48d6102SJamey Sharp // Update the operands for this inst using the 1016d48d6102SJamey Sharp // allocations from the regalloc result. 1017d48d6102SJamey Sharp let mut allocs = regalloc.inst_allocs(iix).iter(); 1018d48d6102SJamey Sharp self.insts[iix.index()].get_operands( 1019d48d6102SJamey Sharp &mut |reg: &mut Reg, constraint, _kind, _pos| { 1020a62b396fSChris Fallin let alloc = 1021a62b396fSChris Fallin allocs.next().expect("enough allocations for all operands"); 1022d48d6102SJamey Sharp 1023a62b396fSChris Fallin if let Some(alloc) = alloc.as_reg() { 1024a62b396fSChris Fallin let alloc: Reg = alloc.into(); 1025d48d6102SJamey Sharp if let OperandConstraint::FixedReg(rreg) = constraint { 1026d48d6102SJamey Sharp debug_assert_eq!(Reg::from(rreg), alloc); 1027d48d6102SJamey Sharp } 1028d48d6102SJamey Sharp *reg = alloc; 1029a62b396fSChris Fallin } else if let Some(alloc) = alloc.as_stack() { 1030a62b396fSChris Fallin let alloc: Reg = alloc.into(); 1031a62b396fSChris Fallin *reg = alloc; 1032a62b396fSChris Fallin } 1033d48d6102SJamey Sharp }, 1034d48d6102SJamey Sharp ); 1035d48d6102SJamey Sharp debug_assert!(allocs.next().is_none()); 1036d48d6102SJamey Sharp 1037a3d6e407SChris Fallin log::trace!("emitting: {:?}", self.insts[iix.index()]); 1038a3d6e407SChris Fallin 1039a0318f36SChris Fallin // Emit the instruction! 1040a0318f36SChris Fallin do_emit( 1041a0318f36SChris Fallin &self.insts[iix.index()], 1042a0318f36SChris Fallin &mut disasm, 1043a0318f36SChris Fallin &mut buffer, 1044a0318f36SChris Fallin &mut state, 1045a0318f36SChris Fallin ); 1046a3d6e407SChris Fallin 1047a3d6e407SChris Fallin if debug_tag_pos == MachDebugTagPos::Post { 1048a3d6e407SChris Fallin place_debug_tags(&self, debug_tag_pos, &mut buffer); 1049a3d6e407SChris Fallin } 1050a3d6e407SChris Fallin 1051e20b4244SNick Fitzgerald if let Some(stack_map_disasm) = stack_map_disasm { 1052e20b4244SNick Fitzgerald disasm.push_str(&stack_map_disasm); 1053e20b4244SNick Fitzgerald disasm.push('\n'); 1054e20b4244SNick Fitzgerald } 1055a3d6e407SChris Fallin if let Some(debug_tag_disasm) = debug_tag_disasm { 1056a3d6e407SChris Fallin disasm.push_str(&debug_tag_disasm); 1057a3d6e407SChris Fallin disasm.push('\n'); 1058a3d6e407SChris Fallin } 1059c84d6be6SChris Fallin } 1060c84d6be6SChris Fallin } 1061a0318f36SChris Fallin 1062a0318f36SChris Fallin InstOrEdit::Edit(Edit::Move { from, to }) => { 1063a0318f36SChris Fallin // Create a move/spill/reload instruction and 1064a0318f36SChris Fallin // immediately emit it. 1065a0318f36SChris Fallin match (from.as_reg(), to.as_reg()) { 1066a0318f36SChris Fallin (Some(from), Some(to)) => { 1067a0318f36SChris Fallin // Reg-to-reg move. 1068a0318f36SChris Fallin let from_rreg = Reg::from(from); 1069a0318f36SChris Fallin let to_rreg = Writable::from_reg(Reg::from(to)); 1070a0318f36SChris Fallin debug_assert_eq!(from.class(), to.class()); 1071a0318f36SChris Fallin let ty = I::canonical_type_for_rc(from.class()); 1072a0318f36SChris Fallin let mv = I::gen_move(to_rreg, from_rreg, ty); 10737d703191SJamey Sharp do_emit(&mv, &mut disasm, &mut buffer, &mut state); 1074a0318f36SChris Fallin } 1075a0318f36SChris Fallin (Some(from), None) => { 1076a0318f36SChris Fallin // Spill from register to spillslot. 1077a0318f36SChris Fallin let to = to.as_stack().unwrap(); 1078a0318f36SChris Fallin let from_rreg = RealReg::from(from); 1079a0318f36SChris Fallin let spill = self.abi.gen_spill(to, from_rreg); 10807d703191SJamey Sharp do_emit(&spill, &mut disasm, &mut buffer, &mut state); 1081a0318f36SChris Fallin } 1082a0318f36SChris Fallin (None, Some(to)) => { 1083a0318f36SChris Fallin // Load from spillslot to register. 1084a0318f36SChris Fallin let from = from.as_stack().unwrap(); 1085a0318f36SChris Fallin let to_rreg = Writable::from_reg(RealReg::from(to)); 1086a0318f36SChris Fallin let reload = self.abi.gen_reload(to_rreg, from); 10877d703191SJamey Sharp do_emit(&reload, &mut disasm, &mut buffer, &mut state); 1088a0318f36SChris Fallin } 1089a0318f36SChris Fallin (None, None) => { 1090a0318f36SChris Fallin panic!("regalloc2 should have eliminated stack-to-stack moves!"); 1091a0318f36SChris Fallin } 1092a0318f36SChris Fallin } 1093a0318f36SChris Fallin } 1094c84d6be6SChris Fallin } 1095d8357426SChris Fallin } 1096b691770fSChris Fallin 1097964c6087SChris Fallin if cur_srcloc.is_some() { 109872e6be93SChris Fallin buffer.end_srcloc(); 1099964c6087SChris Fallin cur_srcloc = None; 1100b691770fSChris Fallin } 110172e6be93SChris Fallin 110249dd8fd7SAlex Crichton // Do we need an island? Get the worst-case size of the next BB, add 110349dd8fd7SAlex Crichton // it to the optional padding behind the block, and pass this to the 110449dd8fd7SAlex Crichton // `MachBuffer` to determine if an island is necessary. 110549dd8fd7SAlex Crichton let worst_case_next_bb = if block_order_idx < final_order.len() - 1 { 1106863659e0SChris Fallin let next_block = final_order[block_order_idx + 1]; 11072c409535SJamey Sharp let next_block_range = self.block_ranges.get(next_block.index()); 11082c409535SJamey Sharp let next_block_size = next_block_range.len() as u32; 1109863659e0SChris Fallin let next_block_ra_insertions = ra_edits_per_block[next_block.index()]; 111049dd8fd7SAlex Crichton I::worst_case_size() * (next_block_size + next_block_ra_insertions) 111149dd8fd7SAlex Crichton } else { 111249dd8fd7SAlex Crichton 0 111349dd8fd7SAlex Crichton }; 111449dd8fd7SAlex Crichton let padding = if bb_padding.is_empty() { 111549dd8fd7SAlex Crichton 0 111649dd8fd7SAlex Crichton } else { 111749dd8fd7SAlex Crichton bb_padding.len() as u32 + I::LabelUse::ALIGN - 1 111849dd8fd7SAlex Crichton }; 111949dd8fd7SAlex Crichton if buffer.island_needed(padding + worst_case_next_bb) { 1120f8c03d5aSAlex Crichton buffer.emit_island(padding + worst_case_next_bb, ctrl_plane); 112172e6be93SChris Fallin } 112249dd8fd7SAlex Crichton 112349dd8fd7SAlex Crichton // Insert padding, if configured, to stress the `MachBuffer`'s 112449dd8fd7SAlex Crichton // relocation and island calculations. 1125475d1ba5SAlex Crichton // 1126475d1ba5SAlex Crichton // Padding can get quite large during fuzzing though so place a 1127475d1ba5SAlex Crichton // total cap on it where when a per-function threshold is exceeded 1128475d1ba5SAlex Crichton // the padding is turned back down to zero. This avoids a small-ish 1129475d1ba5SAlex Crichton // test case generating a GB+ memory footprint in Cranelift for 1130475d1ba5SAlex Crichton // example. 113149dd8fd7SAlex Crichton if !bb_padding.is_empty() { 113249dd8fd7SAlex Crichton buffer.put_data(&bb_padding); 113349dd8fd7SAlex Crichton buffer.align_to(I::LabelUse::ALIGN); 1134475d1ba5SAlex Crichton total_bb_padding += bb_padding.len(); 1135475d1ba5SAlex Crichton if total_bb_padding > (150 << 20) { 1136475d1ba5SAlex Crichton bb_padding = Vec::new(); 1137475d1ba5SAlex Crichton } 113872e6be93SChris Fallin } 1139d8357426SChris Fallin } 1140d8357426SChris Fallin 1141e20b4244SNick Fitzgerald debug_assert!( 1142e20b4244SNick Fitzgerald self.user_stack_maps.is_empty(), 1143e20b4244SNick Fitzgerald "any stack maps should have been consumed by instruction emission, still have: {:#?}", 1144e20b4244SNick Fitzgerald self.user_stack_maps, 1145e20b4244SNick Fitzgerald ); 1146e20b4244SNick Fitzgerald 1147d4a4d4f9SSingleAccretion // Do any optimizations on branches at tail of buffer, as if we had 1148d4a4d4f9SSingleAccretion // bound one last label. 1149d4a4d4f9SSingleAccretion buffer.optimize_branches(ctrl_plane); 1150d4a4d4f9SSingleAccretion 11517eb89140SRemo Senekowitsch // emission state is not needed anymore, move control plane back out 11527eb89140SRemo Senekowitsch *ctrl_plane = state.take_ctrl_plane(); 11537eb89140SRemo Senekowitsch 1154a0318f36SChris Fallin let func_body_len = buffer.cur_offset(); 1155de4af90aSYury Delendik 115611a2ef01SChris Fallin // Create `bb_edges` and final (filtered) `bb_starts`. 115711a2ef01SChris Fallin let mut bb_edges = vec![]; 1158a0318f36SChris Fallin let mut bb_offsets = vec![]; 115949dd8fd7SAlex Crichton if flags.machine_code_cfg_info() { 116011a2ef01SChris Fallin for block in 0..self.num_blocks() { 116111a2ef01SChris Fallin if bb_starts[block].is_none() { 116211a2ef01SChris Fallin // Block was deleted by MachBuffer; skip. 116311a2ef01SChris Fallin continue; 116411a2ef01SChris Fallin } 116511a2ef01SChris Fallin let from = bb_starts[block].unwrap(); 116611a2ef01SChris Fallin 1167a0318f36SChris Fallin bb_offsets.push(from); 116811a2ef01SChris Fallin // Resolve each `succ` label and add edges. 1169a0318f36SChris Fallin let succs = self.block_succs(BlockIndex::new(block)); 1170a0318f36SChris Fallin for &succ in succs.iter() { 1171a0318f36SChris Fallin let to = buffer.resolve_label_offset(MachLabel::from_block(succ)); 117211a2ef01SChris Fallin bb_edges.push((from, to)); 117311a2ef01SChris Fallin } 117411a2ef01SChris Fallin } 1175800cf25bSChris Fallin } 117611a2ef01SChris Fallin 1177d4a4d4f9SSingleAccretion self.monotonize_inst_offsets(&mut inst_offsets[..], func_body_len); 1178a0318f36SChris Fallin let value_labels_ranges = 1179a0318f36SChris Fallin self.compute_value_labels_ranges(regalloc, &inst_offsets[..], func_body_len); 1180a3d6e407SChris Fallin 1181a3d6e407SChris Fallin // Store metadata about frame layout in the MachBuffer. 1182a3d6e407SChris Fallin buffer.set_frame_layout(self.abi.frame_slot_metadata()); 1183a0318f36SChris Fallin 1184a0318f36SChris Fallin EmitResult { 118549dd8fd7SAlex Crichton buffer: buffer.finish(&self.constants, ctrl_plane), 1186a0318f36SChris Fallin bb_offsets, 1187a0318f36SChris Fallin bb_edges, 1188a0318f36SChris Fallin disasm: if want_disasm { Some(disasm) } else { None }, 1189a0318f36SChris Fallin value_labels_ranges, 1190a0318f36SChris Fallin } 1191d8357426SChris Fallin } 1192d8357426SChris Fallin 1193d4a4d4f9SSingleAccretion fn monotonize_inst_offsets(&self, inst_offsets: &mut [CodeOffset], func_body_len: u32) { 1194d4a4d4f9SSingleAccretion if self.debug_value_labels.is_empty() { 1195d4a4d4f9SSingleAccretion return; 1196d4a4d4f9SSingleAccretion } 1197d4a4d4f9SSingleAccretion 1198d4a4d4f9SSingleAccretion // During emission, branch removal can make offsets of instructions incorrect. 1199d4a4d4f9SSingleAccretion // Consider the following sequence: [insi][jmp0][jmp1][jmp2][insj] 1200d4a4d4f9SSingleAccretion // It will be recorded as (say): [30] [34] [38] [42] [<would be 46>] 1201d4a4d4f9SSingleAccretion // When the jumps get removed we are left with (in "inst_offsets"): 1202d4a4d4f9SSingleAccretion // [insi][jmp0][jmp1][jmp2][insj][...] 1203d4a4d4f9SSingleAccretion // [30] [34] [38] [42] [34] 1204d4a4d4f9SSingleAccretion // Which violates the monotonicity invariant. This method sets offsets of these 1205d4a4d4f9SSingleAccretion // removed instructions such as to make them appear zero-sized: 1206d4a4d4f9SSingleAccretion // [insi][jmp0][jmp1][jmp2][insj][...] 1207d4a4d4f9SSingleAccretion // [30] [34] [34] [34] [34] 1208d4a4d4f9SSingleAccretion // 1209d4a4d4f9SSingleAccretion let mut next_offset = func_body_len; 1210d4a4d4f9SSingleAccretion for inst_index in (0..(inst_offsets.len() - 1)).rev() { 1211d4a4d4f9SSingleAccretion let inst_offset = inst_offsets[inst_index]; 1212d4a4d4f9SSingleAccretion 1213d4a4d4f9SSingleAccretion // Not all instructions get their offsets recorded. 1214d4a4d4f9SSingleAccretion if inst_offset == NO_INST_OFFSET { 1215d4a4d4f9SSingleAccretion continue; 1216d4a4d4f9SSingleAccretion } 1217d4a4d4f9SSingleAccretion 1218d4a4d4f9SSingleAccretion if inst_offset > next_offset { 1219d4a4d4f9SSingleAccretion trace!( 1220d4a4d4f9SSingleAccretion "Fixing code offset of the removed Inst {}: {} -> {}", 122190ac295eSAlex Crichton inst_index, inst_offset, next_offset 1222d4a4d4f9SSingleAccretion ); 1223d4a4d4f9SSingleAccretion inst_offsets[inst_index] = next_offset; 1224d4a4d4f9SSingleAccretion continue; 1225d4a4d4f9SSingleAccretion } 1226d4a4d4f9SSingleAccretion 1227d4a4d4f9SSingleAccretion next_offset = inst_offset; 1228d4a4d4f9SSingleAccretion } 1229d4a4d4f9SSingleAccretion } 1230d4a4d4f9SSingleAccretion 1231a0318f36SChris Fallin fn compute_value_labels_ranges( 1232a0318f36SChris Fallin &self, 1233a0318f36SChris Fallin regalloc: ®alloc2::Output, 1234a0318f36SChris Fallin inst_offsets: &[CodeOffset], 1235a0318f36SChris Fallin func_body_len: u32, 1236a0318f36SChris Fallin ) -> ValueLabelsRanges { 1237a0318f36SChris Fallin if self.debug_value_labels.is_empty() { 1238602006ffSbjorn3 return ValueLabelsRanges::default(); 1239997fab55SChris Fallin } 1240997fab55SChris Fallin 12413da7fc8eSSingleAccretion if trace_log_enabled!() { 12423da7fc8eSSingleAccretion self.log_value_labels_ranges(regalloc, inst_offsets); 12433da7fc8eSSingleAccretion } 12443da7fc8eSSingleAccretion 1245a0318f36SChris Fallin let mut value_labels_ranges: ValueLabelsRanges = HashMap::new(); 1246a0318f36SChris Fallin for &(label, from, to, alloc) in ®alloc.debug_locations { 12473da7fc8eSSingleAccretion let label = ValueLabel::from_u32(label); 12483da7fc8eSSingleAccretion let ranges = value_labels_ranges.entry(label).or_insert_with(|| vec![]); 12495b63c874SSingleAccretion let prog_point_to_inst = |prog_point: ProgPoint| { 12505b63c874SSingleAccretion let mut inst = prog_point.inst(); 12515b63c874SSingleAccretion if prog_point.pos() == InstPosition::After { 12525b63c874SSingleAccretion inst = inst.next(); 12535b63c874SSingleAccretion } 12545b63c874SSingleAccretion inst.index() 12555b63c874SSingleAccretion }; 12569fe4cc18SPhilip Craig let inst_to_offset = |inst_index: usize| { 12579fe4cc18SPhilip Craig // Skip over cold blocks. 12589fe4cc18SPhilip Craig for offset in &inst_offsets[inst_index..] { 12599fe4cc18SPhilip Craig if *offset != NO_INST_OFFSET { 12609fe4cc18SPhilip Craig return *offset; 12619fe4cc18SPhilip Craig } 12629fe4cc18SPhilip Craig } 12639fe4cc18SPhilip Craig func_body_len 12649fe4cc18SPhilip Craig }; 12655b63c874SSingleAccretion let from_inst_index = prog_point_to_inst(from); 12665b63c874SSingleAccretion let to_inst_index = prog_point_to_inst(to); 12679fe4cc18SPhilip Craig let from_offset = inst_to_offset(from_inst_index); 12689fe4cc18SPhilip Craig let to_offset = inst_to_offset(to_inst_index); 1269a0318f36SChris Fallin 1270d4a4d4f9SSingleAccretion // Empty ranges or unavailable offsets can happen 1271d4a4d4f9SSingleAccretion // due to cold blocks and branch removal (see above). 12729fe4cc18SPhilip Craig if from_offset == to_offset { 1273a0318f36SChris Fallin continue; 127476d61504Sbjorn3 } 127576d61504Sbjorn3 1276a0318f36SChris Fallin let loc = if let Some(preg) = alloc.as_reg() { 1277a0318f36SChris Fallin LabelValueLoc::Reg(Reg::from(preg)) 1278a0318f36SChris Fallin } else { 127976911c29SSSD #[cfg(not(feature = "unwind"))] 128076911c29SSSD continue; 128176911c29SSSD 128276911c29SSSD #[cfg(feature = "unwind")] 128376911c29SSSD { 12847b16eccdSSingleAccretion let slot = alloc.as_stack().unwrap(); 128561d0b319STrevor Elliott let slot_offset = self.abi.get_spillslot_offset(slot); 128661d0b319STrevor Elliott let slot_base_to_caller_sp_offset = self.abi.slot_base_to_caller_sp_offset(); 12877b16eccdSSingleAccretion let caller_sp_to_cfa_offset = 12887b16eccdSSingleAccretion crate::isa::unwind::systemv::caller_sp_to_cfa_offset(); 128961d0b319STrevor Elliott // NOTE: this is a negative offset because it's relative to the caller's SP 129061d0b319STrevor Elliott let cfa_to_sp_offset = 129161d0b319STrevor Elliott -((slot_base_to_caller_sp_offset + caller_sp_to_cfa_offset) as i64); 129261d0b319STrevor Elliott LabelValueLoc::CFAOffset(cfa_to_sp_offset + slot_offset) 129376911c29SSSD } 1294a0318f36SChris Fallin }; 1295a0318f36SChris Fallin 12967b16eccdSSingleAccretion // Coalesce adjacent ranges that for the same location 12977b16eccdSSingleAccretion // to minimize output size here and for the consumers. 12987b16eccdSSingleAccretion if let Some(last_loc_range) = ranges.last_mut() { 12995b63c874SSingleAccretion if last_loc_range.loc == loc && last_loc_range.end == from_offset { 13007b16eccdSSingleAccretion trace!( 13015b63c874SSingleAccretion "Extending debug range for {:?} in {:?} to Inst {} ({})", 130290ac295eSAlex Crichton label, loc, to_inst_index, to_offset 13037b16eccdSSingleAccretion ); 13045b63c874SSingleAccretion last_loc_range.end = to_offset; 13057b16eccdSSingleAccretion continue; 13067b16eccdSSingleAccretion } 13077b16eccdSSingleAccretion } 13087b16eccdSSingleAccretion 1309d4a4d4f9SSingleAccretion trace!( 13103da7fc8eSSingleAccretion "Recording debug range for {:?} in {:?}: [Inst {}..Inst {}) [{}..{})", 131190ac295eSAlex Crichton label, loc, from_inst_index, to_inst_index, from_offset, to_offset 1312d4a4d4f9SSingleAccretion ); 1313d4a4d4f9SSingleAccretion 13145b63c874SSingleAccretion ranges.push(ValueLocRange { 13155b63c874SSingleAccretion loc, 13165b63c874SSingleAccretion start: from_offset, 13175b63c874SSingleAccretion end: to_offset, 13185b63c874SSingleAccretion }); 1319a0318f36SChris Fallin } 1320a0318f36SChris Fallin 1321a0318f36SChris Fallin value_labels_ranges 1322c84d6be6SChris Fallin } 1323c84d6be6SChris Fallin 13243da7fc8eSSingleAccretion fn log_value_labels_ranges(&self, regalloc: ®alloc2::Output, inst_offsets: &[CodeOffset]) { 13253da7fc8eSSingleAccretion debug_assert!(trace_log_enabled!()); 13263da7fc8eSSingleAccretion 13273da7fc8eSSingleAccretion // What debug labels do we have? Note we'll skip those that have not been 13283da7fc8eSSingleAccretion // allocated any location at all. They will show up as numeric gaps in the table. 13293da7fc8eSSingleAccretion let mut labels = vec![]; 13303da7fc8eSSingleAccretion for &(label, _, _, _) in ®alloc.debug_locations { 13313da7fc8eSSingleAccretion if Some(&label) == labels.last() { 13323da7fc8eSSingleAccretion continue; 13333da7fc8eSSingleAccretion } 13343da7fc8eSSingleAccretion labels.push(label); 13353da7fc8eSSingleAccretion } 13363da7fc8eSSingleAccretion 13373da7fc8eSSingleAccretion // Reformat the data on what VRegs were the VLs assigned to by lowering, since 13383da7fc8eSSingleAccretion // the array we have is sorted by VReg, and we want it sorted by VL for easy 13393da7fc8eSSingleAccretion // access in the loop below. 13403da7fc8eSSingleAccretion let mut vregs = vec![]; 13413da7fc8eSSingleAccretion for &(vreg, start, end, label) in &self.debug_value_labels { 13423da7fc8eSSingleAccretion if matches!(labels.binary_search(&label), Ok(_)) { 13433da7fc8eSSingleAccretion vregs.push((label, start, end, vreg)); 13443da7fc8eSSingleAccretion } 13453da7fc8eSSingleAccretion } 13463da7fc8eSSingleAccretion vregs.sort_unstable_by( 13473da7fc8eSSingleAccretion |(l_label, l_start, _, _), (r_label, r_start, _, _)| match l_label.cmp(r_label) { 13483da7fc8eSSingleAccretion Ordering::Equal => l_start.cmp(r_start), 13493da7fc8eSSingleAccretion cmp => cmp, 13503da7fc8eSSingleAccretion }, 13513da7fc8eSSingleAccretion ); 13523da7fc8eSSingleAccretion 13533da7fc8eSSingleAccretion #[derive(PartialEq)] 13543da7fc8eSSingleAccretion enum Mode { 13553da7fc8eSSingleAccretion Measure, 13563da7fc8eSSingleAccretion Emit, 13573da7fc8eSSingleAccretion } 13583da7fc8eSSingleAccretion #[derive(PartialEq)] 13593da7fc8eSSingleAccretion enum Row { 13603da7fc8eSSingleAccretion Head, 13613da7fc8eSSingleAccretion Line, 13625b63c874SSingleAccretion Inst(usize, usize), 13633da7fc8eSSingleAccretion } 13643da7fc8eSSingleAccretion 13655b63c874SSingleAccretion let mut widths = vec![0; 3 + 2 * labels.len()]; 13663da7fc8eSSingleAccretion let mut row = String::new(); 13673da7fc8eSSingleAccretion let mut output_row = |row_kind: Row, mode: Mode| { 13683da7fc8eSSingleAccretion let mut column_index = 0; 13693da7fc8eSSingleAccretion row.clear(); 13703da7fc8eSSingleAccretion 13713da7fc8eSSingleAccretion macro_rules! output_cell_impl { 13723da7fc8eSSingleAccretion ($fill:literal, $span:literal, $($cell_fmt:tt)*) => { 13733da7fc8eSSingleAccretion let column_start = row.len(); 13743da7fc8eSSingleAccretion { 13753da7fc8eSSingleAccretion row.push('|'); 13763da7fc8eSSingleAccretion write!(row, $($cell_fmt)*).unwrap(); 13773da7fc8eSSingleAccretion } 13783da7fc8eSSingleAccretion 13793da7fc8eSSingleAccretion let next_column_index = column_index + $span; 13803da7fc8eSSingleAccretion let expected_width: usize = widths[column_index..next_column_index].iter().sum(); 13813da7fc8eSSingleAccretion if mode == Mode::Measure { 13823da7fc8eSSingleAccretion let actual_width = row.len() - column_start; 13833da7fc8eSSingleAccretion if actual_width > expected_width { 13843da7fc8eSSingleAccretion widths[next_column_index - 1] += actual_width - expected_width; 13853da7fc8eSSingleAccretion } 13863da7fc8eSSingleAccretion } else { 13873da7fc8eSSingleAccretion let column_end = column_start + expected_width; 13883da7fc8eSSingleAccretion while row.len() != column_end { 13893da7fc8eSSingleAccretion row.push($fill); 13903da7fc8eSSingleAccretion } 13913da7fc8eSSingleAccretion } 13923da7fc8eSSingleAccretion column_index = next_column_index; 13933da7fc8eSSingleAccretion }; 13943da7fc8eSSingleAccretion } 13953da7fc8eSSingleAccretion macro_rules! output_cell { 13963da7fc8eSSingleAccretion ($($cell_fmt:tt)*) => { 13973da7fc8eSSingleAccretion output_cell_impl!(' ', 1, $($cell_fmt)*); 13983da7fc8eSSingleAccretion }; 13993da7fc8eSSingleAccretion } 14003da7fc8eSSingleAccretion 14013da7fc8eSSingleAccretion match row_kind { 14023da7fc8eSSingleAccretion Row::Head => { 14035b63c874SSingleAccretion output_cell!("BB"); 14043da7fc8eSSingleAccretion output_cell!("Inst"); 14053da7fc8eSSingleAccretion output_cell!("IP"); 14063da7fc8eSSingleAccretion for label in &labels { 14073da7fc8eSSingleAccretion output_cell_impl!(' ', 2, "{:?}", ValueLabel::from_u32(*label)); 14083da7fc8eSSingleAccretion } 14093da7fc8eSSingleAccretion } 14103da7fc8eSSingleAccretion Row::Line => { 14113da7fc8eSSingleAccretion debug_assert!(mode == Mode::Emit); 14125b63c874SSingleAccretion for _ in 0..3 { 14133da7fc8eSSingleAccretion output_cell_impl!('-', 1, ""); 14145b63c874SSingleAccretion } 14153da7fc8eSSingleAccretion for _ in &labels { 14163da7fc8eSSingleAccretion output_cell_impl!('-', 2, ""); 14173da7fc8eSSingleAccretion } 14183da7fc8eSSingleAccretion } 14195b63c874SSingleAccretion Row::Inst(block_index, inst_index) => { 14205b63c874SSingleAccretion debug_assert!(inst_index < self.num_insts()); 14215b63c874SSingleAccretion if self.block_ranges.get(block_index).start == inst_index { 14225b63c874SSingleAccretion output_cell!("B{}", block_index); 14235b63c874SSingleAccretion } else { 14245b63c874SSingleAccretion output_cell!(""); 14255b63c874SSingleAccretion } 14263da7fc8eSSingleAccretion output_cell!("Inst {inst_index} "); 14273da7fc8eSSingleAccretion output_cell!("{} ", inst_offsets[inst_index]); 14283da7fc8eSSingleAccretion 14293da7fc8eSSingleAccretion for label in &labels { 14303da7fc8eSSingleAccretion // First, the VReg. 14313da7fc8eSSingleAccretion use regalloc2::Inst; 14323da7fc8eSSingleAccretion let vreg_cmp = |inst: usize, 14333da7fc8eSSingleAccretion vreg_label: &u32, 14343da7fc8eSSingleAccretion range_start: &Inst, 14353da7fc8eSSingleAccretion range_end: &Inst| { 14363da7fc8eSSingleAccretion match vreg_label.cmp(&label) { 14373da7fc8eSSingleAccretion Ordering::Equal => { 14383da7fc8eSSingleAccretion if range_end.index() <= inst { 14393da7fc8eSSingleAccretion Ordering::Less 14403da7fc8eSSingleAccretion } else if range_start.index() > inst { 14413da7fc8eSSingleAccretion Ordering::Greater 14423da7fc8eSSingleAccretion } else { 14433da7fc8eSSingleAccretion Ordering::Equal 14443da7fc8eSSingleAccretion } 14453da7fc8eSSingleAccretion } 14463da7fc8eSSingleAccretion cmp => cmp, 14473da7fc8eSSingleAccretion } 14483da7fc8eSSingleAccretion }; 14493da7fc8eSSingleAccretion let vreg_index = 14505b63c874SSingleAccretion vregs.binary_search_by(|(l, s, e, _)| vreg_cmp(inst_index, l, s, e)); 14513da7fc8eSSingleAccretion if let Ok(vreg_index) = vreg_index { 14523da7fc8eSSingleAccretion let mut prev_vreg = None; 14535b63c874SSingleAccretion if inst_index > 0 { 14543da7fc8eSSingleAccretion let prev_vreg_index = vregs.binary_search_by(|(l, s, e, _)| { 14555b63c874SSingleAccretion vreg_cmp(inst_index - 1, l, s, e) 14563da7fc8eSSingleAccretion }); 14573da7fc8eSSingleAccretion if let Ok(prev_vreg_index) = prev_vreg_index { 14583da7fc8eSSingleAccretion prev_vreg = Some(vregs[prev_vreg_index].3); 14593da7fc8eSSingleAccretion } 14603da7fc8eSSingleAccretion } 14613da7fc8eSSingleAccretion 14623da7fc8eSSingleAccretion let vreg = vregs[vreg_index].3; 14633da7fc8eSSingleAccretion if Some(vreg) == prev_vreg { 14643da7fc8eSSingleAccretion output_cell!("*"); 14653da7fc8eSSingleAccretion } else { 14663da7fc8eSSingleAccretion output_cell!("{}", vreg); 14673da7fc8eSSingleAccretion } 14683da7fc8eSSingleAccretion } else { 14693da7fc8eSSingleAccretion output_cell!(""); 14703da7fc8eSSingleAccretion } 14713da7fc8eSSingleAccretion 14723da7fc8eSSingleAccretion // Second, the allocated location. 14735b63c874SSingleAccretion let inst_prog_point = ProgPoint::before(Inst::new(inst_index)); 14743da7fc8eSSingleAccretion let range_index = regalloc.debug_locations.binary_search_by( 14753da7fc8eSSingleAccretion |(range_label, range_start, range_end, _)| match range_label.cmp(label) 14763da7fc8eSSingleAccretion { 14773da7fc8eSSingleAccretion Ordering::Equal => { 14785b63c874SSingleAccretion if *range_end <= inst_prog_point { 14793da7fc8eSSingleAccretion Ordering::Less 14805b63c874SSingleAccretion } else if *range_start > inst_prog_point { 14813da7fc8eSSingleAccretion Ordering::Greater 14823da7fc8eSSingleAccretion } else { 14833da7fc8eSSingleAccretion Ordering::Equal 14843da7fc8eSSingleAccretion } 14853da7fc8eSSingleAccretion } 14863da7fc8eSSingleAccretion cmp => cmp, 14873da7fc8eSSingleAccretion }, 14883da7fc8eSSingleAccretion ); 14893da7fc8eSSingleAccretion if let Ok(range_index) = range_index { 14903da7fc8eSSingleAccretion // Live at this instruction, print the location. 14913da7fc8eSSingleAccretion if let Some(reg) = regalloc.debug_locations[range_index].3.as_reg() { 14923da7fc8eSSingleAccretion output_cell!("{:?}", Reg::from(reg)); 14933da7fc8eSSingleAccretion } else { 14943da7fc8eSSingleAccretion output_cell!("Stk"); 14953da7fc8eSSingleAccretion } 14963da7fc8eSSingleAccretion } else { 14973da7fc8eSSingleAccretion // Not live at this instruction. 14983da7fc8eSSingleAccretion output_cell!(""); 14993da7fc8eSSingleAccretion } 15003da7fc8eSSingleAccretion } 15013da7fc8eSSingleAccretion } 15023da7fc8eSSingleAccretion } 15033da7fc8eSSingleAccretion row.push('|'); 15043da7fc8eSSingleAccretion 15053da7fc8eSSingleAccretion if mode == Mode::Emit { 15063da7fc8eSSingleAccretion trace!("{}", row.as_str()); 15073da7fc8eSSingleAccretion } 15083da7fc8eSSingleAccretion }; 15093da7fc8eSSingleAccretion 15105b63c874SSingleAccretion for block_index in 0..self.num_blocks() { 15115b63c874SSingleAccretion for inst_index in self.block_ranges.get(block_index) { 15125b63c874SSingleAccretion output_row(Row::Inst(block_index, inst_index), Mode::Measure); 15135b63c874SSingleAccretion } 15143da7fc8eSSingleAccretion } 15153da7fc8eSSingleAccretion output_row(Row::Head, Mode::Measure); 15163da7fc8eSSingleAccretion 15173da7fc8eSSingleAccretion output_row(Row::Head, Mode::Emit); 15183da7fc8eSSingleAccretion output_row(Row::Line, Mode::Emit); 15195b63c874SSingleAccretion for block_index in 0..self.num_blocks() { 15205b63c874SSingleAccretion for inst_index in self.block_ranges.get(block_index) { 15215b63c874SSingleAccretion output_row(Row::Inst(block_index, inst_index), Mode::Emit); 15225b63c874SSingleAccretion } 15233da7fc8eSSingleAccretion } 15243da7fc8eSSingleAccretion } 15253da7fc8eSSingleAccretion 1526d8357426SChris Fallin /// Get the IR block for a BlockIndex, if one exists. 1527d8357426SChris Fallin pub fn bindex_to_bb(&self, block: BlockIndex) -> Option<ir::Block> { 1528a0318f36SChris Fallin self.block_order.lowered_order()[block.index()].orig_block() 1529d8357426SChris Fallin } 15302154c63dSAlex Crichton 15319e4d4462SChris Fallin /// Get the type of a VReg. 15329e4d4462SChris Fallin pub fn vreg_type(&self, vreg: VReg) -> Type { 15339e4d4462SChris Fallin self.vreg_types[vreg.vreg()] 15349e4d4462SChris Fallin } 15359e4d4462SChris Fallin 1536f466aa26SChris Fallin /// Get the fact, if any, for a given VReg. 1537f466aa26SChris Fallin pub fn vreg_fact(&self, vreg: VReg) -> Option<&Fact> { 15389e4d4462SChris Fallin self.facts[vreg.vreg()].as_ref() 1539f466aa26SChris Fallin } 1540f466aa26SChris Fallin 15418d19280aSChris Fallin /// Set the fact for a given VReg. 15428d19280aSChris Fallin pub fn set_vreg_fact(&mut self, vreg: VReg, fact: Fact) { 1543f262c311SChris Fallin trace!("set fact on {}: {:?}", vreg, fact); 15448d19280aSChris Fallin self.facts[vreg.vreg()] = Some(fact); 15458d19280aSChris Fallin } 15468d19280aSChris Fallin 1547f466aa26SChris Fallin /// Does a given instruction define any facts? 1548f466aa26SChris Fallin pub fn inst_defines_facts(&self, inst: InsnIndex) -> bool { 1549f466aa26SChris Fallin self.inst_operands(inst) 1550f466aa26SChris Fallin .iter() 1551f466aa26SChris Fallin .filter(|o| o.kind() == OperandKind::Def) 1552f466aa26SChris Fallin .map(|o| o.vreg()) 15532e7f9414SChris Fallin .any(|vreg| self.facts[vreg.vreg()].is_some()) 1554f466aa26SChris Fallin } 1555e20b4244SNick Fitzgerald 1556e20b4244SNick Fitzgerald /// Get the user stack map associated with the given forward instruction index. 1557e20b4244SNick Fitzgerald pub fn get_user_stack_map(&self, inst: InsnIndex) -> Option<&ir::UserStackMap> { 1558e20b4244SNick Fitzgerald let index = inst.to_backwards_insn_index(self.num_insts()); 1559e20b4244SNick Fitzgerald self.user_stack_maps.get(&index) 1560e20b4244SNick Fitzgerald } 1561f466aa26SChris Fallin } 1562f466aa26SChris Fallin 15630889323aSSSD impl<I: VCodeInst> core::ops::Index<InsnIndex> for VCode<I> { 1564f466aa26SChris Fallin type Output = I; 1565f466aa26SChris Fallin fn index(&self, idx: InsnIndex) -> &Self::Output { 1566f466aa26SChris Fallin &self.insts[idx.index()] 1567f466aa26SChris Fallin } 1568d8357426SChris Fallin } 1569d8357426SChris Fallin 1570d8357426SChris Fallin impl<I: VCodeInst> RegallocFunction for VCode<I> { 1571a0318f36SChris Fallin fn num_insts(&self) -> usize { 1572a0318f36SChris Fallin self.insts.len() 1573d8357426SChris Fallin } 1574d8357426SChris Fallin 1575a0318f36SChris Fallin fn num_blocks(&self) -> usize { 1576a0318f36SChris Fallin self.block_ranges.len() 1577d8357426SChris Fallin } 1578d8357426SChris Fallin 1579a0318f36SChris Fallin fn entry_block(&self) -> BlockIndex { 1580a0318f36SChris Fallin self.entry 1581d8357426SChris Fallin } 1582d8357426SChris Fallin 1583a0318f36SChris Fallin fn block_insns(&self, block: BlockIndex) -> InstRange { 15842c409535SJamey Sharp let range = self.block_ranges.get(block.index()); 15851854929dSTrevor Elliott InstRange::new(InsnIndex::new(range.start), InsnIndex::new(range.end)) 1586d8357426SChris Fallin } 1587d8357426SChris Fallin 1588a0318f36SChris Fallin fn block_succs(&self, block: BlockIndex) -> &[BlockIndex] { 15892c409535SJamey Sharp let range = self.block_succ_range.get(block.index()); 15902c409535SJamey Sharp &self.block_succs[range] 1591d8357426SChris Fallin } 1592d8357426SChris Fallin 1593a0318f36SChris Fallin fn block_preds(&self, block: BlockIndex) -> &[BlockIndex] { 15942c409535SJamey Sharp let range = self.block_pred_range.get(block.index()); 15952c409535SJamey Sharp &self.block_preds[range] 1596d8357426SChris Fallin } 1597d8357426SChris Fallin 1598a0318f36SChris Fallin fn block_params(&self, block: BlockIndex) -> &[VReg] { 1599c5379051STrevor Elliott // As a special case we don't return block params for the entry block, as all the arguments 1600c5379051STrevor Elliott // will be defined by the `Inst::Args` instruction. 1601c5379051STrevor Elliott if block == self.entry { 1602c5379051STrevor Elliott return &[]; 1603c5379051STrevor Elliott } 1604c5379051STrevor Elliott 16052c409535SJamey Sharp let range = self.block_params_range.get(block.index()); 16062c409535SJamey Sharp &self.block_params[range] 1607d8357426SChris Fallin } 1608d8357426SChris Fallin 1609a0318f36SChris Fallin fn branch_blockparams(&self, block: BlockIndex, _insn: InsnIndex, succ_idx: usize) -> &[VReg] { 16102c409535SJamey Sharp let succ_range = self.branch_block_arg_succ_range.get(block.index()); 16112c409535SJamey Sharp debug_assert!(succ_idx < succ_range.len()); 16122c409535SJamey Sharp let branch_block_args = self.branch_block_arg_range.get(succ_range.start + succ_idx); 16132c409535SJamey Sharp &self.branch_block_args[branch_block_args] 1614d8357426SChris Fallin } 1615d8357426SChris Fallin 1616a0318f36SChris Fallin fn is_ret(&self, insn: InsnIndex) -> bool { 1617a0318f36SChris Fallin match self.insts[insn.index()].is_term() { 1618c5379051STrevor Elliott // We treat blocks terminated by an unconditional trap like a return for regalloc. 1619c5379051STrevor Elliott MachTerminator::None => self.insts[insn.index()].is_trap(), 16204154fa47SNick Fitzgerald MachTerminator::Ret | MachTerminator::RetCall => true, 162194ec88eaSChris Fallin MachTerminator::Branch => false, 1622d8357426SChris Fallin } 1623d8357426SChris Fallin } 1624d8357426SChris Fallin 1625a0318f36SChris Fallin fn is_branch(&self, insn: InsnIndex) -> bool { 1626a0318f36SChris Fallin match self.insts[insn.index()].is_term() { 162794ec88eaSChris Fallin MachTerminator::Branch => true, 1628a0318f36SChris Fallin _ => false, 1629a0318f36SChris Fallin } 163071768bb6SChris Fallin } 163171768bb6SChris Fallin 1632a0318f36SChris Fallin fn inst_operands(&self, insn: InsnIndex) -> &[Operand] { 16332c409535SJamey Sharp let range = self.operand_ranges.get(insn.index()); 16342c409535SJamey Sharp &self.operands[range] 1635d8357426SChris Fallin } 1636d8357426SChris Fallin 1637b2e28b91SChris Fallin fn inst_clobbers(&self, insn: InsnIndex) -> PRegSet { 1638b2e28b91SChris Fallin self.clobbers.get(&insn).cloned().unwrap_or_default() 1639be6f060aSChris Fallin } 1640be6f060aSChris Fallin 1641a0318f36SChris Fallin fn num_vregs(&self) -> usize { 1642b1307638SJamey Sharp self.vreg_types.len() 1643d8357426SChris Fallin } 1644d8357426SChris Fallin 1645a0318f36SChris Fallin fn debug_value_labels(&self) -> &[(VReg, InsnIndex, InsnIndex, u32)] { 16463aa32064SJamey Sharp &self.debug_value_labels 1647d8357426SChris Fallin } 1648d8357426SChris Fallin 1649a0318f36SChris Fallin fn spillslot_size(&self, regclass: RegClass) -> usize { 1650a0318f36SChris Fallin self.abi.get_spillslot_size(regclass) as usize 1651d8357426SChris Fallin } 1652d8357426SChris Fallin 1653a0318f36SChris Fallin fn allow_multiple_vreg_defs(&self) -> bool { 1654a0318f36SChris Fallin // At least the s390x backend requires this, because the 1655a0318f36SChris Fallin // `Loop` pseudo-instruction aggregates all Operands so pinned 1656a0318f36SChris Fallin // vregs (RealRegs) may occur more than once. 1657a0318f36SChris Fallin true 1658d8357426SChris Fallin } 1659d8357426SChris Fallin } 1660d8357426SChris Fallin 16613aa32064SJamey Sharp impl<I: VCodeInst> Debug for VRegAllocator<I> { 1662d8357426SChris Fallin fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 16633aa32064SJamey Sharp writeln!(f, "VRegAllocator {{")?; 1664a0318f36SChris Fallin 1665a0318f36SChris Fallin let mut alias_keys = self.vreg_aliases.keys().cloned().collect::<Vec<_>>(); 1666a0318f36SChris Fallin alias_keys.sort_unstable(); 1667a0318f36SChris Fallin for key in alias_keys { 1668a0318f36SChris Fallin let dest = self.vreg_aliases.get(&key).unwrap(); 1669a0318f36SChris Fallin writeln!(f, " {:?} := {:?}", Reg::from(key), Reg::from(*dest))?; 1670a0318f36SChris Fallin } 1671d8357426SChris Fallin 16723aa32064SJamey Sharp for (vreg, fact) in self.facts.iter().enumerate() { 16733aa32064SJamey Sharp if let Some(fact) = fact { 1674a0442ea0SHamir Mahal writeln!(f, " v{vreg} ! {fact}")?; 16753aa32064SJamey Sharp } 16763aa32064SJamey Sharp } 16773aa32064SJamey Sharp 16783aa32064SJamey Sharp writeln!(f, "}}") 16793aa32064SJamey Sharp } 16803aa32064SJamey Sharp } 16813aa32064SJamey Sharp 16823aa32064SJamey Sharp impl<I: VCodeInst> fmt::Debug for VCode<I> { 16833aa32064SJamey Sharp fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 16843aa32064SJamey Sharp writeln!(f, "VCode {{")?; 16853aa32064SJamey Sharp writeln!(f, " Entry block: {}", self.entry.index())?; 16863aa32064SJamey Sharp 16873aa32064SJamey Sharp let mut state = Default::default(); 16883aa32064SJamey Sharp 1689d8357426SChris Fallin for block in 0..self.num_blocks() { 1690a0318f36SChris Fallin let block = BlockIndex::new(block); 1691c510a2b9Sbjorn3 writeln!( 1692c510a2b9Sbjorn3 f, 1693c510a2b9Sbjorn3 "Block {}({:?}):", 1694c510a2b9Sbjorn3 block.index(), 1695c510a2b9Sbjorn3 self.block_params(block) 1696c510a2b9Sbjorn3 )?; 1697a0318f36SChris Fallin if let Some(bb) = self.bindex_to_bb(block) { 1698a0442ea0SHamir Mahal writeln!(f, " (original IR block: {bb})")?; 1699d8357426SChris Fallin } 1700c510a2b9Sbjorn3 for (succ_idx, succ) in self.block_succs(block).iter().enumerate() { 1701c510a2b9Sbjorn3 writeln!( 1702c510a2b9Sbjorn3 f, 1703c510a2b9Sbjorn3 " (successor: Block {}({:?}))", 1704c510a2b9Sbjorn3 succ.index(), 1705c510a2b9Sbjorn3 self.branch_blockparams(block, InsnIndex::new(0) /* dummy */, succ_idx) 1706c510a2b9Sbjorn3 )?; 1707a0318f36SChris Fallin } 17082c409535SJamey Sharp for inst in self.block_ranges.get(block.index()) { 1709a0318f36SChris Fallin writeln!( 1710a0318f36SChris Fallin f, 1711a0318f36SChris Fallin " Inst {}: {}", 1712a0318f36SChris Fallin inst, 17137d703191SJamey Sharp self.insts[inst].pretty_print_inst(&mut state) 1714a0318f36SChris Fallin )?; 17153aa32064SJamey Sharp if !self.operands.is_empty() { 1716f466aa26SChris Fallin for operand in self.inst_operands(InsnIndex::new(inst)) { 1717f466aa26SChris Fallin if operand.kind() == OperandKind::Def { 1718f466aa26SChris Fallin if let Some(fact) = &self.facts[operand.vreg().vreg()] { 1719fef8a90fSChris Fallin writeln!(f, " v{} ! {}", operand.vreg().vreg(), fact)?; 1720f466aa26SChris Fallin } 1721f466aa26SChris Fallin } 1722f466aa26SChris Fallin } 1723d8357426SChris Fallin } 1724e20b4244SNick Fitzgerald if let Some(user_stack_map) = self.get_user_stack_map(InsnIndex::new(inst)) { 1725e20b4244SNick Fitzgerald writeln!(f, " {user_stack_map:?}")?; 1726e20b4244SNick Fitzgerald } 1727d8357426SChris Fallin } 17283aa32064SJamey Sharp } 1729d8357426SChris Fallin 1730d8357426SChris Fallin writeln!(f, "}}")?; 1731d8357426SChris Fallin Ok(()) 1732d8357426SChris Fallin } 1733d8357426SChris Fallin } 1734d8357426SChris Fallin 1735d94173eaSTrevor Elliott /// This structure manages VReg allocation during the lifetime of the VCodeBuilder. 1736d94173eaSTrevor Elliott pub struct VRegAllocator<I> { 1737d94173eaSTrevor Elliott /// VReg IR-level types. 1738d94173eaSTrevor Elliott vreg_types: Vec<Type>, 1739d94173eaSTrevor Elliott 17403aa32064SJamey Sharp /// VReg aliases. When the final VCode is built we rewrite all 17413aa32064SJamey Sharp /// uses of the keys in this table to their replacement values. 17423aa32064SJamey Sharp /// 17433aa32064SJamey Sharp /// We use these aliases to rename an instruction's expected 17443aa32064SJamey Sharp /// result vregs to the returned vregs from lowering, which are 17453aa32064SJamey Sharp /// usually freshly-allocated temps. 17463aa32064SJamey Sharp vreg_aliases: FxHashMap<regalloc2::VReg, regalloc2::VReg>, 17473aa32064SJamey Sharp 174817eeba0eSChris Fallin /// A deferred error, to be bubbled up to the top level of the 174917eeba0eSChris Fallin /// lowering algorithm. We take this approach because we cannot 175017eeba0eSChris Fallin /// currently propagate a `Result` upward through ISLE code (the 175117eeba0eSChris Fallin /// lowering rules) or some ABI code. 175217eeba0eSChris Fallin deferred_error: Option<CodegenError>, 175317eeba0eSChris Fallin 1754f466aa26SChris Fallin /// Facts on VRegs, for proof-carrying code. 1755f466aa26SChris Fallin facts: Vec<Option<Fact>>, 1756f466aa26SChris Fallin 1757d94173eaSTrevor Elliott /// The type of instruction that this allocator makes registers for. 1758d94173eaSTrevor Elliott _inst: core::marker::PhantomData<I>, 1759d94173eaSTrevor Elliott } 1760d94173eaSTrevor Elliott 1761d94173eaSTrevor Elliott impl<I: VCodeInst> VRegAllocator<I> { 1762d94173eaSTrevor Elliott /// Make a new VRegAllocator. 17633aa32064SJamey Sharp pub fn with_capacity(capacity: usize) -> Self { 17643aa32064SJamey Sharp let capacity = first_user_vreg_index() + capacity; 17653aa32064SJamey Sharp let mut vreg_types = Vec::with_capacity(capacity); 17663aa32064SJamey Sharp vreg_types.resize(first_user_vreg_index(), types::INVALID); 1767d94173eaSTrevor Elliott Self { 17683aa32064SJamey Sharp vreg_types, 17693aa32064SJamey Sharp vreg_aliases: FxHashMap::with_capacity_and_hasher(capacity, Default::default()), 177017eeba0eSChris Fallin deferred_error: None, 17713aa32064SJamey Sharp facts: Vec::with_capacity(capacity), 1772d94173eaSTrevor Elliott _inst: core::marker::PhantomData::default(), 1773d94173eaSTrevor Elliott } 1774d94173eaSTrevor Elliott } 1775d94173eaSTrevor Elliott 1776d94173eaSTrevor Elliott /// Allocate a fresh ValueRegs. 1777d94173eaSTrevor Elliott pub fn alloc(&mut self, ty: Type) -> CodegenResult<ValueRegs<Reg>> { 177817eeba0eSChris Fallin if self.deferred_error.is_some() { 177917eeba0eSChris Fallin return Err(CodegenError::CodeTooLarge); 178017eeba0eSChris Fallin } 1781b1307638SJamey Sharp let v = self.vreg_types.len(); 1782d94173eaSTrevor Elliott let (regclasses, tys) = I::rc_for_type(ty)?; 1783*b5d2ff5dSChris Fallin 1784*b5d2ff5dSChris Fallin // Check that new indices are in-bounds for regalloc2's 1785*b5d2ff5dSChris Fallin // VReg/Operand representation. 1786*b5d2ff5dSChris Fallin if v + regclasses.len() > VReg::MAX { 1787d94173eaSTrevor Elliott return Err(CodegenError::CodeTooLarge); 1788d94173eaSTrevor Elliott } 1789d94173eaSTrevor Elliott 1790*b5d2ff5dSChris Fallin // Check that new indices are in-bounds for our Reg 1791*b5d2ff5dSChris Fallin // bit-packing on top of the RA2 types, which represents 1792*b5d2ff5dSChris Fallin // spillslots as well. 1793*b5d2ff5dSChris Fallin let check = |vreg: regalloc2::VReg| -> CodegenResult<Reg> { 1794*b5d2ff5dSChris Fallin Reg::from_virtual_reg_checked(vreg).ok_or(CodegenError::CodeTooLarge) 1795*b5d2ff5dSChris Fallin }; 1796*b5d2ff5dSChris Fallin 1797d94173eaSTrevor Elliott let regs: ValueRegs<Reg> = match regclasses { 1798*b5d2ff5dSChris Fallin &[rc0] => ValueRegs::one(check(VReg::new(v, rc0))?), 1799*b5d2ff5dSChris Fallin &[rc0, rc1] => ValueRegs::two(check(VReg::new(v, rc0))?, check(VReg::new(v + 1, rc1))?), 1800d94173eaSTrevor Elliott // We can extend this if/when we support 32-bit targets; e.g., 1801d94173eaSTrevor Elliott // an i128 on a 32-bit machine will need up to four machine regs 1802d94173eaSTrevor Elliott // for a `Value`. 1803d94173eaSTrevor Elliott _ => panic!("Value must reside in 1 or 2 registers"), 1804d94173eaSTrevor Elliott }; 1805d94173eaSTrevor Elliott for (®_ty, ®) in tys.iter().zip(regs.regs().iter()) { 1806b1307638SJamey Sharp let vreg = reg.to_virtual_reg().unwrap(); 1807b1307638SJamey Sharp debug_assert_eq!(self.vreg_types.len(), vreg.index()); 1808b1307638SJamey Sharp self.vreg_types.push(reg_ty); 1809d94173eaSTrevor Elliott } 1810f466aa26SChris Fallin 1811f466aa26SChris Fallin // Create empty facts for each allocated vreg. 1812b1307638SJamey Sharp self.facts.resize(self.vreg_types.len(), None); 1813f466aa26SChris Fallin 1814d94173eaSTrevor Elliott Ok(regs) 1815d94173eaSTrevor Elliott } 1816d94173eaSTrevor Elliott 181717eeba0eSChris Fallin /// Allocate a fresh ValueRegs, deferring any out-of-vregs 181817eeba0eSChris Fallin /// errors. This is useful in places where we cannot bubble a 181917eeba0eSChris Fallin /// `CodegenResult` upward easily, and which are known to be 182017eeba0eSChris Fallin /// invoked from within the lowering loop that checks the deferred 182117eeba0eSChris Fallin /// error status below. 182217eeba0eSChris Fallin pub fn alloc_with_deferred_error(&mut self, ty: Type) -> ValueRegs<Reg> { 182317eeba0eSChris Fallin match self.alloc(ty) { 182417eeba0eSChris Fallin Ok(x) => x, 182517eeba0eSChris Fallin Err(e) => { 182617eeba0eSChris Fallin self.deferred_error = Some(e); 182717eeba0eSChris Fallin self.bogus_for_deferred_error(ty) 182817eeba0eSChris Fallin } 182917eeba0eSChris Fallin } 183017eeba0eSChris Fallin } 183117eeba0eSChris Fallin 183217eeba0eSChris Fallin /// Take any deferred error that was accumulated by `alloc_with_deferred_error`. 183317eeba0eSChris Fallin pub fn take_deferred_error(&mut self) -> Option<CodegenError> { 183417eeba0eSChris Fallin self.deferred_error.take() 183517eeba0eSChris Fallin } 183617eeba0eSChris Fallin 183717eeba0eSChris Fallin /// Produce an bogus VReg placeholder with the proper number of 183817eeba0eSChris Fallin /// registers for the given type. This is meant to be used with 183917eeba0eSChris Fallin /// deferred allocation errors (see `Lower::alloc_tmp()`). 184017eeba0eSChris Fallin fn bogus_for_deferred_error(&self, ty: Type) -> ValueRegs<Reg> { 184117eeba0eSChris Fallin let (regclasses, _tys) = I::rc_for_type(ty).expect("must have valid type"); 184217eeba0eSChris Fallin match regclasses { 184317eeba0eSChris Fallin &[rc0] => ValueRegs::one(VReg::new(0, rc0).into()), 184417eeba0eSChris Fallin &[rc0, rc1] => ValueRegs::two(VReg::new(0, rc0).into(), VReg::new(1, rc1).into()), 184517eeba0eSChris Fallin _ => panic!("Value must reside in 1 or 2 registers"), 184617eeba0eSChris Fallin } 184717eeba0eSChris Fallin } 184817eeba0eSChris Fallin 18493aa32064SJamey Sharp /// Rewrite any mention of `from` into `to`. 18503aa32064SJamey Sharp pub fn set_vreg_alias(&mut self, from: Reg, to: Reg) { 18513aa32064SJamey Sharp let from = from.into(); 18523aa32064SJamey Sharp let resolved_to = self.resolve_vreg_alias(to.into()); 18533aa32064SJamey Sharp // Disallow cycles (see below). 18543aa32064SJamey Sharp assert_ne!(resolved_to, from); 18553aa32064SJamey Sharp 18563aa32064SJamey Sharp // Maintain the invariant that PCC facts only exist on vregs 18573aa32064SJamey Sharp // which aren't aliases. We want to preserve whatever was 18583aa32064SJamey Sharp // stated about the vreg before its producer was lowered. 18593aa32064SJamey Sharp if let Some(fact) = self.facts[from.vreg()].take() { 18603aa32064SJamey Sharp self.set_fact(resolved_to, fact); 18613aa32064SJamey Sharp } 18623aa32064SJamey Sharp 18633aa32064SJamey Sharp let old_alias = self.vreg_aliases.insert(from, resolved_to); 18643aa32064SJamey Sharp debug_assert_eq!(old_alias, None); 18653aa32064SJamey Sharp } 18663aa32064SJamey Sharp 18673aa32064SJamey Sharp fn resolve_vreg_alias(&self, mut vreg: regalloc2::VReg) -> regalloc2::VReg { 18683aa32064SJamey Sharp // We prevent cycles from existing by resolving targets of 18693aa32064SJamey Sharp // aliases eagerly before setting them. If the target resolves 18703aa32064SJamey Sharp // to the origin of the alias, then a cycle would be created 18713aa32064SJamey Sharp // and the alias is disallowed. Because of the structure of 18723aa32064SJamey Sharp // SSA code (one instruction can refer to another's defs but 18733aa32064SJamey Sharp // not vice-versa, except indirectly through 18743aa32064SJamey Sharp // phis/blockparams), cycles should not occur as we use 18753aa32064SJamey Sharp // aliases to redirect vregs to the temps that actually define 18763aa32064SJamey Sharp // them. 18773aa32064SJamey Sharp while let Some(to) = self.vreg_aliases.get(&vreg) { 18783aa32064SJamey Sharp vreg = *to; 18793aa32064SJamey Sharp } 18803aa32064SJamey Sharp vreg 18813aa32064SJamey Sharp } 18823aa32064SJamey Sharp 18833aa32064SJamey Sharp #[inline] 18843aa32064SJamey Sharp fn debug_assert_no_vreg_aliases(&self, mut list: impl Iterator<Item = VReg>) { 18853aa32064SJamey Sharp debug_assert!(list.all(|vreg| !self.vreg_aliases.contains_key(&vreg))); 18863aa32064SJamey Sharp } 18873aa32064SJamey Sharp 1888f466aa26SChris Fallin /// Set the proof-carrying code fact on a given virtual register. 1889f466aa26SChris Fallin /// 1890f466aa26SChris Fallin /// Returns the old fact, if any (only one fact can be stored). 18913aa32064SJamey Sharp fn set_fact(&mut self, vreg: regalloc2::VReg, fact: Fact) -> Option<Fact> { 1892fef8a90fSChris Fallin trace!("vreg {:?} has fact: {:?}", vreg, fact); 18933aa32064SJamey Sharp debug_assert!(!self.vreg_aliases.contains_key(&vreg)); 18943aa32064SJamey Sharp self.facts[vreg.vreg()].replace(fact) 1895fef8a90fSChris Fallin } 1896fef8a90fSChris Fallin 1897f262c311SChris Fallin /// Set a fact only if one doesn't already exist. 1898f262c311SChris Fallin pub fn set_fact_if_missing(&mut self, vreg: VirtualReg, fact: Fact) { 18993aa32064SJamey Sharp let vreg = self.resolve_vreg_alias(vreg.into()); 19003aa32064SJamey Sharp if self.facts[vreg.vreg()].is_none() { 1901f262c311SChris Fallin self.set_fact(vreg, fact); 1902f262c311SChris Fallin } 1903f262c311SChris Fallin } 1904f262c311SChris Fallin 1905f466aa26SChris Fallin /// Allocate a fresh ValueRegs, with a given fact to apply if 1906f466aa26SChris Fallin /// the value fits in one VReg. 1907f466aa26SChris Fallin pub fn alloc_with_maybe_fact( 1908f466aa26SChris Fallin &mut self, 1909f466aa26SChris Fallin ty: Type, 1910f466aa26SChris Fallin fact: Option<Fact>, 1911f466aa26SChris Fallin ) -> CodegenResult<ValueRegs<Reg>> { 1912f466aa26SChris Fallin let result = self.alloc(ty)?; 1913f466aa26SChris Fallin 1914f466aa26SChris Fallin // Ensure that we don't lose a fact on a value that splits 1915f466aa26SChris Fallin // into multiple VRegs. 1916f466aa26SChris Fallin assert!(result.len() == 1 || fact.is_none()); 1917f466aa26SChris Fallin if let Some(fact) = fact { 19183aa32064SJamey Sharp self.set_fact(result.regs()[0].into(), fact); 1919f466aa26SChris Fallin } 1920f466aa26SChris Fallin 1921f466aa26SChris Fallin Ok(result) 1922f466aa26SChris Fallin } 1923d94173eaSTrevor Elliott } 1924d94173eaSTrevor Elliott 192583f182b3SAndrew Brown /// This structure tracks the large constants used in VCode that will be emitted separately by the 192683f182b3SAndrew Brown /// [MachBuffer]. 192783f182b3SAndrew Brown /// 192883f182b3SAndrew Brown /// First, during the lowering phase, constants are inserted using 1929d38d387aSAlex Crichton /// [VCodeConstants.insert]; an intermediate handle, `VCodeConstant`, tracks what constants are 193083f182b3SAndrew Brown /// used in this phase. Some deduplication is performed, when possible, as constant 193183f182b3SAndrew Brown /// values are inserted. 193283f182b3SAndrew Brown /// 193383f182b3SAndrew Brown /// Secondly, during the emission phase, the [MachBuffer] assigns [MachLabel]s for each of the 193483f182b3SAndrew Brown /// constants so that instructions can refer to the value's memory location. The [MachBuffer] 193583f182b3SAndrew Brown /// then writes the constant values to the buffer. 193683f182b3SAndrew Brown #[derive(Default)] 193783f182b3SAndrew Brown pub struct VCodeConstants { 193883f182b3SAndrew Brown constants: PrimaryMap<VCodeConstant, VCodeConstantData>, 193983f182b3SAndrew Brown pool_uses: HashMap<Constant, VCodeConstant>, 194083f182b3SAndrew Brown well_known_uses: HashMap<*const [u8], VCodeConstant>, 1941eb435f30SChris Fallin u64s: HashMap<[u8; 8], VCodeConstant>, 194283f182b3SAndrew Brown } 194383f182b3SAndrew Brown impl VCodeConstants { 194483f182b3SAndrew Brown /// Initialize the structure with the expected number of constants. 194583f182b3SAndrew Brown pub fn with_capacity(expected_num_constants: usize) -> Self { 194683f182b3SAndrew Brown Self { 194783f182b3SAndrew Brown constants: PrimaryMap::with_capacity(expected_num_constants), 194883f182b3SAndrew Brown pool_uses: HashMap::with_capacity(expected_num_constants), 194983f182b3SAndrew Brown well_known_uses: HashMap::new(), 1950eb435f30SChris Fallin u64s: HashMap::new(), 195183f182b3SAndrew Brown } 195283f182b3SAndrew Brown } 195383f182b3SAndrew Brown 195483f182b3SAndrew Brown /// Insert a constant; using this method indicates that a constant value will be used and thus 195583f182b3SAndrew Brown /// will be emitted to the `MachBuffer`. The current implementation can deduplicate constants 195683f182b3SAndrew Brown /// that are [VCodeConstantData::Pool] or [VCodeConstantData::WellKnown] but not 195783f182b3SAndrew Brown /// [VCodeConstantData::Generated]. 195883f182b3SAndrew Brown pub fn insert(&mut self, data: VCodeConstantData) -> VCodeConstant { 195983f182b3SAndrew Brown match data { 196083f182b3SAndrew Brown VCodeConstantData::Generated(_) => self.constants.push(data), 196183f182b3SAndrew Brown VCodeConstantData::Pool(constant, _) => match self.pool_uses.get(&constant) { 196283f182b3SAndrew Brown None => { 196383f182b3SAndrew Brown let vcode_constant = self.constants.push(data); 196483f182b3SAndrew Brown self.pool_uses.insert(constant, vcode_constant); 196583f182b3SAndrew Brown vcode_constant 196683f182b3SAndrew Brown } 196783f182b3SAndrew Brown Some(&vcode_constant) => vcode_constant, 196883f182b3SAndrew Brown }, 196983f182b3SAndrew Brown VCodeConstantData::WellKnown(data_ref) => { 1970eb435f30SChris Fallin match self.well_known_uses.entry(data_ref as *const [u8]) { 1971eb435f30SChris Fallin Entry::Vacant(v) => { 197283f182b3SAndrew Brown let vcode_constant = self.constants.push(data); 1973eb435f30SChris Fallin v.insert(vcode_constant); 197483f182b3SAndrew Brown vcode_constant 197583f182b3SAndrew Brown } 1976eb435f30SChris Fallin Entry::Occupied(o) => *o.get(), 197783f182b3SAndrew Brown } 197883f182b3SAndrew Brown } 1979eb435f30SChris Fallin VCodeConstantData::U64(value) => match self.u64s.entry(value) { 1980eb435f30SChris Fallin Entry::Vacant(v) => { 1981eb435f30SChris Fallin let vcode_constant = self.constants.push(data); 1982eb435f30SChris Fallin v.insert(vcode_constant); 1983eb435f30SChris Fallin vcode_constant 1984eb435f30SChris Fallin } 1985eb435f30SChris Fallin Entry::Occupied(o) => *o.get(), 1986eb435f30SChris Fallin }, 198783f182b3SAndrew Brown } 198883f182b3SAndrew Brown } 198983f182b3SAndrew Brown 199083f182b3SAndrew Brown /// Return the number of constants inserted. 199183f182b3SAndrew Brown pub fn len(&self) -> usize { 199283f182b3SAndrew Brown self.constants.len() 199383f182b3SAndrew Brown } 199483f182b3SAndrew Brown 1995d38d387aSAlex Crichton /// Iterate over the `VCodeConstant` keys inserted in this structure. 199683f182b3SAndrew Brown pub fn keys(&self) -> Keys<VCodeConstant> { 199783f182b3SAndrew Brown self.constants.keys() 199883f182b3SAndrew Brown } 199983f182b3SAndrew Brown 2000d38d387aSAlex Crichton /// Iterate over the `VCodeConstant` keys and the data (as a byte slice) inserted in this 200183f182b3SAndrew Brown /// structure. 200283f182b3SAndrew Brown pub fn iter(&self) -> impl Iterator<Item = (VCodeConstant, &VCodeConstantData)> { 200383f182b3SAndrew Brown self.constants.iter() 200483f182b3SAndrew Brown } 200549dd8fd7SAlex Crichton 200649dd8fd7SAlex Crichton /// Returns the data associated with the specified constant. 200749dd8fd7SAlex Crichton pub fn get(&self, c: VCodeConstant) -> &VCodeConstantData { 200849dd8fd7SAlex Crichton &self.constants[c] 200949dd8fd7SAlex Crichton } 201097f6a8b3SSaúl Cabrera 201197f6a8b3SSaúl Cabrera /// Checks if the given [VCodeConstantData] is registered as 201297f6a8b3SSaúl Cabrera /// used by the pool. 201397f6a8b3SSaúl Cabrera pub fn pool_uses(&self, constant: &VCodeConstantData) -> bool { 201497f6a8b3SSaúl Cabrera match constant { 201597f6a8b3SSaúl Cabrera VCodeConstantData::Pool(c, _) => self.pool_uses.contains_key(c), 201697f6a8b3SSaúl Cabrera _ => false, 201797f6a8b3SSaúl Cabrera } 201897f6a8b3SSaúl Cabrera } 201983f182b3SAndrew Brown } 202083f182b3SAndrew Brown 202183f182b3SAndrew Brown /// A use of a constant by one or more VCode instructions; see [VCodeConstants]. 202283f182b3SAndrew Brown #[derive(Clone, Copy, Debug, PartialEq, Eq)] 202383f182b3SAndrew Brown pub struct VCodeConstant(u32); 202483f182b3SAndrew Brown entity_impl!(VCodeConstant); 202583f182b3SAndrew Brown 202683f182b3SAndrew Brown /// Identify the different types of constant that can be inserted into [VCodeConstants]. Tracking 202783f182b3SAndrew Brown /// these separately instead of as raw byte buffers allows us to avoid some duplication. 202883f182b3SAndrew Brown pub enum VCodeConstantData { 202983f182b3SAndrew Brown /// A constant already present in the Cranelift IR 203083f182b3SAndrew Brown /// [ConstantPool](crate::ir::constant::ConstantPool). 203183f182b3SAndrew Brown Pool(Constant, ConstantData), 203283f182b3SAndrew Brown /// A reference to a well-known constant value that is statically encoded within the compiler. 203383f182b3SAndrew Brown WellKnown(&'static [u8]), 203483f182b3SAndrew Brown /// A constant value generated during lowering; the value may depend on the instruction context 203583f182b3SAndrew Brown /// which makes it difficult to de-duplicate--if possible, use other variants. 203683f182b3SAndrew Brown Generated(ConstantData), 2037eb435f30SChris Fallin /// A constant of at most 64 bits. These are deduplicated as 2038eb435f30SChris Fallin /// well. Stored as a fixed-size array of `u8` so that we do not 2039eb435f30SChris Fallin /// encounter endianness problems when cross-compiling. 2040eb435f30SChris Fallin U64([u8; 8]), 204183f182b3SAndrew Brown } 204283f182b3SAndrew Brown impl VCodeConstantData { 204383f182b3SAndrew Brown /// Retrieve the constant data as a byte slice. 204483f182b3SAndrew Brown pub fn as_slice(&self) -> &[u8] { 204583f182b3SAndrew Brown match self { 204683f182b3SAndrew Brown VCodeConstantData::Pool(_, d) | VCodeConstantData::Generated(d) => d.as_slice(), 204783f182b3SAndrew Brown VCodeConstantData::WellKnown(d) => d, 2048eb435f30SChris Fallin VCodeConstantData::U64(value) => &value[..], 204983f182b3SAndrew Brown } 205083f182b3SAndrew Brown } 205183f182b3SAndrew Brown 205283f182b3SAndrew Brown /// Calculate the alignment of the constant data. 205383f182b3SAndrew Brown pub fn alignment(&self) -> u32 { 205490ac295eSAlex Crichton if self.as_slice().len() <= 8 { 8 } else { 16 } 205583f182b3SAndrew Brown } 205683f182b3SAndrew Brown } 205783f182b3SAndrew Brown 205883f182b3SAndrew Brown #[cfg(test)] 205983f182b3SAndrew Brown mod test { 206083f182b3SAndrew Brown use super::*; 20610889323aSSSD use core::mem::size_of; 206283f182b3SAndrew Brown 206383f182b3SAndrew Brown #[test] 206483f182b3SAndrew Brown fn size_of_constant_structs() { 206583f182b3SAndrew Brown assert_eq!(size_of::<Constant>(), 4); 206683f182b3SAndrew Brown assert_eq!(size_of::<VCodeConstant>(), 4); 206748f4621fSAlex Crichton assert_eq!(size_of::<ConstantData>(), 3 * size_of::<usize>()); 206848f4621fSAlex Crichton assert_eq!(size_of::<VCodeConstantData>(), 4 * size_of::<usize>()); 206983f182b3SAndrew Brown assert_eq!( 207083f182b3SAndrew Brown size_of::<PrimaryMap<VCodeConstant, VCodeConstantData>>(), 207148f4621fSAlex Crichton 3 * size_of::<usize>() 207283f182b3SAndrew Brown ); 20735e5e5206SChris Fallin // TODO The VCodeConstants structure's memory size could be further optimized. 20745e5e5206SChris Fallin // With certain versions of Rust, each `HashMap` in `VCodeConstants` occupied at 20755e5e5206SChris Fallin // least 48 bytes, making an empty `VCodeConstants` cost 120 bytes. 207683f182b3SAndrew Brown } 207783f182b3SAndrew Brown } 2078