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