]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/build/mod.rs
Auto merge of #41659 - bluss:clone-split-whitespace, r=aturon
[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, CodeExtentData};
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 = ty::ParameterEnvironment::for_item(tcx, 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 region = ty::ReFree(ty::FreeRegion {
210         scope: Some(tcx.item_extent(body_id.node_id)),
211         bound_region: ty::BoundRegion::BrEnv,
212     });
213     let region = tcx.mk_region(region);
214
215     match tcx.closure_kind(tcx.hir.local_def_id(closure_expr_id)) {
216         ty::ClosureKind::Fn =>
217             tcx.mk_ref(region,
218                        ty::TypeAndMut { ty: closure_ty,
219                                         mutbl: hir::MutImmutable }),
220         ty::ClosureKind::FnMut =>
221             tcx.mk_ref(region,
222                        ty::TypeAndMut { ty: closure_ty,
223                                         mutbl: hir::MutMutable }),
224         ty::ClosureKind::FnOnce =>
225             closure_ty
226     }
227 }
228
229 struct Builder<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
230     hir: Cx<'a, 'gcx, 'tcx>,
231     cfg: CFG<'tcx>,
232
233     fn_span: Span,
234     arg_count: usize,
235
236     /// the current set of scopes, updated as we traverse;
237     /// see the `scope` module for more details
238     scopes: Vec<scope::Scope<'tcx>>,
239
240     /// the current set of breakables; see the `scope` module for more
241     /// details
242     breakable_scopes: Vec<scope::BreakableScope<'tcx>>,
243
244     /// the vector of all scopes that we have created thus far;
245     /// we track this for debuginfo later
246     visibility_scopes: IndexVec<VisibilityScope, VisibilityScopeData>,
247     visibility_scope: VisibilityScope,
248
249     /// Maps node ids of variable bindings to the `Local`s created for them.
250     var_indices: NodeMap<Local>,
251     local_decls: IndexVec<Local, LocalDecl<'tcx>>,
252     unit_temp: Option<Lvalue<'tcx>>,
253
254     /// cached block with the RESUME terminator; this is created
255     /// when first set of cleanups are built.
256     cached_resume_block: Option<BasicBlock>,
257     /// cached block with the RETURN terminator
258     cached_return_block: Option<BasicBlock>,
259 }
260
261 struct CFG<'tcx> {
262     basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
263 }
264
265 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
266 pub struct ScopeId(u32);
267
268 impl Idx for ScopeId {
269     fn new(index: usize) -> ScopeId {
270         assert!(index < (u32::MAX as usize));
271         ScopeId(index as u32)
272     }
273
274     fn index(self) -> usize {
275         self.0 as usize
276     }
277 }
278
279 ///////////////////////////////////////////////////////////////////////////
280 /// The `BlockAnd` "monad" packages up the new basic block along with a
281 /// produced value (sometimes just unit, of course). The `unpack!`
282 /// macro (and methods below) makes working with `BlockAnd` much more
283 /// convenient.
284
285 #[must_use] // if you don't use one of these results, you're leaving a dangling edge
286 struct BlockAnd<T>(BasicBlock, T);
287
288 trait BlockAndExtension {
289     fn and<T>(self, v: T) -> BlockAnd<T>;
290     fn unit(self) -> BlockAnd<()>;
291 }
292
293 impl BlockAndExtension for BasicBlock {
294     fn and<T>(self, v: T) -> BlockAnd<T> {
295         BlockAnd(self, v)
296     }
297
298     fn unit(self) -> BlockAnd<()> {
299         BlockAnd(self, ())
300     }
301 }
302
303 /// Update a block pointer and return the value.
304 /// Use it like `let x = unpack!(block = self.foo(block, foo))`.
305 macro_rules! unpack {
306     ($x:ident = $c:expr) => {
307         {
308             let BlockAnd(b, v) = $c;
309             $x = b;
310             v
311         }
312     };
313
314     ($c:expr) => {
315         {
316             let BlockAnd(b, ()) = $c;
317             b
318         }
319     };
320 }
321
322 ///////////////////////////////////////////////////////////////////////////
323 /// the main entry point for building MIR for a function
324
325 fn construct_fn<'a, 'gcx, 'tcx, A>(hir: Cx<'a, 'gcx, 'tcx>,
326                                    fn_id: ast::NodeId,
327                                    arguments: A,
328                                    abi: Abi,
329                                    return_ty: Ty<'gcx>,
330                                    body: &'gcx hir::Body)
331                                    -> Mir<'tcx>
332     where A: Iterator<Item=(Ty<'gcx>, Option<&'gcx hir::Pat>)>
333 {
334     let arguments: Vec<_> = arguments.collect();
335
336     let tcx = hir.tcx();
337     let span = tcx.hir.span(fn_id);
338     let mut builder = Builder::new(hir.clone(), span, arguments.len(), return_ty);
339
340     let call_site_extent =
341         tcx.intern_code_extent(
342             CodeExtentData::CallSiteScope { fn_id: fn_id, body_id: body.value.id });
343     let arg_extent =
344         tcx.intern_code_extent(
345             CodeExtentData::ParameterScope { fn_id: fn_id, body_id: body.value.id });
346     let mut block = START_BLOCK;
347     unpack!(block = builder.in_scope(call_site_extent, block, |builder| {
348         unpack!(block = builder.in_scope(arg_extent, block, |builder| {
349             builder.args_and_body(block, &arguments, arg_extent, &body.value)
350         }));
351         // Attribute epilogue to function's closing brace
352         let fn_end = Span { lo: span.hi, ..span };
353         let source_info = builder.source_info(fn_end);
354         let return_block = builder.return_block();
355         builder.cfg.terminate(block, source_info,
356                               TerminatorKind::Goto { target: return_block });
357         builder.cfg.terminate(return_block, source_info,
358                               TerminatorKind::Return);
359         return_block.unit()
360     }));
361     assert_eq!(block, builder.return_block());
362
363     let mut spread_arg = None;
364     if abi == Abi::RustCall {
365         // RustCall pseudo-ABI untuples the last argument.
366         spread_arg = Some(Local::new(arguments.len()));
367     }
368
369     // Gather the upvars of a closure, if any.
370     let upvar_decls: Vec<_> = tcx.with_freevars(fn_id, |freevars| {
371         freevars.iter().map(|fv| {
372             let var_id = tcx.hir.as_local_node_id(fv.def.def_id()).unwrap();
373             let by_ref = hir.tables().upvar_capture(ty::UpvarId {
374                 var_id: var_id,
375                 closure_expr_id: fn_id
376             }).map_or(false, |capture| match capture {
377                 ty::UpvarCapture::ByValue => false,
378                 ty::UpvarCapture::ByRef(..) => true
379             });
380             let mut decl = UpvarDecl {
381                 debug_name: keywords::Invalid.name(),
382                 by_ref: by_ref
383             };
384             if let Some(hir::map::NodeLocal(pat)) = tcx.hir.find(var_id) {
385                 if let hir::PatKind::Binding(_, _, ref ident, _) = pat.node {
386                     decl.debug_name = ident.node;
387                 }
388             }
389             decl
390         }).collect()
391     });
392
393     let mut mir = builder.finish(upvar_decls, return_ty);
394     mir.spread_arg = spread_arg;
395     mir
396 }
397
398 pub fn construct_const<'a, 'gcx, 'tcx>(hir: Cx<'a, 'gcx, 'tcx>,
399                                        body_id: hir::BodyId)
400                                        -> Mir<'tcx> {
401     let tcx = hir.tcx();
402     let ast_expr = &tcx.hir.body(body_id).value;
403     let ty = hir.tables().expr_ty_adjusted(ast_expr);
404     let owner_id = tcx.hir.body_owner(body_id);
405     let span = tcx.hir.span(owner_id);
406     let mut builder = Builder::new(hir.clone(), span, 0, ty);
407
408     let extent = hir.region_maps.temporary_scope(tcx, ast_expr.id)
409                                 .unwrap_or(tcx.item_extent(owner_id));
410     let mut block = START_BLOCK;
411     let _ = builder.in_scope(extent, block, |builder| {
412         let expr = builder.hir.mirror(ast_expr);
413         unpack!(block = builder.into(&Lvalue::Local(RETURN_POINTER), block, expr));
414
415         let source_info = builder.source_info(span);
416         let return_block = builder.return_block();
417         builder.cfg.terminate(block, source_info,
418                               TerminatorKind::Goto { target: return_block });
419         builder.cfg.terminate(return_block, source_info,
420                               TerminatorKind::Return);
421
422         return_block.unit()
423     });
424
425     builder.finish(vec![], ty)
426 }
427
428 pub fn construct_error<'a, 'gcx, 'tcx>(hir: Cx<'a, 'gcx, 'tcx>,
429                                        body_id: hir::BodyId)
430                                        -> Mir<'tcx> {
431     let span = hir.tcx().hir.span(hir.tcx().hir.body_owner(body_id));
432     let ty = hir.tcx().types.err;
433     let mut builder = Builder::new(hir, span, 0, ty);
434     let source_info = builder.source_info(span);
435     builder.cfg.terminate(START_BLOCK, source_info, TerminatorKind::Unreachable);
436     builder.finish(vec![], ty)
437 }
438
439 impl<'a, 'gcx, 'tcx> Builder<'a, 'gcx, 'tcx> {
440     fn new(hir: Cx<'a, 'gcx, 'tcx>,
441            span: Span,
442            arg_count: usize,
443            return_ty: Ty<'tcx>)
444            -> Builder<'a, 'gcx, 'tcx> {
445         let mut builder = Builder {
446             hir: hir,
447             cfg: CFG { basic_blocks: IndexVec::new() },
448             fn_span: span,
449             arg_count: arg_count,
450             scopes: vec![],
451             visibility_scopes: IndexVec::new(),
452             visibility_scope: ARGUMENT_VISIBILITY_SCOPE,
453             breakable_scopes: vec![],
454             local_decls: IndexVec::from_elem_n(LocalDecl::new_return_pointer(return_ty,
455                                                                              span), 1),
456             var_indices: NodeMap(),
457             unit_temp: None,
458             cached_resume_block: None,
459             cached_return_block: None
460         };
461
462         assert_eq!(builder.cfg.start_new_block(), START_BLOCK);
463         assert_eq!(builder.new_visibility_scope(span), ARGUMENT_VISIBILITY_SCOPE);
464         builder.visibility_scopes[ARGUMENT_VISIBILITY_SCOPE].parent_scope = None;
465
466         builder
467     }
468
469     fn finish(self,
470               upvar_decls: Vec<UpvarDecl>,
471               return_ty: Ty<'tcx>)
472               -> Mir<'tcx> {
473         for (index, block) in self.cfg.basic_blocks.iter().enumerate() {
474             if block.terminator.is_none() {
475                 span_bug!(self.fn_span, "no terminator on block {:?}", index);
476             }
477         }
478
479         Mir::new(self.cfg.basic_blocks,
480                  self.visibility_scopes,
481                  IndexVec::new(),
482                  return_ty,
483                  self.local_decls,
484                  self.arg_count,
485                  upvar_decls,
486                  self.fn_span
487         )
488     }
489
490     fn args_and_body(&mut self,
491                      mut block: BasicBlock,
492                      arguments: &[(Ty<'gcx>, Option<&'gcx hir::Pat>)],
493                      argument_extent: CodeExtent<'tcx>,
494                      ast_body: &'gcx hir::Expr)
495                      -> BlockAnd<()>
496     {
497         // Allocate locals for the function arguments
498         for &(ty, pattern) in arguments.iter() {
499             // If this is a simple binding pattern, give the local a nice name for debuginfo.
500             let mut name = None;
501             if let Some(pat) = pattern {
502                 if let hir::PatKind::Binding(_, _, ref ident, _) = pat.node {
503                     name = Some(ident.node);
504                 }
505             }
506
507             self.local_decls.push(LocalDecl {
508                 mutability: Mutability::Not,
509                 ty: ty,
510                 source_info: SourceInfo {
511                     scope: ARGUMENT_VISIBILITY_SCOPE,
512                     span: pattern.map_or(self.fn_span, |pat| pat.span)
513                 },
514                 name: name,
515                 is_user_variable: false,
516             });
517         }
518
519         let mut scope = None;
520         // Bind the argument patterns
521         for (index, &(ty, pattern)) in arguments.iter().enumerate() {
522             // Function arguments always get the first Local indices after the return pointer
523             let lvalue = Lvalue::Local(Local::new(index + 1));
524
525             if let Some(pattern) = pattern {
526                 let pattern = Pattern::from_hir(self.hir.tcx(), self.hir.tables(), pattern);
527                 scope = self.declare_bindings(scope, ast_body.span, &pattern);
528                 unpack!(block = self.lvalue_into_pattern(block, pattern, &lvalue));
529             }
530
531             // Make sure we drop (parts of) the argument even when not matched on.
532             self.schedule_drop(pattern.as_ref().map_or(ast_body.span, |pat| pat.span),
533                                argument_extent, &lvalue, ty);
534
535         }
536
537         // Enter the argument pattern bindings visibility scope, if it exists.
538         if let Some(visibility_scope) = scope {
539             self.visibility_scope = visibility_scope;
540         }
541
542         let body = self.hir.mirror(ast_body);
543         self.into(&Lvalue::Local(RETURN_POINTER), block, body)
544     }
545
546     fn get_unit_temp(&mut self) -> Lvalue<'tcx> {
547         match self.unit_temp {
548             Some(ref tmp) => tmp.clone(),
549             None => {
550                 let ty = self.hir.unit_ty();
551                 let fn_span = self.fn_span;
552                 let tmp = self.temp(ty, fn_span);
553                 self.unit_temp = Some(tmp.clone());
554                 tmp
555             }
556         }
557     }
558
559     fn return_block(&mut self) -> BasicBlock {
560         match self.cached_return_block {
561             Some(rb) => rb,
562             None => {
563                 let rb = self.cfg.start_new_block();
564                 self.cached_return_block = Some(rb);
565                 rb
566             }
567         }
568     }
569 }
570
571 ///////////////////////////////////////////////////////////////////////////
572 // Builder methods are broken up into modules, depending on what kind
573 // of thing is being translated. Note that they use the `unpack` macro
574 // above extensively.
575
576 mod block;
577 mod cfg;
578 mod expr;
579 mod into;
580 mod matches;
581 mod misc;
582 mod scope;