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