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::alias_analysis::AliasAnalysis; 13 use crate::dce::do_dce; 14 use crate::dominator_tree::DominatorTree; 15 use crate::egraph::EgraphPass; 16 use crate::flowgraph::ControlFlowGraph; 17 use crate::ir::Function; 18 use crate::isa::TargetIsa; 19 use crate::legalizer::simple_legalize; 20 use crate::loop_analysis::LoopAnalysis; 21 use crate::machinst::{CompiledCode, CompiledCodeStencil}; 22 use crate::nan_canonicalization::do_nan_canonicalization; 23 use crate::remove_constant_phis::do_remove_constant_phis; 24 use crate::result::{CodegenResult, CompileResult}; 25 use crate::settings::{FlagsOrIsa, OptLevel}; 26 use crate::trace; 27 use crate::unreachable_code::eliminate_unreachable_code; 28 use crate::verifier::{verify_context, VerifierErrors, VerifierResult}; 29 use crate::{timing, CompileError}; 30 #[cfg(feature = "souper-harvest")] 31 use alloc::string::String; 32 use alloc::vec::Vec; 33 use cranelift_control::ControlPlane; 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(crate) compiled_code: Option<CompiledCode>, 54 55 /// Flag: do we want a disassembly with the CompiledCode? 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 compiled_code: 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.compiled_code = None; 90 self.want_disasm = false; 91 } 92 93 /// Returns the compilation result for this function, available after any `compile` function 94 /// has been called. 95 pub fn compiled_code(&self) -> Option<&CompiledCode> { 96 self.compiled_code.as_ref() 97 } 98 99 /// Set the flag to request a disassembly when compiling with a 100 /// `MachBackend` backend. 101 pub fn set_disasm(&mut self, val: bool) { 102 self.want_disasm = val; 103 } 104 105 /// Compile the function, and emit machine code into a `Vec<u8>`. 106 /// 107 /// Run the function through all the passes necessary to generate 108 /// code for the target ISA represented by `isa`, as well as the 109 /// final step of emitting machine code into a `Vec<u8>`. The 110 /// machine code is not relocated. Instead, any relocations can be 111 /// obtained from `compiled_code()`. 112 /// 113 /// Performs any optimizations that are enabled, unless 114 /// `optimize()` was already invoked. 115 /// 116 /// This function calls `compile`, taking care to resize `mem` as 117 /// needed. 118 /// 119 /// Returns information about the function's code and read-only 120 /// data. 121 pub fn compile_and_emit( 122 &mut self, 123 isa: &dyn TargetIsa, 124 mem: &mut Vec<u8>, 125 ctrl_plane: &mut ControlPlane, 126 ) -> CompileResult<&CompiledCode> { 127 let compiled_code = self.compile(isa, ctrl_plane)?; 128 mem.extend_from_slice(compiled_code.code_buffer()); 129 Ok(compiled_code) 130 } 131 132 /// Internally compiles the function into a stencil. 133 /// 134 /// Public only for testing and fuzzing purposes. 135 pub fn compile_stencil( 136 &mut self, 137 isa: &dyn TargetIsa, 138 ctrl_plane: &mut ControlPlane, 139 ) -> CodegenResult<CompiledCodeStencil> { 140 let _tt = timing::compile(); 141 142 self.verify_if(isa)?; 143 144 self.optimize(isa, ctrl_plane)?; 145 146 isa.compile_function(&self.func, &self.domtree, self.want_disasm, ctrl_plane) 147 } 148 149 /// Optimize the function, performing all compilation steps up to 150 /// but not including machine-code lowering and register 151 /// allocation. 152 /// 153 /// Public only for testing purposes. 154 pub fn optimize( 155 &mut self, 156 isa: &dyn TargetIsa, 157 ctrl_plane: &mut ControlPlane, 158 ) -> CodegenResult<()> { 159 log::debug!( 160 "Number of CLIF instructions to optimize: {}", 161 self.func.dfg.num_insts() 162 ); 163 log::debug!( 164 "Number of CLIF blocks to optimize: {}", 165 self.func.dfg.num_blocks() 166 ); 167 168 let opt_level = isa.flags().opt_level(); 169 crate::trace!( 170 "Optimizing (opt level {:?}):\n{}", 171 opt_level, 172 self.func.display() 173 ); 174 175 self.compute_cfg(); 176 if isa.flags().enable_nan_canonicalization() { 177 self.canonicalize_nans(isa)?; 178 } 179 180 self.legalize(isa)?; 181 182 self.compute_domtree(); 183 self.eliminate_unreachable_code(isa)?; 184 185 if opt_level != OptLevel::None { 186 self.dce(isa)?; 187 } 188 189 self.remove_constant_phis(isa)?; 190 191 if opt_level != OptLevel::None { 192 self.egraph_pass(isa, ctrl_plane)?; 193 } 194 195 Ok(()) 196 } 197 198 /// Compile the function. 199 /// 200 /// Run the function through all the passes necessary to generate code for the target ISA 201 /// represented by `isa`. This does not include the final step of emitting machine code into a 202 /// code sink. 203 /// 204 /// Returns information about the function's code and read-only data. 205 pub fn compile( 206 &mut self, 207 isa: &dyn TargetIsa, 208 ctrl_plane: &mut ControlPlane, 209 ) -> CompileResult<&CompiledCode> { 210 let stencil = self 211 .compile_stencil(isa, ctrl_plane) 212 .map_err(|error| CompileError { 213 inner: error, 214 func: &self.func, 215 })?; 216 Ok(self 217 .compiled_code 218 .insert(stencil.apply_params(&self.func.params))) 219 } 220 221 /// If available, return information about the code layout in the 222 /// final machine code: the offsets (in bytes) of each basic-block 223 /// start, and all basic-block edges. 224 #[deprecated = "use CompiledCode::get_code_bb_layout"] 225 pub fn get_code_bb_layout(&self) -> Option<(Vec<usize>, Vec<(usize, usize)>)> { 226 self.compiled_code().map(CompiledCode::get_code_bb_layout) 227 } 228 229 /// Creates unwind information for the function. 230 /// 231 /// Returns `None` if the function has no unwind information. 232 #[cfg(feature = "unwind")] 233 #[deprecated = "use CompiledCode::create_unwind_info"] 234 pub fn create_unwind_info( 235 &self, 236 isa: &dyn TargetIsa, 237 ) -> CodegenResult<Option<crate::isa::unwind::UnwindInfo>> { 238 self.compiled_code().unwrap().create_unwind_info(isa) 239 } 240 241 /// Run the verifier on the function. 242 /// 243 /// Also check that the dominator tree and control flow graph are consistent with the function. 244 /// 245 /// TODO: rename to "CLIF validate" or similar. 246 pub fn verify<'a, FOI: Into<FlagsOrIsa<'a>>>(&self, fisa: FOI) -> VerifierResult<()> { 247 let mut errors = VerifierErrors::default(); 248 let _ = verify_context(&self.func, &self.cfg, &self.domtree, fisa, &mut errors); 249 250 if errors.is_empty() { 251 Ok(()) 252 } else { 253 Err(errors) 254 } 255 } 256 257 /// Run the verifier only if the `enable_verifier` setting is true. 258 pub fn verify_if<'a, FOI: Into<FlagsOrIsa<'a>>>(&self, fisa: FOI) -> CodegenResult<()> { 259 let fisa = fisa.into(); 260 if fisa.flags.enable_verifier() { 261 self.verify(fisa)?; 262 } 263 Ok(()) 264 } 265 266 /// Perform dead-code elimination on the function. 267 pub fn dce<'a, FOI: Into<FlagsOrIsa<'a>>>(&mut self, fisa: FOI) -> CodegenResult<()> { 268 do_dce(&mut self.func, &mut self.domtree); 269 self.verify_if(fisa)?; 270 Ok(()) 271 } 272 273 /// Perform constant-phi removal on the function. 274 pub fn remove_constant_phis<'a, FOI: Into<FlagsOrIsa<'a>>>( 275 &mut self, 276 fisa: FOI, 277 ) -> CodegenResult<()> { 278 do_remove_constant_phis(&mut self.func, &mut self.domtree); 279 self.verify_if(fisa)?; 280 Ok(()) 281 } 282 283 /// Perform NaN canonicalizing rewrites on the function. 284 pub fn canonicalize_nans(&mut self, isa: &dyn TargetIsa) -> CodegenResult<()> { 285 do_nan_canonicalization(&mut self.func); 286 self.verify_if(isa) 287 } 288 289 /// Run the legalizer for `isa` on the function. 290 pub fn legalize(&mut self, isa: &dyn TargetIsa) -> CodegenResult<()> { 291 // Legalization invalidates the domtree and loop_analysis by mutating the CFG. 292 // TODO: Avoid doing this when legalization doesn't actually mutate the CFG. 293 self.domtree.clear(); 294 self.loop_analysis.clear(); 295 296 // Run some specific legalizations only. 297 simple_legalize(&mut self.func, &mut self.cfg, isa); 298 self.verify_if(isa) 299 } 300 301 /// Compute the control flow graph. 302 pub fn compute_cfg(&mut self) { 303 self.cfg.compute(&self.func) 304 } 305 306 /// Compute dominator tree. 307 pub fn compute_domtree(&mut self) { 308 self.domtree.compute(&self.func, &self.cfg) 309 } 310 311 /// Compute the loop analysis. 312 pub fn compute_loop_analysis(&mut self) { 313 self.loop_analysis 314 .compute(&self.func, &self.cfg, &self.domtree) 315 } 316 317 /// Compute the control flow graph and dominator tree. 318 pub fn flowgraph(&mut self) { 319 self.compute_cfg(); 320 self.compute_domtree() 321 } 322 323 /// Perform unreachable code elimination. 324 pub fn eliminate_unreachable_code<'a, FOI>(&mut self, fisa: FOI) -> CodegenResult<()> 325 where 326 FOI: Into<FlagsOrIsa<'a>>, 327 { 328 eliminate_unreachable_code(&mut self.func, &mut self.cfg, &self.domtree); 329 self.verify_if(fisa) 330 } 331 332 /// Replace all redundant loads with the known values in 333 /// memory. These are loads whose values were already loaded by 334 /// other loads earlier, as well as loads whose values were stored 335 /// by a store instruction to the same instruction (so-called 336 /// "store-to-load forwarding"). 337 pub fn replace_redundant_loads(&mut self) -> CodegenResult<()> { 338 let mut analysis = AliasAnalysis::new(&self.func, &self.domtree); 339 analysis.compute_and_update_aliases(&mut self.func); 340 Ok(()) 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 /// Run optimizations via the egraph infrastructure. 354 pub fn egraph_pass<'a, FOI>( 355 &mut self, 356 fisa: FOI, 357 ctrl_plane: &mut ControlPlane, 358 ) -> CodegenResult<()> 359 where 360 FOI: Into<FlagsOrIsa<'a>>, 361 { 362 let _tt = timing::egraph(); 363 364 trace!( 365 "About to optimize with egraph phase:\n{}", 366 self.func.display() 367 ); 368 self.compute_loop_analysis(); 369 let mut alias_analysis = AliasAnalysis::new(&self.func, &self.domtree); 370 let mut pass = EgraphPass::new( 371 &mut self.func, 372 &self.domtree, 373 &self.loop_analysis, 374 &mut alias_analysis, 375 ctrl_plane, 376 ); 377 pass.run(); 378 log::debug!("egraph stats: {:?}", pass.stats); 379 trace!("pinned_union_count: {}", pass.eclasses.pinned_union_count); 380 trace!("After egraph optimization:\n{}", self.func.display()); 381 382 self.verify_if(fisa) 383 } 384 } 385