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