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)?;
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(&mut self, isa: &dyn TargetIsa) -> CodegenResult<()> {
155         log::debug!(
156             "Number of CLIF instructions to optimize: {}",
157             self.func.dfg.num_insts()
158         );
159         log::debug!(
160             "Number of CLIF blocks to optimize: {}",
161             self.func.dfg.num_blocks()
162         );
163 
164         let opt_level = isa.flags().opt_level();
165         crate::trace!(
166             "Optimizing (opt level {:?}):\n{}",
167             opt_level,
168             self.func.display()
169         );
170 
171         self.compute_cfg();
172         if isa.flags().enable_nan_canonicalization() {
173             self.canonicalize_nans(isa)?;
174         }
175 
176         self.legalize(isa)?;
177 
178         self.compute_domtree();
179         self.eliminate_unreachable_code(isa)?;
180 
181         if opt_level != OptLevel::None {
182             self.dce(isa)?;
183         }
184 
185         self.remove_constant_phis(isa)?;
186 
187         if opt_level != OptLevel::None {
188             self.egraph_pass()?;
189         }
190 
191         Ok(())
192     }
193 
194     /// Compile the function.
195     ///
196     /// Run the function through all the passes necessary to generate code for the target ISA
197     /// represented by `isa`. This does not include the final step of emitting machine code into a
198     /// code sink.
199     ///
200     /// Returns information about the function's code and read-only data.
201     pub fn compile(
202         &mut self,
203         isa: &dyn TargetIsa,
204         ctrl_plane: &mut ControlPlane,
205     ) -> CompileResult<&CompiledCode> {
206         let stencil = self
207             .compile_stencil(isa, ctrl_plane)
208             .map_err(|error| CompileError {
209                 inner: error,
210                 func: &self.func,
211             })?;
212         Ok(self
213             .compiled_code
214             .insert(stencil.apply_params(&self.func.params)))
215     }
216 
217     /// If available, return information about the code layout in the
218     /// final machine code: the offsets (in bytes) of each basic-block
219     /// start, and all basic-block edges.
220     #[deprecated = "use CompiledCode::get_code_bb_layout"]
221     pub fn get_code_bb_layout(&self) -> Option<(Vec<usize>, Vec<(usize, usize)>)> {
222         self.compiled_code().map(CompiledCode::get_code_bb_layout)
223     }
224 
225     /// Creates unwind information for the function.
226     ///
227     /// Returns `None` if the function has no unwind information.
228     #[cfg(feature = "unwind")]
229     #[deprecated = "use CompiledCode::create_unwind_info"]
230     pub fn create_unwind_info(
231         &self,
232         isa: &dyn TargetIsa,
233     ) -> CodegenResult<Option<crate::isa::unwind::UnwindInfo>> {
234         self.compiled_code().unwrap().create_unwind_info(isa)
235     }
236 
237     /// Run the verifier on the function.
238     ///
239     /// Also check that the dominator tree and control flow graph are consistent with the function.
240     pub fn verify<'a, FOI: Into<FlagsOrIsa<'a>>>(&self, fisa: FOI) -> VerifierResult<()> {
241         let mut errors = VerifierErrors::default();
242         let _ = verify_context(&self.func, &self.cfg, &self.domtree, fisa, &mut errors);
243 
244         if errors.is_empty() {
245             Ok(())
246         } else {
247             Err(errors)
248         }
249     }
250 
251     /// Run the verifier only if the `enable_verifier` setting is true.
252     pub fn verify_if<'a, FOI: Into<FlagsOrIsa<'a>>>(&self, fisa: FOI) -> CodegenResult<()> {
253         let fisa = fisa.into();
254         if fisa.flags.enable_verifier() {
255             self.verify(fisa)?;
256         }
257         Ok(())
258     }
259 
260     /// Perform dead-code elimination on the function.
261     pub fn dce<'a, FOI: Into<FlagsOrIsa<'a>>>(&mut self, fisa: FOI) -> CodegenResult<()> {
262         do_dce(&mut self.func, &mut self.domtree);
263         self.verify_if(fisa)?;
264         Ok(())
265     }
266 
267     /// Perform constant-phi removal on the function.
268     pub fn remove_constant_phis<'a, FOI: Into<FlagsOrIsa<'a>>>(
269         &mut self,
270         fisa: FOI,
271     ) -> CodegenResult<()> {
272         do_remove_constant_phis(&mut self.func, &mut self.domtree);
273         self.verify_if(fisa)?;
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 unreachable code elimination.
318     pub fn eliminate_unreachable_code<'a, FOI>(&mut self, fisa: FOI) -> CodegenResult<()>
319     where
320         FOI: Into<FlagsOrIsa<'a>>,
321     {
322         eliminate_unreachable_code(&mut self.func, &mut self.cfg, &self.domtree);
323         self.verify_if(fisa)
324     }
325 
326     /// Replace all redundant loads with the known values in
327     /// memory. These are loads whose values were already loaded by
328     /// other loads earlier, as well as loads whose values were stored
329     /// by a store instruction to the same instruction (so-called
330     /// "store-to-load forwarding").
331     pub fn replace_redundant_loads(&mut self) -> CodegenResult<()> {
332         let mut analysis = AliasAnalysis::new(&self.func, &self.domtree);
333         analysis.compute_and_update_aliases(&mut self.func);
334         Ok(())
335     }
336 
337     /// Harvest candidate left-hand sides for superoptimization with Souper.
338     #[cfg(feature = "souper-harvest")]
339     pub fn souper_harvest(
340         &mut self,
341         out: &mut std::sync::mpsc::Sender<String>,
342     ) -> CodegenResult<()> {
343         do_souper_harvest(&self.func, out);
344         Ok(())
345     }
346 
347     /// Run optimizations via the egraph infrastructure.
348     pub fn egraph_pass(&mut self) -> CodegenResult<()> {
349         let _tt = timing::egraph();
350 
351         trace!(
352             "About to optimize with egraph phase:\n{}",
353             self.func.display()
354         );
355         self.compute_loop_analysis();
356         let mut alias_analysis = AliasAnalysis::new(&self.func, &self.domtree);
357         let mut pass = EgraphPass::new(
358             &mut self.func,
359             &self.domtree,
360             &self.loop_analysis,
361             &mut alias_analysis,
362         );
363         pass.run();
364         log::debug!("egraph stats: {:?}", pass.stats);
365         trace!("After egraph optimization:\n{}", self.func.display());
366         Ok(())
367     }
368 }
369