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