1 //! Cranelift compilation context and main entry point. 2 //! 3 //! When compiling many small functions, it is important to avoid repeatedly allocating and 4 //! deallocating the data structures needed for compilation. The `Context` struct is used to hold 5 //! on to memory allocations between function compilations. 6 //! 7 //! The context does not hold a `TargetIsa` instance which has to be provided as an argument 8 //! instead. This is because an ISA instance is immutable and can be used by multiple compilation 9 //! contexts concurrently. Typically, you would have one context per compilation thread and only a 10 //! single ISA instance. 11 12 use crate::binemit::CodeInfo; 13 use crate::dce::do_dce; 14 use crate::dominator_tree::DominatorTree; 15 use crate::flowgraph::ControlFlowGraph; 16 use crate::ir::Function; 17 use crate::isa::TargetIsa; 18 use crate::legalizer::simple_legalize; 19 use crate::licm::do_licm; 20 use crate::loop_analysis::LoopAnalysis; 21 use crate::machinst::MachCompileResult; 22 use crate::nan_canonicalization::do_nan_canonicalization; 23 use crate::remove_constant_phis::do_remove_constant_phis; 24 use crate::result::CodegenResult; 25 use crate::settings::{FlagsOrIsa, OptLevel}; 26 use crate::simple_gvn::do_simple_gvn; 27 use crate::simple_preopt::do_preopt; 28 use crate::timing; 29 use crate::unreachable_code::eliminate_unreachable_code; 30 use crate::verifier::{verify_context, VerifierErrors, VerifierResult}; 31 #[cfg(feature = "souper-harvest")] 32 use alloc::string::String; 33 use alloc::vec::Vec; 34 35 #[cfg(feature = "souper-harvest")] 36 use crate::souper_harvest::do_souper_harvest; 37 38 /// Persistent data structures and compilation pipeline. 39 pub struct Context { 40 /// The function we're compiling. 41 pub func: Function, 42 43 /// The control flow graph of `func`. 44 pub cfg: ControlFlowGraph, 45 46 /// Dominator tree for `func`. 47 pub domtree: DominatorTree, 48 49 /// Loop analysis of `func`. 50 pub loop_analysis: LoopAnalysis, 51 52 /// Result of MachBackend compilation, if computed. 53 pub mach_compile_result: Option<MachCompileResult>, 54 55 /// Flag: do we want a disassembly with the MachCompileResult? 56 pub want_disasm: bool, 57 } 58 59 impl Context { 60 /// Allocate a new compilation context. 61 /// 62 /// The returned instance should be reused for compiling multiple functions in order to avoid 63 /// needless allocator thrashing. 64 pub fn new() -> Self { 65 Self::for_function(Function::new()) 66 } 67 68 /// Allocate a new compilation context with an existing Function. 69 /// 70 /// The returned instance should be reused for compiling multiple functions in order to avoid 71 /// needless allocator thrashing. 72 pub fn for_function(func: Function) -> Self { 73 Self { 74 func, 75 cfg: ControlFlowGraph::new(), 76 domtree: DominatorTree::new(), 77 loop_analysis: LoopAnalysis::new(), 78 mach_compile_result: None, 79 want_disasm: false, 80 } 81 } 82 83 /// Clear all data structures in this context. 84 pub fn clear(&mut self) { 85 self.func.clear(); 86 self.cfg.clear(); 87 self.domtree.clear(); 88 self.loop_analysis.clear(); 89 self.mach_compile_result = None; 90 self.want_disasm = false; 91 } 92 93 /// Set the flag to request a disassembly when compiling with a 94 /// `MachBackend` backend. 95 pub fn set_disasm(&mut self, val: bool) { 96 self.want_disasm = val; 97 } 98 99 /// Compile the function, and emit machine code into a `Vec<u8>`. 100 /// 101 /// Run the function through all the passes necessary to generate code for the target ISA 102 /// represented by `isa`, as well as the final step of emitting machine code into a 103 /// `Vec<u8>`. The machine code is not relocated. Instead, any relocations are emitted 104 /// into `relocs`. 105 /// 106 /// This function calls `compile` and `emit_to_memory`, taking care to resize `mem` as 107 /// needed, so it provides a safe interface. 108 /// 109 /// Returns information about the function's code and read-only data. 110 pub fn compile_and_emit( 111 &mut self, 112 isa: &dyn TargetIsa, 113 mem: &mut Vec<u8>, 114 ) -> CodegenResult<()> { 115 let info = self.compile(isa)?; 116 let old_len = mem.len(); 117 mem.resize(old_len + info.total_size as usize, 0); 118 let new_info = unsafe { self.emit_to_memory(mem.as_mut_ptr().add(old_len)) }; 119 debug_assert!(new_info == info); 120 Ok(()) 121 } 122 123 /// Compile the function. 124 /// 125 /// Run the function through all the passes necessary to generate code for the target ISA 126 /// represented by `isa`. This does not include the final step of emitting machine code into a 127 /// code sink. 128 /// 129 /// Returns information about the function's code and read-only data. 130 pub fn compile(&mut self, isa: &dyn TargetIsa) -> CodegenResult<CodeInfo> { 131 let _tt = timing::compile(); 132 self.verify_if(isa)?; 133 134 let opt_level = isa.flags().opt_level(); 135 log::debug!( 136 "Compiling (opt level {:?}):\n{}", 137 opt_level, 138 self.func.display() 139 ); 140 141 self.compute_cfg(); 142 if opt_level != OptLevel::None { 143 self.preopt(isa)?; 144 } 145 if isa.flags().enable_nan_canonicalization() { 146 self.canonicalize_nans(isa)?; 147 } 148 149 self.legalize(isa)?; 150 if opt_level != OptLevel::None { 151 self.compute_domtree(); 152 self.compute_loop_analysis(); 153 self.licm(isa)?; 154 self.simple_gvn(isa)?; 155 } 156 157 self.compute_domtree(); 158 self.eliminate_unreachable_code(isa)?; 159 if opt_level != OptLevel::None { 160 self.dce(isa)?; 161 } 162 163 self.remove_constant_phis(isa)?; 164 165 let result = isa.compile_function(&self.func, self.want_disasm)?; 166 let info = result.code_info(); 167 self.mach_compile_result = Some(result); 168 Ok(info) 169 } 170 171 /// Emit machine code directly into raw memory. 172 /// 173 /// Write all of the function's machine code to the memory at `mem`. The size of the machine 174 /// code is returned by `compile` above. 175 /// 176 /// The machine code is not relocated. Instead, any relocations are emitted into `relocs`. 177 /// 178 /// # Safety 179 /// 180 /// This function is unsafe since it does not perform bounds checking on the memory buffer, 181 /// and it can't guarantee that the `mem` pointer is valid. 182 /// 183 /// Returns information about the emitted code and data. 184 #[deny(unsafe_op_in_unsafe_fn)] 185 pub unsafe fn emit_to_memory(&self, mem: *mut u8) -> CodeInfo { 186 let _tt = timing::binemit(); 187 let result = self 188 .mach_compile_result 189 .as_ref() 190 .expect("only using mach backend now"); 191 let info = result.code_info(); 192 193 let mem = unsafe { std::slice::from_raw_parts_mut(mem, info.total_size as usize) }; 194 mem.copy_from_slice(result.buffer.data()); 195 196 info 197 } 198 199 /// If available, return information about the code layout in the 200 /// final machine code: the offsets (in bytes) of each basic-block 201 /// start, and all basic-block edges. 202 pub fn get_code_bb_layout(&self) -> Option<(Vec<usize>, Vec<(usize, usize)>)> { 203 if let Some(result) = self.mach_compile_result.as_ref() { 204 Some(( 205 result.bb_starts.iter().map(|&off| off as usize).collect(), 206 result 207 .bb_edges 208 .iter() 209 .map(|&(from, to)| (from as usize, to as usize)) 210 .collect(), 211 )) 212 } else { 213 None 214 } 215 } 216 217 /// Creates unwind information for the function. 218 /// 219 /// Returns `None` if the function has no unwind information. 220 #[cfg(feature = "unwind")] 221 pub fn create_unwind_info( 222 &self, 223 isa: &dyn TargetIsa, 224 ) -> CodegenResult<Option<crate::isa::unwind::UnwindInfo>> { 225 let unwind_info_kind = isa.unwind_info_kind(); 226 let result = self.mach_compile_result.as_ref().unwrap(); 227 isa.emit_unwind_info(result, unwind_info_kind) 228 } 229 230 /// Run the verifier on the function. 231 /// 232 /// Also check that the dominator tree and control flow graph are consistent with the function. 233 pub fn verify<'a, FOI: Into<FlagsOrIsa<'a>>>(&self, fisa: FOI) -> VerifierResult<()> { 234 let mut errors = VerifierErrors::default(); 235 let _ = verify_context(&self.func, &self.cfg, &self.domtree, fisa, &mut errors); 236 237 if errors.is_empty() { 238 Ok(()) 239 } else { 240 Err(errors) 241 } 242 } 243 244 /// Run the verifier only if the `enable_verifier` setting is true. 245 pub fn verify_if<'a, FOI: Into<FlagsOrIsa<'a>>>(&self, fisa: FOI) -> CodegenResult<()> { 246 let fisa = fisa.into(); 247 if fisa.flags.enable_verifier() { 248 self.verify(fisa)?; 249 } 250 Ok(()) 251 } 252 253 /// Perform dead-code elimination on the function. 254 pub fn dce<'a, FOI: Into<FlagsOrIsa<'a>>>(&mut self, fisa: FOI) -> CodegenResult<()> { 255 do_dce(&mut self.func, &mut self.domtree); 256 self.verify_if(fisa)?; 257 Ok(()) 258 } 259 260 /// Perform constant-phi removal on the function. 261 pub fn remove_constant_phis<'a, FOI: Into<FlagsOrIsa<'a>>>( 262 &mut self, 263 fisa: FOI, 264 ) -> CodegenResult<()> { 265 do_remove_constant_phis(&mut self.func, &mut self.domtree); 266 self.verify_if(fisa)?; 267 Ok(()) 268 } 269 270 /// Perform pre-legalization rewrites on the function. 271 pub fn preopt(&mut self, isa: &dyn TargetIsa) -> CodegenResult<()> { 272 do_preopt(&mut self.func, &mut self.cfg, isa); 273 self.verify_if(isa)?; 274 Ok(()) 275 } 276 277 /// Perform NaN canonicalizing rewrites on the function. 278 pub fn canonicalize_nans(&mut self, isa: &dyn TargetIsa) -> CodegenResult<()> { 279 do_nan_canonicalization(&mut self.func); 280 self.verify_if(isa) 281 } 282 283 /// Run the legalizer for `isa` on the function. 284 pub fn legalize(&mut self, isa: &dyn TargetIsa) -> CodegenResult<()> { 285 // Legalization invalidates the domtree and loop_analysis by mutating the CFG. 286 // TODO: Avoid doing this when legalization doesn't actually mutate the CFG. 287 self.domtree.clear(); 288 self.loop_analysis.clear(); 289 290 // Run some specific legalizations only. 291 simple_legalize(&mut self.func, &mut self.cfg, isa); 292 self.verify_if(isa) 293 } 294 295 /// Compute the control flow graph. 296 pub fn compute_cfg(&mut self) { 297 self.cfg.compute(&self.func) 298 } 299 300 /// Compute dominator tree. 301 pub fn compute_domtree(&mut self) { 302 self.domtree.compute(&self.func, &self.cfg) 303 } 304 305 /// Compute the loop analysis. 306 pub fn compute_loop_analysis(&mut self) { 307 self.loop_analysis 308 .compute(&self.func, &self.cfg, &self.domtree) 309 } 310 311 /// Compute the control flow graph and dominator tree. 312 pub fn flowgraph(&mut self) { 313 self.compute_cfg(); 314 self.compute_domtree() 315 } 316 317 /// Perform simple GVN on the function. 318 pub fn simple_gvn<'a, FOI: Into<FlagsOrIsa<'a>>>(&mut self, fisa: FOI) -> CodegenResult<()> { 319 do_simple_gvn(&mut self.func, &mut self.domtree); 320 self.verify_if(fisa) 321 } 322 323 /// Perform LICM on the function. 324 pub fn licm(&mut self, isa: &dyn TargetIsa) -> CodegenResult<()> { 325 do_licm( 326 &mut self.func, 327 &mut self.cfg, 328 &mut self.domtree, 329 &mut self.loop_analysis, 330 ); 331 self.verify_if(isa) 332 } 333 334 /// Perform unreachable code elimination. 335 pub fn eliminate_unreachable_code<'a, FOI>(&mut self, fisa: FOI) -> CodegenResult<()> 336 where 337 FOI: Into<FlagsOrIsa<'a>>, 338 { 339 eliminate_unreachable_code(&mut self.func, &mut self.cfg, &self.domtree); 340 self.verify_if(fisa) 341 } 342 343 /// Harvest candidate left-hand sides for superoptimization with Souper. 344 #[cfg(feature = "souper-harvest")] 345 pub fn souper_harvest( 346 &mut self, 347 out: &mut std::sync::mpsc::Sender<String>, 348 ) -> CodegenResult<()> { 349 do_souper_harvest(&self.func, out); 350 Ok(()) 351 } 352 } 353