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