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