]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/build/mod.rs
7490ee60e1f9f6c10f8da4fc12591cd45efaa581
[rust.git] / src / librustc_mir / build / mod.rs
1 // Copyright 2012-2014 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.
4 //
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.
10
11
12 use build;
13 use hair::cx::Cx;
14 use hair::Pattern;
15 use rustc::hir;
16 use rustc::hir::def_id::DefId;
17 use rustc::middle::region::CodeExtent;
18 use rustc::mir::*;
19 use rustc::mir::transform::MirSource;
20 use rustc::mir::visit::MutVisitor;
21 use rustc::ty::{self, Ty, TyCtxt};
22 use rustc::ty::subst::Substs;
23 use rustc::util::nodemap::NodeMap;
24 use rustc_data_structures::indexed_vec::{IndexVec, Idx};
25 use shim;
26 use std::mem;
27 use std::u32;
28 use syntax::abi::Abi;
29 use syntax::ast;
30 use syntax::symbol::keywords;
31 use syntax_pos::Span;
32 use util as mir_util;
33
34 /// Construct the MIR for a given def-id.
35 pub fn mir_build<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> Mir<'tcx> {
36     let id = tcx.hir.as_local_node_id(def_id).unwrap();
37     let unsupported = || {
38         span_bug!(tcx.hir.span(id), "can't build MIR for {:?}", def_id);
39     };
40
41     // Figure out what primary body this item has.
42     let body_id = match tcx.hir.get(id) {
43         hir::map::NodeItem(item) => {
44             match item.node {
45                 hir::ItemConst(_, body) |
46                 hir::ItemStatic(_, _, body) |
47                 hir::ItemFn(.., body) => body,
48                 _ => unsupported()
49             }
50         }
51         hir::map::NodeTraitItem(item) => {
52             match item.node {
53                 hir::TraitItemKind::Const(_, Some(body)) |
54                 hir::TraitItemKind::Method(_,
55                     hir::TraitMethod::Provided(body)) => body,
56                 _ => unsupported()
57             }
58         }
59         hir::map::NodeImplItem(item) => {
60             match item.node {
61                 hir::ImplItemKind::Const(_, body) |
62                 hir::ImplItemKind::Method(_, body) => body,
63                 _ => unsupported()
64             }
65         }
66         hir::map::NodeExpr(expr) => {
67             // FIXME(eddyb) Closures should have separate
68             // function definition IDs and expression IDs.
69             // Type-checking should not let closures get
70             // this far in a constant position.
71             // Assume that everything other than closures
72             // is a constant "initializer" expression.
73             match expr.node {
74                 hir::ExprClosure(_, _, body, _) => body,
75                 _ => hir::BodyId { node_id: expr.id }
76             }
77         }
78         hir::map::NodeVariant(variant) =>
79             return create_constructor_shim(tcx, id, &variant.node.data),
80         hir::map::NodeStructCtor(ctor) =>
81             return create_constructor_shim(tcx, id, ctor),
82         _ => unsupported()
83     };
84
85     let src = MirSource::from_node(tcx, id);
86     tcx.infer_ctxt(body_id).enter(|infcx| {
87         let cx = Cx::new(&infcx, src);
88         let mut mir = if cx.tables().tainted_by_errors {
89             build::construct_error(cx, body_id)
90         } else if let MirSource::Fn(id) = src {
91             // fetch the fully liberated fn signature (that is, all bound
92             // types/lifetimes replaced)
93             let fn_sig = cx.tables().liberated_fn_sigs[&id].clone();
94
95             let ty = tcx.type_of(tcx.hir.local_def_id(id));
96             let mut abi = fn_sig.abi;
97             let implicit_argument = if let ty::TyClosure(..) = ty.sty {
98                 // HACK(eddyb) Avoid having RustCall on closures,
99                 // as it adds unnecessary (and wrong) auto-tupling.
100                 abi = Abi::Rust;
101                 Some((closure_self_ty(tcx, id, body_id), None))
102             } else {
103                 None
104             };
105
106             let body = tcx.hir.body(body_id);
107             let explicit_arguments =
108                 body.arguments
109                     .iter()
110                     .enumerate()
111                     .map(|(index, arg)| {
112                         (fn_sig.inputs()[index], Some(&*arg.pat))
113                     });
114
115             let arguments = implicit_argument.into_iter().chain(explicit_arguments);
116             build::construct_fn(cx, id, arguments, abi, fn_sig.output(), body)
117         } else {
118             build::construct_const(cx, body_id)
119         };
120
121         // Convert the Mir to global types.
122         let mut globalizer = GlobalizeMir {
123             tcx: tcx,
124             span: mir.span
125         };
126         globalizer.visit_mir(&mut mir);
127         let mir = unsafe {
128             mem::transmute::<Mir, Mir<'tcx>>(mir)
129         };
130
131         mir_util::dump_mir(tcx, None, "mir_map", &0, src, &mir);
132
133         mir
134     })
135 }
136
137 /// A pass to lift all the types and substitutions in a Mir
138 /// to the global tcx. Sadly, we don't have a "folder" that
139 /// can change 'tcx so we have to transmute afterwards.
140 struct GlobalizeMir<'a, 'gcx: 'a> {
141     tcx: TyCtxt<'a, 'gcx, 'gcx>,
142     span: Span
143 }
144
145 impl<'a, 'gcx: 'tcx, 'tcx> MutVisitor<'tcx> for GlobalizeMir<'a, 'gcx> {
146     fn visit_ty(&mut self, ty: &mut Ty<'tcx>) {
147         if let Some(lifted) = self.tcx.lift(ty) {
148             *ty = lifted;
149         } else {
150             span_bug!(self.span,
151                       "found type `{:?}` with inference types/regions in MIR",
152                       ty);
153         }
154     }
155
156     fn visit_substs(&mut self, substs: &mut &'tcx Substs<'tcx>) {
157         if let Some(lifted) = self.tcx.lift(substs) {
158             *substs = lifted;
159         } else {
160             span_bug!(self.span,
161                       "found substs `{:?}` with inference types/regions in MIR",
162                       substs);
163         }
164     }
165 }
166
167 fn create_constructor_shim<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
168                                      ctor_id: ast::NodeId,
169                                      v: &'tcx hir::VariantData)
170                                      -> Mir<'tcx>
171 {
172     let span = tcx.hir.span(ctor_id);
173     if let hir::VariantData::Tuple(ref fields, ctor_id) = *v {
174         tcx.infer_ctxt(()).enter(|infcx| {
175             let (mut mir, src) =
176                 shim::build_adt_ctor(&infcx, ctor_id, fields, span);
177
178             // Convert the Mir to global types.
179             let tcx = infcx.tcx.global_tcx();
180             let mut globalizer = GlobalizeMir {
181                 tcx: tcx,
182                 span: mir.span
183             };
184             globalizer.visit_mir(&mut mir);
185             let mir = unsafe {
186                 mem::transmute::<Mir, Mir<'tcx>>(mir)
187             };
188
189             mir_util::dump_mir(tcx, None, "mir_map", &0, src, &mir);
190
191             mir
192         })
193     } else {
194         span_bug!(span, "attempting to create MIR for non-tuple variant {:?}", v);
195     }
196 }
197
198 ///////////////////////////////////////////////////////////////////////////
199 // BuildMir -- walks a crate, looking for fn items and methods to build MIR from
200
201 fn closure_self_ty<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
202                              closure_expr_id: ast::NodeId,
203                              body_id: hir::BodyId)
204                              -> Ty<'tcx> {
205     let closure_ty = tcx.body_tables(body_id).node_id_to_type(closure_expr_id);
206
207     let closure_def_id = tcx.hir.local_def_id(closure_expr_id);
208     let region = ty::ReFree(ty::FreeRegion {
209         scope: closure_def_id,
210         bound_region: ty::BoundRegion::BrEnv,
211     });
212     let region = tcx.mk_region(region);
213
214     match tcx.closure_kind(closure_def_id) {
215         ty::ClosureKind::Fn =>
216             tcx.mk_ref(region,
217                        ty::TypeAndMut { ty: closure_ty,
218                                         mutbl: hir::MutImmutable }),
219         ty::ClosureKind::FnMut =>
220             tcx.mk_ref(region,
221                        ty::TypeAndMut { ty: closure_ty,
222                                         mutbl: hir::MutMutable }),
223         ty::ClosureKind::FnOnce =>
224             closure_ty
225     }
226 }
227
228 struct Builder<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
229     hir: Cx<'a, 'gcx, 'tcx>,
230     cfg: CFG<'tcx>,
231
232     fn_span: Span,
233     arg_count: usize,
234
235     /// the current set of scopes, updated as we traverse;
236     /// see the `scope` module for more details
237     scopes: Vec<scope::Scope<'tcx>>,
238
239     /// the current set of breakables; see the `scope` module for more
240     /// details
241     breakable_scopes: Vec<scope::BreakableScope<'tcx>>,
242
243     /// the vector of all scopes that we have created thus far;
244     /// we track this for debuginfo later
245     visibility_scopes: IndexVec<VisibilityScope, VisibilityScopeData>,
246     visibility_scope: VisibilityScope,
247
248     /// Maps node ids of variable bindings to the `Local`s created for them.
249     var_indices: NodeMap<Local>,
250     local_decls: IndexVec<Local, LocalDecl<'tcx>>,
251     unit_temp: Option<Lvalue<'tcx>>,
252
253     /// cached block with the RESUME terminator; this is created
254     /// when first set of cleanups are built.
255     cached_resume_block: Option<BasicBlock>,
256     /// cached block with the RETURN terminator
257     cached_return_block: Option<BasicBlock>,
258 }
259
260 struct CFG<'tcx> {
261     basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
262 }
263
264 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
265 pub struct ScopeId(u32);
266
267 impl Idx for ScopeId {
268     fn new(index: usize) -> ScopeId {
269         assert!(index < (u32::MAX as usize));
270         ScopeId(index as u32)
271     }
272
273     fn index(self) -> usize {
274         self.0 as usize
275     }
276 }
277
278 ///////////////////////////////////////////////////////////////////////////
279 /// The `BlockAnd` "monad" packages up the new basic block along with a
280 /// produced value (sometimes just unit, of course). The `unpack!`
281 /// macro (and methods below) makes working with `BlockAnd` much more
282 /// convenient.
283
284 #[must_use] // if you don't use one of these results, you're leaving a dangling edge
285 struct BlockAnd<T>(BasicBlock, T);
286
287 trait BlockAndExtension {
288     fn and<T>(self, v: T) -> BlockAnd<T>;
289     fn unit(self) -> BlockAnd<()>;
290 }
291
292 impl BlockAndExtension for BasicBlock {
293     fn and<T>(self, v: T) -> BlockAnd<T> {
294         BlockAnd(self, v)
295     }
296
297     fn unit(self) -> BlockAnd<()> {
298         BlockAnd(self, ())
299     }
300 }
301
302 /// Update a block pointer and return the value.
303 /// Use it like `let x = unpack!(block = self.foo(block, foo))`.
304 macro_rules! unpack {
305     ($x:ident = $c:expr) => {
306         {
307             let BlockAnd(b, v) = $c;
308             $x = b;
309             v
310         }
311     };
312
313     ($c:expr) => {
314         {
315             let BlockAnd(b, ()) = $c;
316             b
317         }
318     };
319 }
320
321 ///////////////////////////////////////////////////////////////////////////
322 /// the main entry point for building MIR for a function
323
324 fn construct_fn<'a, 'gcx, 'tcx, A>(hir: Cx<'a, 'gcx, 'tcx>,
325                                    fn_id: ast::NodeId,
326                                    arguments: A,
327                                    abi: Abi,
328                                    return_ty: Ty<'gcx>,
329                                    body: &'gcx hir::Body)
330                                    -> Mir<'tcx>
331     where A: Iterator<Item=(Ty<'gcx>, Option<&'gcx hir::Pat>)>
332 {
333     let arguments: Vec<_> = arguments.collect();
334
335     let tcx = hir.tcx();
336     let span = tcx.hir.span(fn_id);
337     let mut builder = Builder::new(hir.clone(), span, arguments.len(), return_ty);
338
339     let call_site_extent = CodeExtent::CallSiteScope(body.id());
340     let arg_extent = CodeExtent::ParameterScope(body.id());
341     let mut block = START_BLOCK;
342     unpack!(block = builder.in_scope(call_site_extent, block, |builder| {
343         unpack!(block = builder.in_scope(arg_extent, block, |builder| {
344             builder.args_and_body(block, &arguments, arg_extent, &body.value)
345         }));
346         // Attribute epilogue to function's closing brace
347         let fn_end = Span { lo: span.hi, ..span };
348         let source_info = builder.source_info(fn_end);
349         let return_block = builder.return_block();
350         builder.cfg.terminate(block, source_info,
351                               TerminatorKind::Goto { target: return_block });
352         builder.cfg.terminate(return_block, source_info,
353                               TerminatorKind::Return);
354         return_block.unit()
355     }));
356     assert_eq!(block, builder.return_block());
357
358     let mut spread_arg = None;
359     if abi == Abi::RustCall {
360         // RustCall pseudo-ABI untuples the last argument.
361         spread_arg = Some(Local::new(arguments.len()));
362     }
363
364     // Gather the upvars of a closure, if any.
365     let upvar_decls: Vec<_> = tcx.with_freevars(fn_id, |freevars| {
366         freevars.iter().map(|fv| {
367             let var_id = tcx.hir.as_local_node_id(fv.def.def_id()).unwrap();
368             let capture = hir.tables().upvar_capture(ty::UpvarId {
369                 var_id: var_id,
370                 closure_expr_id: fn_id
371             });
372             let by_ref = match capture {
373                 ty::UpvarCapture::ByValue => false,
374                 ty::UpvarCapture::ByRef(..) => true
375             };
376             let mut decl = UpvarDecl {
377                 debug_name: keywords::Invalid.name(),
378                 by_ref: by_ref
379             };
380             if let Some(hir::map::NodeLocal(pat)) = tcx.hir.find(var_id) {
381                 if let hir::PatKind::Binding(_, _, ref ident, _) = pat.node {
382                     decl.debug_name = ident.node;
383                 }
384             }
385             decl
386         }).collect()
387     });
388
389     let mut mir = builder.finish(upvar_decls, return_ty);
390     mir.spread_arg = spread_arg;
391     mir
392 }
393
394 fn construct_const<'a, 'gcx, 'tcx>(hir: Cx<'a, 'gcx, 'tcx>,
395                                    body_id: hir::BodyId)
396                                    -> Mir<'tcx> {
397     let tcx = hir.tcx();
398     let ast_expr = &tcx.hir.body(body_id).value;
399     let ty = hir.tables().expr_ty_adjusted(ast_expr);
400     let owner_id = tcx.hir.body_owner(body_id);
401     let span = tcx.hir.span(owner_id);
402     let mut builder = Builder::new(hir.clone(), span, 0, ty);
403
404     let mut block = START_BLOCK;
405     let expr = builder.hir.mirror(ast_expr);
406     unpack!(block = builder.into_expr(&Lvalue::Local(RETURN_POINTER), block, expr));
407
408     let source_info = builder.source_info(span);
409     builder.cfg.terminate(block, source_info, TerminatorKind::Return);
410
411     // Constants can't `return` so a return block should not be created.
412     assert_eq!(builder.cached_return_block, None);
413
414     builder.finish(vec![], ty)
415 }
416
417 fn construct_error<'a, 'gcx, 'tcx>(hir: Cx<'a, 'gcx, 'tcx>,
418                                        body_id: hir::BodyId)
419                                        -> Mir<'tcx> {
420     let span = hir.tcx().hir.span(hir.tcx().hir.body_owner(body_id));
421     let ty = hir.tcx().types.err;
422     let mut builder = Builder::new(hir, span, 0, ty);
423     let source_info = builder.source_info(span);
424     builder.cfg.terminate(START_BLOCK, source_info, TerminatorKind::Unreachable);
425     builder.finish(vec![], ty)
426 }
427
428 impl<'a, 'gcx, 'tcx> Builder<'a, 'gcx, 'tcx> {
429     fn new(hir: Cx<'a, 'gcx, 'tcx>,
430            span: Span,
431            arg_count: usize,
432            return_ty: Ty<'tcx>)
433            -> Builder<'a, 'gcx, 'tcx> {
434         let mut builder = Builder {
435             hir: hir,
436             cfg: CFG { basic_blocks: IndexVec::new() },
437             fn_span: span,
438             arg_count: arg_count,
439             scopes: vec![],
440             visibility_scopes: IndexVec::new(),
441             visibility_scope: ARGUMENT_VISIBILITY_SCOPE,
442             breakable_scopes: vec![],
443             local_decls: IndexVec::from_elem_n(LocalDecl::new_return_pointer(return_ty,
444                                                                              span), 1),
445             var_indices: NodeMap(),
446             unit_temp: None,
447             cached_resume_block: None,
448             cached_return_block: None
449         };
450
451         assert_eq!(builder.cfg.start_new_block(), START_BLOCK);
452         assert_eq!(builder.new_visibility_scope(span), ARGUMENT_VISIBILITY_SCOPE);
453         builder.visibility_scopes[ARGUMENT_VISIBILITY_SCOPE].parent_scope = None;
454
455         builder
456     }
457
458     fn finish(self,
459               upvar_decls: Vec<UpvarDecl>,
460               return_ty: Ty<'tcx>)
461               -> Mir<'tcx> {
462         for (index, block) in self.cfg.basic_blocks.iter().enumerate() {
463             if block.terminator.is_none() {
464                 span_bug!(self.fn_span, "no terminator on block {:?}", index);
465             }
466         }
467
468         Mir::new(self.cfg.basic_blocks,
469                  self.visibility_scopes,
470                  IndexVec::new(),
471                  return_ty,
472                  self.local_decls,
473                  self.arg_count,
474                  upvar_decls,
475                  self.fn_span
476         )
477     }
478
479     fn args_and_body(&mut self,
480                      mut block: BasicBlock,
481                      arguments: &[(Ty<'gcx>, Option<&'gcx hir::Pat>)],
482                      argument_extent: CodeExtent,
483                      ast_body: &'gcx hir::Expr)
484                      -> BlockAnd<()>
485     {
486         // Allocate locals for the function arguments
487         for &(ty, pattern) in arguments.iter() {
488             // If this is a simple binding pattern, give the local a nice name for debuginfo.
489             let mut name = None;
490             if let Some(pat) = pattern {
491                 if let hir::PatKind::Binding(_, _, ref ident, _) = pat.node {
492                     name = Some(ident.node);
493                 }
494             }
495
496             self.local_decls.push(LocalDecl {
497                 mutability: Mutability::Not,
498                 ty: ty,
499                 source_info: SourceInfo {
500                     scope: ARGUMENT_VISIBILITY_SCOPE,
501                     span: pattern.map_or(self.fn_span, |pat| pat.span)
502                 },
503                 name: name,
504                 is_user_variable: false,
505             });
506         }
507
508         let mut scope = None;
509         // Bind the argument patterns
510         for (index, &(ty, pattern)) in arguments.iter().enumerate() {
511             // Function arguments always get the first Local indices after the return pointer
512             let lvalue = Lvalue::Local(Local::new(index + 1));
513
514             if let Some(pattern) = pattern {
515                 let pattern = Pattern::from_hir(self.hir.tcx(), self.hir.tables(), pattern);
516                 scope = self.declare_bindings(scope, ast_body.span, &pattern);
517                 unpack!(block = self.lvalue_into_pattern(block, pattern, &lvalue));
518             }
519
520             // Make sure we drop (parts of) the argument even when not matched on.
521             self.schedule_drop(pattern.as_ref().map_or(ast_body.span, |pat| pat.span),
522                                argument_extent, &lvalue, ty);
523
524         }
525
526         // Enter the argument pattern bindings visibility scope, if it exists.
527         if let Some(visibility_scope) = scope {
528             self.visibility_scope = visibility_scope;
529         }
530
531         let body = self.hir.mirror(ast_body);
532         self.into(&Lvalue::Local(RETURN_POINTER), block, body)
533     }
534
535     fn get_unit_temp(&mut self) -> Lvalue<'tcx> {
536         match self.unit_temp {
537             Some(ref tmp) => tmp.clone(),
538             None => {
539                 let ty = self.hir.unit_ty();
540                 let fn_span = self.fn_span;
541                 let tmp = self.temp(ty, fn_span);
542                 self.unit_temp = Some(tmp.clone());
543                 tmp
544             }
545         }
546     }
547
548     fn return_block(&mut self) -> BasicBlock {
549         match self.cached_return_block {
550             Some(rb) => rb,
551             None => {
552                 let rb = self.cfg.start_new_block();
553                 self.cached_return_block = Some(rb);
554                 rb
555             }
556         }
557     }
558 }
559
560 ///////////////////////////////////////////////////////////////////////////
561 // Builder methods are broken up into modules, depending on what kind
562 // of thing is being translated. Note that they use the `unpack` macro
563 // above extensively.
564
565 mod block;
566 mod cfg;
567 mod expr;
568 mod into;
569 mod matches;
570 mod misc;
571 mod scope;