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