2 use std::collections::HashMap;
5 use cranelift::codegen::{
7 ir::{self, entities::AnyEntity, function::DisplayFunctionAnnotations},
8 write::{FuncWriter, PlainWriter},
12 use crate::prelude::*;
14 /// This module provides the [CommentWriter] which makes it possible
15 /// to add comments to the written cranelift ir.
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)
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]
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] }
41 /// ebb0(v0: i64, v1: i64, v2: i64):
42 /// v3 = stack_addr.i64 ss0
43 /// v4 = stack_addr.i64 ss1
45 /// v5 = stack_addr.i64 ss2
55 /// ; _0 = const mini_core::FnMut::call_mut(move _3, move _4)
57 /// call fn0(v0, v3, v7)
69 pub struct CommentWriter {
70 global_comments: Vec<String>,
71 entity_comments: HashMap<AnyEntity, String>,
72 inst_comments: HashMap<Inst, String>,
76 pub fn new<'tcx>(tcx: TyCtxt<'tcx>, instance: Instance<'tcx>) -> Self {
77 let global_comments = if cfg!(debug_assertions) {
79 format!("symbol {}", tcx.symbol_name(instance).name.as_str()),
80 format!("instance {:?}", instance),
83 tcx.normalize_erasing_late_bound_regions(
84 ParamEnv::reveal_all(),
85 &crate::abi::fn_sig_for_fn_abi(tcx, instance)
96 entity_comments: HashMap::new(),
97 inst_comments: HashMap::new(),
102 impl FuncWriter for &'_ CommentWriter {
105 w: &mut dyn fmt::Write,
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)?;
116 if !self.global_comments.is_empty() {
120 self.super_preamble(w, func, reg_info)
123 fn write_entity_definition(
125 w: &mut dyn fmt::Write,
128 value: &dyn fmt::Display,
130 write!(w, " {} = {}", entity, value)?;
132 if let Some(comment) = self.entity_comments.get(&entity) {
133 writeln!(w, " ; {}", comment.replace('\n', "\n; "))
141 w: &mut dyn fmt::Write,
143 isa: Option<&dyn isa::TargetIsa>,
147 PlainWriter.write_ebb_header(w, func, isa, ebb, indent)
150 fn write_instruction(
152 w: &mut dyn fmt::Write,
154 aliases: &SecondaryMap<Value, Vec<Value>>,
155 isa: Option<&dyn isa::TargetIsa>,
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; "))?;
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());
173 pub fn add_entity_comment<'s, S: Into<Cow<'s, str>>, E: Into<AnyEntity>>(
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());
184 Entry::Vacant(vac) => {
185 vac.insert(comment.into().into_owned());
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());
197 Entry::Vacant(vac) => {
198 vac.insert(comment.into().into_owned());
204 pub fn write_clif_file<'tcx>(
207 instance: Instance<'tcx>,
209 mut clif_comments: &CommentWriter,
210 value_ranges: Option<&ValueLabelsRanges>,
214 let symbol_name = tcx.symbol_name(instance).name.as_str();
215 let clif_file_name = format!(
217 concat!(env!("CARGO_MANIFEST_DIR"), "/target/out/clif"),
218 tcx.crate_name(LOCAL_CRATE),
223 let mut clif = String::new();
224 cranelift::codegen::write::decorate_function(
228 &DisplayFunctionAnnotations {
229 isa: Some(&*crate::build_isa(
230 tcx.sess, true, /* PIC doesn't matter here */
237 match ::std::fs::File::create(clif_file_name) {
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();
247 tcx.sess.warn(&format!("err opening clif file: {:?}", e));
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)?;
257 let mut clif = String::new();
258 ::cranelift::codegen::write::decorate_function(
259 &mut &self.clif_comments,
262 &DisplayFunctionAnnotations::default(),
265 writeln!(f, "\n{}", clif)