2 use crate::build::scope::DropKind;
3 use crate::hair::cx::Cx;
4 use crate::hair::{LintLevel, BindingMode, PatKind};
5 use crate::transform::MirSource;
6 use crate::util as mir_util;
8 use rustc::hir::{Node, GeneratorKind};
9 use rustc::hir::def_id::DefId;
10 use rustc::middle::lang_items;
11 use rustc::middle::region;
13 use rustc::ty::{self, Ty, TyCtxt};
14 use rustc::ty::subst::Subst;
15 use rustc::util::nodemap::HirIdMap;
16 use rustc_target::spec::PanicStrategy;
17 use rustc_index::vec::{IndexVec, Idx};
19 use rustc_target::spec::abi::Abi;
20 use syntax::attr::{self, UnwindAttr};
21 use syntax::symbol::kw;
26 /// Construct the MIR for a given `DefId`.
27 pub fn mir_build(tcx: TyCtxt<'_>, def_id: DefId) -> Body<'_> {
28 let id = tcx.hir().as_local_hir_id(def_id).unwrap();
30 // Figure out what primary body this item has.
31 let (body_id, return_ty_span) = match tcx.hir().get(id) {
32 Node::Expr(hir::Expr { kind: hir::ExprKind::Closure(_, decl, body_id, _, _), .. })
35 kind: hir::ItemKind::Fn(hir::FnSig { decl, .. }, _, body_id),
41 kind: hir::ImplItemKind::Method(hir::FnSig { decl, .. }, body_id),
47 kind: hir::TraitItemKind::Method(
48 hir::FnSig { decl, .. },
49 hir::TraitMethod::Provided(body_id),
54 (*body_id, decl.output.span())
56 Node::Item(hir::Item { kind: hir::ItemKind::Static(ty, _, body_id), .. })
57 | Node::Item(hir::Item { kind: hir::ItemKind::Const(ty, body_id), .. })
58 | Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Const(ty, body_id), .. })
60 hir::TraitItem { kind: hir::TraitItemKind::Const(ty, Some(body_id)), .. }
64 Node::AnonConst(hir::AnonConst { body, hir_id, .. }) => {
65 (*body, tcx.hir().span(*hir_id))
68 _ => span_bug!(tcx.hir().span(id), "can't build MIR for {:?}", def_id),
71 tcx.infer_ctxt().enter(|infcx| {
72 let cx = Cx::new(&infcx, id);
73 let body = if cx.tables().tainted_by_errors {
74 build::construct_error(cx, body_id)
75 } else if cx.body_owner_kind.is_fn_or_closure() {
76 // fetch the fully liberated fn signature (that is, all bound
77 // types/lifetimes replaced)
78 let fn_sig = cx.tables().liberated_fn_sigs()[id].clone();
79 let fn_def_id = tcx.hir().local_def_id(id);
81 let ty = tcx.type_of(fn_def_id);
82 let mut abi = fn_sig.abi;
83 let implicit_argument = match ty.kind {
85 // HACK(eddyb) Avoid having RustCall on closures,
86 // as it adds unnecessary (and wrong) auto-tupling.
88 Some(ArgInfo(liberated_closure_env_ty(tcx, id, body_id), None, None, None))
90 ty::Generator(..) => {
91 let gen_ty = tcx.body_tables(body_id).node_type(id);
92 Some(ArgInfo(gen_ty, None, None, None))
97 let safety = match fn_sig.unsafety {
98 hir::Unsafety::Normal => Safety::Safe,
99 hir::Unsafety::Unsafe => Safety::FnUnsafe,
102 let body = tcx.hir().body(body_id);
103 let explicit_arguments =
107 .map(|(index, arg)| {
108 let owner_id = tcx.hir().body_owner(body_id);
111 if let Some(ref fn_decl) = tcx.hir().fn_decl_by_hir_id(owner_id) {
112 opt_ty_info = fn_decl.inputs.get(index).map(|ty| ty.span);
113 self_arg = if index == 0 && fn_decl.implicit_self.has_implicit_self() {
114 match fn_decl.implicit_self {
115 hir::ImplicitSelfKind::Imm => Some(ImplicitSelfKind::Imm),
116 hir::ImplicitSelfKind::Mut => Some(ImplicitSelfKind::Mut),
117 hir::ImplicitSelfKind::ImmRef => Some(ImplicitSelfKind::ImmRef),
118 hir::ImplicitSelfKind::MutRef => Some(ImplicitSelfKind::MutRef),
129 // C-variadic fns also have a `VaList` input that's not listed in `fn_sig`
130 // (as it's created inside the body itself, not passed in from outside).
131 let ty = if fn_sig.c_variadic && index == fn_sig.inputs().len() {
132 let va_list_did = tcx.require_lang_item(
133 lang_items::VaListTypeLangItem,
136 let region = tcx.mk_region(ty::ReScope(region::Scope {
137 id: body.value.hir_id.local_id,
138 data: region::ScopeData::CallSite
141 tcx.type_of(va_list_did).subst(tcx, &[region.into()])
143 fn_sig.inputs()[index]
146 ArgInfo(ty, opt_ty_info, Some(&arg), self_arg)
149 let arguments = implicit_argument.into_iter().chain(explicit_arguments);
151 let (yield_ty, return_ty) = if body.generator_kind.is_some() {
152 let gen_sig = match ty.kind {
153 ty::Generator(gen_def_id, gen_substs, ..) =>
154 gen_substs.as_generator().sig(gen_def_id, tcx),
156 span_bug!(tcx.hir().span(id),
157 "generator w/o generator type: {:?}", ty),
159 (Some(gen_sig.yield_ty), gen_sig.return_ty)
161 (None, fn_sig.output())
164 let mut mir = build::construct_fn(
174 mir.yield_ty = yield_ty;
177 // Get the revealed type of this const. This is *not* the adjusted
178 // type of its body, which may be a subtype of this type. For
182 // static X: fn(&'static ()) = foo;
184 // The adjusted type of the body of X is `for<'a> fn(&'a ())` which
185 // is not the same as the type of X. We need the type of the return
186 // place to be the type of the constant because NLL typeck will
189 let return_ty = cx.tables().node_type(id);
191 build::construct_const(cx, body_id, return_ty, return_ty_span)
194 mir_util::dump_mir(tcx, None, "mir_map", &0,
195 MirSource::item(def_id), &body, |_, _| Ok(()) );
197 lints::check(tcx, &body, def_id);
203 ///////////////////////////////////////////////////////////////////////////
204 // BuildMir -- walks a crate, looking for fn items and methods to build MIR from
206 fn liberated_closure_env_ty(
208 closure_expr_id: hir::HirId,
209 body_id: hir::BodyId,
211 let closure_ty = tcx.body_tables(body_id).node_type(closure_expr_id);
213 let (closure_def_id, closure_substs) = match closure_ty.kind {
214 ty::Closure(closure_def_id, closure_substs) => (closure_def_id, closure_substs),
215 _ => bug!("closure expr does not have closure type: {:?}", closure_ty)
218 let closure_env_ty = tcx.closure_env_ty(closure_def_id, closure_substs).unwrap();
219 tcx.liberate_late_bound_regions(closure_def_id, &closure_env_ty)
222 #[derive(Debug, PartialEq, Eq)]
223 pub enum BlockFrame {
224 /// Evaluation is currently within a statement.
226 /// Examples include:
228 /// 2. `let _ = EXPR;`
229 /// 3. `let x = EXPR;`
231 /// If true, then statement discards result from evaluating
232 /// the expression (such as examples 1 and 2 above).
233 ignores_expr_result: bool
236 /// Evaluation is currently within the tail expression of a block.
238 /// Example: `{ STMT_1; STMT_2; EXPR }`
240 /// If true, then the surrounding context of the block ignores
241 /// the result of evaluating the block's tail expression.
243 /// Example: `let _ = { STMT_1; EXPR };`
244 tail_result_is_ignored: bool
247 /// Generic mark meaning that the block occurred as a subexpression
248 /// where the result might be used.
250 /// Examples: `foo(EXPR)`, `match EXPR { ... }`
255 fn is_tail_expr(&self) -> bool {
257 BlockFrame::TailExpr { .. } => true,
259 BlockFrame::Statement { .. } |
260 BlockFrame::SubExpr => false,
263 fn is_statement(&self) -> bool {
265 BlockFrame::Statement { .. } => true,
267 BlockFrame::TailExpr { .. } |
268 BlockFrame::SubExpr => false,
274 struct BlockContext(Vec<BlockFrame>);
276 struct Builder<'a, 'tcx> {
282 generator_kind: Option<GeneratorKind>,
284 /// The current set of scopes, updated as we traverse;
285 /// see the `scope` module for more details.
286 scopes: scope::Scopes<'tcx>,
288 /// The block-context: each time we build the code within an hair::Block,
289 /// we push a frame here tracking whether we are building a statement or
290 /// if we are pushing the tail expression of the block. This is used to
291 /// embed information in generated temps about whether they were created
292 /// for a block tail expression or not.
294 /// It would be great if we could fold this into `self.scopes`
295 /// somehow, but right now I think that is very tightly tied to
296 /// the code generation in ways that we cannot (or should not)
297 /// start just throwing new entries onto that vector in order to
298 /// distinguish the context of EXPR1 from the context of EXPR2 in
299 /// `{ STMTS; EXPR1 } + EXPR2`.
300 block_context: BlockContext,
302 /// The current unsafe block in scope, even if it is hidden by
303 /// a `PushUnsafeBlock`.
304 unpushed_unsafe: Safety,
306 /// The number of `push_unsafe_block` levels in scope.
307 push_unsafe_count: usize,
309 /// The vector of all scopes that we have created thus far;
310 /// we track this for debuginfo later.
311 source_scopes: IndexVec<SourceScope, SourceScopeData>,
312 source_scope_local_data: IndexVec<SourceScope, SourceScopeLocalData>,
313 source_scope: SourceScope,
315 /// The guard-context: each time we build the guard expression for
316 /// a match arm, we push onto this stack, and then pop when we
317 /// finish building it.
318 guard_context: Vec<GuardFrame>,
320 /// Maps `HirId`s of variable bindings to the `Local`s created for them.
321 /// (A match binding can have two locals; the 2nd is for the arm's guard.)
322 var_indices: HirIdMap<LocalsForNode>,
323 local_decls: IndexVec<Local, LocalDecl<'tcx>>,
324 canonical_user_type_annotations: ty::CanonicalUserTypeAnnotations<'tcx>,
325 upvar_mutbls: Vec<Mutability>,
326 unit_temp: Option<Place<'tcx>>,
328 var_debug_info: Vec<VarDebugInfo<'tcx>>,
330 /// Cached block with the `RESUME` terminator; this is created
331 /// when first set of cleanups are built.
332 cached_resume_block: Option<BasicBlock>,
333 /// Cached block with the `RETURN` terminator.
334 cached_return_block: Option<BasicBlock>,
335 /// Cached block with the `UNREACHABLE` terminator.
336 cached_unreachable_block: Option<BasicBlock>,
339 impl<'a, 'tcx> Builder<'a, 'tcx> {
340 fn is_bound_var_in_guard(&self, id: hir::HirId) -> bool {
341 self.guard_context.iter().any(|frame| frame.locals.iter().any(|local| local.id == id))
344 fn var_local_id(&self, id: hir::HirId, for_guard: ForGuard) -> Local {
345 self.var_indices[&id].local_id(for_guard)
350 fn new() -> Self { BlockContext(vec![]) }
351 fn push(&mut self, bf: BlockFrame) { self.0.push(bf); }
352 fn pop(&mut self) -> Option<BlockFrame> { self.0.pop() }
354 /// Traverses the frames on the `BlockContext`, searching for either
355 /// the first block-tail expression frame with no intervening
358 /// Notably, this skips over `SubExpr` frames; this method is
359 /// meant to be used in the context of understanding the
360 /// relationship of a temp (created within some complicated
361 /// expression) with its containing expression, and whether the
362 /// value of that *containing expression* (not the temp!) is
364 fn currently_in_block_tail(&self) -> Option<BlockTailInfo> {
365 for bf in self.0.iter().rev() {
367 BlockFrame::SubExpr => continue,
368 BlockFrame::Statement { .. } => break,
369 &BlockFrame::TailExpr { tail_result_is_ignored } =>
370 return Some(BlockTailInfo { tail_result_is_ignored })
377 /// Looks at the topmost frame on the BlockContext and reports
378 /// whether its one that would discard a block tail result.
380 /// Unlike `currently_within_ignored_tail_expression`, this does
381 /// *not* skip over `SubExpr` frames: here, we want to know
382 /// whether the block result itself is discarded.
383 fn currently_ignores_tail_results(&self) -> bool {
384 match self.0.last() {
385 // no context: conservatively assume result is read
388 // sub-expression: block result feeds into some computation
389 Some(BlockFrame::SubExpr) => false,
391 // otherwise: use accumulated is_ignored state.
392 Some(BlockFrame::TailExpr { tail_result_is_ignored: ignored }) |
393 Some(BlockFrame::Statement { ignores_expr_result: ignored }) => *ignored,
400 /// In the usual case, a `HirId` for an identifier maps to at most
401 /// one `Local` declaration.
404 /// The exceptional case is identifiers in a match arm's pattern
405 /// that are referenced in a guard of that match arm. For these,
406 /// we have `2` Locals.
408 /// * `for_arm_body` is the Local used in the arm body (which is
409 /// just like the `One` case above),
411 /// * `ref_for_guard` is the Local used in the arm's guard (which
412 /// is a reference to a temp that is an alias of
414 ForGuard { ref_for_guard: Local, for_arm_body: Local },
418 struct GuardFrameLocal {
422 impl GuardFrameLocal {
423 fn new(id: hir::HirId, _binding_mode: BindingMode) -> Self {
432 /// These are the id's of names that are bound by patterns of the
433 /// arm of *this* guard.
435 /// (Frames higher up the stack will have the id's bound in arms
436 /// further out, such as in a case like:
439 /// P1(id1) if (... (match E2 { P2(id2) if ... => B2 })) => B1,
442 /// here, when building for FIXME.
443 locals: Vec<GuardFrameLocal>,
446 /// `ForGuard` indicates whether we are talking about:
447 /// 1. The variable for use outside of guard expressions, or
448 /// 2. The temp that holds reference to (1.), which is actually what the
449 /// guard expressions see.
450 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
457 fn local_id(&self, for_guard: ForGuard) -> Local {
458 match (self, for_guard) {
459 (&LocalsForNode::One(local_id), ForGuard::OutsideGuard) |
460 (&LocalsForNode::ForGuard { ref_for_guard: local_id, .. }, ForGuard::RefWithinGuard) |
461 (&LocalsForNode::ForGuard { for_arm_body: local_id, .. }, ForGuard::OutsideGuard) =>
464 (&LocalsForNode::One(_), ForGuard::RefWithinGuard) =>
465 bug!("anything with one local should never be within a guard."),
471 basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
474 rustc_index::newtype_index! {
475 pub struct ScopeId { .. }
478 ///////////////////////////////////////////////////////////////////////////
479 /// The `BlockAnd` "monad" packages up the new basic block along with a
480 /// produced value (sometimes just unit, of course). The `unpack!`
481 /// macro (and methods below) makes working with `BlockAnd` much more
484 #[must_use = "if you don't use one of these results, you're leaving a dangling edge"]
485 struct BlockAnd<T>(BasicBlock, T);
487 trait BlockAndExtension {
488 fn and<T>(self, v: T) -> BlockAnd<T>;
489 fn unit(self) -> BlockAnd<()>;
492 impl BlockAndExtension for BasicBlock {
493 fn and<T>(self, v: T) -> BlockAnd<T> {
497 fn unit(self) -> BlockAnd<()> {
502 /// Update a block pointer and return the value.
503 /// Use it like `let x = unpack!(block = self.foo(block, foo))`.
504 macro_rules! unpack {
505 ($x:ident = $c:expr) => {
507 let BlockAnd(b, v) = $c;
515 let BlockAnd(b, ()) = $c;
521 fn should_abort_on_panic(tcx: TyCtxt<'_>, fn_def_id: DefId, _abi: Abi) -> bool {
522 // Validate `#[unwind]` syntax regardless of platform-specific panic strategy.
523 let attrs = &tcx.get_attrs(fn_def_id);
524 let unwind_attr = attr::find_unwind_attr(Some(tcx.sess.diagnostic()), attrs);
526 // We never unwind, so it's not relevant to stop an unwind.
527 if tcx.sess.panic_strategy() != PanicStrategy::Unwind { return false; }
529 // We cannot add landing pads, so don't add one.
530 if tcx.sess.no_landing_pads() { return false; }
532 // This is a special case: some functions have a C abi but are meant to
533 // unwind anyway. Don't stop them.
535 None => false, // FIXME(#58794); should be `!(abi == Abi::Rust || abi == Abi::RustCall)`
536 Some(UnwindAttr::Allowed) => false,
537 Some(UnwindAttr::Aborts) => true,
541 ///////////////////////////////////////////////////////////////////////////
542 /// the main entry point for building MIR for a function
544 struct ArgInfo<'tcx>(Ty<'tcx>, Option<Span>, Option<&'tcx hir::Param>, Option<ImplicitSelfKind>);
546 fn construct_fn<'a, 'tcx, A>(
553 return_ty_span: Span,
554 body: &'tcx hir::Body,
557 A: Iterator<Item=ArgInfo<'tcx>>
559 let arguments: Vec<_> = arguments.collect();
562 let tcx_hir = tcx.hir();
563 let span = tcx_hir.span(fn_id);
565 let fn_def_id = tcx_hir.local_def_id(fn_id);
567 let mut builder = Builder::new(hir,
573 body.generator_kind);
575 let call_site_scope = region::Scope {
576 id: body.value.hir_id.local_id,
577 data: region::ScopeData::CallSite
579 let arg_scope = region::Scope {
580 id: body.value.hir_id.local_id,
581 data: region::ScopeData::Arguments
583 let mut block = START_BLOCK;
584 let source_info = builder.source_info(span);
585 let call_site_s = (call_site_scope, source_info);
586 unpack!(block = builder.in_scope(call_site_s, LintLevel::Inherited, |builder| {
587 if should_abort_on_panic(tcx, fn_def_id, abi) {
588 builder.schedule_abort();
591 let arg_scope_s = (arg_scope, source_info);
592 // `return_block` is called when we evaluate a `return` expression, so
593 // we just use `START_BLOCK` here.
594 unpack!(block = builder.in_breakable_scope(
597 Place::return_place(),
599 builder.in_scope(arg_scope_s, LintLevel::Inherited, |builder| {
600 builder.args_and_body(block, fn_def_id, &arguments, arg_scope, &body.value)
604 // Attribute epilogue to function's closing brace
605 let fn_end = span.shrink_to_hi();
606 let source_info = builder.source_info(fn_end);
607 let return_block = builder.return_block();
608 builder.cfg.terminate(block, source_info,
609 TerminatorKind::Goto { target: return_block });
610 builder.cfg.terminate(return_block, source_info,
611 TerminatorKind::Return);
612 // Attribute any unreachable codepaths to the function's closing brace
613 if let Some(unreachable_block) = builder.cached_unreachable_block {
614 builder.cfg.terminate(unreachable_block, source_info,
615 TerminatorKind::Unreachable);
619 assert_eq!(block, builder.return_block());
621 let mut spread_arg = None;
622 if abi == Abi::RustCall {
623 // RustCall pseudo-ABI untuples the last argument.
624 spread_arg = Some(Local::new(arguments.len()));
626 info!("fn_id {:?} has attrs {:?}", fn_def_id,
627 tcx.get_attrs(fn_def_id));
629 let mut body = builder.finish();
630 body.spread_arg = spread_arg;
634 fn construct_const<'a, 'tcx>(
636 body_id: hir::BodyId,
641 let owner_id = tcx.hir().body_owner(body_id);
642 let span = tcx.hir().span(owner_id);
643 let mut builder = Builder::new(
653 let mut block = START_BLOCK;
654 let ast_expr = &tcx.hir().body(body_id).value;
655 let expr = builder.hir.mirror(ast_expr);
656 unpack!(block = builder.into_expr(&Place::return_place(), block, expr));
658 let source_info = builder.source_info(span);
659 builder.cfg.terminate(block, source_info, TerminatorKind::Return);
661 // Constants can't `return` so a return block should not be created.
662 assert_eq!(builder.cached_return_block, None);
664 // Constants may be match expressions in which case an unreachable block may
665 // be created, so terminate it properly.
666 if let Some(unreachable_block) = builder.cached_unreachable_block {
667 builder.cfg.terminate(unreachable_block, source_info,
668 TerminatorKind::Unreachable);
674 fn construct_error<'a, 'tcx>(
678 let owner_id = hir.tcx().hir().body_owner(body_id);
679 let span = hir.tcx().hir().span(owner_id);
680 let ty = hir.tcx().types.err;
681 let mut builder = Builder::new(hir, span, 0, Safety::Safe, ty, span, None);
682 let source_info = builder.source_info(span);
683 builder.cfg.terminate(START_BLOCK, source_info, TerminatorKind::Unreachable);
687 impl<'a, 'tcx> Builder<'a, 'tcx> {
688 fn new(hir: Cx<'a, 'tcx>,
694 generator_kind: Option<GeneratorKind>)
695 -> Builder<'a, 'tcx> {
696 let lint_level = LintLevel::Explicit(hir.root_lint_level);
697 let mut builder = Builder {
699 cfg: CFG { basic_blocks: IndexVec::new() },
703 scopes: Default::default(),
704 block_context: BlockContext::new(),
705 source_scopes: IndexVec::new(),
706 source_scope: OUTERMOST_SOURCE_SCOPE,
707 source_scope_local_data: IndexVec::new(),
708 guard_context: vec![],
709 push_unsafe_count: 0,
710 unpushed_unsafe: safety,
711 local_decls: IndexVec::from_elem_n(
712 LocalDecl::new_return_place(return_ty, return_span),
715 canonical_user_type_annotations: IndexVec::new(),
716 upvar_mutbls: vec![],
717 var_indices: Default::default(),
719 var_debug_info: vec![],
720 cached_resume_block: None,
721 cached_return_block: None,
722 cached_unreachable_block: None,
725 assert_eq!(builder.cfg.start_new_block(), START_BLOCK);
727 builder.new_source_scope(span, lint_level, Some(safety)),
728 OUTERMOST_SOURCE_SCOPE);
729 builder.source_scopes[OUTERMOST_SOURCE_SCOPE].parent_scope = None;
734 fn finish(self) -> Body<'tcx> {
735 for (index, block) in self.cfg.basic_blocks.iter().enumerate() {
736 if block.terminator.is_none() {
737 span_bug!(self.fn_span, "no terminator on block {:?}", index);
742 self.cfg.basic_blocks,
744 ClearCrossCrate::Set(self.source_scope_local_data),
746 self.canonical_user_type_annotations,
750 self.hir.control_flow_destroyed(),
755 fn args_and_body(&mut self,
756 mut block: BasicBlock,
758 arguments: &[ArgInfo<'tcx>],
759 argument_scope: region::Scope,
760 ast_body: &'tcx hir::Expr)
763 // Allocate locals for the function arguments
764 for &ArgInfo(ty, _, arg_opt, _) in arguments.iter() {
765 let source_info = SourceInfo {
766 scope: OUTERMOST_SOURCE_SCOPE,
767 span: arg_opt.map_or(self.fn_span, |arg| arg.pat.span)
769 let arg_local = self.local_decls.push(LocalDecl {
770 mutability: Mutability::Mut,
772 user_ty: UserTypeProjections::none(),
775 local_info: LocalInfo::Other,
779 // If this is a simple binding pattern, give debuginfo a nice name.
780 if let Some(arg) = arg_opt {
781 if let Some(ident) = arg.pat.simple_ident() {
782 self.var_debug_info.push(VarDebugInfo {
785 place: arg_local.into(),
791 let tcx = self.hir.tcx();
792 let tcx_hir = tcx.hir();
793 let hir_tables = self.hir.tables();
795 // In analyze_closure() in upvar.rs we gathered a list of upvars used by a
796 // closure and we stored in a map called upvar_list in TypeckTables indexed
797 // with the closure's DefId. Here, we run through that vec of UpvarIds for
798 // the given closure and use the necessary information to create upvar
799 // debuginfo and to fill `self.upvar_mutbls`.
800 if let Some(upvars) = hir_tables.upvar_list.get(&fn_def_id) {
801 let closure_env_arg = Local::new(1);
802 let mut closure_env_projs = vec![];
803 let mut closure_ty = self.local_decls[closure_env_arg].ty;
804 if let ty::Ref(_, ty, _) = closure_ty.kind {
805 closure_env_projs.push(ProjectionElem::Deref);
808 let (def_id, upvar_substs) = match closure_ty.kind {
809 ty::Closure(def_id, substs) => (def_id, ty::UpvarSubsts::Closure(substs)),
810 ty::Generator(def_id, substs, _) => (def_id, ty::UpvarSubsts::Generator(substs)),
811 _ => span_bug!(self.fn_span, "upvars with non-closure env ty {:?}", closure_ty)
813 let upvar_tys = upvar_substs.upvar_tys(def_id, tcx);
814 let upvars_with_tys = upvars.iter().zip(upvar_tys);
815 self.upvar_mutbls = upvars_with_tys.enumerate().map(|(i, ((&var_id, &upvar_id), ty))| {
816 let capture = hir_tables.upvar_capture(upvar_id);
818 let mut mutability = Mutability::Not;
819 let mut name = kw::Invalid;
820 if let Some(Node::Binding(pat)) = tcx_hir.find(var_id) {
821 if let hir::PatKind::Binding(_, _, ident, _) = pat.kind {
824 if let Some(&bm) = hir_tables.pat_binding_modes().get(pat.hir_id) {
825 if bm == ty::BindByValue(hir::Mutability::Mutable) {
826 mutability = Mutability::Mut;
828 mutability = Mutability::Not;
831 tcx.sess.delay_span_bug(pat.span, "missing binding mode");
836 let mut projs = closure_env_projs.clone();
837 projs.push(ProjectionElem::Field(Field::new(i), ty));
839 ty::UpvarCapture::ByValue => {}
840 ty::UpvarCapture::ByRef(..) => {
841 projs.push(ProjectionElem::Deref);
845 self.var_debug_info.push(VarDebugInfo {
847 source_info: SourceInfo {
848 scope: OUTERMOST_SOURCE_SCOPE,
849 span: tcx_hir.span(var_id),
852 base: closure_env_arg.into(),
853 projection: tcx.intern_place_elems(&projs),
861 let mut scope = None;
862 // Bind the argument patterns
863 for (index, arg_info) in arguments.iter().enumerate() {
864 // Function arguments always get the first Local indices after the return place
865 let local = Local::new(index + 1);
866 let place = Place::from(local);
867 let &ArgInfo(_, opt_ty_info, arg_opt, ref self_binding) = arg_info;
869 // Make sure we drop (parts of) the argument even when not matched on.
871 arg_opt.as_ref().map_or(ast_body.span, |arg| arg.pat.span),
872 argument_scope, local, DropKind::Value,
875 if let Some(arg) = arg_opt {
876 let pattern = self.hir.pattern_from_hir(&arg.pat);
877 let original_source_scope = self.source_scope;
878 let span = pattern.span;
879 self.set_correct_source_scope_for_arg(arg.hir_id, original_source_scope, span);
880 match *pattern.kind {
881 // Don't introduce extra copies for simple bindings
885 mode: BindingMode::ByValue,
889 self.local_decls[local].mutability = mutability;
890 self.local_decls[local].source_info.scope = self.source_scope;
891 self.local_decls[local].local_info =
892 if let Some(kind) = self_binding {
893 LocalInfo::User(ClearCrossCrate::Set(
894 BindingForm::ImplicitSelf(*kind),
897 let binding_mode = ty::BindingMode::BindByValue(mutability.into());
898 LocalInfo::User(ClearCrossCrate::Set(BindingForm::Var(
902 opt_match_place: Some((Some(place.clone()), span)),
907 self.var_indices.insert(var, LocalsForNode::One(local));
910 scope = self.declare_bindings(
914 matches::ArmHasGuard(false),
915 Some((Some(&place), span)),
917 unpack!(block = self.place_into_pattern(block, pattern, &place, false));
920 self.source_scope = original_source_scope;
924 // Enter the argument pattern bindings source scope, if it exists.
925 if let Some(source_scope) = scope {
926 self.source_scope = source_scope;
929 let body = self.hir.mirror(ast_body);
930 self.into(&Place::return_place(), block, body)
933 fn set_correct_source_scope_for_arg(
935 arg_hir_id: hir::HirId,
936 original_source_scope: SourceScope,
939 let tcx = self.hir.tcx();
940 let current_root = tcx.maybe_lint_level_root_bounded(
942 self.hir.root_lint_level
944 let parent_root = tcx.maybe_lint_level_root_bounded(
945 self.source_scope_local_data[original_source_scope].lint_root,
946 self.hir.root_lint_level,
948 if current_root != parent_root {
949 self.source_scope = self.new_source_scope(
951 LintLevel::Explicit(current_root),
957 fn get_unit_temp(&mut self) -> Place<'tcx> {
958 match self.unit_temp {
959 Some(ref tmp) => tmp.clone(),
961 let ty = self.hir.unit_ty();
962 let fn_span = self.fn_span;
963 let tmp = self.temp(ty, fn_span);
964 self.unit_temp = Some(tmp.clone());
970 fn return_block(&mut self) -> BasicBlock {
971 match self.cached_return_block {
974 let rb = self.cfg.start_new_block();
975 self.cached_return_block = Some(rb);
982 ///////////////////////////////////////////////////////////////////////////
983 // Builder methods are broken up into modules, depending on what kind
984 // of thing is being lowered. Note that they use the `unpack` macro
985 // above extensively.