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