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