]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_monomorphize/src/util.rs
Rollup merge of #101864 - notriddle:notriddle/h1-h2-h3-h4, r=GuillaumeGomez
[rust.git] / compiler / rustc_monomorphize / src / util.rs
1 use rustc_middle::ty::{self, ClosureSizeProfileData, Instance, TyCtxt};
2 use std::fs::OpenOptions;
3 use std::io::prelude::*;
4
5 /// For a given closure, writes out the data for the profiling the impact of RFC 2229 on
6 /// closure size into a CSV.
7 ///
8 /// During the same compile all closures dump the information in the same file
9 /// "closure_profile_XXXXX.csv", which is created in the directory where the compiler is invoked.
10 pub(crate) fn dump_closure_profile<'tcx>(tcx: TyCtxt<'tcx>, closure_instance: Instance<'tcx>) {
11     let Ok(mut file) = OpenOptions::new()
12         .create(true)
13         .append(true)
14         .open(&format!("closure_profile_{}.csv", std::process::id()))
15     else {
16         eprintln!("Couldn't open file for writing closure profile");
17         return;
18     };
19
20     let closure_def_id = closure_instance.def_id().expect_local();
21     let typeck_results = tcx.typeck(closure_def_id);
22
23     if typeck_results.closure_size_eval.contains_key(&closure_def_id) {
24         let param_env = ty::ParamEnv::reveal_all();
25
26         let ClosureSizeProfileData { before_feature_tys, after_feature_tys } =
27             typeck_results.closure_size_eval[&closure_def_id];
28
29         let before_feature_tys = tcx.subst_and_normalize_erasing_regions(
30             closure_instance.substs,
31             param_env,
32             before_feature_tys,
33         );
34         let after_feature_tys = tcx.subst_and_normalize_erasing_regions(
35             closure_instance.substs,
36             param_env,
37             after_feature_tys,
38         );
39
40         let new_size = tcx
41             .layout_of(param_env.and(after_feature_tys))
42             .map(|l| format!("{:?}", l.size.bytes()))
43             .unwrap_or_else(|e| format!("Failed {:?}", e));
44
45         let old_size = tcx
46             .layout_of(param_env.and(before_feature_tys))
47             .map(|l| format!("{:?}", l.size.bytes()))
48             .unwrap_or_else(|e| format!("Failed {:?}", e));
49
50         let closure_span = tcx.def_span(closure_def_id);
51         let src_file = tcx.sess.source_map().span_to_filename(closure_span);
52         let line_nos = tcx
53             .sess
54             .source_map()
55             .span_to_lines(closure_span)
56             .map(|l| format!("{:?} {:?}", l.lines.first(), l.lines.last()))
57             .unwrap_or_else(|e| format!("{:?}", e));
58
59         if let Err(e) = writeln!(
60             file,
61             "{}, {}, {}, {:?}",
62             old_size,
63             new_size,
64             src_file.prefer_local(),
65             line_nos
66         ) {
67             eprintln!("Error writing to file {}", e)
68         }
69     }
70 }