1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! An experimental pass that scources for `#[rustc_mir]` attributes,
12 //! builds the resulting MIR, and dumps it out into a file for inspection.
14 //! The attribute formats that are currently accepted are:
16 //! - `#[rustc_mir(graphviz="file.gv")]`
17 //! - `#[rustc_mir(pretty="file.mir")]`
21 extern crate rustc_front;
27 use rustc::mir::repr::Mir;
31 use self::rustc::middle::infer;
32 use self::rustc::middle::region::CodeExtentData;
33 use self::rustc::middle::ty::{self, Ty};
34 use self::rustc::util::common::ErrorReported;
35 use self::rustc::util::nodemap::NodeMap;
36 use self::rustc_front::hir;
37 use self::rustc_front::intravisit::{self, Visitor};
38 use self::syntax::ast;
39 use self::syntax::attr::AttrMetaMethods;
40 use self::syntax::codemap::Span;
42 pub type MirMap<'tcx> = NodeMap<Mir<'tcx>>;
44 pub fn build_mir_for_crate<'tcx>(tcx: &ty::ctxt<'tcx>) -> MirMap<'tcx> {
45 let mut map = NodeMap();
47 let mut dump = OuterDump {
51 tcx.map.krate().visit_all_items(&mut dump);
56 ///////////////////////////////////////////////////////////////////////////
57 // OuterDump -- walks a crate, looking for fn items and methods to build MIR from
59 struct OuterDump<'a, 'tcx: 'a> {
60 tcx: &'a ty::ctxt<'tcx>,
61 map: &'a mut MirMap<'tcx>,
64 impl<'a, 'tcx> OuterDump<'a, 'tcx> {
65 fn visit_mir<OP>(&mut self, attributes: &'a [ast::Attribute], mut walk_op: OP)
66 where OP: for<'m> FnMut(&mut InnerDump<'a, 'm, 'tcx>)
68 let mut closure_dump = InnerDump {
73 for attr in attributes {
74 if attr.check_name("rustc_mir") {
75 closure_dump.attr = Some(attr);
78 walk_op(&mut closure_dump);
83 impl<'a, 'tcx> Visitor<'tcx> for OuterDump<'a, 'tcx> {
84 fn visit_item(&mut self, item: &'tcx hir::Item) {
85 self.visit_mir(&item.attrs, |c| intravisit::walk_item(c, item));
86 intravisit::walk_item(self, item);
89 fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem) {
90 match trait_item.node {
91 hir::MethodTraitItem(_, Some(_)) => {
92 self.visit_mir(&trait_item.attrs, |c| intravisit::walk_trait_item(c, trait_item));
94 hir::MethodTraitItem(_, None) |
95 hir::ConstTraitItem(..) |
96 hir::TypeTraitItem(..) => {}
98 intravisit::walk_trait_item(self, trait_item);
101 fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem) {
102 match impl_item.node {
103 hir::ImplItemKind::Method(..) => {
104 self.visit_mir(&impl_item.attrs, |c| intravisit::walk_impl_item(c, impl_item));
106 hir::ImplItemKind::Const(..) | hir::ImplItemKind::Type(..) => {}
108 intravisit::walk_impl_item(self, impl_item);
112 ///////////////////////////////////////////////////////////////////////////
113 // InnerDump -- dumps MIR for a single fn and its contained closures
115 struct InnerDump<'a, 'm, 'tcx: 'a + 'm> {
116 tcx: &'a ty::ctxt<'tcx>,
117 map: &'m mut MirMap<'tcx>,
118 attr: Option<&'a ast::Attribute>,
121 impl<'a, 'm, 'tcx> Visitor<'tcx> for InnerDump<'a,'m,'tcx> {
122 fn visit_trait_item(&mut self, _: &'tcx hir::TraitItem) {
123 // ignore methods; the outer dump will call us for them independently
126 fn visit_impl_item(&mut self, _: &'tcx hir::ImplItem) {
127 // ignore methods; the outer dump will call us for them independently
130 fn visit_fn(&mut self,
131 fk: intravisit::FnKind<'tcx>,
132 decl: &'tcx hir::FnDecl,
133 body: &'tcx hir::Block,
136 let (prefix, implicit_arg_tys) = match fk {
137 intravisit::FnKind::Closure =>
138 (format!("{}-", id), vec![closure_self_ty(&self.tcx, id, body.id)]),
140 (format!(""), vec![]),
143 let param_env = ty::ParameterEnvironment::for_item(self.tcx, id);
145 let infcx = infer::new_infer_ctxt(self.tcx, &self.tcx.tables, Some(param_env), true);
147 match build_mir(Cx::new(&infcx), implicit_arg_tys, id, span, decl, body) {
149 simplify_cfg::SimplifyCfg::new().run_on_mir(&mut mir);
151 let meta_item_list = self.attr
153 .flat_map(|a| a.meta_item_list())
154 .flat_map(|l| l.iter());
155 for item in meta_item_list {
156 if item.check_name("graphviz") || item.check_name("pretty") {
157 match item.value_str() {
159 let filename = format!("{}{}", prefix, s);
160 let result = File::create(&filename).and_then(|ref mut output| {
161 if item.check_name("graphviz") {
162 graphviz::write_mir_graphviz(&mir, output)
164 pretty::write_mir_pretty(&mir, output)
168 if let Err(e) = result {
169 self.tcx.sess.span_fatal(
171 &format!("Error writing MIR {} results to `{}`: {}",
172 item.name(), filename, e));
176 self.tcx.sess.span_err(
178 &format!("{} attribute requires a path", item.name()));
184 let previous = self.map.insert(id, mir);
185 assert!(previous.is_none());
187 Err(ErrorReported) => {}
190 intravisit::walk_fn(self, fk, decl, body, span);
194 fn build_mir<'a,'tcx:'a>(cx: Cx<'a,'tcx>,
195 implicit_arg_tys: Vec<Ty<'tcx>>,
198 decl: &'tcx hir::FnDecl,
199 body: &'tcx hir::Block)
200 -> Result<Mir<'tcx>, ErrorReported> {
201 // fetch the fully liberated fn signature (that is, all bound
202 // types/lifetimes replaced)
203 let fn_sig = match cx.tcx().tables.borrow().liberated_fn_sigs.get(&fn_id) {
204 Some(f) => f.clone(),
206 cx.tcx().sess.span_bug(span,
207 &format!("no liberated fn sig for {:?}", fn_id));
215 .map(|(index, arg)| {
216 (fn_sig.inputs[index], &*arg.pat)
220 let parameter_scope =
221 cx.tcx().region_maps.lookup_code_extent(
222 CodeExtentData::ParameterScope { fn_id: fn_id, body_id: body.id });
223 Ok(build::construct(cx,
232 fn closure_self_ty<'a, 'tcx>(tcx: &ty::ctxt<'tcx>,
233 closure_expr_id: ast::NodeId,
234 body_id: ast::NodeId)
236 let closure_ty = tcx.node_id_to_type(closure_expr_id);
238 // We're just hard-coding the idea that the signature will be
239 // &self or &mut self and hence will have a bound region with
241 let region = ty::Region::ReFree(ty::FreeRegion {
242 scope: tcx.region_maps.item_extent(body_id),
243 bound_region: ty::BoundRegion::BrAnon(0),
245 let region = tcx.mk_region(region);
247 match tcx.closure_kind(tcx.map.local_def_id(closure_expr_id)) {
248 ty::ClosureKind::FnClosureKind =>
250 ty::TypeAndMut { ty: closure_ty,
251 mutbl: hir::MutImmutable }),
252 ty::ClosureKind::FnMutClosureKind =>
254 ty::TypeAndMut { ty: closure_ty,
255 mutbl: hir::MutMutable }),
256 ty::ClosureKind::FnOnceClosureKind =>