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