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