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