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 2083f182b3SAndrew Brown use crate::ir::{self, types, Constant, ConstantData, SourceLoc}; 21d8357426SChris Fallin use crate::machinst::*; 22d8357426SChris Fallin use crate::settings; 232b9fefe8SChris Fallin use crate::timing; 24d8357426SChris Fallin use regalloc::Function as RegallocFunction; 25d8357426SChris Fallin use regalloc::Set as RegallocSet; 26be6f060aSChris Fallin use regalloc::{ 2771768bb6SChris Fallin BlockIx, InstIx, PrettyPrint, Range, RegAllocResult, RegClass, RegUsageCollector, 2871768bb6SChris Fallin RegUsageMapper, SpillSlot, StackmapRequestInfo, 29be6f060aSChris Fallin }; 30d8357426SChris Fallin 31d8357426SChris Fallin use alloc::boxed::Box; 324f919c64SBenjamin Bouvier use alloc::{borrow::Cow, vec::Vec}; 3383f182b3SAndrew Brown use cranelift_entity::{entity_impl, Keys, PrimaryMap}; 34de4af90aSYury Delendik use std::cell::RefCell; 3583f182b3SAndrew Brown use std::collections::HashMap; 36d8357426SChris Fallin use std::fmt; 37d8357426SChris Fallin use std::iter; 38d8357426SChris Fallin use std::string::String; 39d8357426SChris Fallin 40d8357426SChris Fallin /// Index referring to an instruction in VCode. 41d8357426SChris Fallin pub type InsnIndex = u32; 42d8357426SChris Fallin /// Index referring to a basic block in VCode. 43d8357426SChris Fallin pub type BlockIndex = u32; 44d8357426SChris Fallin 45d8357426SChris Fallin /// VCodeInst wraps all requirements for a MachInst to be in VCode: it must be 46d8357426SChris Fallin /// a `MachInst` and it must be able to emit itself at least to a `SizeCodeSink`. 4772e6be93SChris Fallin pub trait VCodeInst: MachInst + MachInstEmit {} 4872e6be93SChris Fallin impl<I: MachInst + MachInstEmit> VCodeInst for I {} 49d8357426SChris Fallin 50d8357426SChris Fallin /// A function in "VCode" (virtualized-register code) form, after lowering. 51d8357426SChris Fallin /// This is essentially a standard CFG of basic blocks, where each basic block 52d8357426SChris Fallin /// consists of lowered instructions produced by the machine-specific backend. 53d8357426SChris Fallin pub struct VCode<I: VCodeInst> { 54d8357426SChris Fallin /// Function liveins. 55d8357426SChris Fallin liveins: RegallocSet<RealReg>, 56d8357426SChris Fallin 57d8357426SChris Fallin /// Function liveouts. 58d8357426SChris Fallin liveouts: RegallocSet<RealReg>, 59d8357426SChris Fallin 60d8357426SChris Fallin /// VReg IR-level types. 61d8357426SChris Fallin vreg_types: Vec<Type>, 62d8357426SChris Fallin 6308353fccSChris Fallin /// Do we have any ref values among our vregs? 6408353fccSChris Fallin have_ref_values: bool, 6508353fccSChris Fallin 66d8357426SChris Fallin /// Lowered machine instructions in order corresponding to the original IR. 6748cf2c2fSChris Fallin insts: Vec<I>, 68d8357426SChris Fallin 69b691770fSChris Fallin /// Source locations for each instruction. (`SourceLoc` is a `u32`, so it is 70b691770fSChris Fallin /// reasonable to keep one of these per instruction.) 71b691770fSChris Fallin srclocs: Vec<SourceLoc>, 72b691770fSChris Fallin 73d8357426SChris Fallin /// Entry block. 74d8357426SChris Fallin entry: BlockIndex, 75d8357426SChris Fallin 76d8357426SChris Fallin /// Block instruction indices. 7748cf2c2fSChris Fallin block_ranges: Vec<(InsnIndex, InsnIndex)>, 78d8357426SChris Fallin 79d8357426SChris Fallin /// Block successors: index range in the successor-list below. 80d8357426SChris Fallin block_succ_range: Vec<(usize, usize)>, 81d8357426SChris Fallin 82d8357426SChris Fallin /// Block successor lists, concatenated into one Vec. The `block_succ_range` 83d8357426SChris Fallin /// list of tuples above gives (start, end) ranges within this list that 84d8357426SChris Fallin /// correspond to each basic block's successors. 854f919c64SBenjamin Bouvier block_succs: Vec<BlockIx>, 86d8357426SChris Fallin 8772e6be93SChris Fallin /// Block-order information. 8872e6be93SChris Fallin block_order: BlockLoweringOrder, 89d8357426SChris Fallin 90d8357426SChris Fallin /// ABI object. 91e8f772c1SChris Fallin abi: Box<dyn ABICallee<I = I>>, 9208353fccSChris Fallin 93c5bbc874SBenjamin Bouvier /// Constant information used during code emission. This should be 94c5bbc874SBenjamin Bouvier /// immutable across function compilations within the same module. 95c5bbc874SBenjamin Bouvier emit_info: I::Info, 96c5bbc874SBenjamin Bouvier 9708353fccSChris Fallin /// Safepoint instruction indices. Filled in post-regalloc. (Prior to 9808353fccSChris Fallin /// regalloc, the safepoint instructions are listed in the separate 9908353fccSChris Fallin /// `StackmapRequestInfo` held separate from the `VCode`.) 10008353fccSChris Fallin safepoint_insns: Vec<InsnIndex>, 10108353fccSChris Fallin 10208353fccSChris Fallin /// For each safepoint entry in `safepoint_insns`, a list of `SpillSlot`s. 10308353fccSChris Fallin /// These are used to generate actual stack maps at emission. Filled in 10408353fccSChris Fallin /// post-regalloc. 10508353fccSChris Fallin safepoint_slots: Vec<Vec<SpillSlot>>, 106de4af90aSYury Delendik 107c84d6be6SChris Fallin /// Do we generate debug info? 108c84d6be6SChris Fallin generate_debug_info: bool, 109c84d6be6SChris Fallin 110c84d6be6SChris Fallin /// Instruction end offsets, instruction indices at each label, and total 111c84d6be6SChris Fallin /// buffer size. Only present if `generate_debug_info` is set. 112c84d6be6SChris Fallin insts_layout: RefCell<(Vec<u32>, Vec<u32>, u32)>, 11383f182b3SAndrew Brown 11483f182b3SAndrew Brown /// Constants. 11583f182b3SAndrew Brown constants: VCodeConstants, 116997fab55SChris Fallin 117997fab55SChris Fallin /// Are any debug value-labels present? If not, we can skip the 118997fab55SChris Fallin /// post-emission analysis. 119997fab55SChris Fallin has_value_labels: bool, 120d8357426SChris Fallin } 121d8357426SChris Fallin 122d8357426SChris Fallin /// A builder for a VCode function body. This builder is designed for the 123d8357426SChris Fallin /// lowering approach that we take: we traverse basic blocks in forward 124d8357426SChris Fallin /// (original IR) order, but within each basic block, we generate code from 125d8357426SChris Fallin /// bottom to top; and within each IR instruction that we visit in this reverse 126d8357426SChris Fallin /// order, we emit machine instructions in *forward* order again. 127d8357426SChris Fallin /// 128d8357426SChris Fallin /// Hence, to produce the final instructions in proper order, we perform two 129d8357426SChris Fallin /// swaps. First, the machine instructions (`I` instances) are produced in 130d8357426SChris Fallin /// forward order for an individual IR instruction. Then these are *reversed* 131d8357426SChris Fallin /// and concatenated to `bb_insns` at the end of the IR instruction lowering. 132d8357426SChris Fallin /// The `bb_insns` vec will thus contain all machine instructions for a basic 133d8357426SChris Fallin /// block, in reverse order. Finally, when we're done with a basic block, we 134d8357426SChris Fallin /// reverse the whole block's vec of instructions again, and concatenate onto 135d8357426SChris Fallin /// the VCode's insts. 136d8357426SChris Fallin pub struct VCodeBuilder<I: VCodeInst> { 137d8357426SChris Fallin /// In-progress VCode. 138d8357426SChris Fallin vcode: VCode<I>, 139d8357426SChris Fallin 14008353fccSChris Fallin /// In-progress stack map-request info. 14105bf9ea3SNick Fitzgerald stack_map_info: StackmapRequestInfo, 14208353fccSChris Fallin 14372e6be93SChris Fallin /// Index of the last block-start in the vcode. 14472e6be93SChris Fallin block_start: InsnIndex, 145d8357426SChris Fallin 146d8357426SChris Fallin /// Start of succs for the current block in the concatenated succs list. 147d8357426SChris Fallin succ_start: usize, 148b691770fSChris Fallin 149b691770fSChris Fallin /// Current source location. 150b691770fSChris Fallin cur_srcloc: SourceLoc, 151d8357426SChris Fallin } 152d8357426SChris Fallin 153d8357426SChris Fallin impl<I: VCodeInst> VCodeBuilder<I> { 154d8357426SChris Fallin /// Create a new VCodeBuilder. 155c5bbc874SBenjamin Bouvier pub fn new( 156c5bbc874SBenjamin Bouvier abi: Box<dyn ABICallee<I = I>>, 157c5bbc874SBenjamin Bouvier emit_info: I::Info, 158c5bbc874SBenjamin Bouvier block_order: BlockLoweringOrder, 15983f182b3SAndrew Brown constants: VCodeConstants, 160c5bbc874SBenjamin Bouvier ) -> VCodeBuilder<I> { 16126529006SChris Fallin let reftype_class = I::ref_type_regclass(abi.flags()); 162c84d6be6SChris Fallin let vcode = VCode::new( 163c84d6be6SChris Fallin abi, 164c84d6be6SChris Fallin emit_info, 165c84d6be6SChris Fallin block_order, 166c84d6be6SChris Fallin constants, 167c84d6be6SChris Fallin /* generate_debug_info = */ true, 168c84d6be6SChris Fallin ); 16905bf9ea3SNick Fitzgerald let stack_map_info = StackmapRequestInfo { 17008353fccSChris Fallin reftype_class, 17108353fccSChris Fallin reftyped_vregs: vec![], 17208353fccSChris Fallin safepoint_insns: vec![], 17308353fccSChris Fallin }; 17408353fccSChris Fallin 175d8357426SChris Fallin VCodeBuilder { 176d8357426SChris Fallin vcode, 17705bf9ea3SNick Fitzgerald stack_map_info, 17872e6be93SChris Fallin block_start: 0, 179d8357426SChris Fallin succ_start: 0, 180b691770fSChris Fallin cur_srcloc: SourceLoc::default(), 181d8357426SChris Fallin } 182d8357426SChris Fallin } 183d8357426SChris Fallin 184d8357426SChris Fallin /// Access the ABI object. 185e8f772c1SChris Fallin pub fn abi(&mut self) -> &mut dyn ABICallee<I = I> { 186d8357426SChris Fallin &mut *self.vcode.abi 187d8357426SChris Fallin } 188d8357426SChris Fallin 18972e6be93SChris Fallin /// Access to the BlockLoweringOrder object. 19072e6be93SChris Fallin pub fn block_order(&self) -> &BlockLoweringOrder { 19172e6be93SChris Fallin &self.vcode.block_order 1921d90751bSBenjamin Bouvier } 1931d90751bSBenjamin Bouvier 194d8357426SChris Fallin /// Set the type of a VReg. 195d8357426SChris Fallin pub fn set_vreg_type(&mut self, vreg: VirtualReg, ty: Type) { 19648f0b10cSJohnnie Birch if self.vcode.vreg_types.len() <= vreg.get_index() { 197ef5de04dSBenjamin Bouvier self.vcode 198ef5de04dSBenjamin Bouvier .vreg_types 199ef5de04dSBenjamin Bouvier .resize(vreg.get_index() + 1, ir::types::I8); 200d8357426SChris Fallin } 201d8357426SChris Fallin self.vcode.vreg_types[vreg.get_index()] = ty; 20208353fccSChris Fallin if is_reftype(ty) { 20305bf9ea3SNick Fitzgerald self.stack_map_info.reftyped_vregs.push(vreg); 20408353fccSChris Fallin self.vcode.have_ref_values = true; 20508353fccSChris Fallin } 20608353fccSChris Fallin } 20708353fccSChris Fallin 208d8357426SChris Fallin /// Set the current block as the entry block. 209d8357426SChris Fallin pub fn set_entry(&mut self, block: BlockIndex) { 210d8357426SChris Fallin self.vcode.entry = block; 211d8357426SChris Fallin } 212d8357426SChris Fallin 213d8357426SChris Fallin /// End the current basic block. Must be called after emitting vcode insts 214d8357426SChris Fallin /// for IR insts and prior to ending the function (building the VCode). 21572e6be93SChris Fallin pub fn end_bb(&mut self) { 21672e6be93SChris Fallin let start_idx = self.block_start; 217d8357426SChris Fallin let end_idx = self.vcode.insts.len() as InsnIndex; 21872e6be93SChris Fallin self.block_start = end_idx; 219d8357426SChris Fallin // Add the instruction index range to the list of blocks. 220d8357426SChris Fallin self.vcode.block_ranges.push((start_idx, end_idx)); 221d8357426SChris Fallin // End the successors list. 222d8357426SChris Fallin let succ_end = self.vcode.block_succs.len(); 223d8357426SChris Fallin self.vcode 224d8357426SChris Fallin .block_succ_range 225d8357426SChris Fallin .push((self.succ_start, succ_end)); 226d8357426SChris Fallin self.succ_start = succ_end; 227d8357426SChris Fallin } 228d8357426SChris Fallin 229d8357426SChris Fallin /// Push an instruction for the current BB and current IR inst within the BB. 23008353fccSChris Fallin pub fn push(&mut self, insn: I, is_safepoint: bool) { 231d8357426SChris Fallin match insn.is_term() { 232d8357426SChris Fallin MachTerminator::None | MachTerminator::Ret => {} 233d8357426SChris Fallin MachTerminator::Uncond(target) => { 23472e6be93SChris Fallin self.vcode.block_succs.push(BlockIx::new(target.get())); 235d8357426SChris Fallin } 236d8357426SChris Fallin MachTerminator::Cond(true_branch, false_branch) => { 23772e6be93SChris Fallin self.vcode.block_succs.push(BlockIx::new(true_branch.get())); 23872e6be93SChris Fallin self.vcode 23972e6be93SChris Fallin .block_succs 24072e6be93SChris Fallin .push(BlockIx::new(false_branch.get())); 241d8357426SChris Fallin } 242d8357426SChris Fallin MachTerminator::Indirect(targets) => { 243d8357426SChris Fallin for target in targets { 24472e6be93SChris Fallin self.vcode.block_succs.push(BlockIx::new(target.get())); 245d8357426SChris Fallin } 246d8357426SChris Fallin } 247d8357426SChris Fallin } 248997fab55SChris Fallin if insn.defines_value_label().is_some() { 249997fab55SChris Fallin self.vcode.has_value_labels = true; 250997fab55SChris Fallin } 25172e6be93SChris Fallin self.vcode.insts.push(insn); 25272e6be93SChris Fallin self.vcode.srclocs.push(self.cur_srcloc); 25308353fccSChris Fallin if is_safepoint { 25405bf9ea3SNick Fitzgerald self.stack_map_info 25508353fccSChris Fallin .safepoint_insns 25608353fccSChris Fallin .push(InstIx::new((self.vcode.insts.len() - 1) as u32)); 25708353fccSChris Fallin } 25872e6be93SChris Fallin } 25972e6be93SChris Fallin 260b691770fSChris Fallin /// Set the current source location. 261b691770fSChris Fallin pub fn set_srcloc(&mut self, srcloc: SourceLoc) { 262b691770fSChris Fallin self.cur_srcloc = srcloc; 263d8357426SChris Fallin } 264d8357426SChris Fallin 26583f182b3SAndrew Brown /// Access the constants. 26683f182b3SAndrew Brown pub fn constants(&mut self) -> &mut VCodeConstants { 26783f182b3SAndrew Brown &mut self.vcode.constants 26883f182b3SAndrew Brown } 26983f182b3SAndrew Brown 27008353fccSChris Fallin /// Build the final VCode, returning the vcode itself as well as auxiliary 27108353fccSChris Fallin /// information, such as the stack map request information. 27208353fccSChris Fallin pub fn build(self) -> (VCode<I>, StackmapRequestInfo) { 27308353fccSChris Fallin // TODO: come up with an abstraction for "vcode and auxiliary data". The 27408353fccSChris Fallin // auxiliary data needs to be separate from the vcode so that it can be 27508353fccSChris Fallin // referenced as the vcode is mutated (e.g. by the register allocator). 27605bf9ea3SNick Fitzgerald (self.vcode, self.stack_map_info) 277d8357426SChris Fallin } 278d8357426SChris Fallin } 279d8357426SChris Fallin 280d8357426SChris Fallin fn is_redundant_move<I: VCodeInst>(insn: &I) -> bool { 281d8357426SChris Fallin if let Some((to, from)) = insn.is_move() { 282d8357426SChris Fallin to.to_reg() == from 283d8357426SChris Fallin } else { 284d8357426SChris Fallin false 285d8357426SChris Fallin } 286d8357426SChris Fallin } 287d8357426SChris Fallin 28808353fccSChris Fallin /// Is this type a reference type? 28908353fccSChris Fallin fn is_reftype(ty: Type) -> bool { 29026529006SChris Fallin ty == types::R64 || ty == types::R32 29108353fccSChris Fallin } 29208353fccSChris Fallin 293d8357426SChris Fallin impl<I: VCodeInst> VCode<I> { 294d8357426SChris Fallin /// New empty VCode. 295c5bbc874SBenjamin Bouvier fn new( 296c5bbc874SBenjamin Bouvier abi: Box<dyn ABICallee<I = I>>, 297c5bbc874SBenjamin Bouvier emit_info: I::Info, 298c5bbc874SBenjamin Bouvier block_order: BlockLoweringOrder, 29983f182b3SAndrew Brown constants: VCodeConstants, 300c84d6be6SChris Fallin generate_debug_info: bool, 301c5bbc874SBenjamin Bouvier ) -> VCode<I> { 302d8357426SChris Fallin VCode { 303d8357426SChris Fallin liveins: abi.liveins(), 304d8357426SChris Fallin liveouts: abi.liveouts(), 305d8357426SChris Fallin vreg_types: vec![], 30608353fccSChris Fallin have_ref_values: false, 307d8357426SChris Fallin insts: vec![], 308b691770fSChris Fallin srclocs: vec![], 309d8357426SChris Fallin entry: 0, 310d8357426SChris Fallin block_ranges: vec![], 311d8357426SChris Fallin block_succ_range: vec![], 312d8357426SChris Fallin block_succs: vec![], 31372e6be93SChris Fallin block_order, 314d8357426SChris Fallin abi, 315c5bbc874SBenjamin Bouvier emit_info, 31608353fccSChris Fallin safepoint_insns: vec![], 31708353fccSChris Fallin safepoint_slots: vec![], 318c84d6be6SChris Fallin generate_debug_info, 319c84d6be6SChris Fallin insts_layout: RefCell::new((vec![], vec![], 0)), 32083f182b3SAndrew Brown constants, 321997fab55SChris Fallin has_value_labels: false, 322d8357426SChris Fallin } 323d8357426SChris Fallin } 324d8357426SChris Fallin 325d1b5df31SBenjamin Bouvier /// Returns the flags controlling this function's compilation. 326d1b5df31SBenjamin Bouvier pub fn flags(&self) -> &settings::Flags { 327d1b5df31SBenjamin Bouvier self.abi.flags() 328d1b5df31SBenjamin Bouvier } 329d1b5df31SBenjamin Bouvier 330d8357426SChris Fallin /// Get the IR-level type of a VReg. 331d8357426SChris Fallin pub fn vreg_type(&self, vreg: VirtualReg) -> Type { 332d8357426SChris Fallin self.vreg_types[vreg.get_index()] 333d8357426SChris Fallin } 334d8357426SChris Fallin 335d8357426SChris Fallin /// Get the number of blocks. Block indices will be in the range `0 .. 336d8357426SChris Fallin /// (self.num_blocks() - 1)`. 337d8357426SChris Fallin pub fn num_blocks(&self) -> usize { 338d8357426SChris Fallin self.block_ranges.len() 339d8357426SChris Fallin } 340d8357426SChris Fallin 341d8357426SChris Fallin /// Stack frame size for the full function's body. 342d8357426SChris Fallin pub fn frame_size(&self) -> u32 { 343d8357426SChris Fallin self.abi.frame_size() 344d8357426SChris Fallin } 345d8357426SChris Fallin 346d8357426SChris Fallin /// Get the successors for a block. 3474f919c64SBenjamin Bouvier pub fn succs(&self, block: BlockIndex) -> &[BlockIx] { 348d8357426SChris Fallin let (start, end) = self.block_succ_range[block as usize]; 349d8357426SChris Fallin &self.block_succs[start..end] 350d8357426SChris Fallin } 351d8357426SChris Fallin 352d8357426SChris Fallin /// Take the results of register allocation, with a sequence of 353d8357426SChris Fallin /// instructions including spliced fill/reload/move instructions, and replace 354d8357426SChris Fallin /// the VCode with them. 355d1b5df31SBenjamin Bouvier pub fn replace_insns_from_regalloc(&mut self, result: RegAllocResult<Self>) { 356d8357426SChris Fallin // Record the spillslot count and clobbered registers for the ABI/stack 357d8357426SChris Fallin // setup code. 358d8357426SChris Fallin self.abi.set_num_spillslots(result.num_spill_slots as usize); 359d8357426SChris Fallin self.abi 360d8357426SChris Fallin .set_clobbered(result.clobbered_registers.map(|r| Writable::from_reg(*r))); 361d8357426SChris Fallin 362d8357426SChris Fallin let mut final_insns = vec![]; 363d8357426SChris Fallin let mut final_block_ranges = vec![(0, 0); self.num_blocks()]; 364b691770fSChris Fallin let mut final_srclocs = vec![]; 36508353fccSChris Fallin let mut final_safepoint_insns = vec![]; 36608353fccSChris Fallin let mut safept_idx = 0; 367d8357426SChris Fallin 36808353fccSChris Fallin assert!(result.target_map.elems().len() == self.num_blocks()); 36972e6be93SChris Fallin for block in 0..self.num_blocks() { 37008353fccSChris Fallin let start = result.target_map.elems()[block].get() as usize; 37108353fccSChris Fallin let end = if block == self.num_blocks() - 1 { 37208353fccSChris Fallin result.insns.len() 37308353fccSChris Fallin } else { 37408353fccSChris Fallin result.target_map.elems()[block + 1].get() as usize 37508353fccSChris Fallin }; 37672e6be93SChris Fallin let block = block as BlockIndex; 377d8357426SChris Fallin let final_start = final_insns.len() as InsnIndex; 378d8357426SChris Fallin 37972e6be93SChris Fallin if block == self.entry { 380d8357426SChris Fallin // Start with the prologue. 381b691770fSChris Fallin let prologue = self.abi.gen_prologue(); 382b691770fSChris Fallin let len = prologue.len(); 383b691770fSChris Fallin final_insns.extend(prologue.into_iter()); 384b691770fSChris Fallin final_srclocs.extend(iter::repeat(SourceLoc::default()).take(len)); 385d8357426SChris Fallin } 386d8357426SChris Fallin 387d8357426SChris Fallin for i in start..end { 388d8357426SChris Fallin let insn = &result.insns[i]; 389d8357426SChris Fallin 390d8357426SChris Fallin // Elide redundant moves at this point (we only know what is 391d8357426SChris Fallin // redundant once registers are allocated). 392d8357426SChris Fallin if is_redundant_move(insn) { 393d8357426SChris Fallin continue; 394d8357426SChris Fallin } 395d8357426SChris Fallin 396b691770fSChris Fallin // Is there a srcloc associated with this insn? Look it up based on original 397b691770fSChris Fallin // instruction index (if new insn corresponds to some original insn, i.e., is not 398b691770fSChris Fallin // an inserted load/spill/move). 399b691770fSChris Fallin let orig_iix = result.orig_insn_map[InstIx::new(i as u32)]; 400b691770fSChris Fallin let srcloc = if orig_iix.is_invalid() { 401b691770fSChris Fallin SourceLoc::default() 402b691770fSChris Fallin } else { 403b691770fSChris Fallin self.srclocs[orig_iix.get() as usize] 404b691770fSChris Fallin }; 405b691770fSChris Fallin 406d8357426SChris Fallin // Whenever encountering a return instruction, replace it 407d8357426SChris Fallin // with the epilogue. 408d8357426SChris Fallin let is_ret = insn.is_term() == MachTerminator::Ret; 409d8357426SChris Fallin if is_ret { 410b691770fSChris Fallin let epilogue = self.abi.gen_epilogue(); 411b691770fSChris Fallin let len = epilogue.len(); 412b691770fSChris Fallin final_insns.extend(epilogue.into_iter()); 413b691770fSChris Fallin final_srclocs.extend(iter::repeat(srcloc).take(len)); 414d8357426SChris Fallin } else { 415d8357426SChris Fallin final_insns.push(insn.clone()); 416b691770fSChris Fallin final_srclocs.push(srcloc); 417d8357426SChris Fallin } 41808353fccSChris Fallin 41908353fccSChris Fallin // Was this instruction a safepoint instruction? Add its final 42008353fccSChris Fallin // index to the safepoint insn-index list if so. 42108353fccSChris Fallin if safept_idx < result.new_safepoint_insns.len() 42208353fccSChris Fallin && (result.new_safepoint_insns[safept_idx].get() as usize) == i 42308353fccSChris Fallin { 42408353fccSChris Fallin let idx = final_insns.len() - 1; 42508353fccSChris Fallin final_safepoint_insns.push(idx as InsnIndex); 42608353fccSChris Fallin safept_idx += 1; 42708353fccSChris Fallin } 428d8357426SChris Fallin } 429d8357426SChris Fallin 430d8357426SChris Fallin let final_end = final_insns.len() as InsnIndex; 43172e6be93SChris Fallin final_block_ranges[block as usize] = (final_start, final_end); 432d8357426SChris Fallin } 433d8357426SChris Fallin 434b691770fSChris Fallin debug_assert!(final_insns.len() == final_srclocs.len()); 435b691770fSChris Fallin 436d8357426SChris Fallin self.insts = final_insns; 437b691770fSChris Fallin self.srclocs = final_srclocs; 438d8357426SChris Fallin self.block_ranges = final_block_ranges; 43908353fccSChris Fallin self.safepoint_insns = final_safepoint_insns; 44008353fccSChris Fallin 44108353fccSChris Fallin // Save safepoint slot-lists. These will be passed to the `EmitState` 44208353fccSChris Fallin // for the machine backend during emission so that it can do 44308353fccSChris Fallin // target-specific translations of slot numbers to stack offsets. 44408353fccSChris Fallin self.safepoint_slots = result.stackmaps; 445d8357426SChris Fallin } 446d8357426SChris Fallin 44772e6be93SChris Fallin /// Emit the instructions to a `MachBuffer`, containing fixed-up code and external 44872e6be93SChris Fallin /// reloc/trap/etc. records ready for use. 44911a2ef01SChris Fallin pub fn emit( 45011a2ef01SChris Fallin &self, 45111a2ef01SChris Fallin ) -> ( 45211a2ef01SChris Fallin MachBuffer<I>, 45311a2ef01SChris Fallin Vec<CodeOffset>, 45411a2ef01SChris Fallin Vec<(CodeOffset, CodeOffset)>, 45511a2ef01SChris Fallin ) 456d8357426SChris Fallin where 45772e6be93SChris Fallin I: MachInstEmit, 458d8357426SChris Fallin { 4592b9fefe8SChris Fallin let _tt = timing::vcode_emit(); 46072e6be93SChris Fallin let mut buffer = MachBuffer::new(); 46108353fccSChris Fallin let mut state = I::State::new(&*self.abi); 462800cf25bSChris Fallin let cfg_metadata = self.flags().machine_code_cfg_info(); 46311a2ef01SChris Fallin let mut bb_starts: Vec<Option<CodeOffset>> = vec![]; 464d8357426SChris Fallin 46583f182b3SAndrew Brown // The first M MachLabels are reserved for block indices, the next N MachLabels for 46683f182b3SAndrew Brown // constants. 46783f182b3SAndrew Brown buffer.reserve_labels_for_blocks(self.num_blocks() as BlockIndex); 46883f182b3SAndrew Brown buffer.reserve_labels_for_constants(&self.constants); 469d8357426SChris Fallin 470c84d6be6SChris Fallin let mut inst_ends = vec![0; self.insts.len()]; 471c84d6be6SChris Fallin let mut label_insn_iix = vec![0; self.num_blocks()]; 472de4af90aSYury Delendik 473*ef1b2d2fSChris Fallin // Construct the final order we emit code in: cold blocks at the end. 474*ef1b2d2fSChris Fallin let mut final_order: SmallVec<[BlockIndex; 16]> = smallvec![]; 475*ef1b2d2fSChris Fallin let mut cold_blocks: SmallVec<[BlockIndex; 16]> = smallvec![]; 476*ef1b2d2fSChris Fallin for block in 0..self.num_blocks() { 477*ef1b2d2fSChris Fallin let block = block as BlockIndex; 478*ef1b2d2fSChris Fallin if self.block_order.is_cold(block) { 479*ef1b2d2fSChris Fallin cold_blocks.push(block); 480*ef1b2d2fSChris Fallin } else { 481*ef1b2d2fSChris Fallin final_order.push(block); 482*ef1b2d2fSChris Fallin } 483*ef1b2d2fSChris Fallin } 484*ef1b2d2fSChris Fallin final_order.extend(cold_blocks); 485*ef1b2d2fSChris Fallin 486*ef1b2d2fSChris Fallin // Emit blocks. 48708353fccSChris Fallin let mut safepoint_idx = 0; 488964c6087SChris Fallin let mut cur_srcloc = None; 48911a2ef01SChris Fallin let mut last_offset = None; 490*ef1b2d2fSChris Fallin for block in final_order { 49172e6be93SChris Fallin let new_offset = I::align_basic_block(buffer.cur_offset()); 49272e6be93SChris Fallin while new_offset > buffer.cur_offset() { 493d8357426SChris Fallin // Pad with NOPs up to the aligned block offset. 49472e6be93SChris Fallin let nop = I::gen_nop((new_offset - buffer.cur_offset()) as usize); 495c5bbc874SBenjamin Bouvier nop.emit(&mut buffer, &self.emit_info, &mut Default::default()); 496d8357426SChris Fallin } 49772e6be93SChris Fallin assert_eq!(buffer.cur_offset(), new_offset); 498d8357426SChris Fallin 49948cf2c2fSChris Fallin let (start, end) = self.block_ranges[block as usize]; 50072e6be93SChris Fallin buffer.bind_label(MachLabel::from_block(block)); 501c84d6be6SChris Fallin label_insn_iix[block as usize] = start; 50211a2ef01SChris Fallin 503800cf25bSChris Fallin if cfg_metadata { 50411a2ef01SChris Fallin // Track BB starts. If we have backed up due to MachBuffer 50511a2ef01SChris Fallin // branch opts, note that the removed blocks were removed. 50611a2ef01SChris Fallin let cur_offset = buffer.cur_offset(); 50711a2ef01SChris Fallin if last_offset.is_some() && cur_offset <= last_offset.unwrap() { 50811a2ef01SChris Fallin for i in (0..bb_starts.len()).rev() { 50911a2ef01SChris Fallin if bb_starts[i].is_some() && cur_offset > bb_starts[i].unwrap() { 51011a2ef01SChris Fallin break; 51111a2ef01SChris Fallin } 51211a2ef01SChris Fallin bb_starts[i] = None; 51311a2ef01SChris Fallin } 51411a2ef01SChris Fallin } 51511a2ef01SChris Fallin bb_starts.push(Some(cur_offset)); 51611a2ef01SChris Fallin last_offset = Some(cur_offset); 517800cf25bSChris Fallin } 51811a2ef01SChris Fallin 519d8357426SChris Fallin for iix in start..end { 520b691770fSChris Fallin let srcloc = self.srclocs[iix as usize]; 521964c6087SChris Fallin if cur_srcloc != Some(srcloc) { 522964c6087SChris Fallin if cur_srcloc.is_some() { 52372e6be93SChris Fallin buffer.end_srcloc(); 524b691770fSChris Fallin } 52572e6be93SChris Fallin buffer.start_srcloc(srcloc); 526964c6087SChris Fallin cur_srcloc = Some(srcloc); 527b691770fSChris Fallin } 5284dce5109SChris Fallin state.pre_sourceloc(cur_srcloc.unwrap_or(SourceLoc::default())); 529b691770fSChris Fallin 53008353fccSChris Fallin if safepoint_idx < self.safepoint_insns.len() 53108353fccSChris Fallin && self.safepoint_insns[safepoint_idx] == iix 53208353fccSChris Fallin { 53308353fccSChris Fallin if self.safepoint_slots[safepoint_idx].len() > 0 { 53405bf9ea3SNick Fitzgerald let stack_map = self.abi.spillslots_to_stack_map( 53508353fccSChris Fallin &self.safepoint_slots[safepoint_idx][..], 53608353fccSChris Fallin &state, 53708353fccSChris Fallin ); 53805bf9ea3SNick Fitzgerald state.pre_safepoint(stack_map); 53908353fccSChris Fallin } 54008353fccSChris Fallin safepoint_idx += 1; 54108353fccSChris Fallin } 54208353fccSChris Fallin 543c5bbc874SBenjamin Bouvier self.insts[iix as usize].emit(&mut buffer, &self.emit_info, &mut state); 544de4af90aSYury Delendik 545c84d6be6SChris Fallin if self.generate_debug_info { 546c84d6be6SChris Fallin // Buffer truncation may have happened since last inst append; trim inst-end 547c84d6be6SChris Fallin // layout info as appropriate. 548c84d6be6SChris Fallin let l = &mut inst_ends[0..iix as usize]; 549c84d6be6SChris Fallin for end in l.iter_mut().rev() { 550c84d6be6SChris Fallin if *end > buffer.cur_offset() { 551c84d6be6SChris Fallin *end = buffer.cur_offset(); 552c84d6be6SChris Fallin } else { 553c84d6be6SChris Fallin break; 554c84d6be6SChris Fallin } 555c84d6be6SChris Fallin } 556c84d6be6SChris Fallin inst_ends[iix as usize] = buffer.cur_offset(); 557c84d6be6SChris Fallin } 558d8357426SChris Fallin } 559b691770fSChris Fallin 560964c6087SChris Fallin if cur_srcloc.is_some() { 56172e6be93SChris Fallin buffer.end_srcloc(); 562964c6087SChris Fallin cur_srcloc = None; 563b691770fSChris Fallin } 56472e6be93SChris Fallin 56572e6be93SChris Fallin // Do we need an island? Get the worst-case size of the next BB and see if, having 56672e6be93SChris Fallin // emitted that many bytes, we will be beyond the deadline. 56772e6be93SChris Fallin if block < (self.num_blocks() - 1) as BlockIndex { 56872e6be93SChris Fallin let next_block = block + 1; 56972e6be93SChris Fallin let next_block_range = self.block_ranges[next_block as usize]; 57072e6be93SChris Fallin let next_block_size = next_block_range.1 - next_block_range.0; 57172e6be93SChris Fallin let worst_case_next_bb = I::worst_case_size() * next_block_size; 57272e6be93SChris Fallin if buffer.island_needed(worst_case_next_bb) { 5731532516aSAlex Crichton buffer.emit_island(worst_case_next_bb); 57472e6be93SChris Fallin } 57572e6be93SChris Fallin } 576d8357426SChris Fallin } 577d8357426SChris Fallin 57883f182b3SAndrew Brown // Emit the constants used by the function. 57983f182b3SAndrew Brown for (constant, data) in self.constants.iter() { 58083f182b3SAndrew Brown let label = buffer.get_label_for_constant(constant); 58183f182b3SAndrew Brown buffer.defer_constant(label, data.alignment(), data.as_slice(), u32::max_value()); 58283f182b3SAndrew Brown } 58383f182b3SAndrew Brown 584c84d6be6SChris Fallin if self.generate_debug_info { 585c84d6be6SChris Fallin for end in inst_ends.iter_mut().rev() { 586c84d6be6SChris Fallin if *end > buffer.cur_offset() { 587c84d6be6SChris Fallin *end = buffer.cur_offset(); 588c84d6be6SChris Fallin } else { 589c84d6be6SChris Fallin break; 590c84d6be6SChris Fallin } 591c84d6be6SChris Fallin } 592c84d6be6SChris Fallin *self.insts_layout.borrow_mut() = (inst_ends, label_insn_iix, buffer.cur_offset()); 593c84d6be6SChris Fallin } 594de4af90aSYury Delendik 59511a2ef01SChris Fallin // Create `bb_edges` and final (filtered) `bb_starts`. 59611a2ef01SChris Fallin let mut final_bb_starts = vec![]; 59711a2ef01SChris Fallin let mut bb_edges = vec![]; 598800cf25bSChris Fallin if cfg_metadata { 59911a2ef01SChris Fallin for block in 0..self.num_blocks() { 60011a2ef01SChris Fallin if bb_starts[block].is_none() { 60111a2ef01SChris Fallin // Block was deleted by MachBuffer; skip. 60211a2ef01SChris Fallin continue; 60311a2ef01SChris Fallin } 60411a2ef01SChris Fallin let from = bb_starts[block].unwrap(); 60511a2ef01SChris Fallin 60611a2ef01SChris Fallin final_bb_starts.push(from); 60711a2ef01SChris Fallin // Resolve each `succ` label and add edges. 60811a2ef01SChris Fallin let succs = self.block_succs(BlockIx::new(block as u32)); 60911a2ef01SChris Fallin for succ in succs.iter() { 61011a2ef01SChris Fallin let to = buffer.resolve_label_offset(MachLabel::from_block(succ.get())); 61111a2ef01SChris Fallin bb_edges.push((from, to)); 61211a2ef01SChris Fallin } 61311a2ef01SChris Fallin } 614800cf25bSChris Fallin } 61511a2ef01SChris Fallin 61611a2ef01SChris Fallin (buffer, final_bb_starts, bb_edges) 617d8357426SChris Fallin } 618d8357426SChris Fallin 619c84d6be6SChris Fallin /// Generates value-label ranges. 620602006ffSbjorn3 pub fn value_labels_ranges(&self) -> ValueLabelsRanges { 621997fab55SChris Fallin if !self.has_value_labels { 622602006ffSbjorn3 return ValueLabelsRanges::default(); 623997fab55SChris Fallin } 624997fab55SChris Fallin 625c84d6be6SChris Fallin let layout = &self.insts_layout.borrow(); 626602006ffSbjorn3 debug::compute(&self.insts, &layout.0[..], &layout.1[..]) 62776d61504Sbjorn3 } 62876d61504Sbjorn3 62976d61504Sbjorn3 /// Get the offsets of stackslots. 63076d61504Sbjorn3 pub fn stackslot_offsets(&self) -> &PrimaryMap<StackSlot, u32> { 63176d61504Sbjorn3 self.abi.stackslot_offsets() 632c84d6be6SChris Fallin } 633c84d6be6SChris Fallin 634d8357426SChris Fallin /// Get the IR block for a BlockIndex, if one exists. 635d8357426SChris Fallin pub fn bindex_to_bb(&self, block: BlockIndex) -> Option<ir::Block> { 63672e6be93SChris Fallin self.block_order.lowered_order()[block as usize].orig_block() 637d8357426SChris Fallin } 638d8357426SChris Fallin } 639d8357426SChris Fallin 640d8357426SChris Fallin impl<I: VCodeInst> RegallocFunction for VCode<I> { 641d8357426SChris Fallin type Inst = I; 642d8357426SChris Fallin 643d8357426SChris Fallin fn insns(&self) -> &[I] { 644d8357426SChris Fallin &self.insts[..] 645d8357426SChris Fallin } 646d8357426SChris Fallin 647d8357426SChris Fallin fn insns_mut(&mut self) -> &mut [I] { 648d8357426SChris Fallin &mut self.insts[..] 649d8357426SChris Fallin } 650d8357426SChris Fallin 651d8357426SChris Fallin fn get_insn(&self, insn: InstIx) -> &I { 652d8357426SChris Fallin &self.insts[insn.get() as usize] 653d8357426SChris Fallin } 654d8357426SChris Fallin 655d8357426SChris Fallin fn get_insn_mut(&mut self, insn: InstIx) -> &mut I { 656d8357426SChris Fallin &mut self.insts[insn.get() as usize] 657d8357426SChris Fallin } 658d8357426SChris Fallin 659d8357426SChris Fallin fn blocks(&self) -> Range<BlockIx> { 660d8357426SChris Fallin Range::new(BlockIx::new(0), self.block_ranges.len()) 661d8357426SChris Fallin } 662d8357426SChris Fallin 663d8357426SChris Fallin fn entry_block(&self) -> BlockIx { 664d8357426SChris Fallin BlockIx::new(self.entry) 665d8357426SChris Fallin } 666d8357426SChris Fallin 667d8357426SChris Fallin fn block_insns(&self, block: BlockIx) -> Range<InstIx> { 668d8357426SChris Fallin let (start, end) = self.block_ranges[block.get() as usize]; 669d8357426SChris Fallin Range::new(InstIx::new(start), (end - start) as usize) 670d8357426SChris Fallin } 671d8357426SChris Fallin 6724f919c64SBenjamin Bouvier fn block_succs(&self, block: BlockIx) -> Cow<[BlockIx]> { 673d8357426SChris Fallin let (start, end) = self.block_succ_range[block.get() as usize]; 6744f919c64SBenjamin Bouvier Cow::Borrowed(&self.block_succs[start..end]) 675d8357426SChris Fallin } 676d8357426SChris Fallin 677d8357426SChris Fallin fn is_ret(&self, insn: InstIx) -> bool { 678d8357426SChris Fallin match self.insts[insn.get() as usize].is_term() { 679d8357426SChris Fallin MachTerminator::Ret => true, 680d8357426SChris Fallin _ => false, 681d8357426SChris Fallin } 682d8357426SChris Fallin } 683d8357426SChris Fallin 68471768bb6SChris Fallin fn is_included_in_clobbers(&self, insn: &I) -> bool { 68571768bb6SChris Fallin insn.is_included_in_clobbers() 68671768bb6SChris Fallin } 68771768bb6SChris Fallin 688d8357426SChris Fallin fn get_regs(insn: &I, collector: &mut RegUsageCollector) { 689d8357426SChris Fallin insn.get_regs(collector) 690d8357426SChris Fallin } 691d8357426SChris Fallin 6921f620e1bSBenjamin Bouvier fn map_regs<RUM: RegUsageMapper>(insn: &mut I, mapper: &RUM) { 693be6f060aSChris Fallin insn.map_regs(mapper); 694d8357426SChris Fallin } 695d8357426SChris Fallin 696d8357426SChris Fallin fn is_move(&self, insn: &I) -> Option<(Writable<Reg>, Reg)> { 697d8357426SChris Fallin insn.is_move() 698d8357426SChris Fallin } 699d8357426SChris Fallin 70046093f61SBenjamin Bouvier fn get_num_vregs(&self) -> usize { 70146093f61SBenjamin Bouvier self.vreg_types.len() 702be6f060aSChris Fallin } 703be6f060aSChris Fallin 704833ebeedSChris Fallin fn get_spillslot_size(&self, regclass: RegClass, _: VirtualReg) -> u32 { 705833ebeedSChris Fallin self.abi.get_spillslot_size(regclass) 706d8357426SChris Fallin } 707d8357426SChris Fallin 708833ebeedSChris Fallin fn gen_spill(&self, to_slot: SpillSlot, from_reg: RealReg, _: Option<VirtualReg>) -> I { 709833ebeedSChris Fallin self.abi.gen_spill(to_slot, from_reg) 710d8357426SChris Fallin } 711d8357426SChris Fallin 71208353fccSChris Fallin fn gen_reload( 71308353fccSChris Fallin &self, 71408353fccSChris Fallin to_reg: Writable<RealReg>, 71508353fccSChris Fallin from_slot: SpillSlot, 716833ebeedSChris Fallin _: Option<VirtualReg>, 71708353fccSChris Fallin ) -> I { 718833ebeedSChris Fallin self.abi.gen_reload(to_reg, from_slot) 719d8357426SChris Fallin } 720d8357426SChris Fallin 721d8357426SChris Fallin fn gen_move(&self, to_reg: Writable<RealReg>, from_reg: RealReg, vreg: VirtualReg) -> I { 722d8357426SChris Fallin let ty = self.vreg_type(vreg); 723d8357426SChris Fallin I::gen_move(to_reg.map(|r| r.to_reg()), from_reg.to_reg(), ty) 724d8357426SChris Fallin } 725d8357426SChris Fallin 726d8357426SChris Fallin fn gen_zero_len_nop(&self) -> I { 72799be82c8SKasey Carrothers I::gen_nop(0) 728d8357426SChris Fallin } 729d8357426SChris Fallin 730d8357426SChris Fallin fn maybe_direct_reload(&self, insn: &I, reg: VirtualReg, slot: SpillSlot) -> Option<I> { 731d8357426SChris Fallin insn.maybe_direct_reload(reg, slot) 732d8357426SChris Fallin } 733d8357426SChris Fallin 734d8357426SChris Fallin fn func_liveins(&self) -> RegallocSet<RealReg> { 735d8357426SChris Fallin self.liveins.clone() 736d8357426SChris Fallin } 737d8357426SChris Fallin 738d8357426SChris Fallin fn func_liveouts(&self) -> RegallocSet<RealReg> { 739d8357426SChris Fallin self.liveouts.clone() 740d8357426SChris Fallin } 741d8357426SChris Fallin } 742d8357426SChris Fallin 743d8357426SChris Fallin impl<I: VCodeInst> fmt::Debug for VCode<I> { 744d8357426SChris Fallin fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 745d8357426SChris Fallin writeln!(f, "VCode_Debug {{")?; 746d8357426SChris Fallin writeln!(f, " Entry block: {}", self.entry)?; 747d8357426SChris Fallin 748d8357426SChris Fallin for block in 0..self.num_blocks() { 749d8357426SChris Fallin writeln!(f, "Block {}:", block,)?; 750d8357426SChris Fallin for succ in self.succs(block as BlockIndex) { 7514f919c64SBenjamin Bouvier writeln!(f, " (successor: Block {})", succ.get())?; 752d8357426SChris Fallin } 753d8357426SChris Fallin let (start, end) = self.block_ranges[block]; 754d8357426SChris Fallin writeln!(f, " (instruction range: {} .. {})", start, end)?; 755d8357426SChris Fallin for inst in start..end { 756d8357426SChris Fallin writeln!(f, " Inst {}: {:?}", inst, self.insts[inst as usize])?; 757d8357426SChris Fallin } 758d8357426SChris Fallin } 759d8357426SChris Fallin 760d8357426SChris Fallin writeln!(f, "}}")?; 761d8357426SChris Fallin Ok(()) 762d8357426SChris Fallin } 763d8357426SChris Fallin } 764d8357426SChris Fallin 76548cf2c2fSChris Fallin /// Pretty-printing with `RealRegUniverse` context. 76671768bb6SChris Fallin impl<I: VCodeInst> PrettyPrint for VCode<I> { 767d8357426SChris Fallin fn show_rru(&self, mb_rru: Option<&RealRegUniverse>) -> String { 768d8357426SChris Fallin use std::fmt::Write; 769d8357426SChris Fallin 770d8357426SChris Fallin let mut s = String::new(); 77148cf2c2fSChris Fallin write!(&mut s, "VCode_ShowWithRRU {{{{\n").unwrap(); 77248cf2c2fSChris Fallin write!(&mut s, " Entry block: {}\n", self.entry).unwrap(); 773d8357426SChris Fallin 77408353fccSChris Fallin let mut state = Default::default(); 77508353fccSChris Fallin let mut safepoint_idx = 0; 776d8357426SChris Fallin for i in 0..self.num_blocks() { 77772e6be93SChris Fallin let block = i as BlockIndex; 778d8357426SChris Fallin 77972e6be93SChris Fallin write!(&mut s, "Block {}:\n", block).unwrap(); 78072e6be93SChris Fallin if let Some(bb) = self.bindex_to_bb(block) { 78148cf2c2fSChris Fallin write!(&mut s, " (original IR block: {})\n", bb).unwrap(); 782d8357426SChris Fallin } 78372e6be93SChris Fallin for succ in self.succs(block) { 7844f919c64SBenjamin Bouvier write!(&mut s, " (successor: Block {})\n", succ.get()).unwrap(); 785d8357426SChris Fallin } 78672e6be93SChris Fallin let (start, end) = self.block_ranges[block as usize]; 78748cf2c2fSChris Fallin write!(&mut s, " (instruction range: {} .. {})\n", start, end).unwrap(); 788d8357426SChris Fallin for inst in start..end { 78908353fccSChris Fallin if safepoint_idx < self.safepoint_insns.len() 79008353fccSChris Fallin && self.safepoint_insns[safepoint_idx] == inst 79108353fccSChris Fallin { 79208353fccSChris Fallin write!( 79308353fccSChris Fallin &mut s, 79408353fccSChris Fallin " (safepoint: slots {:?} with EmitState {:?})\n", 79508353fccSChris Fallin self.safepoint_slots[safepoint_idx], state, 79608353fccSChris Fallin ) 79708353fccSChris Fallin .unwrap(); 79808353fccSChris Fallin safepoint_idx += 1; 79908353fccSChris Fallin } 80048cf2c2fSChris Fallin write!( 80148cf2c2fSChris Fallin &mut s, 80248cf2c2fSChris Fallin " Inst {}: {}\n", 803d8357426SChris Fallin inst, 80408353fccSChris Fallin self.insts[inst as usize].pretty_print(mb_rru, &mut state) 80548cf2c2fSChris Fallin ) 80648cf2c2fSChris Fallin .unwrap(); 807d8357426SChris Fallin } 808d8357426SChris Fallin } 809d8357426SChris Fallin 81048cf2c2fSChris Fallin write!(&mut s, "}}}}\n").unwrap(); 811d8357426SChris Fallin 812d8357426SChris Fallin s 813d8357426SChris Fallin } 814d8357426SChris Fallin } 81583f182b3SAndrew Brown 81683f182b3SAndrew Brown /// This structure tracks the large constants used in VCode that will be emitted separately by the 81783f182b3SAndrew Brown /// [MachBuffer]. 81883f182b3SAndrew Brown /// 81983f182b3SAndrew Brown /// First, during the lowering phase, constants are inserted using 82083f182b3SAndrew Brown /// [VCodeConstants.insert]; an intermediate handle, [VCodeConstant], tracks what constants are 82183f182b3SAndrew Brown /// used in this phase. Some deduplication is performed, when possible, as constant 82283f182b3SAndrew Brown /// values are inserted. 82383f182b3SAndrew Brown /// 82483f182b3SAndrew Brown /// Secondly, during the emission phase, the [MachBuffer] assigns [MachLabel]s for each of the 82583f182b3SAndrew Brown /// constants so that instructions can refer to the value's memory location. The [MachBuffer] 82683f182b3SAndrew Brown /// then writes the constant values to the buffer. 82783f182b3SAndrew Brown #[derive(Default)] 82883f182b3SAndrew Brown pub struct VCodeConstants { 82983f182b3SAndrew Brown constants: PrimaryMap<VCodeConstant, VCodeConstantData>, 83083f182b3SAndrew Brown pool_uses: HashMap<Constant, VCodeConstant>, 83183f182b3SAndrew Brown well_known_uses: HashMap<*const [u8], VCodeConstant>, 83283f182b3SAndrew Brown } 83383f182b3SAndrew Brown impl VCodeConstants { 83483f182b3SAndrew Brown /// Initialize the structure with the expected number of constants. 83583f182b3SAndrew Brown pub fn with_capacity(expected_num_constants: usize) -> Self { 83683f182b3SAndrew Brown Self { 83783f182b3SAndrew Brown constants: PrimaryMap::with_capacity(expected_num_constants), 83883f182b3SAndrew Brown pool_uses: HashMap::with_capacity(expected_num_constants), 83983f182b3SAndrew Brown well_known_uses: HashMap::new(), 84083f182b3SAndrew Brown } 84183f182b3SAndrew Brown } 84283f182b3SAndrew Brown 84383f182b3SAndrew Brown /// Insert a constant; using this method indicates that a constant value will be used and thus 84483f182b3SAndrew Brown /// will be emitted to the `MachBuffer`. The current implementation can deduplicate constants 84583f182b3SAndrew Brown /// that are [VCodeConstantData::Pool] or [VCodeConstantData::WellKnown] but not 84683f182b3SAndrew Brown /// [VCodeConstantData::Generated]. 84783f182b3SAndrew Brown pub fn insert(&mut self, data: VCodeConstantData) -> VCodeConstant { 84883f182b3SAndrew Brown match data { 84983f182b3SAndrew Brown VCodeConstantData::Generated(_) => self.constants.push(data), 85083f182b3SAndrew Brown VCodeConstantData::Pool(constant, _) => match self.pool_uses.get(&constant) { 85183f182b3SAndrew Brown None => { 85283f182b3SAndrew Brown let vcode_constant = self.constants.push(data); 85383f182b3SAndrew Brown self.pool_uses.insert(constant, vcode_constant); 85483f182b3SAndrew Brown vcode_constant 85583f182b3SAndrew Brown } 85683f182b3SAndrew Brown Some(&vcode_constant) => vcode_constant, 85783f182b3SAndrew Brown }, 85883f182b3SAndrew Brown VCodeConstantData::WellKnown(data_ref) => { 85983f182b3SAndrew Brown match self.well_known_uses.get(&(data_ref as *const [u8])) { 86083f182b3SAndrew Brown None => { 86183f182b3SAndrew Brown let vcode_constant = self.constants.push(data); 86283f182b3SAndrew Brown self.well_known_uses 86383f182b3SAndrew Brown .insert(data_ref as *const [u8], vcode_constant); 86483f182b3SAndrew Brown vcode_constant 86583f182b3SAndrew Brown } 86683f182b3SAndrew Brown Some(&vcode_constant) => vcode_constant, 86783f182b3SAndrew Brown } 86883f182b3SAndrew Brown } 86983f182b3SAndrew Brown } 87083f182b3SAndrew Brown } 87183f182b3SAndrew Brown 87283f182b3SAndrew Brown /// Return the number of constants inserted. 87383f182b3SAndrew Brown pub fn len(&self) -> usize { 87483f182b3SAndrew Brown self.constants.len() 87583f182b3SAndrew Brown } 87683f182b3SAndrew Brown 87783f182b3SAndrew Brown /// Iterate over the [VCodeConstant] keys inserted in this structure. 87883f182b3SAndrew Brown pub fn keys(&self) -> Keys<VCodeConstant> { 87983f182b3SAndrew Brown self.constants.keys() 88083f182b3SAndrew Brown } 88183f182b3SAndrew Brown 88283f182b3SAndrew Brown /// Iterate over the [VCodeConstant] keys and the data (as a byte slice) inserted in this 88383f182b3SAndrew Brown /// structure. 88483f182b3SAndrew Brown pub fn iter(&self) -> impl Iterator<Item = (VCodeConstant, &VCodeConstantData)> { 88583f182b3SAndrew Brown self.constants.iter() 88683f182b3SAndrew Brown } 88783f182b3SAndrew Brown } 88883f182b3SAndrew Brown 88983f182b3SAndrew Brown /// A use of a constant by one or more VCode instructions; see [VCodeConstants]. 89083f182b3SAndrew Brown #[derive(Clone, Copy, Debug, PartialEq, Eq)] 89183f182b3SAndrew Brown pub struct VCodeConstant(u32); 89283f182b3SAndrew Brown entity_impl!(VCodeConstant); 89383f182b3SAndrew Brown 89483f182b3SAndrew Brown /// Identify the different types of constant that can be inserted into [VCodeConstants]. Tracking 89583f182b3SAndrew Brown /// these separately instead of as raw byte buffers allows us to avoid some duplication. 89683f182b3SAndrew Brown pub enum VCodeConstantData { 89783f182b3SAndrew Brown /// A constant already present in the Cranelift IR 89883f182b3SAndrew Brown /// [ConstantPool](crate::ir::constant::ConstantPool). 89983f182b3SAndrew Brown Pool(Constant, ConstantData), 90083f182b3SAndrew Brown /// A reference to a well-known constant value that is statically encoded within the compiler. 90183f182b3SAndrew Brown WellKnown(&'static [u8]), 90283f182b3SAndrew Brown /// A constant value generated during lowering; the value may depend on the instruction context 90383f182b3SAndrew Brown /// which makes it difficult to de-duplicate--if possible, use other variants. 90483f182b3SAndrew Brown Generated(ConstantData), 90583f182b3SAndrew Brown } 90683f182b3SAndrew Brown impl VCodeConstantData { 90783f182b3SAndrew Brown /// Retrieve the constant data as a byte slice. 90883f182b3SAndrew Brown pub fn as_slice(&self) -> &[u8] { 90983f182b3SAndrew Brown match self { 91083f182b3SAndrew Brown VCodeConstantData::Pool(_, d) | VCodeConstantData::Generated(d) => d.as_slice(), 91183f182b3SAndrew Brown VCodeConstantData::WellKnown(d) => d, 91283f182b3SAndrew Brown } 91383f182b3SAndrew Brown } 91483f182b3SAndrew Brown 91583f182b3SAndrew Brown /// Calculate the alignment of the constant data. 91683f182b3SAndrew Brown pub fn alignment(&self) -> u32 { 91783f182b3SAndrew Brown if self.as_slice().len() <= 8 { 91883f182b3SAndrew Brown 8 91983f182b3SAndrew Brown } else { 92083f182b3SAndrew Brown 16 92183f182b3SAndrew Brown } 92283f182b3SAndrew Brown } 92383f182b3SAndrew Brown } 92483f182b3SAndrew Brown 92583f182b3SAndrew Brown #[cfg(test)] 92683f182b3SAndrew Brown mod test { 92783f182b3SAndrew Brown use super::*; 9285e5e5206SChris Fallin use std::mem::size_of; 92983f182b3SAndrew Brown 93083f182b3SAndrew Brown #[test] 93183f182b3SAndrew Brown fn size_of_constant_structs() { 93283f182b3SAndrew Brown assert_eq!(size_of::<Constant>(), 4); 93383f182b3SAndrew Brown assert_eq!(size_of::<VCodeConstant>(), 4); 93483f182b3SAndrew Brown assert_eq!(size_of::<ConstantData>(), 24); 93583f182b3SAndrew Brown assert_eq!(size_of::<VCodeConstantData>(), 32); 93683f182b3SAndrew Brown assert_eq!( 93783f182b3SAndrew Brown size_of::<PrimaryMap<VCodeConstant, VCodeConstantData>>(), 93883f182b3SAndrew Brown 24 93983f182b3SAndrew Brown ); 9405e5e5206SChris Fallin // TODO The VCodeConstants structure's memory size could be further optimized. 9415e5e5206SChris Fallin // With certain versions of Rust, each `HashMap` in `VCodeConstants` occupied at 9425e5e5206SChris Fallin // least 48 bytes, making an empty `VCodeConstants` cost 120 bytes. 94383f182b3SAndrew Brown } 94483f182b3SAndrew Brown } 945