]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/build/mod.rs
Improve some compiletest documentation
[rust.git] / src / librustc_mir / build / mod.rs
1 use crate::build;
2 use crate::build::scope::{CachedBlock, DropKind};
3 use crate::hair::cx::Cx;
4 use crate::hair::{LintLevel, BindingMode, PatternKind};
5 use crate::shim;
6 use crate::transform::MirSource;
7 use crate::util as mir_util;
8 use rustc::hir;
9 use rustc::hir::Node;
10 use rustc::hir::def_id::DefId;
11 use rustc::middle::region;
12 use rustc::mir::*;
13 use rustc::mir::visit::{MutVisitor, TyContext};
14 use rustc::ty::{self, Ty, TyCtxt};
15 use rustc::ty::subst::SubstsRef;
16 use rustc::util::nodemap::HirIdMap;
17 use rustc_target::spec::PanicStrategy;
18 use rustc_data_structures::indexed_vec::{IndexVec, Idx};
19 use std::mem;
20 use std::u32;
21 use rustc_target::spec::abi::Abi;
22 use syntax::attr::{self, UnwindAttr};
23 use syntax::symbol::keywords;
24 use syntax_pos::Span;
25
26 use super::lints;
27
28 /// Construct the MIR for a given `DefId`.
29 pub fn mir_build<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> Mir<'tcx> {
30     let id = tcx.hir().as_local_hir_id(def_id).unwrap();
31
32     // Figure out what primary body this item has.
33     let (body_id, return_ty_span) = match tcx.hir().get_by_hir_id(id) {
34         Node::Variant(variant) =>
35             return create_constructor_shim(tcx, id, &variant.node.data),
36         Node::StructCtor(ctor) =>
37             return create_constructor_shim(tcx, id, ctor),
38
39         Node::Expr(hir::Expr { node: hir::ExprKind::Closure(_, decl, body_id, _, _), .. })
40         | Node::Item(hir::Item { node: hir::ItemKind::Fn(decl, _, _, body_id), .. })
41         | Node::ImplItem(
42             hir::ImplItem {
43                 node: hir::ImplItemKind::Method(hir::MethodSig { decl, .. }, body_id),
44                 ..
45             }
46         )
47         | Node::TraitItem(
48             hir::TraitItem {
49                 node: hir::TraitItemKind::Method(
50                     hir::MethodSig { decl, .. },
51                     hir::TraitMethod::Provided(body_id),
52                 ),
53                 ..
54             }
55         ) => {
56             (*body_id, decl.output.span())
57         }
58         Node::Item(hir::Item { node: hir::ItemKind::Static(ty, _, body_id), .. })
59         | Node::Item(hir::Item { node: hir::ItemKind::Const(ty, body_id), .. })
60         | Node::ImplItem(hir::ImplItem { node: hir::ImplItemKind::Const(ty, body_id), .. })
61         | Node::TraitItem(
62             hir::TraitItem { node: hir::TraitItemKind::Const(ty, Some(body_id)), .. }
63         ) => {
64             (*body_id, ty.span)
65         }
66         Node::AnonConst(hir::AnonConst { body, hir_id, .. }) => {
67             (*body, tcx.hir().span_by_hir_id(*hir_id))
68         }
69
70         _ => span_bug!(tcx.hir().span_by_hir_id(id), "can't build MIR for {:?}", def_id),
71     };
72
73     tcx.infer_ctxt().enter(|infcx| {
74         let cx = Cx::new(&infcx, id);
75         let mut mir = if cx.tables().tainted_by_errors {
76             build::construct_error(cx, body_id)
77         } else if cx.body_owner_kind.is_fn_or_closure() {
78             // fetch the fully liberated fn signature (that is, all bound
79             // types/lifetimes replaced)
80             let fn_sig = cx.tables().liberated_fn_sigs()[id].clone();
81             let fn_def_id = tcx.hir().local_def_id_from_hir_id(id);
82
83             let ty = tcx.type_of(fn_def_id);
84             let mut abi = fn_sig.abi;
85             let implicit_argument = match ty.sty {
86                 ty::Closure(..) => {
87                     // HACK(eddyb) Avoid having RustCall on closures,
88                     // as it adds unnecessary (and wrong) auto-tupling.
89                     abi = Abi::Rust;
90                     Some(ArgInfo(liberated_closure_env_ty(tcx, id, body_id), None, None, None))
91                 }
92                 ty::Generator(..) => {
93                     let gen_ty = tcx.body_tables(body_id).node_type(id);
94                     Some(ArgInfo(gen_ty, None, None, None))
95                 }
96                 _ => None,
97             };
98
99             let safety = match fn_sig.unsafety {
100                 hir::Unsafety::Normal => Safety::Safe,
101                 hir::Unsafety::Unsafe => Safety::FnUnsafe,
102             };
103
104             let body = tcx.hir().body(body_id);
105             let explicit_arguments =
106                 body.arguments
107                     .iter()
108                     .enumerate()
109                     .map(|(index, arg)| {
110                         let owner_id = tcx.hir().body_owner(body_id);
111                         let opt_ty_info;
112                         let self_arg;
113                         if let Some(ref fn_decl) = tcx.hir().fn_decl(owner_id) {
114                             let ty_hir_id = fn_decl.inputs[index].hir_id;
115                             let ty_span = tcx.hir().span_by_hir_id(ty_hir_id);
116                             opt_ty_info = Some(ty_span);
117                             self_arg = if index == 0 && fn_decl.implicit_self.has_implicit_self() {
118                                 match fn_decl.implicit_self {
119                                     hir::ImplicitSelfKind::Imm => Some(ImplicitSelfKind::Imm),
120                                     hir::ImplicitSelfKind::Mut => Some(ImplicitSelfKind::Mut),
121                                     hir::ImplicitSelfKind::ImmRef => Some(ImplicitSelfKind::ImmRef),
122                                     hir::ImplicitSelfKind::MutRef => Some(ImplicitSelfKind::MutRef),
123                                     _ => None,
124                                 }
125                             } else {
126                                 None
127                             };
128                         } else {
129                             opt_ty_info = None;
130                             self_arg = None;
131                         }
132                         ArgInfo(fn_sig.inputs()[index], opt_ty_info, Some(&*arg.pat), self_arg)
133                     });
134
135             let arguments = implicit_argument.into_iter().chain(explicit_arguments);
136
137             let (yield_ty, return_ty) = if body.is_generator {
138                 let gen_sig = match ty.sty {
139                     ty::Generator(gen_def_id, gen_substs, ..) =>
140                         gen_substs.sig(gen_def_id, tcx),
141                     _ =>
142                         span_bug!(tcx.hir().span_by_hir_id(id),
143                                   "generator w/o generator type: {:?}", ty),
144                 };
145                 (Some(gen_sig.yield_ty), gen_sig.return_ty)
146             } else {
147                 (None, fn_sig.output())
148             };
149
150             build::construct_fn(cx, id, arguments, safety, abi,
151                                 return_ty, yield_ty, return_ty_span, body)
152         } else {
153             build::construct_const(cx, body_id, return_ty_span)
154         };
155
156         // Convert the Mir to global types.
157         let mut globalizer = GlobalizeMir {
158             tcx,
159             span: mir.span
160         };
161         globalizer.visit_mir(&mut mir);
162         let mir = unsafe {
163             mem::transmute::<Mir<'_>, Mir<'tcx>>(mir)
164         };
165
166         mir_util::dump_mir(tcx, None, "mir_map", &0,
167                            MirSource::item(def_id), &mir, |_, _| Ok(()) );
168
169         lints::check(tcx, &mir, def_id);
170
171         mir
172     })
173 }
174
175 /// A pass to lift all the types and substitutions in a MIR
176 /// to the global tcx. Sadly, we don't have a "folder" that
177 /// can change `'tcx` so we have to transmute afterwards.
178 struct GlobalizeMir<'a, 'gcx: 'a> {
179     tcx: TyCtxt<'a, 'gcx, 'gcx>,
180     span: Span
181 }
182
183 impl<'a, 'gcx: 'tcx, 'tcx> MutVisitor<'tcx> for GlobalizeMir<'a, 'gcx> {
184     fn visit_ty(&mut self, ty: &mut Ty<'tcx>, _: TyContext) {
185         if let Some(lifted) = self.tcx.lift(ty) {
186             *ty = lifted;
187         } else {
188             span_bug!(self.span,
189                       "found type `{:?}` with inference types/regions in MIR",
190                       ty);
191         }
192     }
193
194     fn visit_region(&mut self, region: &mut ty::Region<'tcx>, _: Location) {
195         if let Some(lifted) = self.tcx.lift(region) {
196             *region = lifted;
197         } else {
198             span_bug!(self.span,
199                       "found region `{:?}` with inference types/regions in MIR",
200                       region);
201         }
202     }
203
204     fn visit_const(&mut self, constant: &mut &'tcx ty::Const<'tcx>, _: Location) {
205         if let Some(lifted) = self.tcx.lift(constant) {
206             *constant = lifted;
207         } else {
208             span_bug!(self.span,
209                       "found constant `{:?}` with inference types/regions in MIR",
210                       constant);
211         }
212     }
213
214     fn visit_substs(&mut self, substs: &mut SubstsRef<'tcx>, _: Location) {
215         if let Some(lifted) = self.tcx.lift(substs) {
216             *substs = lifted;
217         } else {
218             span_bug!(self.span,
219                       "found substs `{:?}` with inference types/regions in MIR",
220                       substs);
221         }
222     }
223 }
224
225 fn create_constructor_shim<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
226                                      ctor_id: hir::HirId,
227                                      v: &'tcx hir::VariantData)
228                                      -> Mir<'tcx>
229 {
230     let span = tcx.hir().span_by_hir_id(ctor_id);
231     if let hir::VariantData::Tuple(ref fields, ctor_id) = *v {
232         tcx.infer_ctxt().enter(|infcx| {
233             let mut mir = shim::build_adt_ctor(&infcx, ctor_id, fields, span);
234
235             // Convert the Mir to global types.
236             let tcx = infcx.tcx.global_tcx();
237             let mut globalizer = GlobalizeMir {
238                 tcx,
239                 span: mir.span
240             };
241             globalizer.visit_mir(&mut mir);
242             let mir = unsafe {
243                 mem::transmute::<Mir<'_>, Mir<'tcx>>(mir)
244             };
245
246             mir_util::dump_mir(tcx, None, "mir_map", &0,
247                                MirSource::item(tcx.hir().local_def_id_from_hir_id(ctor_id)),
248                                &mir, |_, _| Ok(()) );
249
250             mir
251         })
252     } else {
253         span_bug!(span, "attempting to create MIR for non-tuple variant {:?}", v);
254     }
255 }
256
257 ///////////////////////////////////////////////////////////////////////////
258 // BuildMir -- walks a crate, looking for fn items and methods to build MIR from
259
260 fn liberated_closure_env_ty<'a, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'tcx>,
261                                             closure_expr_id: hir::HirId,
262                                             body_id: hir::BodyId)
263                                             -> Ty<'tcx> {
264     let closure_ty = tcx.body_tables(body_id).node_type(closure_expr_id);
265
266     let (closure_def_id, closure_substs) = match closure_ty.sty {
267         ty::Closure(closure_def_id, closure_substs) => (closure_def_id, closure_substs),
268         _ => bug!("closure expr does not have closure type: {:?}", closure_ty)
269     };
270
271     let closure_env_ty = tcx.closure_env_ty(closure_def_id, closure_substs).unwrap();
272     tcx.liberate_late_bound_regions(closure_def_id, &closure_env_ty)
273 }
274
275 #[derive(Debug, PartialEq, Eq)]
276 pub enum BlockFrame {
277     /// Evaluation is currently within a statement.
278     ///
279     /// Examples include:
280     ///  1. `EXPR;`
281     ///  2. `let _ = EXPR;`
282     ///  3. `let x = EXPR;`
283     Statement {
284         /// If true, then statement discards result from evaluating
285         /// the expression (such as examples 1 and 2 above).
286         ignores_expr_result: bool
287     },
288
289     /// Evaluation is currently within the tail expression of a block.
290     ///
291     /// Example: `{ STMT_1; STMT_2; EXPR }`
292     TailExpr {
293         /// If true, then the surrounding context of the block ignores
294         /// the result of evaluating the block's tail expression.
295         ///
296         /// Example: `let _ = { STMT_1; EXPR };`
297         tail_result_is_ignored: bool
298     },
299
300     /// Generic mark meaning that the block occurred as a subexpression
301     /// where the result might be used.
302     ///
303     /// Examples: `foo(EXPR)`, `match EXPR { ... }`
304     SubExpr,
305 }
306
307 impl BlockFrame {
308     fn is_tail_expr(&self) -> bool {
309         match *self {
310             BlockFrame::TailExpr { .. } => true,
311
312             BlockFrame::Statement { .. } |
313             BlockFrame::SubExpr => false,
314         }
315     }
316     fn is_statement(&self) -> bool {
317         match *self {
318             BlockFrame::Statement { .. } => true,
319
320             BlockFrame::TailExpr { .. } |
321             BlockFrame::SubExpr => false,
322         }
323     }
324  }
325
326 #[derive(Debug)]
327 struct BlockContext(Vec<BlockFrame>);
328
329 struct Builder<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
330     hir: Cx<'a, 'gcx, 'tcx>,
331     cfg: CFG<'tcx>,
332
333     fn_span: Span,
334     arg_count: usize,
335
336     /// The current set of scopes, updated as we traverse;
337     /// see the `scope` module for more details.
338     scopes: Vec<scope::Scope<'tcx>>,
339
340     /// The block-context: each time we build the code within an hair::Block,
341     /// we push a frame here tracking whether we are building a statement or
342     /// if we are pushing the tail expression of the block. This is used to
343     /// embed information in generated temps about whether they were created
344     /// for a block tail expression or not.
345     ///
346     /// It would be great if we could fold this into `self.scopes`
347     /// somehow, but right now I think that is very tightly tied to
348     /// the code generation in ways that we cannot (or should not)
349     /// start just throwing new entries onto that vector in order to
350     /// distinguish the context of EXPR1 from the context of EXPR2 in
351     /// `{ STMTS; EXPR1 } + EXPR2`.
352     block_context: BlockContext,
353
354     /// The current unsafe block in scope, even if it is hidden by
355     /// a `PushUnsafeBlock`.
356     unpushed_unsafe: Safety,
357
358     /// The number of `push_unsafe_block` levels in scope.
359     push_unsafe_count: usize,
360
361     /// The current set of breakables; see the `scope` module for more
362     /// details.
363     breakable_scopes: Vec<scope::BreakableScope<'tcx>>,
364
365     /// The vector of all scopes that we have created thus far;
366     /// we track this for debuginfo later.
367     source_scopes: IndexVec<SourceScope, SourceScopeData>,
368     source_scope_local_data: IndexVec<SourceScope, SourceScopeLocalData>,
369     source_scope: SourceScope,
370
371     /// The guard-context: each time we build the guard expression for
372     /// a match arm, we push onto this stack, and then pop when we
373     /// finish building it.
374     guard_context: Vec<GuardFrame>,
375
376     /// Maps `HirId`s of variable bindings to the `Local`s created for them.
377     /// (A match binding can have two locals; the 2nd is for the arm's guard.)
378     var_indices: HirIdMap<LocalsForNode>,
379     local_decls: IndexVec<Local, LocalDecl<'tcx>>,
380     canonical_user_type_annotations: ty::CanonicalUserTypeAnnotations<'tcx>,
381     upvar_decls: Vec<UpvarDecl>,
382     unit_temp: Option<Place<'tcx>>,
383
384     /// Cached block with the `RESUME` terminator; this is created
385     /// when first set of cleanups are built.
386     cached_resume_block: Option<BasicBlock>,
387     /// Cached block with the `RETURN` terminator.
388     cached_return_block: Option<BasicBlock>,
389     /// Cached block with the `UNREACHABLE` terminator.
390     cached_unreachable_block: Option<BasicBlock>,
391 }
392
393 impl<'a, 'gcx, 'tcx> Builder<'a, 'gcx, 'tcx> {
394     fn is_bound_var_in_guard(&self, id: hir::HirId) -> bool {
395         self.guard_context.iter().any(|frame| frame.locals.iter().any(|local| local.id == id))
396     }
397
398     fn var_local_id(&self, id: hir::HirId, for_guard: ForGuard) -> Local {
399         self.var_indices[&id].local_id(for_guard)
400     }
401 }
402
403 impl BlockContext {
404     fn new() -> Self { BlockContext(vec![]) }
405     fn push(&mut self, bf: BlockFrame) { self.0.push(bf); }
406     fn pop(&mut self) -> Option<BlockFrame> { self.0.pop() }
407
408     /// Traverses the frames on the `BlockContext`, searching for either
409     /// the first block-tail expression frame with no intervening
410     /// statement frame.
411     ///
412     /// Notably, this skips over `SubExpr` frames; this method is
413     /// meant to be used in the context of understanding the
414     /// relationship of a temp (created within some complicated
415     /// expression) with its containing expression, and whether the
416     /// value of that *containing expression* (not the temp!) is
417     /// ignored.
418     fn currently_in_block_tail(&self) -> Option<BlockTailInfo> {
419         for bf in self.0.iter().rev() {
420             match bf {
421                 BlockFrame::SubExpr => continue,
422                 BlockFrame::Statement { .. } => break,
423                 &BlockFrame::TailExpr { tail_result_is_ignored } =>
424                     return Some(BlockTailInfo { tail_result_is_ignored })
425             }
426         }
427
428         return None;
429     }
430
431     /// Looks at the topmost frame on the BlockContext and reports
432     /// whether its one that would discard a block tail result.
433     ///
434     /// Unlike `currently_within_ignored_tail_expression`, this does
435     /// *not* skip over `SubExpr` frames: here, we want to know
436     /// whether the block result itself is discarded.
437     fn currently_ignores_tail_results(&self) -> bool {
438         match self.0.last() {
439             // no context: conservatively assume result is read
440             None => false,
441
442             // sub-expression: block result feeds into some computation
443             Some(BlockFrame::SubExpr) => false,
444
445             // otherwise: use accumulated is_ignored state.
446             Some(BlockFrame::TailExpr { tail_result_is_ignored: ignored }) |
447             Some(BlockFrame::Statement { ignores_expr_result: ignored }) => *ignored,
448         }
449     }
450 }
451
452 #[derive(Debug)]
453 enum LocalsForNode {
454     /// In the usual case, a `HirId` for an identifier maps to at most
455     /// one `Local` declaration.
456     One(Local),
457
458     /// The exceptional case is identifiers in a match arm's pattern
459     /// that are referenced in a guard of that match arm. For these,
460     /// we have `2` Locals.
461     ///
462     /// * `for_arm_body` is the Local used in the arm body (which is
463     ///   just like the `One` case above),
464     ///
465     /// * `ref_for_guard` is the Local used in the arm's guard (which
466     ///   is a reference to a temp that is an alias of
467     ///   `for_arm_body`).
468     ForGuard { ref_for_guard: Local, for_arm_body: Local },
469 }
470
471 #[derive(Debug)]
472 struct GuardFrameLocal {
473     id: hir::HirId,
474 }
475
476 impl GuardFrameLocal {
477     fn new(id: hir::HirId, _binding_mode: BindingMode) -> Self {
478         GuardFrameLocal {
479             id: id,
480         }
481     }
482 }
483
484 #[derive(Debug)]
485 struct GuardFrame {
486     /// These are the id's of names that are bound by patterns of the
487     /// arm of *this* guard.
488     ///
489     /// (Frames higher up the stack will have the id's bound in arms
490     /// further out, such as in a case like:
491     ///
492     /// match E1 {
493     ///      P1(id1) if (... (match E2 { P2(id2) if ... => B2 })) => B1,
494     /// }
495     ///
496     /// here, when building for FIXME.
497     locals: Vec<GuardFrameLocal>,
498 }
499
500 /// `ForGuard` indicates whether we are talking about:
501 ///   1. The variable for use outside of guard expressions, or
502 ///   2. The temp that holds reference to (1.), which is actually what the
503 ///      guard expressions see.
504 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
505 enum ForGuard {
506     RefWithinGuard,
507     OutsideGuard,
508 }
509
510 impl LocalsForNode {
511     fn local_id(&self, for_guard: ForGuard) -> Local {
512         match (self, for_guard) {
513             (&LocalsForNode::One(local_id), ForGuard::OutsideGuard) |
514             (&LocalsForNode::ForGuard { ref_for_guard: local_id, .. }, ForGuard::RefWithinGuard) |
515             (&LocalsForNode::ForGuard { for_arm_body: local_id, .. }, ForGuard::OutsideGuard) =>
516                 local_id,
517
518             (&LocalsForNode::One(_), ForGuard::RefWithinGuard) =>
519                 bug!("anything with one local should never be within a guard."),
520         }
521     }
522 }
523
524 struct CFG<'tcx> {
525     basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
526 }
527
528 newtype_index! {
529     pub struct ScopeId { .. }
530 }
531
532 ///////////////////////////////////////////////////////////////////////////
533 /// The `BlockAnd` "monad" packages up the new basic block along with a
534 /// produced value (sometimes just unit, of course). The `unpack!`
535 /// macro (and methods below) makes working with `BlockAnd` much more
536 /// convenient.
537
538 #[must_use = "if you don't use one of these results, you're leaving a dangling edge"]
539 struct BlockAnd<T>(BasicBlock, T);
540
541 trait BlockAndExtension {
542     fn and<T>(self, v: T) -> BlockAnd<T>;
543     fn unit(self) -> BlockAnd<()>;
544 }
545
546 impl BlockAndExtension for BasicBlock {
547     fn and<T>(self, v: T) -> BlockAnd<T> {
548         BlockAnd(self, v)
549     }
550
551     fn unit(self) -> BlockAnd<()> {
552         BlockAnd(self, ())
553     }
554 }
555
556 /// Update a block pointer and return the value.
557 /// Use it like `let x = unpack!(block = self.foo(block, foo))`.
558 macro_rules! unpack {
559     ($x:ident = $c:expr) => {
560         {
561             let BlockAnd(b, v) = $c;
562             $x = b;
563             v
564         }
565     };
566
567     ($c:expr) => {
568         {
569             let BlockAnd(b, ()) = $c;
570             b
571         }
572     };
573 }
574
575 fn should_abort_on_panic<'a, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'tcx>,
576                                          fn_def_id: DefId,
577                                          abi: Abi)
578                                          -> bool {
579     // Not callable from C, so we can safely unwind through these
580     if abi == Abi::Rust || abi == Abi::RustCall { return false; }
581
582     // Validate `#[unwind]` syntax regardless of platform-specific panic strategy
583     let attrs = &tcx.get_attrs(fn_def_id);
584     let unwind_attr = attr::find_unwind_attr(Some(tcx.sess.diagnostic()), attrs);
585
586     // We never unwind, so it's not relevant to stop an unwind
587     if tcx.sess.panic_strategy() != PanicStrategy::Unwind { return false; }
588
589     // We cannot add landing pads, so don't add one
590     if tcx.sess.no_landing_pads() { return false; }
591
592     // This is a special case: some functions have a C abi but are meant to
593     // unwind anyway. Don't stop them.
594     match unwind_attr {
595         None => true,
596         Some(UnwindAttr::Allowed) => false,
597         Some(UnwindAttr::Aborts) => true,
598     }
599 }
600
601 ///////////////////////////////////////////////////////////////////////////
602 /// the main entry point for building MIR for a function
603
604 struct ArgInfo<'gcx>(Ty<'gcx>,
605                      Option<Span>,
606                      Option<&'gcx hir::Pat>,
607                      Option<ImplicitSelfKind>);
608
609 fn construct_fn<'a, 'gcx, 'tcx, A>(hir: Cx<'a, 'gcx, 'tcx>,
610                                    fn_id: hir::HirId,
611                                    arguments: A,
612                                    safety: Safety,
613                                    abi: Abi,
614                                    return_ty: Ty<'gcx>,
615                                    yield_ty: Option<Ty<'gcx>>,
616                                    return_ty_span: Span,
617                                    body: &'gcx hir::Body)
618                                    -> Mir<'tcx>
619     where A: Iterator<Item=ArgInfo<'gcx>>
620 {
621     let arguments: Vec<_> = arguments.collect();
622
623     let tcx = hir.tcx();
624     let tcx_hir = tcx.hir();
625     let span = tcx_hir.span_by_hir_id(fn_id);
626
627     let hir_tables = hir.tables();
628     let fn_def_id = tcx_hir.local_def_id_from_hir_id(fn_id);
629
630     // Gather the upvars of a closure, if any.
631     // In analyze_closure() in upvar.rs we gathered a list of upvars used by a
632     // closure and we stored in a map called upvar_list in TypeckTables indexed
633     // with the closure's DefId. Here, we run through that vec of UpvarIds for
634     // the given closure and use the necessary information to create UpvarDecl.
635     let upvar_decls: Vec<_> = hir_tables
636         .upvar_list
637         .get(&fn_def_id)
638         .into_iter()
639         .flatten()
640         .map(|upvar_id| {
641             let var_hir_id = upvar_id.var_path.hir_id;
642             let var_node_id = tcx_hir.hir_to_node_id(var_hir_id);
643             let capture = hir_tables.upvar_capture(*upvar_id);
644             let by_ref = match capture {
645                 ty::UpvarCapture::ByValue => false,
646                 ty::UpvarCapture::ByRef(..) => true,
647             };
648             let mut decl = UpvarDecl {
649                 debug_name: keywords::Invalid.name(),
650                 var_hir_id: ClearCrossCrate::Set(var_hir_id),
651                 by_ref,
652                 mutability: Mutability::Not,
653             };
654             if let Some(Node::Binding(pat)) = tcx_hir.find(var_node_id) {
655                 if let hir::PatKind::Binding(_, _, ident, _) = pat.node {
656                     decl.debug_name = ident.name;
657                     if let Some(&bm) = hir.tables.pat_binding_modes().get(pat.hir_id) {
658                         if bm == ty::BindByValue(hir::MutMutable) {
659                             decl.mutability = Mutability::Mut;
660                         } else {
661                             decl.mutability = Mutability::Not;
662                         }
663                     } else {
664                         tcx.sess.delay_span_bug(pat.span, "missing binding mode");
665                     }
666                 }
667             }
668             decl
669         })
670         .collect();
671
672     let mut builder = Builder::new(hir,
673         span,
674         arguments.len(),
675         safety,
676         return_ty,
677         return_ty_span,
678         upvar_decls);
679
680     let call_site_scope = region::Scope {
681         id: body.value.hir_id.local_id,
682         data: region::ScopeData::CallSite
683     };
684     let arg_scope = region::Scope {
685         id: body.value.hir_id.local_id,
686         data: region::ScopeData::Arguments
687     };
688     let mut block = START_BLOCK;
689     let source_info = builder.source_info(span);
690     let call_site_s = (call_site_scope, source_info);
691     unpack!(block = builder.in_scope(call_site_s, LintLevel::Inherited, block, |builder| {
692         if should_abort_on_panic(tcx, fn_def_id, abi) {
693             builder.schedule_abort();
694         }
695
696         let arg_scope_s = (arg_scope, source_info);
697         unpack!(block = builder.in_scope(arg_scope_s, LintLevel::Inherited, block, |builder| {
698             builder.args_and_body(block, &arguments, arg_scope, &body.value)
699         }));
700         // Attribute epilogue to function's closing brace
701         let fn_end = span.shrink_to_hi();
702         let source_info = builder.source_info(fn_end);
703         let return_block = builder.return_block();
704         builder.cfg.terminate(block, source_info,
705                               TerminatorKind::Goto { target: return_block });
706         builder.cfg.terminate(return_block, source_info,
707                               TerminatorKind::Return);
708         // Attribute any unreachable codepaths to the function's closing brace
709         if let Some(unreachable_block) = builder.cached_unreachable_block {
710             builder.cfg.terminate(unreachable_block, source_info,
711                                   TerminatorKind::Unreachable);
712         }
713         return_block.unit()
714     }));
715     assert_eq!(block, builder.return_block());
716
717     let mut spread_arg = None;
718     if abi == Abi::RustCall {
719         // RustCall pseudo-ABI untuples the last argument.
720         spread_arg = Some(Local::new(arguments.len()));
721     }
722     info!("fn_id {:?} has attrs {:?}", fn_def_id,
723           tcx.get_attrs(fn_def_id));
724
725     let mut mir = builder.finish(yield_ty);
726     mir.spread_arg = spread_arg;
727     mir
728 }
729
730 fn construct_const<'a, 'gcx, 'tcx>(
731     hir: Cx<'a, 'gcx, 'tcx>,
732     body_id: hir::BodyId,
733     ty_span: Span,
734 ) -> Mir<'tcx> {
735     let tcx = hir.tcx();
736     let ast_expr = &tcx.hir().body(body_id).value;
737     let ty = hir.tables().expr_ty_adjusted(ast_expr);
738     let owner_id = tcx.hir().body_owner(body_id);
739     let span = tcx.hir().span(owner_id);
740     let mut builder = Builder::new(hir, span, 0, Safety::Safe, ty, ty_span,vec![]);
741
742     let mut block = START_BLOCK;
743     let expr = builder.hir.mirror(ast_expr);
744     unpack!(block = builder.into_expr(&Place::RETURN_PLACE, block, expr));
745
746     let source_info = builder.source_info(span);
747     builder.cfg.terminate(block, source_info, TerminatorKind::Return);
748
749     // Constants can't `return` so a return block should not be created.
750     assert_eq!(builder.cached_return_block, None);
751
752     // Constants may be match expressions in which case an unreachable block may
753     // be created, so terminate it properly.
754     if let Some(unreachable_block) = builder.cached_unreachable_block {
755         builder.cfg.terminate(unreachable_block, source_info,
756                               TerminatorKind::Unreachable);
757     }
758
759     builder.finish(None)
760 }
761
762 fn construct_error<'a, 'gcx, 'tcx>(hir: Cx<'a, 'gcx, 'tcx>,
763                                    body_id: hir::BodyId)
764                                    -> Mir<'tcx> {
765     let owner_id = hir.tcx().hir().body_owner(body_id);
766     let span = hir.tcx().hir().span(owner_id);
767     let ty = hir.tcx().types.err;
768     let mut builder = Builder::new(hir, span, 0, Safety::Safe, ty, span, vec![]);
769     let source_info = builder.source_info(span);
770     builder.cfg.terminate(START_BLOCK, source_info, TerminatorKind::Unreachable);
771     builder.finish(None)
772 }
773
774 impl<'a, 'gcx, 'tcx> Builder<'a, 'gcx, 'tcx> {
775     fn new(hir: Cx<'a, 'gcx, 'tcx>,
776            span: Span,
777            arg_count: usize,
778            safety: Safety,
779            return_ty: Ty<'tcx>,
780            return_span: Span,
781            upvar_decls: Vec<UpvarDecl>)
782            -> Builder<'a, 'gcx, 'tcx> {
783         let lint_level = LintLevel::Explicit(hir.root_lint_level);
784         let mut builder = Builder {
785             hir,
786             cfg: CFG { basic_blocks: IndexVec::new() },
787             fn_span: span,
788             arg_count,
789             scopes: vec![],
790             block_context: BlockContext::new(),
791             source_scopes: IndexVec::new(),
792             source_scope: OUTERMOST_SOURCE_SCOPE,
793             source_scope_local_data: IndexVec::new(),
794             guard_context: vec![],
795             push_unsafe_count: 0,
796             unpushed_unsafe: safety,
797             breakable_scopes: vec![],
798             local_decls: IndexVec::from_elem_n(
799                 LocalDecl::new_return_place(return_ty, return_span),
800                 1,
801             ),
802             canonical_user_type_annotations: IndexVec::new(),
803             upvar_decls,
804             var_indices: Default::default(),
805             unit_temp: None,
806             cached_resume_block: None,
807             cached_return_block: None,
808             cached_unreachable_block: None,
809         };
810
811         assert_eq!(builder.cfg.start_new_block(), START_BLOCK);
812         assert_eq!(
813             builder.new_source_scope(span, lint_level, Some(safety)),
814             OUTERMOST_SOURCE_SCOPE);
815         builder.source_scopes[OUTERMOST_SOURCE_SCOPE].parent_scope = None;
816
817         builder
818     }
819
820     fn finish(self,
821               yield_ty: Option<Ty<'tcx>>)
822               -> Mir<'tcx> {
823         for (index, block) in self.cfg.basic_blocks.iter().enumerate() {
824             if block.terminator.is_none() {
825                 span_bug!(self.fn_span, "no terminator on block {:?}", index);
826             }
827         }
828
829         Mir::new(
830             self.cfg.basic_blocks,
831             self.source_scopes,
832             ClearCrossCrate::Set(self.source_scope_local_data),
833             IndexVec::new(),
834             yield_ty,
835             self.local_decls,
836             self.canonical_user_type_annotations,
837             self.arg_count,
838             self.upvar_decls,
839             self.fn_span,
840             self.hir.control_flow_destroyed(),
841         )
842     }
843
844     fn args_and_body(&mut self,
845                      mut block: BasicBlock,
846                      arguments: &[ArgInfo<'gcx>],
847                      argument_scope: region::Scope,
848                      ast_body: &'gcx hir::Expr)
849                      -> BlockAnd<()>
850     {
851         // Allocate locals for the function arguments
852         for &ArgInfo(ty, _, pattern, _) in arguments.iter() {
853             // If this is a simple binding pattern, give the local a name for
854             // debuginfo and so that error reporting knows that this is a user
855             // variable. For any other pattern the pattern introduces new
856             // variables which will be named instead.
857             let mut name = None;
858             if let Some(pat) = pattern {
859                 match pat.node {
860                     hir::PatKind::Binding(hir::BindingAnnotation::Unannotated, _, ident, _)
861                     | hir::PatKind::Binding(hir::BindingAnnotation::Mutable, _, ident, _) => {
862                         name = Some(ident.name);
863                     }
864                     _ => (),
865                 }
866             }
867
868             let source_info = SourceInfo {
869                 scope: OUTERMOST_SOURCE_SCOPE,
870                 span: pattern.map_or(self.fn_span, |pat| pat.span)
871             };
872             self.local_decls.push(LocalDecl {
873                 mutability: Mutability::Mut,
874                 ty,
875                 user_ty: UserTypeProjections::none(),
876                 source_info,
877                 visibility_scope: source_info.scope,
878                 name,
879                 internal: false,
880                 is_user_variable: None,
881                 is_block_tail: None,
882             });
883         }
884
885         let mut scope = None;
886         // Bind the argument patterns
887         for (index, arg_info) in arguments.iter().enumerate() {
888             // Function arguments always get the first Local indices after the return place
889             let local = Local::new(index + 1);
890             let place = Place::Base(PlaceBase::Local(local));
891             let &ArgInfo(ty, opt_ty_info, pattern, ref self_binding) = arg_info;
892
893             // Make sure we drop (parts of) the argument even when not matched on.
894             self.schedule_drop(
895                 pattern.as_ref().map_or(ast_body.span, |pat| pat.span),
896                 argument_scope, &place, ty,
897                 DropKind::Value { cached_block: CachedBlock::default() },
898             );
899
900             if let Some(pattern) = pattern {
901                 let pattern = self.hir.pattern_from_hir(pattern);
902                 let span = pattern.span;
903
904                 match *pattern.kind {
905                     // Don't introduce extra copies for simple bindings
906                     PatternKind::Binding { mutability, var, mode: BindingMode::ByValue, .. } => {
907                         self.local_decls[local].mutability = mutability;
908                         self.local_decls[local].is_user_variable =
909                             if let Some(kind) = self_binding {
910                                 Some(ClearCrossCrate::Set(BindingForm::ImplicitSelf(*kind)))
911                             } else {
912                                 let binding_mode = ty::BindingMode::BindByValue(mutability.into());
913                                 Some(ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
914                                     binding_mode,
915                                     opt_ty_info,
916                                     opt_match_place: Some((Some(place.clone()), span)),
917                                     pat_span: span,
918                                 })))
919                             };
920                         self.var_indices.insert(var, LocalsForNode::One(local));
921                     }
922                     _ => {
923                         scope = self.declare_bindings(scope, ast_body.span,
924                                                       LintLevel::Inherited, &pattern,
925                                                       matches::ArmHasGuard(false),
926                                                       Some((Some(&place), span)));
927                         unpack!(block = self.place_into_pattern(block, pattern, &place, false));
928                     }
929                 }
930             }
931         }
932
933         // Enter the argument pattern bindings source scope, if it exists.
934         if let Some(source_scope) = scope {
935             self.source_scope = source_scope;
936         }
937
938         let body = self.hir.mirror(ast_body);
939         self.into(&Place::RETURN_PLACE, block, body)
940     }
941
942     fn get_unit_temp(&mut self) -> Place<'tcx> {
943         match self.unit_temp {
944             Some(ref tmp) => tmp.clone(),
945             None => {
946                 let ty = self.hir.unit_ty();
947                 let fn_span = self.fn_span;
948                 let tmp = self.temp(ty, fn_span);
949                 self.unit_temp = Some(tmp.clone());
950                 tmp
951             }
952         }
953     }
954
955     fn return_block(&mut self) -> BasicBlock {
956         match self.cached_return_block {
957             Some(rb) => rb,
958             None => {
959                 let rb = self.cfg.start_new_block();
960                 self.cached_return_block = Some(rb);
961                 rb
962             }
963         }
964     }
965
966     fn unreachable_block(&mut self) -> BasicBlock {
967         match self.cached_unreachable_block {
968             Some(ub) => ub,
969             None => {
970                 let ub = self.cfg.start_new_block();
971                 self.cached_unreachable_block = Some(ub);
972                 ub
973             }
974         }
975     }
976 }
977
978 ///////////////////////////////////////////////////////////////////////////
979 // Builder methods are broken up into modules, depending on what kind
980 // of thing is being lowered. Note that they use the `unpack` macro
981 // above extensively.
982
983 mod block;
984 mod cfg;
985 mod expr;
986 mod into;
987 mod matches;
988 mod misc;
989 mod scope;