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