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