2 use crate::build::scope::DropKind;
3 use crate::hair::cx::Cx;
4 use crate::hair::{BindingMode, LintLevel, PatKind};
5 use rustc_attr::{self as attr, UnwindAttr};
6 use rustc_errors::ErrorReported;
8 use rustc_hir::def_id::{DefId, LocalDefId};
9 use rustc_hir::lang_items;
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;
19 use rustc_target::spec::abi::Abi;
20 use rustc_target::spec::PanicStrategy;
24 crate fn mir_built<'tcx>(
26 def: ty::WithOptConstParam<LocalDefId>,
27 ) -> &'tcx ty::steal::Steal<Body<'tcx>> {
28 if def.const_param_did.is_none() {
29 if let const_param_did @ Some(_) = tcx.opt_const_param_of(def.did) {
30 return tcx.mir_built(ty::WithOptConstParam { const_param_did, ..def });
34 tcx.alloc_steal_mir(mir_build(tcx, def))
37 /// Construct the MIR for a given `DefId`.
38 fn mir_build(tcx: TyCtxt<'_>, def: ty::WithOptConstParam<LocalDefId>) -> Body<'_> {
39 let id = tcx.hir().as_local_hir_id(def.did);
41 // Figure out what primary body this item has.
42 let (body_id, return_ty_span) = match tcx.hir().get(id) {
43 Node::Expr(hir::Expr { kind: hir::ExprKind::Closure(_, decl, body_id, _, _), .. }) => {
44 (*body_id, decl.output.span())
46 Node::Item(hir::Item {
47 kind: hir::ItemKind::Fn(hir::FnSig { decl, .. }, _, body_id),
50 | Node::ImplItem(hir::ImplItem {
51 kind: hir::ImplItemKind::Fn(hir::FnSig { decl, .. }, body_id),
54 | Node::TraitItem(hir::TraitItem {
55 kind: hir::TraitItemKind::Fn(hir::FnSig { decl, .. }, hir::TraitFn::Provided(body_id)),
57 }) => (*body_id, decl.output.span()),
58 Node::Item(hir::Item {
59 kind: hir::ItemKind::Static(ty, _, body_id) | hir::ItemKind::Const(ty, body_id),
62 | Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Const(ty, body_id), .. })
63 | Node::TraitItem(hir::TraitItem {
64 kind: hir::TraitItemKind::Const(ty, Some(body_id)),
66 }) => (*body_id, ty.span),
67 Node::AnonConst(hir::AnonConst { body, hir_id, .. }) => (*body, tcx.hir().span(*hir_id)),
69 _ => span_bug!(tcx.hir().span(id), "can't build MIR for {:?}", def.did),
72 tcx.infer_ctxt().enter(|infcx| {
73 let cx = Cx::new(&infcx, def, id);
74 let body = if let Some(ErrorReported) = cx.typeck_results().tainted_by_errors {
75 build::construct_error(cx, body_id)
76 } else if cx.body_owner_kind.is_fn_or_closure() {
77 // fetch the fully liberated fn signature (that is, all bound
78 // types/lifetimes replaced)
79 let fn_sig = cx.typeck_results().liberated_fn_sigs()[id];
80 let fn_def_id = tcx.hir().local_def_id(id);
82 let safety = match fn_sig.unsafety {
83 hir::Unsafety::Normal => Safety::Safe,
84 hir::Unsafety::Unsafe => Safety::FnUnsafe,
87 let body = tcx.hir().body(body_id);
88 let ty = tcx.type_of(fn_def_id);
89 let mut abi = fn_sig.abi;
90 let implicit_argument = match ty.kind {
92 // HACK(eddyb) Avoid having RustCall on closures,
93 // as it adds unnecessary (and wrong) auto-tupling.
95 vec![ArgInfo(liberated_closure_env_ty(tcx, id, body_id), None, None, None)]
97 ty::Generator(..) => {
98 let gen_ty = tcx.typeck_body(body_id).node_type(id);
100 // The resume argument may be missing, in that case we need to provide it here.
101 // It will always be `()` in this case.
102 if body.params.is_empty() {
104 ArgInfo(gen_ty, None, None, None),
105 ArgInfo(tcx.mk_unit(), None, None, None),
108 vec![ArgInfo(gen_ty, None, None, None)]
114 let explicit_arguments = body.params.iter().enumerate().map(|(index, arg)| {
115 let owner_id = tcx.hir().body_owner(body_id);
118 if let Some(ref fn_decl) = tcx.hir().fn_decl_by_hir_id(owner_id) {
119 opt_ty_info = fn_decl.inputs.get(index).map(|ty| ty.span);
120 self_arg = if index == 0 && fn_decl.implicit_self.has_implicit_self() {
121 match fn_decl.implicit_self {
122 hir::ImplicitSelfKind::Imm => Some(ImplicitSelfKind::Imm),
123 hir::ImplicitSelfKind::Mut => Some(ImplicitSelfKind::Mut),
124 hir::ImplicitSelfKind::ImmRef => Some(ImplicitSelfKind::ImmRef),
125 hir::ImplicitSelfKind::MutRef => Some(ImplicitSelfKind::MutRef),
136 // C-variadic fns also have a `VaList` input that's not listed in `fn_sig`
137 // (as it's created inside the body itself, not passed in from outside).
138 let ty = if fn_sig.c_variadic && index == fn_sig.inputs().len() {
140 tcx.require_lang_item(lang_items::VaListTypeLangItem, Some(arg.span));
142 tcx.type_of(va_list_did).subst(tcx, &[tcx.lifetimes.re_erased.into()])
144 fn_sig.inputs()[index]
147 ArgInfo(ty, opt_ty_info, Some(&arg), self_arg)
150 let arguments = implicit_argument.into_iter().chain(explicit_arguments);
152 let (yield_ty, return_ty) = if body.generator_kind.is_some() {
153 let gen_ty = tcx.typeck_body(body_id).node_type(id);
154 let gen_sig = match gen_ty.kind {
155 ty::Generator(_, gen_substs, ..) => gen_substs.as_generator().sig(),
156 _ => span_bug!(tcx.hir().span(id), "generator w/o generator type: {:?}", ty),
158 (Some(gen_sig.yield_ty), gen_sig.return_ty)
160 (None, fn_sig.output())
163 let mut mir = build::construct_fn(
173 mir.yield_ty = yield_ty;
176 // Get the revealed type of this const. This is *not* the adjusted
177 // type of its body, which may be a subtype of this type. For
181 // static X: fn(&'static ()) = foo;
183 // The adjusted type of the body of X is `for<'a> fn(&'a ())` which
184 // is not the same as the type of X. We need the type of the return
185 // place to be the type of the constant because NLL typeck will
188 let return_ty = cx.typeck_results().node_type(id);
190 build::construct_const(cx, body_id, return_ty, return_ty_span)
193 lints::check(tcx, &body, def.did);
195 // The borrow checker will replace all the regions here with its own
196 // inference variables. There's no point having non-erased regions here.
197 // The exception is `body.user_type_annotations`, which is used unmodified
198 // by borrow checking.
200 !(body.local_decls.has_free_regions()
201 || body.basic_blocks().has_free_regions()
202 || body.var_debug_info.has_free_regions()
203 || body.yield_ty.has_free_regions()),
204 "Unexpected free regions in MIR: {:?}",
212 ///////////////////////////////////////////////////////////////////////////
213 // BuildMir -- walks a crate, looking for fn items and methods to build MIR from
215 fn liberated_closure_env_ty(
217 closure_expr_id: hir::HirId,
218 body_id: hir::BodyId,
220 let closure_ty = tcx.typeck_body(body_id).node_type(closure_expr_id);
222 let (closure_def_id, closure_substs) = match closure_ty.kind {
223 ty::Closure(closure_def_id, closure_substs) => (closure_def_id, closure_substs),
224 _ => bug!("closure expr does not have closure type: {:?}", closure_ty),
227 let closure_env_ty = tcx.closure_env_ty(closure_def_id, closure_substs).unwrap();
228 tcx.erase_late_bound_regions(&closure_env_ty)
231 #[derive(Debug, PartialEq, Eq)]
233 /// Evaluation is currently within a statement.
235 /// Examples include:
237 /// 2. `let _ = EXPR;`
238 /// 3. `let x = EXPR;`
240 /// If true, then statement discards result from evaluating
241 /// the expression (such as examples 1 and 2 above).
242 ignores_expr_result: bool,
245 /// Evaluation is currently within the tail expression of a block.
247 /// Example: `{ STMT_1; STMT_2; EXPR }`
249 /// If true, then the surrounding context of the block ignores
250 /// the result of evaluating the block's tail expression.
252 /// Example: `let _ = { STMT_1; EXPR };`
253 tail_result_is_ignored: bool,
255 /// `Span` of the tail expression.
259 /// Generic mark meaning that the block occurred as a subexpression
260 /// where the result might be used.
262 /// Examples: `foo(EXPR)`, `match EXPR { ... }`
267 fn is_tail_expr(&self) -> bool {
269 BlockFrame::TailExpr { .. } => true,
271 BlockFrame::Statement { .. } | BlockFrame::SubExpr => false,
274 fn is_statement(&self) -> bool {
276 BlockFrame::Statement { .. } => true,
278 BlockFrame::TailExpr { .. } | BlockFrame::SubExpr => false,
284 struct BlockContext(Vec<BlockFrame>);
286 struct Builder<'a, 'tcx> {
292 generator_kind: Option<GeneratorKind>,
294 /// The current set of scopes, updated as we traverse;
295 /// see the `scope` module for more details.
296 scopes: scope::Scopes<'tcx>,
298 /// The block-context: each time we build the code within an hair::Block,
299 /// we push a frame here tracking whether we are building a statement or
300 /// if we are pushing the tail expression of the block. This is used to
301 /// embed information in generated temps about whether they were created
302 /// for a block tail expression or not.
304 /// It would be great if we could fold this into `self.scopes`
305 /// somehow, but right now I think that is very tightly tied to
306 /// the code generation in ways that we cannot (or should not)
307 /// start just throwing new entries onto that vector in order to
308 /// distinguish the context of EXPR1 from the context of EXPR2 in
309 /// `{ STMTS; EXPR1 } + EXPR2`.
310 block_context: BlockContext,
312 /// The current unsafe block in scope, even if it is hidden by
313 /// a `PushUnsafeBlock`.
314 unpushed_unsafe: Safety,
316 /// The number of `push_unsafe_block` levels in scope.
317 push_unsafe_count: usize,
319 /// The vector of all scopes that we have created thus far;
320 /// we track this for debuginfo later.
321 source_scopes: IndexVec<SourceScope, SourceScopeData>,
322 source_scope: SourceScope,
324 /// The guard-context: each time we build the guard expression for
325 /// a match arm, we push onto this stack, and then pop when we
326 /// finish building it.
327 guard_context: Vec<GuardFrame>,
329 /// Maps `HirId`s of variable bindings to the `Local`s created for them.
330 /// (A match binding can have two locals; the 2nd is for the arm's guard.)
331 var_indices: HirIdMap<LocalsForNode>,
332 local_decls: IndexVec<Local, LocalDecl<'tcx>>,
333 canonical_user_type_annotations: ty::CanonicalUserTypeAnnotations<'tcx>,
334 upvar_mutbls: Vec<Mutability>,
335 unit_temp: Option<Place<'tcx>>,
337 var_debug_info: Vec<VarDebugInfo<'tcx>>,
339 /// Cached block with the `RESUME` terminator; this is created
340 /// when first set of cleanups are built.
341 cached_resume_block: Option<BasicBlock>,
342 /// Cached block with the `RETURN` terminator.
343 cached_return_block: Option<BasicBlock>,
344 /// Cached block with the `UNREACHABLE` terminator.
345 cached_unreachable_block: Option<BasicBlock>,
348 impl<'a, 'tcx> Builder<'a, 'tcx> {
349 fn is_bound_var_in_guard(&self, id: hir::HirId) -> bool {
350 self.guard_context.iter().any(|frame| frame.locals.iter().any(|local| local.id == id))
353 fn var_local_id(&self, id: hir::HirId, for_guard: ForGuard) -> Local {
354 self.var_indices[&id].local_id(for_guard)
362 fn push(&mut self, bf: BlockFrame) {
365 fn pop(&mut self) -> Option<BlockFrame> {
369 /// Traverses the frames on the `BlockContext`, searching for either
370 /// the first block-tail expression frame with no intervening
373 /// Notably, this skips over `SubExpr` frames; this method is
374 /// meant to be used in the context of understanding the
375 /// relationship of a temp (created within some complicated
376 /// expression) with its containing expression, and whether the
377 /// value of that *containing expression* (not the temp!) is
379 fn currently_in_block_tail(&self) -> Option<BlockTailInfo> {
380 for bf in self.0.iter().rev() {
382 BlockFrame::SubExpr => continue,
383 BlockFrame::Statement { .. } => break,
384 &BlockFrame::TailExpr { tail_result_is_ignored, span } => {
385 return Some(BlockTailInfo { tail_result_is_ignored, span });
393 /// Looks at the topmost frame on the BlockContext and reports
394 /// whether its one that would discard a block tail result.
396 /// Unlike `currently_within_ignored_tail_expression`, this does
397 /// *not* skip over `SubExpr` frames: here, we want to know
398 /// whether the block result itself is discarded.
399 fn currently_ignores_tail_results(&self) -> bool {
400 match self.0.last() {
401 // no context: conservatively assume result is read
404 // sub-expression: block result feeds into some computation
405 Some(BlockFrame::SubExpr) => false,
407 // otherwise: use accumulated is_ignored state.
409 BlockFrame::TailExpr { tail_result_is_ignored: ignored, .. }
410 | BlockFrame::Statement { ignores_expr_result: ignored },
418 /// In the usual case, a `HirId` for an identifier maps to at most
419 /// one `Local` declaration.
422 /// The exceptional case is identifiers in a match arm's pattern
423 /// that are referenced in a guard of that match arm. For these,
424 /// we have `2` Locals.
426 /// * `for_arm_body` is the Local used in the arm body (which is
427 /// just like the `One` case above),
429 /// * `ref_for_guard` is the Local used in the arm's guard (which
430 /// is a reference to a temp that is an alias of
432 ForGuard { ref_for_guard: Local, for_arm_body: Local },
436 struct GuardFrameLocal {
440 impl GuardFrameLocal {
441 fn new(id: hir::HirId, _binding_mode: BindingMode) -> Self {
442 GuardFrameLocal { id }
448 /// These are the id's of names that are bound by patterns of the
449 /// arm of *this* guard.
451 /// (Frames higher up the stack will have the id's bound in arms
452 /// further out, such as in a case like:
455 /// P1(id1) if (... (match E2 { P2(id2) if ... => B2 })) => B1,
458 /// here, when building for FIXME.
459 locals: Vec<GuardFrameLocal>,
462 /// `ForGuard` indicates whether we are talking about:
463 /// 1. The variable for use outside of guard expressions, or
464 /// 2. The temp that holds reference to (1.), which is actually what the
465 /// guard expressions see.
466 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
473 fn local_id(&self, for_guard: ForGuard) -> Local {
474 match (self, for_guard) {
475 (&LocalsForNode::One(local_id), ForGuard::OutsideGuard)
477 &LocalsForNode::ForGuard { ref_for_guard: local_id, .. },
478 ForGuard::RefWithinGuard,
480 | (&LocalsForNode::ForGuard { for_arm_body: local_id, .. }, ForGuard::OutsideGuard) => {
484 (&LocalsForNode::One(_), ForGuard::RefWithinGuard) => {
485 bug!("anything with one local should never be within a guard.")
492 basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
495 rustc_index::newtype_index! {
496 struct ScopeId { .. }
499 ///////////////////////////////////////////////////////////////////////////
500 /// The `BlockAnd` "monad" packages up the new basic block along with a
501 /// produced value (sometimes just unit, of course). The `unpack!`
502 /// macro (and methods below) makes working with `BlockAnd` much more
505 #[must_use = "if you don't use one of these results, you're leaving a dangling edge"]
506 struct BlockAnd<T>(BasicBlock, T);
508 trait BlockAndExtension {
509 fn and<T>(self, v: T) -> BlockAnd<T>;
510 fn unit(self) -> BlockAnd<()>;
513 impl BlockAndExtension for BasicBlock {
514 fn and<T>(self, v: T) -> BlockAnd<T> {
518 fn unit(self) -> BlockAnd<()> {
523 /// Update a block pointer and return the value.
524 /// Use it like `let x = unpack!(block = self.foo(block, foo))`.
525 macro_rules! unpack {
526 ($x:ident = $c:expr) => {{
527 let BlockAnd(b, v) = $c;
533 let BlockAnd(b, ()) = $c;
538 fn should_abort_on_panic(tcx: TyCtxt<'_>, fn_def_id: LocalDefId, _abi: Abi) -> bool {
539 // Validate `#[unwind]` syntax regardless of platform-specific panic strategy.
540 let attrs = &tcx.get_attrs(fn_def_id.to_def_id());
541 let unwind_attr = attr::find_unwind_attr(Some(tcx.sess.diagnostic()), attrs);
543 // We never unwind, so it's not relevant to stop an unwind.
544 if tcx.sess.panic_strategy() != PanicStrategy::Unwind {
548 // This is a special case: some functions have a C abi but are meant to
549 // unwind anyway. Don't stop them.
551 None => false, // FIXME(#58794); should be `!(abi == Abi::Rust || abi == Abi::RustCall)`
552 Some(UnwindAttr::Allowed) => false,
553 Some(UnwindAttr::Aborts) => true,
557 ///////////////////////////////////////////////////////////////////////////
558 /// the main entry point for building MIR for a function
560 struct ArgInfo<'tcx>(
563 Option<&'tcx hir::Param<'tcx>>,
564 Option<ImplicitSelfKind>,
567 fn construct_fn<'a, 'tcx, A>(
574 return_ty_span: Span,
575 body: &'tcx hir::Body<'tcx>,
578 A: Iterator<Item = ArgInfo<'tcx>>,
580 let arguments: Vec<_> = arguments.collect();
583 let tcx_hir = tcx.hir();
584 let span = tcx_hir.span(fn_id);
586 let fn_def_id = tcx_hir.local_def_id(fn_id);
588 let mut builder = Builder::new(
598 let call_site_scope =
599 region::Scope { id: body.value.hir_id.local_id, data: region::ScopeData::CallSite };
601 region::Scope { id: body.value.hir_id.local_id, data: region::ScopeData::Arguments };
602 let mut block = START_BLOCK;
603 let source_info = builder.source_info(span);
604 let call_site_s = (call_site_scope, source_info);
606 block = builder.in_scope(call_site_s, LintLevel::Inherited, |builder| {
607 if should_abort_on_panic(tcx, fn_def_id, abi) {
608 builder.schedule_abort();
611 let arg_scope_s = (arg_scope, source_info);
612 // `return_block` is called when we evaluate a `return` expression, so
613 // we just use `START_BLOCK` here.
615 block = builder.in_breakable_scope(
618 Place::return_place(),
620 builder.in_scope(arg_scope_s, LintLevel::Inherited, |builder| {
621 builder.args_and_body(
623 fn_def_id.to_def_id(),
632 // Attribute epilogue to function's closing brace
633 let fn_end = span.shrink_to_hi();
634 let source_info = builder.source_info(fn_end);
635 let return_block = builder.return_block();
636 builder.cfg.goto(block, source_info, return_block);
637 builder.cfg.terminate(return_block, source_info, TerminatorKind::Return);
638 // Attribute any unreachable codepaths to the function's closing brace
639 if let Some(unreachable_block) = builder.cached_unreachable_block {
640 builder.cfg.terminate(unreachable_block, source_info, TerminatorKind::Unreachable);
645 assert_eq!(block, builder.return_block());
647 let spread_arg = if abi == Abi::RustCall {
648 // RustCall pseudo-ABI untuples the last argument.
649 Some(Local::new(arguments.len()))
653 debug!("fn_id {:?} has attrs {:?}", fn_def_id, tcx.get_attrs(fn_def_id.to_def_id()));
655 let mut body = builder.finish();
656 body.spread_arg = spread_arg;
660 fn construct_const<'a, 'tcx>(
662 body_id: hir::BodyId,
667 let owner_id = tcx.hir().body_owner(body_id);
668 let span = tcx.hir().span(owner_id);
669 let mut builder = Builder::new(hir, span, 0, Safety::Safe, const_ty, const_ty_span, None);
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 unpack!(block = builder.into_expr(Place::return_place(), block, expr));
676 let source_info = builder.source_info(span);
677 builder.cfg.terminate(block, source_info, TerminatorKind::Return);
679 // Constants can't `return` so a return block should not be created.
680 assert_eq!(builder.cached_return_block, None);
682 // Constants may be match expressions in which case an unreachable block may
683 // be created, so terminate it properly.
684 if let Some(unreachable_block) = builder.cached_unreachable_block {
685 builder.cfg.terminate(unreachable_block, source_info, TerminatorKind::Unreachable);
691 /// Construct MIR for a item that has had errors in type checking.
693 /// This is required because we may still want to run MIR passes on an item
694 /// with type errors, but normal MIR construction can't handle that in general.
695 fn construct_error<'a, 'tcx>(hir: Cx<'a, 'tcx>, body_id: hir::BodyId) -> Body<'tcx> {
697 let owner_id = tcx.hir().body_owner(body_id);
698 let span = tcx.hir().span(owner_id);
699 let ty = tcx.ty_error();
700 let num_params = match hir.body_owner_kind {
701 hir::BodyOwnerKind::Fn => tcx.hir().fn_decl_by_hir_id(owner_id).unwrap().inputs.len(),
702 hir::BodyOwnerKind::Closure => {
703 if tcx.hir().body(body_id).generator_kind().is_some() {
704 // Generators have an implicit `self` parameter *and* a possibly
705 // implicit resume parameter.
708 // The implicit self parameter adds another local in MIR.
709 1 + tcx.hir().fn_decl_by_hir_id(owner_id).unwrap().inputs.len()
712 hir::BodyOwnerKind::Const => 0,
713 hir::BodyOwnerKind::Static(_) => 0,
715 let mut builder = Builder::new(hir, span, num_params, Safety::Safe, ty, span, None);
716 let source_info = builder.source_info(span);
717 // Some MIR passes will expect the number of parameters to match the
718 // function declaration.
719 for _ in 0..num_params {
720 builder.local_decls.push(LocalDecl::with_source_info(ty, source_info));
722 builder.cfg.terminate(START_BLOCK, source_info, TerminatorKind::Unreachable);
723 let mut body = builder.finish();
724 if tcx.hir().body(body_id).generator_kind.is_some() {
725 body.yield_ty = Some(ty);
730 impl<'a, 'tcx> Builder<'a, 'tcx> {
738 generator_kind: Option<GeneratorKind>,
739 ) -> Builder<'a, 'tcx> {
740 let lint_level = LintLevel::Explicit(hir.root_lint_level);
741 let mut builder = Builder {
743 cfg: CFG { basic_blocks: IndexVec::new() },
747 scopes: Default::default(),
748 block_context: BlockContext::new(),
749 source_scopes: IndexVec::new(),
750 source_scope: OUTERMOST_SOURCE_SCOPE,
751 guard_context: vec![],
752 push_unsafe_count: 0,
753 unpushed_unsafe: safety,
754 local_decls: IndexVec::from_elem_n(LocalDecl::new(return_ty, return_span), 1),
755 canonical_user_type_annotations: IndexVec::new(),
756 upvar_mutbls: vec![],
757 var_indices: Default::default(),
759 var_debug_info: vec![],
760 cached_resume_block: None,
761 cached_return_block: None,
762 cached_unreachable_block: None,
765 assert_eq!(builder.cfg.start_new_block(), START_BLOCK);
767 builder.new_source_scope(span, lint_level, Some(safety)),
768 OUTERMOST_SOURCE_SCOPE
770 builder.source_scopes[OUTERMOST_SOURCE_SCOPE].parent_scope = None;
775 fn finish(self) -> Body<'tcx> {
776 for (index, block) in self.cfg.basic_blocks.iter().enumerate() {
777 if block.terminator.is_none() {
778 span_bug!(self.fn_span, "no terminator on block {:?}", index);
783 self.cfg.basic_blocks,
786 self.canonical_user_type_annotations,
796 mut block: BasicBlock,
798 arguments: &[ArgInfo<'tcx>],
799 argument_scope: region::Scope,
800 ast_body: &'tcx hir::Expr<'tcx>,
802 // Allocate locals for the function arguments
803 for &ArgInfo(ty, _, arg_opt, _) in arguments.iter() {
805 SourceInfo::outermost(arg_opt.map_or(self.fn_span, |arg| arg.pat.span));
806 let arg_local = self.local_decls.push(LocalDecl::with_source_info(ty, source_info));
808 // If this is a simple binding pattern, give debuginfo a nice name.
809 if let Some(arg) = arg_opt {
810 if let Some(ident) = arg.pat.simple_ident() {
811 self.var_debug_info.push(VarDebugInfo {
814 place: arg_local.into(),
820 let tcx = self.hir.tcx();
821 let tcx_hir = tcx.hir();
822 let hir_typeck_results = self.hir.typeck_results();
824 // In analyze_closure() in upvar.rs we gathered a list of upvars used by a
825 // indexed closure and we stored in a map called closure_captures in TypeckResults
826 // with the closure's DefId. Here, we run through that vec of UpvarIds for
827 // the given closure and use the necessary information to create upvar
828 // debuginfo and to fill `self.upvar_mutbls`.
829 if let Some(upvars) = hir_typeck_results.closure_captures.get(&fn_def_id) {
830 let closure_env_arg = Local::new(1);
831 let mut closure_env_projs = vec![];
832 let mut closure_ty = self.local_decls[closure_env_arg].ty;
833 if let ty::Ref(_, ty, _) = closure_ty.kind {
834 closure_env_projs.push(ProjectionElem::Deref);
837 let upvar_substs = match closure_ty.kind {
838 ty::Closure(_, substs) => ty::UpvarSubsts::Closure(substs),
839 ty::Generator(_, substs, _) => ty::UpvarSubsts::Generator(substs),
840 _ => span_bug!(self.fn_span, "upvars with non-closure env ty {:?}", closure_ty),
842 let upvar_tys = upvar_substs.upvar_tys();
843 let upvars_with_tys = upvars.iter().zip(upvar_tys);
844 self.upvar_mutbls = upvars_with_tys
846 .map(|(i, ((&var_id, &upvar_id), ty))| {
847 let capture = hir_typeck_results.upvar_capture(upvar_id);
849 let mut mutability = Mutability::Not;
850 let mut name = kw::Invalid;
851 if let Some(Node::Binding(pat)) = tcx_hir.find(var_id) {
852 if let hir::PatKind::Binding(_, _, ident, _) = pat.kind {
854 match hir_typeck_results
855 .extract_binding_mode(tcx.sess, pat.hir_id, pat.span)
857 Some(ty::BindByValue(hir::Mutability::Mut)) => {
858 mutability = Mutability::Mut;
860 Some(_) => mutability = Mutability::Not,
866 let mut projs = closure_env_projs.clone();
867 projs.push(ProjectionElem::Field(Field::new(i), ty));
869 ty::UpvarCapture::ByValue => {}
870 ty::UpvarCapture::ByRef(..) => {
871 projs.push(ProjectionElem::Deref);
875 self.var_debug_info.push(VarDebugInfo {
877 source_info: SourceInfo::outermost(tcx_hir.span(var_id)),
879 local: closure_env_arg,
880 projection: tcx.intern_place_elems(&projs),
889 let mut scope = None;
890 // Bind the argument patterns
891 for (index, arg_info) in arguments.iter().enumerate() {
892 // Function arguments always get the first Local indices after the return place
893 let local = Local::new(index + 1);
894 let place = Place::from(local);
895 let &ArgInfo(_, opt_ty_info, arg_opt, ref self_binding) = arg_info;
897 // Make sure we drop (parts of) the argument even when not matched on.
899 arg_opt.as_ref().map_or(ast_body.span, |arg| arg.pat.span),
905 if let Some(arg) = arg_opt {
906 let pattern = self.hir.pattern_from_hir(&arg.pat);
907 let original_source_scope = self.source_scope;
908 let span = pattern.span;
909 self.set_correct_source_scope_for_arg(arg.hir_id, original_source_scope, span);
910 match *pattern.kind {
911 // Don't introduce extra copies for simple bindings
915 mode: BindingMode::ByValue,
919 self.local_decls[local].mutability = mutability;
920 self.local_decls[local].source_info.scope = self.source_scope;
921 self.local_decls[local].local_info = if let Some(kind) = self_binding {
922 Some(box LocalInfo::User(ClearCrossCrate::Set(
923 BindingForm::ImplicitSelf(*kind),
926 let binding_mode = ty::BindingMode::BindByValue(mutability);
927 Some(box LocalInfo::User(ClearCrossCrate::Set(BindingForm::Var(
931 opt_match_place: Some((Some(place), span)),
936 self.var_indices.insert(var, LocalsForNode::One(local));
939 scope = self.declare_bindings(
943 matches::ArmHasGuard(false),
944 Some((Some(&place), span)),
946 unpack!(block = self.place_into_pattern(block, pattern, place, false));
949 self.source_scope = original_source_scope;
953 // Enter the argument pattern bindings source scope, if it exists.
954 if let Some(source_scope) = scope {
955 self.source_scope = source_scope;
958 let body = self.hir.mirror(ast_body);
959 self.into(Place::return_place(), block, body)
962 fn set_correct_source_scope_for_arg(
964 arg_hir_id: hir::HirId,
965 original_source_scope: SourceScope,
968 let tcx = self.hir.tcx();
969 let current_root = tcx.maybe_lint_level_root_bounded(arg_hir_id, self.hir.root_lint_level);
970 let parent_root = tcx.maybe_lint_level_root_bounded(
971 self.source_scopes[original_source_scope]
974 .assert_crate_local()
976 self.hir.root_lint_level,
978 if current_root != parent_root {
980 self.new_source_scope(pattern_span, LintLevel::Explicit(current_root), None);
984 fn get_unit_temp(&mut self) -> Place<'tcx> {
985 match self.unit_temp {
988 let ty = self.hir.unit_ty();
989 let fn_span = self.fn_span;
990 let tmp = self.temp(ty, fn_span);
991 self.unit_temp = Some(tmp);
997 fn return_block(&mut self) -> BasicBlock {
998 match self.cached_return_block {
1001 let rb = self.cfg.start_new_block();
1002 self.cached_return_block = Some(rb);
1009 ///////////////////////////////////////////////////////////////////////////
1010 // Builder methods are broken up into modules, depending on what kind
1011 // of thing is being lowered. Note that they use the `unpack` macro
1012 // above extensively.