]> git.lizzy.rs Git - rust.git/blob - src/pretty_clif.rs
97bb2e0caecb4adcc58757c33daed71cc8765a84
[rust.git] / src / pretty_clif.rs
1 use std::borrow::Cow;
2 use std::collections::HashMap;
3 use std::fmt;
4
5 use cranelift::codegen::{
6     entity::SecondaryMap,
7     ir::{self, entities::AnyEntity, function::DisplayFunctionAnnotations},
8     write::{FuncWriter, PlainWriter},
9     ValueLabelsRanges,
10 };
11
12 use crate::prelude::*;
13
14 /// This module provides the [CommentWriter] which makes it possible
15 /// to add comments to the written cranelift ir.
16 ///
17 /// # Example
18 ///
19 /// ```clif
20 /// test compile
21 /// target x86_64
22 ///
23 /// function u0:0(i64, i64, i64) system_v {
24 /// ; symbol _ZN119_$LT$example..IsNotEmpty$u20$as$u20$mini_core..FnOnce$LT$$LP$$RF$$u27$a$u20$$RF$$u27$b$u20$$u5b$u16$u5d$$C$$RP$$GT$$GT$9call_once17he85059d5e6a760a0E
25 /// ; instance Instance { def: Item(DefId(0/0:29 ~ example[8787]::{{impl}}[0]::call_once[0])), substs: [ReErased, ReErased] }
26 /// ; sig ([IsNotEmpty, (&&[u16],)]; c_variadic: false)->(u8, u8)
27 ///
28 /// ; ssa {_2: NOT_SSA, _4: NOT_SSA, _0: NOT_SSA, _3: (empty), _1: NOT_SSA}
29 /// ; msg   loc.idx    param    pass mode            ssa flags  ty
30 /// ; ret    _0      = v0       ByRef                NOT_SSA    (u8, u8)
31 /// ; arg    _1      = v1       ByRef                NOT_SSA    IsNotEmpty
32 /// ; arg    _2.0    = v2       ByVal(types::I64)    NOT_SSA    &&[u16]
33 ///
34 ///     ss0 = explicit_slot 0 ; _1: IsNotEmpty size=0 align=1,8
35 ///     ss1 = explicit_slot 8 ; _2: (&&[u16],) size=8 align=8,8
36 ///     ss2 = explicit_slot 8 ; _4: (&&[u16],) size=8 align=8,8
37 ///     sig0 = (i64, i64, i64) system_v
38 ///     sig1 = (i64, i64, i64) system_v
39 ///     fn0 = colocated u0:6 sig1 ; Instance { def: Item(DefId(0/0:31 ~ example[8787]::{{impl}}[1]::call_mut[0])), substs: [ReErased, ReErased] }
40 ///
41 /// ebb0(v0: i64, v1: i64, v2: i64):
42 ///     v3 = stack_addr.i64 ss0
43 ///     v4 = stack_addr.i64 ss1
44 ///     store v2, v4
45 ///     v5 = stack_addr.i64 ss2
46 ///     jump ebb1
47 ///
48 /// ebb1:
49 ///     nop
50 /// ; _3 = &mut _1
51 /// ; _4 = _2
52 ///     v6 = load.i64 v4
53 ///     store v6, v5
54 /// ;
55 /// ; _0 = const mini_core::FnMut::call_mut(move _3, move _4)
56 ///     v7 = load.i64 v5
57 ///     call fn0(v0, v3, v7)
58 ///     jump ebb2
59 ///
60 /// ebb2:
61 ///     nop
62 /// ;
63 /// ; return
64 ///     return
65 /// }
66 /// ```
67
68 #[derive(Debug)]
69 pub struct CommentWriter {
70     global_comments: Vec<String>,
71     entity_comments: HashMap<AnyEntity, String>,
72     inst_comments: HashMap<Inst, String>,
73 }
74
75 impl CommentWriter {
76     pub fn new<'tcx>(tcx: TyCtxt<'tcx>, instance: Instance<'tcx>) -> Self {
77         let global_comments = if cfg!(debug_assertions) {
78             vec![
79                 format!("symbol {}", tcx.symbol_name(instance).name.as_str()),
80                 format!("instance {:?}", instance),
81                 format!(
82                     "sig {:?}",
83                     tcx.normalize_erasing_late_bound_regions(
84                         ParamEnv::reveal_all(),
85                         &crate::abi::fn_sig_for_fn_abi(tcx, instance)
86                     )
87                 ),
88                 String::new(),
89             ]
90         } else {
91             vec![]
92         };
93
94         CommentWriter {
95             global_comments,
96             entity_comments: HashMap::new(),
97             inst_comments: HashMap::new(),
98         }
99     }
100 }
101
102 impl FuncWriter for &'_ CommentWriter {
103     fn write_preamble(
104         &mut self,
105         w: &mut dyn fmt::Write,
106         func: &Function,
107         reg_info: Option<&isa::RegInfo>,
108     ) -> Result<bool, fmt::Error> {
109         for comment in &self.global_comments {
110             if !comment.is_empty() {
111                 writeln!(w, "; {}", comment)?;
112             } else {
113                 writeln!(w, "")?;
114             }
115         }
116         if !self.global_comments.is_empty() {
117             writeln!(w, "")?;
118         }
119
120         self.super_preamble(w, func, reg_info)
121     }
122
123     fn write_entity_definition(
124         &mut self,
125         w: &mut dyn fmt::Write,
126         _func: &Function,
127         entity: AnyEntity,
128         value: &dyn fmt::Display,
129     ) -> fmt::Result {
130         write!(w, "    {} = {}", entity, value)?;
131
132         if let Some(comment) = self.entity_comments.get(&entity) {
133             writeln!(w, " ; {}", comment.replace('\n', "\n; "))
134         } else {
135             writeln!(w, "")
136         }
137     }
138
139     fn write_ebb_header(
140         &mut self,
141         w: &mut dyn fmt::Write,
142         func: &Function,
143         isa: Option<&dyn isa::TargetIsa>,
144         ebb: Ebb,
145         indent: usize,
146     ) -> fmt::Result {
147         PlainWriter.write_ebb_header(w, func, isa, ebb, indent)
148     }
149
150     fn write_instruction(
151         &mut self,
152         w: &mut dyn fmt::Write,
153         func: &Function,
154         aliases: &SecondaryMap<Value, Vec<Value>>,
155         isa: Option<&dyn isa::TargetIsa>,
156         inst: Inst,
157         indent: usize,
158     ) -> fmt::Result {
159         PlainWriter.write_instruction(w, func, aliases, isa, inst, indent)?;
160         if let Some(comment) = self.inst_comments.get(&inst) {
161             writeln!(w, "; {}", comment.replace('\n', "\n; "))?;
162         }
163         Ok(())
164     }
165 }
166
167 #[cfg(debug_assertions)]
168 impl<'a, 'tcx, B: Backend + 'static> FunctionCx<'_, 'tcx, B> {
169     pub fn add_global_comment<S: Into<String>>(&mut self, comment: S) {
170         self.clif_comments.global_comments.push(comment.into());
171     }
172
173     pub fn add_entity_comment<'s, S: Into<Cow<'s, str>>, E: Into<AnyEntity>>(
174         &mut self,
175         entity: E,
176         comment: S,
177     ) {
178         use std::collections::hash_map::Entry;
179         match self.clif_comments.entity_comments.entry(entity.into()) {
180             Entry::Occupied(mut occ) => {
181                 occ.get_mut().push('\n');
182                 occ.get_mut().push_str(comment.into().as_ref());
183             }
184             Entry::Vacant(vac) => {
185                 vac.insert(comment.into().into_owned());
186             }
187         }
188     }
189
190     pub fn add_comment<'s, S: Into<Cow<'s, str>>>(&mut self, inst: Inst, comment: S) {
191         use std::collections::hash_map::Entry;
192         match self.clif_comments.inst_comments.entry(inst) {
193             Entry::Occupied(mut occ) => {
194                 occ.get_mut().push('\n');
195                 occ.get_mut().push_str(comment.into().as_ref());
196             }
197             Entry::Vacant(vac) => {
198                 vac.insert(comment.into().into_owned());
199             }
200         }
201     }
202 }
203
204 pub fn write_clif_file<'tcx>(
205     tcx: TyCtxt<'tcx>,
206     postfix: &str,
207     instance: Instance<'tcx>,
208     func: &ir::Function,
209     mut clif_comments: &CommentWriter,
210     value_ranges: Option<&ValueLabelsRanges>,
211 ) {
212     use std::io::Write;
213
214     let symbol_name = tcx.symbol_name(instance).name.as_str();
215     let clif_file_name = format!(
216         "{}/{}__{}.{}.clif",
217         concat!(env!("CARGO_MANIFEST_DIR"), "/target/out/clif"),
218         tcx.crate_name(LOCAL_CRATE),
219         symbol_name,
220         postfix,
221     );
222
223     let mut clif = String::new();
224     cranelift::codegen::write::decorate_function(
225         &mut clif_comments,
226         &mut clif,
227         &func,
228         &DisplayFunctionAnnotations {
229             isa: Some(&*crate::build_isa(
230                 tcx.sess, true, /* PIC doesn't matter here */
231             )),
232             value_ranges,
233         },
234     )
235     .unwrap();
236
237     match ::std::fs::File::create(clif_file_name) {
238         Ok(mut file) => {
239             let target_triple = crate::target_triple(tcx.sess);
240             writeln!(file, "test compile").unwrap();
241             writeln!(file, "set is_pic").unwrap();
242             writeln!(file, "target {}", target_triple).unwrap();
243             writeln!(file, "").unwrap();
244             file.write(clif.as_bytes()).unwrap();
245         }
246         Err(e) => {
247             tcx.sess.warn(&format!("err opening clif file: {:?}", e));
248         }
249     }
250 }
251
252 impl<'a, 'tcx, B: Backend + 'static> fmt::Debug for FunctionCx<'_, 'tcx, B> {
253     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
254         writeln!(f, "{:?}", self.instance.substs)?;
255         writeln!(f, "{:?}", self.local_map)?;
256
257         let mut clif = String::new();
258         ::cranelift::codegen::write::decorate_function(
259             &mut &self.clif_comments,
260             &mut clif,
261             &self.bcx.func,
262             &DisplayFunctionAnnotations::default(),
263         )
264         .unwrap();
265         writeln!(f, "\n{}", clif)
266     }
267 }