2 use crate::build::expr::as_place::PlaceBuilder;
3 use crate::build::scope::DropKind;
4 use crate::thir::pattern::pat_from_hir;
5 use rustc_errors::ErrorReported;
7 use rustc_hir::def_id::{DefId, LocalDefId};
8 use rustc_hir::lang_items::LangItem;
9 use rustc_hir::{GeneratorKind, HirIdMap, Node};
10 use rustc_index::vec::{Idx, IndexVec};
11 use rustc_infer::infer::{InferCtxt, TyCtxtInferExt};
12 use rustc_middle::hir::place::PlaceBase as HirPlaceBase;
13 use rustc_middle::middle::region;
14 use rustc_middle::mir::*;
15 use rustc_middle::thir::{BindingMode, Expr, ExprId, LintLevel, PatKind, Thir};
16 use rustc_middle::ty::subst::Subst;
17 use rustc_middle::ty::{self, Ty, TyCtxt, TypeFoldable, TypeckResults};
18 use rustc_span::symbol::{kw, sym};
20 use rustc_target::spec::abi::Abi;
24 crate fn mir_built<'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);
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()));
38 tcx.alloc_steal_mir(body)
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 let body_owner_kind = tcx.hir().body_owner_kind(id);
45 let typeck_results = tcx.typeck_opt_const_arg(def);
47 // Ensure unsafeck is ran before we steal the THIR.
49 ty::WithOptConstParam { did, const_param_did: Some(const_param_did) } => {
50 tcx.ensure().thir_check_unsafety_for_const_arg((did, const_param_did))
52 ty::WithOptConstParam { did, const_param_did: None } => {
53 tcx.ensure().thir_check_unsafety(did)
57 // Figure out what primary body this item has.
58 let (body_id, return_ty_span, span_with_body) = match tcx.hir().get(id) {
59 Node::Expr(hir::Expr { kind: hir::ExprKind::Closure(_, decl, body_id, _, _), .. }) => {
60 (*body_id, decl.output.span(), None)
62 Node::Item(hir::Item {
63 kind: hir::ItemKind::Fn(hir::FnSig { decl, .. }, _, body_id),
67 | Node::ImplItem(hir::ImplItem {
68 kind: hir::ImplItemKind::Fn(hir::FnSig { decl, .. }, body_id),
72 | Node::TraitItem(hir::TraitItem {
73 kind: hir::TraitItemKind::Fn(hir::FnSig { decl, .. }, hir::TraitFn::Provided(body_id)),
77 // Use the `Span` of the `Item/ImplItem/TraitItem` as the body span,
78 // since the def span of a function does not include the body
79 (*body_id, decl.output.span(), Some(*span))
81 Node::Item(hir::Item {
82 kind: hir::ItemKind::Static(ty, _, body_id) | hir::ItemKind::Const(ty, body_id),
85 | Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Const(ty, body_id), .. })
86 | Node::TraitItem(hir::TraitItem {
87 kind: hir::TraitItemKind::Const(ty, Some(body_id)),
89 }) => (*body_id, ty.span, None),
90 Node::AnonConst(hir::AnonConst { body, hir_id, .. }) => {
91 (*body, tcx.hir().span(*hir_id), None)
94 _ => span_bug!(tcx.hir().span(id), "can't build MIR for {:?}", def.did),
97 // If we don't have a specialized span for the body, just use the
99 let span_with_body = span_with_body.unwrap_or_else(|| tcx.hir().span(id));
101 tcx.infer_ctxt().enter(|infcx| {
102 let body = if let Some(ErrorReported) = typeck_results.tainted_by_errors {
103 build::construct_error(&infcx, def, id, body_id, body_owner_kind)
104 } else if body_owner_kind.is_fn_or_closure() {
105 // fetch the fully liberated fn signature (that is, all bound
106 // types/lifetimes replaced)
107 let fn_sig = typeck_results.liberated_fn_sigs()[id];
108 let fn_def_id = tcx.hir().local_def_id(id);
110 let safety = match fn_sig.unsafety {
111 hir::Unsafety::Normal => Safety::Safe,
112 hir::Unsafety::Unsafe => Safety::FnUnsafe,
115 let body = tcx.hir().body(body_id);
116 let (thir, expr) = tcx.thir_body(def);
117 // We ran all queries that depended on THIR at the beginning
118 // of `mir_build`, so now we can steal it
119 let thir = thir.steal();
120 let ty = tcx.type_of(fn_def_id);
121 let mut abi = fn_sig.abi;
122 let implicit_argument = match ty.kind() {
124 // HACK(eddyb) Avoid having RustCall on closures,
125 // as it adds unnecessary (and wrong) auto-tupling.
127 vec![ArgInfo(liberated_closure_env_ty(tcx, id, body_id), None, None, None)]
129 ty::Generator(..) => {
130 let gen_ty = tcx.typeck_body(body_id).node_type(id);
132 // The resume argument may be missing, in that case we need to provide it here.
133 // It will always be `()` in this case.
134 if body.params.is_empty() {
136 ArgInfo(gen_ty, None, None, None),
137 ArgInfo(tcx.mk_unit(), None, None, None),
140 vec![ArgInfo(gen_ty, None, None, None)]
146 let explicit_arguments = body.params.iter().enumerate().map(|(index, arg)| {
147 let owner_id = tcx.hir().body_owner(body_id);
150 if let Some(ref fn_decl) = tcx.hir().fn_decl_by_hir_id(owner_id) {
151 opt_ty_info = fn_decl.inputs.get(index).map(|ty| ty.span);
152 self_arg = if index == 0 && fn_decl.implicit_self.has_implicit_self() {
153 match fn_decl.implicit_self {
154 hir::ImplicitSelfKind::Imm => Some(ImplicitSelfKind::Imm),
155 hir::ImplicitSelfKind::Mut => Some(ImplicitSelfKind::Mut),
156 hir::ImplicitSelfKind::ImmRef => Some(ImplicitSelfKind::ImmRef),
157 hir::ImplicitSelfKind::MutRef => Some(ImplicitSelfKind::MutRef),
168 // C-variadic fns also have a `VaList` input that's not listed in `fn_sig`
169 // (as it's created inside the body itself, not passed in from outside).
170 let ty = if fn_sig.c_variadic && index == fn_sig.inputs().len() {
171 let va_list_did = tcx.require_lang_item(LangItem::VaList, Some(arg.span));
173 tcx.type_of(va_list_did).subst(tcx, &[tcx.lifetimes.re_erased.into()])
175 fn_sig.inputs()[index]
178 ArgInfo(ty, opt_ty_info, Some(&arg), self_arg)
181 let arguments = implicit_argument.into_iter().chain(explicit_arguments);
183 let (yield_ty, return_ty) = if body.generator_kind.is_some() {
184 let gen_ty = tcx.typeck_body(body_id).node_type(id);
185 let gen_sig = match gen_ty.kind() {
186 ty::Generator(_, gen_substs, ..) => gen_substs.as_generator().sig(),
187 _ => span_bug!(tcx.hir().span(id), "generator w/o generator type: {:?}", ty),
189 (Some(gen_sig.yield_ty), gen_sig.return_ty)
191 (None, fn_sig.output())
194 let mut mir = build::construct_fn(
208 if yield_ty.is_some() {
209 mir.generator.as_mut().unwrap().yield_ty = yield_ty;
213 // Get the revealed type of this const. This is *not* the adjusted
214 // type of its body, which may be a subtype of this type. For
218 // static X: fn(&'static ()) = foo;
220 // The adjusted type of the body of X is `for<'a> fn(&'a ())` which
221 // is not the same as the type of X. We need the type of the return
222 // place to be the type of the constant because NLL typeck will
225 let return_ty = typeck_results.node_type(id);
227 let (thir, expr) = tcx.thir_body(def);
228 // We ran all queries that depended on THIR at the beginning
229 // of `mir_build`, so now we can steal it
230 let thir = thir.steal();
232 build::construct_const(&thir, &infcx, expr, def, id, return_ty, return_ty_span)
235 lints::check(tcx, &body);
237 // The borrow checker will replace all the regions here with its own
238 // inference variables. There's no point having non-erased regions here.
239 // The exception is `body.user_type_annotations`, which is used unmodified
240 // by borrow checking.
242 !(body.local_decls.has_free_regions()
243 || body.basic_blocks().has_free_regions()
244 || body.var_debug_info.has_free_regions()
245 || body.yield_ty().has_free_regions()),
246 "Unexpected free regions in MIR: {:?}",
254 ///////////////////////////////////////////////////////////////////////////
255 // BuildMir -- walks a crate, looking for fn items and methods to build MIR from
257 fn liberated_closure_env_ty(
259 closure_expr_id: hir::HirId,
260 body_id: hir::BodyId,
262 let closure_ty = tcx.typeck_body(body_id).node_type(closure_expr_id);
264 let (closure_def_id, closure_substs) = match *closure_ty.kind() {
265 ty::Closure(closure_def_id, closure_substs) => (closure_def_id, closure_substs),
266 _ => bug!("closure expr does not have closure type: {:?}", closure_ty),
270 tcx.mk_bound_variable_kinds(std::iter::once(ty::BoundVariableKind::Region(ty::BrEnv)));
272 ty::BoundRegion { var: ty::BoundVar::from_usize(bound_vars.len() - 1), kind: ty::BrEnv };
273 let env_region = ty::ReLateBound(ty::INNERMOST, br);
274 let closure_env_ty = tcx.closure_env_ty(closure_def_id, closure_substs, env_region).unwrap();
275 tcx.erase_late_bound_regions(ty::Binder::bind_with_vars(closure_env_ty, bound_vars))
278 #[derive(Debug, PartialEq, Eq)]
280 /// Evaluation is currently within a statement.
282 /// Examples include:
284 /// 2. `let _ = EXPR;`
285 /// 3. `let x = EXPR;`
287 /// If true, then statement discards result from evaluating
288 /// the expression (such as examples 1 and 2 above).
289 ignores_expr_result: bool,
292 /// Evaluation is currently within the tail expression of a block.
294 /// Example: `{ STMT_1; STMT_2; EXPR }`
296 /// If true, then the surrounding context of the block ignores
297 /// the result of evaluating the block's tail expression.
299 /// Example: `let _ = { STMT_1; EXPR };`
300 tail_result_is_ignored: bool,
302 /// `Span` of the tail expression.
306 /// Generic mark meaning that the block occurred as a subexpression
307 /// where the result might be used.
309 /// Examples: `foo(EXPR)`, `match EXPR { ... }`
314 fn is_tail_expr(&self) -> bool {
316 BlockFrame::TailExpr { .. } => true,
318 BlockFrame::Statement { .. } | BlockFrame::SubExpr => false,
321 fn is_statement(&self) -> bool {
323 BlockFrame::Statement { .. } => true,
325 BlockFrame::TailExpr { .. } | BlockFrame::SubExpr => false,
331 struct BlockContext(Vec<BlockFrame>);
333 struct Builder<'a, 'tcx> {
335 infcx: &'a InferCtxt<'a, 'tcx>,
336 typeck_results: &'tcx TypeckResults<'tcx>,
337 region_scope_tree: &'tcx region::ScopeTree,
338 param_env: ty::ParamEnv<'tcx>,
340 thir: &'a Thir<'tcx>,
345 check_overflow: bool,
348 generator_kind: Option<GeneratorKind>,
350 /// The current set of scopes, updated as we traverse;
351 /// see the `scope` module for more details.
352 scopes: scope::Scopes<'tcx>,
354 /// The block-context: each time we build the code within an thir::Block,
355 /// we push a frame here tracking whether we are building a statement or
356 /// if we are pushing the tail expression of the block. This is used to
357 /// embed information in generated temps about whether they were created
358 /// for a block tail expression or not.
360 /// It would be great if we could fold this into `self.scopes`
361 /// somehow, but right now I think that is very tightly tied to
362 /// the code generation in ways that we cannot (or should not)
363 /// start just throwing new entries onto that vector in order to
364 /// distinguish the context of EXPR1 from the context of EXPR2 in
365 /// `{ STMTS; EXPR1 } + EXPR2`.
366 block_context: BlockContext,
368 /// The current unsafe block in scope
369 in_scope_unsafe: Safety,
371 /// The vector of all scopes that we have created thus far;
372 /// we track this for debuginfo later.
373 source_scopes: IndexVec<SourceScope, SourceScopeData<'tcx>>,
374 source_scope: SourceScope,
376 /// The guard-context: each time we build the guard expression for
377 /// a match arm, we push onto this stack, and then pop when we
378 /// finish building it.
379 guard_context: Vec<GuardFrame>,
381 /// Maps `HirId`s of variable bindings to the `Local`s created for them.
382 /// (A match binding can have two locals; the 2nd is for the arm's guard.)
383 var_indices: HirIdMap<LocalsForNode>,
384 local_decls: IndexVec<Local, LocalDecl<'tcx>>,
385 canonical_user_type_annotations: ty::CanonicalUserTypeAnnotations<'tcx>,
386 upvar_mutbls: Vec<Mutability>,
387 unit_temp: Option<Place<'tcx>>,
389 var_debug_info: Vec<VarDebugInfo<'tcx>>,
392 impl<'a, 'tcx> Builder<'a, 'tcx> {
393 fn is_bound_var_in_guard(&self, id: hir::HirId) -> bool {
394 self.guard_context.iter().any(|frame| frame.locals.iter().any(|local| local.id == id))
397 fn var_local_id(&self, id: hir::HirId, for_guard: ForGuard) -> Local {
398 self.var_indices[&id].local_id(for_guard)
406 fn push(&mut self, bf: BlockFrame) {
409 fn pop(&mut self) -> Option<BlockFrame> {
413 /// Traverses the frames on the `BlockContext`, searching for either
414 /// the first block-tail expression frame with no intervening
417 /// Notably, this skips over `SubExpr` frames; this method is
418 /// meant to be used in the context of understanding the
419 /// relationship of a temp (created within some complicated
420 /// expression) with its containing expression, and whether the
421 /// value of that *containing expression* (not the temp!) is
423 fn currently_in_block_tail(&self) -> Option<BlockTailInfo> {
424 for bf in self.0.iter().rev() {
426 BlockFrame::SubExpr => continue,
427 BlockFrame::Statement { .. } => break,
428 &BlockFrame::TailExpr { tail_result_is_ignored, span } => {
429 return Some(BlockTailInfo { tail_result_is_ignored, span });
437 /// Looks at the topmost frame on the BlockContext and reports
438 /// whether its one that would discard a block tail result.
440 /// Unlike `currently_within_ignored_tail_expression`, this does
441 /// *not* skip over `SubExpr` frames: here, we want to know
442 /// whether the block result itself is discarded.
443 fn currently_ignores_tail_results(&self) -> bool {
444 match self.0.last() {
445 // no context: conservatively assume result is read
448 // sub-expression: block result feeds into some computation
449 Some(BlockFrame::SubExpr) => false,
451 // otherwise: use accumulated is_ignored state.
453 BlockFrame::TailExpr { tail_result_is_ignored: ignored, .. }
454 | BlockFrame::Statement { ignores_expr_result: ignored },
462 /// In the usual case, a `HirId` for an identifier maps to at most
463 /// one `Local` declaration.
466 /// The exceptional case is identifiers in a match arm's pattern
467 /// that are referenced in a guard of that match arm. For these,
468 /// we have `2` Locals.
470 /// * `for_arm_body` is the Local used in the arm body (which is
471 /// just like the `One` case above),
473 /// * `ref_for_guard` is the Local used in the arm's guard (which
474 /// is a reference to a temp that is an alias of
476 ForGuard { ref_for_guard: Local, for_arm_body: Local },
480 struct GuardFrameLocal {
484 impl GuardFrameLocal {
485 fn new(id: hir::HirId, _binding_mode: BindingMode) -> Self {
486 GuardFrameLocal { id }
492 /// These are the id's of names that are bound by patterns of the
493 /// arm of *this* guard.
495 /// (Frames higher up the stack will have the id's bound in arms
496 /// further out, such as in a case like:
499 /// P1(id1) if (... (match E2 { P2(id2) if ... => B2 })) => B1,
502 /// here, when building for FIXME.
503 locals: Vec<GuardFrameLocal>,
506 /// `ForGuard` indicates whether we are talking about:
507 /// 1. The variable for use outside of guard expressions, or
508 /// 2. The temp that holds reference to (1.), which is actually what the
509 /// guard expressions see.
510 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
517 fn local_id(&self, for_guard: ForGuard) -> Local {
518 match (self, for_guard) {
519 (&LocalsForNode::One(local_id), ForGuard::OutsideGuard)
521 &LocalsForNode::ForGuard { ref_for_guard: local_id, .. },
522 ForGuard::RefWithinGuard,
524 | (&LocalsForNode::ForGuard { for_arm_body: local_id, .. }, ForGuard::OutsideGuard) => {
528 (&LocalsForNode::One(_), ForGuard::RefWithinGuard) => {
529 bug!("anything with one local should never be within a guard.")
536 basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
539 rustc_index::newtype_index! {
540 struct ScopeId { .. }
543 ///////////////////////////////////////////////////////////////////////////
544 /// The `BlockAnd` "monad" packages up the new basic block along with a
545 /// produced value (sometimes just unit, of course). The `unpack!`
546 /// macro (and methods below) makes working with `BlockAnd` much more
549 #[must_use = "if you don't use one of these results, you're leaving a dangling edge"]
550 struct BlockAnd<T>(BasicBlock, T);
552 trait BlockAndExtension {
553 fn and<T>(self, v: T) -> BlockAnd<T>;
554 fn unit(self) -> BlockAnd<()>;
557 impl BlockAndExtension for BasicBlock {
558 fn and<T>(self, v: T) -> BlockAnd<T> {
562 fn unit(self) -> BlockAnd<()> {
567 /// Update a block pointer and return the value.
568 /// Use it like `let x = unpack!(block = self.foo(block, foo))`.
569 macro_rules! unpack {
570 ($x:ident = $c:expr) => {{
571 let BlockAnd(b, v) = $c;
577 let BlockAnd(b, ()) = $c;
582 ///////////////////////////////////////////////////////////////////////////
583 /// the main entry point for building MIR for a function
585 struct ArgInfo<'tcx>(
588 Option<&'tcx hir::Param<'tcx>>,
589 Option<ImplicitSelfKind>,
592 fn construct_fn<'tcx, A>(
594 infcx: &InferCtxt<'_, 'tcx>,
595 fn_def: ty::WithOptConstParam<LocalDefId>,
601 return_ty_span: Span,
602 body: &'tcx hir::Body<'tcx>,
604 span_with_body: Span,
607 A: Iterator<Item = ArgInfo<'tcx>>,
609 let arguments: Vec<_> = arguments.collect();
612 let span = tcx.hir().span(fn_id);
614 let mut builder = Builder::new(
627 let call_site_scope =
628 region::Scope { id: body.value.hir_id.local_id, data: region::ScopeData::CallSite };
630 region::Scope { id: body.value.hir_id.local_id, data: region::ScopeData::Arguments };
631 let source_info = builder.source_info(span);
632 let call_site_s = (call_site_scope, source_info);
633 unpack!(builder.in_scope(call_site_s, LintLevel::Inherited, |builder| {
634 let arg_scope_s = (arg_scope, source_info);
635 // Attribute epilogue to function's closing brace
636 let fn_end = span_with_body.shrink_to_hi();
638 unpack!(builder.in_breakable_scope(None, Place::return_place(), fn_end, |builder| {
639 Some(builder.in_scope(arg_scope_s, LintLevel::Inherited, |builder| {
640 builder.args_and_body(
642 fn_def.did.to_def_id(),
649 let source_info = builder.source_info(fn_end);
650 builder.cfg.terminate(return_block, source_info, TerminatorKind::Return);
651 builder.build_drop_trees();
655 let spread_arg = if abi == Abi::RustCall {
656 // RustCall pseudo-ABI untuples the last argument.
657 Some(Local::new(arguments.len()))
661 debug!("fn_id {:?} has attrs {:?}", fn_def, tcx.get_attrs(fn_def.did.to_def_id()));
663 let mut body = builder.finish();
664 body.spread_arg = spread_arg;
668 fn construct_const<'a, 'tcx>(
669 thir: &'a Thir<'tcx>,
670 infcx: &'a InferCtxt<'a, 'tcx>,
672 def: ty::WithOptConstParam<LocalDefId>,
678 let span = tcx.hir().span(hir_id);
679 let mut builder = Builder::new(
692 let mut block = START_BLOCK;
693 unpack!(block = builder.expr_into_dest(Place::return_place(), block, &thir[expr]));
695 let source_info = builder.source_info(span);
696 builder.cfg.terminate(block, source_info, TerminatorKind::Return);
698 builder.build_drop_trees();
703 /// Construct MIR for a item that has had errors in type checking.
705 /// This is required because we may still want to run MIR passes on an item
706 /// with type errors, but normal MIR construction can't handle that in general.
707 fn construct_error<'a, 'tcx>(
708 infcx: &'a InferCtxt<'a, 'tcx>,
709 def: ty::WithOptConstParam<LocalDefId>,
711 body_id: hir::BodyId,
712 body_owner_kind: hir::BodyOwnerKind,
715 let span = tcx.hir().span(hir_id);
716 let ty = tcx.ty_error();
717 let generator_kind = tcx.hir().body(body_id).generator_kind;
718 let num_params = match body_owner_kind {
719 hir::BodyOwnerKind::Fn => tcx.hir().fn_decl_by_hir_id(hir_id).unwrap().inputs.len(),
720 hir::BodyOwnerKind::Closure => {
721 if generator_kind.is_some() {
722 // Generators have an implicit `self` parameter *and* a possibly
723 // implicit resume parameter.
726 // The implicit self parameter adds another local in MIR.
727 1 + tcx.hir().fn_decl_by_hir_id(hir_id).unwrap().inputs.len()
730 hir::BodyOwnerKind::Const => 0,
731 hir::BodyOwnerKind::Static(_) => 0,
733 let mut cfg = CFG { basic_blocks: IndexVec::new() };
734 let mut source_scopes = IndexVec::new();
735 let mut local_decls = IndexVec::from_elem_n(LocalDecl::new(ty, span), 1);
737 cfg.start_new_block();
738 source_scopes.push(SourceScopeData {
742 inlined_parent_scope: None,
743 local_data: ClearCrossCrate::Set(SourceScopeLocalData {
745 safety: Safety::Safe,
748 let source_info = SourceInfo { span, scope: OUTERMOST_SOURCE_SCOPE };
750 // Some MIR passes will expect the number of parameters to match the
751 // function declaration.
752 for _ in 0..num_params {
753 local_decls.push(LocalDecl::with_source_info(ty, source_info));
755 cfg.terminate(START_BLOCK, source_info, TerminatorKind::Unreachable);
757 let mut body = Body::new(
758 MirSource::item(def.did.to_def_id()),
768 body.generator.as_mut().map(|gen| gen.yield_ty = Some(ty));
772 impl<'a, 'tcx> Builder<'a, 'tcx> {
774 thir: &'a Thir<'tcx>,
775 infcx: &'a InferCtxt<'a, 'tcx>,
776 def: ty::WithOptConstParam<LocalDefId>,
783 generator_kind: Option<GeneratorKind>,
784 ) -> Builder<'a, 'tcx> {
786 let attrs = tcx.hir().attrs(hir_id);
787 // Some functions always have overflow checks enabled,
788 // however, they may not get codegen'd, depending on
789 // the settings for the crate they are codegened in.
790 let mut check_overflow = tcx.sess.contains_name(attrs, sym::rustc_inherit_overflow_checks);
791 // Respect -C overflow-checks.
792 check_overflow |= tcx.sess.overflow_checks();
793 // Constants always need overflow checks.
794 check_overflow |= matches!(
795 tcx.hir().body_owner_kind(hir_id),
796 hir::BodyOwnerKind::Const | hir::BodyOwnerKind::Static(_)
799 let lint_level = LintLevel::Explicit(hir_id);
800 let mut builder = Builder {
804 typeck_results: tcx.typeck_opt_const_arg(def),
805 region_scope_tree: tcx.region_scope_tree(def.did),
806 param_env: tcx.param_env(def.did),
807 def_id: def.did.to_def_id(),
810 cfg: CFG { basic_blocks: IndexVec::new() },
814 scopes: scope::Scopes::new(),
815 block_context: BlockContext::new(),
816 source_scopes: IndexVec::new(),
817 source_scope: OUTERMOST_SOURCE_SCOPE,
818 guard_context: vec![],
819 in_scope_unsafe: safety,
820 local_decls: IndexVec::from_elem_n(LocalDecl::new(return_ty, return_span), 1),
821 canonical_user_type_annotations: IndexVec::new(),
822 upvar_mutbls: vec![],
823 var_indices: Default::default(),
825 var_debug_info: vec![],
828 assert_eq!(builder.cfg.start_new_block(), START_BLOCK);
830 builder.new_source_scope(span, lint_level, Some(safety)),
831 OUTERMOST_SOURCE_SCOPE
833 builder.source_scopes[OUTERMOST_SOURCE_SCOPE].parent_scope = None;
838 fn finish(self) -> Body<'tcx> {
839 for (index, block) in self.cfg.basic_blocks.iter().enumerate() {
840 if block.terminator.is_none() {
841 span_bug!(self.fn_span, "no terminator on block {:?}", index);
846 MirSource::item(self.def_id),
847 self.cfg.basic_blocks,
850 self.canonical_user_type_annotations,
860 mut block: BasicBlock,
862 arguments: &[ArgInfo<'tcx>],
863 argument_scope: region::Scope,
866 // Allocate locals for the function arguments
867 for &ArgInfo(ty, _, arg_opt, _) in arguments.iter() {
869 SourceInfo::outermost(arg_opt.map_or(self.fn_span, |arg| arg.pat.span));
870 let arg_local = self.local_decls.push(LocalDecl::with_source_info(ty, source_info));
872 // If this is a simple binding pattern, give debuginfo a nice name.
873 if let Some(arg) = arg_opt {
874 if let Some(ident) = arg.pat.simple_ident() {
875 self.var_debug_info.push(VarDebugInfo {
878 value: VarDebugInfoContents::Place(arg_local.into()),
885 let tcx_hir = tcx.hir();
886 let hir_typeck_results = self.typeck_results;
888 // In analyze_closure() in upvar.rs we gathered a list of upvars used by a
889 // indexed closure and we stored in a map called closure_min_captures in TypeckResults
890 // with the closure's DefId. Here, we run through that vec of UpvarIds for
891 // the given closure and use the necessary information to create upvar
892 // debuginfo and to fill `self.upvar_mutbls`.
893 if hir_typeck_results.closure_min_captures.get(&fn_def_id).is_some() {
894 let mut closure_env_projs = vec![];
895 let mut closure_ty = self.local_decls[ty::CAPTURE_STRUCT_LOCAL].ty;
896 if let ty::Ref(_, ty, _) = closure_ty.kind() {
897 closure_env_projs.push(ProjectionElem::Deref);
900 let upvar_substs = match closure_ty.kind() {
901 ty::Closure(_, substs) => ty::UpvarSubsts::Closure(substs),
902 ty::Generator(_, substs, _) => ty::UpvarSubsts::Generator(substs),
903 _ => span_bug!(self.fn_span, "upvars with non-closure env ty {:?}", closure_ty),
905 let capture_tys = upvar_substs.upvar_tys();
906 let captures_with_tys =
907 hir_typeck_results.closure_min_captures_flattened(fn_def_id).zip(capture_tys);
909 self.upvar_mutbls = captures_with_tys
911 .map(|(i, (captured_place, ty))| {
912 let capture = captured_place.info.capture_kind;
913 let var_id = match captured_place.place.base {
914 HirPlaceBase::Upvar(upvar_id) => upvar_id.var_path.hir_id,
915 _ => bug!("Expected an upvar"),
918 let mutability = captured_place.mutability;
920 // FIXME(project-rfc-2229#8): Store more precise information
921 let mut name = kw::Empty;
922 if let Some(Node::Binding(pat)) = tcx_hir.find(var_id) {
923 if let hir::PatKind::Binding(_, _, ident, _) = pat.kind {
928 let mut projs = closure_env_projs.clone();
929 projs.push(ProjectionElem::Field(Field::new(i), ty));
931 ty::UpvarCapture::ByValue(_) => {}
932 ty::UpvarCapture::ByRef(..) => {
933 projs.push(ProjectionElem::Deref);
937 self.var_debug_info.push(VarDebugInfo {
939 source_info: SourceInfo::outermost(tcx_hir.span(var_id)),
940 value: VarDebugInfoContents::Place(Place {
941 local: ty::CAPTURE_STRUCT_LOCAL,
942 projection: tcx.intern_place_elems(&projs),
951 let mut scope = None;
952 // Bind the argument patterns
953 for (index, arg_info) in arguments.iter().enumerate() {
954 // Function arguments always get the first Local indices after the return place
955 let local = Local::new(index + 1);
956 let place = Place::from(local);
957 let &ArgInfo(_, opt_ty_info, arg_opt, ref self_binding) = arg_info;
959 // Make sure we drop (parts of) the argument even when not matched on.
961 arg_opt.as_ref().map_or(expr.span, |arg| arg.pat.span),
967 if let Some(arg) = arg_opt {
968 let pat = match tcx.hir().get(arg.pat.hir_id) {
969 Node::Pat(pat) | Node::Binding(pat) => pat,
970 node => bug!("pattern became {:?}", node),
972 let pattern = pat_from_hir(tcx, self.param_env, self.typeck_results, pat);
973 let original_source_scope = self.source_scope;
974 let span = pattern.span;
975 self.set_correct_source_scope_for_arg(arg.hir_id, original_source_scope, span);
976 match *pattern.kind {
977 // Don't introduce extra copies for simple bindings
981 mode: BindingMode::ByValue,
985 self.local_decls[local].mutability = mutability;
986 self.local_decls[local].source_info.scope = self.source_scope;
987 self.local_decls[local].local_info = if let Some(kind) = self_binding {
988 Some(box LocalInfo::User(ClearCrossCrate::Set(
989 BindingForm::ImplicitSelf(*kind),
992 let binding_mode = ty::BindingMode::BindByValue(mutability);
993 Some(box LocalInfo::User(ClearCrossCrate::Set(BindingForm::Var(
997 opt_match_place: Some((Some(place), span)),
1002 self.var_indices.insert(var, LocalsForNode::One(local));
1005 scope = self.declare_bindings(
1009 matches::ArmHasGuard(false),
1010 Some((Some(&place), span)),
1012 let place_builder = PlaceBuilder::from(local);
1014 block = self.place_into_pattern(block, pattern, place_builder, false)
1018 self.source_scope = original_source_scope;
1022 // Enter the argument pattern bindings source scope, if it exists.
1023 if let Some(source_scope) = scope {
1024 self.source_scope = source_scope;
1027 self.expr_into_dest(Place::return_place(), block, &expr)
1030 fn set_correct_source_scope_for_arg(
1032 arg_hir_id: hir::HirId,
1033 original_source_scope: SourceScope,
1037 let current_root = tcx.maybe_lint_level_root_bounded(arg_hir_id, self.hir_id);
1038 let parent_root = tcx.maybe_lint_level_root_bounded(
1039 self.source_scopes[original_source_scope]
1042 .assert_crate_local()
1046 if current_root != parent_root {
1048 self.new_source_scope(pattern_span, LintLevel::Explicit(current_root), None);
1052 fn get_unit_temp(&mut self) -> Place<'tcx> {
1053 match self.unit_temp {
1056 let ty = self.tcx.mk_unit();
1057 let fn_span = self.fn_span;
1058 let tmp = self.temp(ty, fn_span);
1059 self.unit_temp = Some(tmp);
1066 ///////////////////////////////////////////////////////////////////////////
1067 // Builder methods are broken up into modules, depending on what kind
1068 // of thing is being lowered. Note that they use the `unpack` macro
1069 // above extensively.
1078 pub(crate) use expr::category::Category as ExprCategory;