]> git.lizzy.rs Git - rust.git/blob - src/pretty_clif.rs
Querify `fn_abi_of_{fn_ptr,instance}`.
[rust.git] / src / pretty_clif.rs
1 //! This module provides the [CommentWriter] which makes it possible
2 //! to add comments to the written cranelift ir.
3 //!
4 //! # Example
5 //!
6 //! ```clif
7 //! test compile
8 //! target x86_64
9 //!
10 //! function u0:0(i64, i64, i64) system_v {
11 //! ; 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
12 //! ; instance Instance { def: Item(DefId(0/0:29 ~ example[8787]::{{impl}}[0]::call_once[0])), substs: [ReErased, ReErased] }
13 //! ; sig ([IsNotEmpty, (&&[u16],)]; c_variadic: false)->(u8, u8)
14 //!
15 //! ; ssa {_2: NOT_SSA, _4: NOT_SSA, _0: NOT_SSA, _3: (empty), _1: NOT_SSA}
16 //! ; msg   loc.idx    param    pass mode            ssa flags  ty
17 //! ; ret    _0      = v0       ByRef                NOT_SSA    (u8, u8)
18 //! ; arg    _1      = v1       ByRef                NOT_SSA    IsNotEmpty
19 //! ; arg    _2.0    = v2       ByVal(types::I64)    NOT_SSA    &&[u16]
20 //!
21 //!     ss0 = explicit_slot 0 ; _1: IsNotEmpty size=0 align=1,8
22 //!     ss1 = explicit_slot 8 ; _2: (&&[u16],) size=8 align=8,8
23 //!     ss2 = explicit_slot 8 ; _4: (&&[u16],) size=8 align=8,8
24 //!     sig0 = (i64, i64, i64) system_v
25 //!     sig1 = (i64, i64, i64) system_v
26 //!     fn0 = colocated u0:6 sig1 ; Instance { def: Item(DefId(0/0:31 ~ example[8787]::{{impl}}[1]::call_mut[0])), substs: [ReErased, ReErased] }
27 //!
28 //! block0(v0: i64, v1: i64, v2: i64):
29 //!     v3 = stack_addr.i64 ss0
30 //!     v4 = stack_addr.i64 ss1
31 //!     store v2, v4
32 //!     v5 = stack_addr.i64 ss2
33 //!     jump block1
34 //!
35 //! block1:
36 //!     nop
37 //! ; _3 = &mut _1
38 //! ; _4 = _2
39 //!     v6 = load.i64 v4
40 //!     store v6, v5
41 //! ;
42 //! ; _0 = const mini_core::FnMut::call_mut(move _3, move _4)
43 //!     v7 = load.i64 v5
44 //!     call fn0(v0, v3, v7)
45 //!     jump block2
46 //!
47 //! block2:
48 //!     nop
49 //! ;
50 //! ; return
51 //!     return
52 //! }
53 //! ```
54
55 use std::fmt;
56 use std::io::Write;
57
58 use cranelift_codegen::{
59     entity::SecondaryMap,
60     ir::{entities::AnyEntity, function::DisplayFunctionAnnotations},
61     write::{FuncWriter, PlainWriter},
62 };
63
64 use rustc_middle::ty::layout::FnAbiOf;
65 use rustc_session::config::OutputType;
66
67 use crate::prelude::*;
68
69 #[derive(Debug)]
70 pub(crate) struct CommentWriter {
71     enabled: bool,
72     global_comments: Vec<String>,
73     entity_comments: FxHashMap<AnyEntity, String>,
74 }
75
76 impl CommentWriter {
77     pub(crate) fn new<'tcx>(tcx: TyCtxt<'tcx>, instance: Instance<'tcx>) -> Self {
78         let enabled = should_write_ir(tcx);
79         let global_comments = if enabled {
80             vec![
81                 format!("symbol {}", tcx.symbol_name(instance).name),
82                 format!("instance {:?}", instance),
83                 format!(
84                     "abi {:?}",
85                     RevealAllLayoutCx(tcx).fn_abi_of_instance(instance, ty::List::empty())
86                 ),
87                 String::new(),
88             ]
89         } else {
90             vec![]
91         };
92
93         CommentWriter { enabled, global_comments, entity_comments: FxHashMap::default() }
94     }
95 }
96
97 impl CommentWriter {
98     pub(crate) fn enabled(&self) -> bool {
99         self.enabled
100     }
101
102     pub(crate) fn add_global_comment<S: Into<String>>(&mut self, comment: S) {
103         debug_assert!(self.enabled);
104         self.global_comments.push(comment.into());
105     }
106
107     pub(crate) fn add_comment<S: Into<String> + AsRef<str>, E: Into<AnyEntity>>(
108         &mut self,
109         entity: E,
110         comment: S,
111     ) {
112         debug_assert!(self.enabled);
113
114         use std::collections::hash_map::Entry;
115         match self.entity_comments.entry(entity.into()) {
116             Entry::Occupied(mut occ) => {
117                 occ.get_mut().push('\n');
118                 occ.get_mut().push_str(comment.as_ref());
119             }
120             Entry::Vacant(vac) => {
121                 vac.insert(comment.into());
122             }
123         }
124     }
125 }
126
127 impl FuncWriter for &'_ CommentWriter {
128     fn write_preamble(
129         &mut self,
130         w: &mut dyn fmt::Write,
131         func: &Function,
132         reg_info: Option<&isa::RegInfo>,
133     ) -> Result<bool, fmt::Error> {
134         for comment in &self.global_comments {
135             if !comment.is_empty() {
136                 writeln!(w, "; {}", comment)?;
137             } else {
138                 writeln!(w)?;
139             }
140         }
141         if !self.global_comments.is_empty() {
142             writeln!(w)?;
143         }
144
145         self.super_preamble(w, func, reg_info)
146     }
147
148     fn write_entity_definition(
149         &mut self,
150         w: &mut dyn fmt::Write,
151         _func: &Function,
152         entity: AnyEntity,
153         value: &dyn fmt::Display,
154     ) -> fmt::Result {
155         write!(w, "    {} = {}", entity, value)?;
156
157         if let Some(comment) = self.entity_comments.get(&entity) {
158             writeln!(w, " ; {}", comment.replace('\n', "\n; "))
159         } else {
160             writeln!(w)
161         }
162     }
163
164     fn write_block_header(
165         &mut self,
166         w: &mut dyn fmt::Write,
167         func: &Function,
168         isa: Option<&dyn isa::TargetIsa>,
169         block: Block,
170         indent: usize,
171     ) -> fmt::Result {
172         PlainWriter.write_block_header(w, func, isa, block, indent)
173     }
174
175     fn write_instruction(
176         &mut self,
177         w: &mut dyn fmt::Write,
178         func: &Function,
179         aliases: &SecondaryMap<Value, Vec<Value>>,
180         isa: Option<&dyn isa::TargetIsa>,
181         inst: Inst,
182         indent: usize,
183     ) -> fmt::Result {
184         PlainWriter.write_instruction(w, func, aliases, isa, inst, indent)?;
185         if let Some(comment) = self.entity_comments.get(&inst.into()) {
186             writeln!(w, "; {}", comment.replace('\n', "\n; "))?;
187         }
188         Ok(())
189     }
190 }
191
192 impl FunctionCx<'_, '_, '_> {
193     pub(crate) fn add_global_comment<S: Into<String>>(&mut self, comment: S) {
194         self.clif_comments.add_global_comment(comment);
195     }
196
197     pub(crate) fn add_comment<S: Into<String> + AsRef<str>, E: Into<AnyEntity>>(
198         &mut self,
199         entity: E,
200         comment: S,
201     ) {
202         self.clif_comments.add_comment(entity, comment);
203     }
204 }
205
206 pub(crate) fn should_write_ir(tcx: TyCtxt<'_>) -> bool {
207     tcx.sess.opts.output_types.contains_key(&OutputType::LlvmAssembly)
208 }
209
210 pub(crate) fn write_ir_file(
211     tcx: TyCtxt<'_>,
212     name: impl FnOnce() -> String,
213     write: impl FnOnce(&mut dyn Write) -> std::io::Result<()>,
214 ) {
215     if !should_write_ir(tcx) {
216         return;
217     }
218
219     let clif_output_dir = tcx.output_filenames(()).with_extension("clif");
220
221     match std::fs::create_dir(&clif_output_dir) {
222         Ok(()) => {}
223         Err(err) if err.kind() == std::io::ErrorKind::AlreadyExists => {}
224         res @ Err(_) => res.unwrap(),
225     }
226
227     let clif_file_name = clif_output_dir.join(name());
228
229     let res = std::fs::File::create(clif_file_name).and_then(|mut file| write(&mut file));
230     if let Err(err) = res {
231         tcx.sess.warn(&format!("error writing ir file: {}", err));
232     }
233 }
234
235 pub(crate) fn write_clif_file<'tcx>(
236     tcx: TyCtxt<'tcx>,
237     postfix: &str,
238     isa: &dyn cranelift_codegen::isa::TargetIsa,
239     instance: Instance<'tcx>,
240     context: &cranelift_codegen::Context,
241     mut clif_comments: &CommentWriter,
242 ) {
243     write_ir_file(
244         tcx,
245         || format!("{}.{}.clif", tcx.symbol_name(instance).name, postfix),
246         |file| {
247             let mut clif = String::new();
248             cranelift_codegen::write::decorate_function(
249                 &mut clif_comments,
250                 &mut clif,
251                 &context.func,
252                 &DisplayFunctionAnnotations { isa: Some(isa), value_ranges: None },
253             )
254             .unwrap();
255
256             for flag in isa.flags().iter() {
257                 writeln!(file, "set {}", flag)?;
258             }
259             write!(file, "target {}", isa.triple().architecture.to_string())?;
260             for isa_flag in isa.isa_flags().iter() {
261                 write!(file, " {}", isa_flag)?;
262             }
263             writeln!(file, "\n")?;
264             writeln!(file)?;
265             file.write_all(clif.as_bytes())?;
266             Ok(())
267         },
268     );
269 }
270
271 impl fmt::Debug for FunctionCx<'_, '_, '_> {
272     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
273         writeln!(f, "{:?}", self.instance.substs)?;
274         writeln!(f, "{:?}", self.local_map)?;
275
276         let mut clif = String::new();
277         ::cranelift_codegen::write::decorate_function(
278             &mut &self.clif_comments,
279             &mut clif,
280             &self.bcx.func,
281             &DisplayFunctionAnnotations::default(),
282         )
283         .unwrap();
284         writeln!(f, "\n{}", clif)
285     }
286 }