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