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