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_attr::{self as attr, UnwindAttr};
6 use rustc_errors::ErrorReported;
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::{InferCtxt, TyCtxtInferExt};
13 use rustc_middle::hir::place::PlaceBase as HirPlaceBase;
14 use rustc_middle::middle::region;
15 use rustc_middle::mir::*;
16 use rustc_middle::thir::{BindingMode, Expr, ExprId, LintLevel, PatKind, Thir};
17 use rustc_middle::ty::subst::Subst;
18 use rustc_middle::ty::{self, Ty, TyCtxt, TypeFoldable, TypeckResults};
19 use rustc_span::symbol::{kw, sym};
21 use rustc_target::spec::abi::Abi;
22 use rustc_target::spec::PanicStrategy;
26 crate fn mir_built<'tcx>(
28 def: ty::WithOptConstParam<LocalDefId>,
29 ) -> &'tcx rustc_data_structures::steal::Steal<Body<'tcx>> {
30 if let Some(def) = def.try_upgrade(tcx) {
31 return tcx.mir_built(def);
34 let mut body = mir_build(tcx, def);
35 if def.const_param_did.is_some() {
36 assert!(matches!(body.source.instance, ty::InstanceDef::Item(_)));
37 body.source = MirSource::from_instance(ty::InstanceDef::Item(def.to_global()));
40 tcx.alloc_steal_mir(body)
43 /// Construct the MIR for a given `DefId`.
44 fn mir_build(tcx: TyCtxt<'_>, def: ty::WithOptConstParam<LocalDefId>) -> Body<'_> {
45 let id = tcx.hir().local_def_id_to_hir_id(def.did);
46 let body_owner_kind = tcx.hir().body_owner_kind(id);
47 let typeck_results = tcx.typeck_opt_const_arg(def);
49 // Ensure unsafeck is ran before we steal the THIR.
51 ty::WithOptConstParam { did, const_param_did: Some(const_param_did) } => {
52 tcx.ensure().thir_check_unsafety_for_const_arg((did, const_param_did))
54 ty::WithOptConstParam { did, const_param_did: None } => {
55 tcx.ensure().thir_check_unsafety(did)
59 // Figure out what primary body this item has.
60 let (body_id, return_ty_span, span_with_body) = match tcx.hir().get(id) {
61 Node::Expr(hir::Expr { kind: hir::ExprKind::Closure(_, decl, body_id, _, _), .. }) => {
62 (*body_id, decl.output.span(), None)
64 Node::Item(hir::Item {
65 kind: hir::ItemKind::Fn(hir::FnSig { decl, .. }, _, body_id),
69 | Node::ImplItem(hir::ImplItem {
70 kind: hir::ImplItemKind::Fn(hir::FnSig { decl, .. }, body_id),
74 | Node::TraitItem(hir::TraitItem {
75 kind: hir::TraitItemKind::Fn(hir::FnSig { decl, .. }, hir::TraitFn::Provided(body_id)),
79 // Use the `Span` of the `Item/ImplItem/TraitItem` as the body span,
80 // since the def span of a function does not include the body
81 (*body_id, decl.output.span(), Some(*span))
83 Node::Item(hir::Item {
84 kind: hir::ItemKind::Static(ty, _, body_id) | hir::ItemKind::Const(ty, body_id),
87 | Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Const(ty, body_id), .. })
88 | Node::TraitItem(hir::TraitItem {
89 kind: hir::TraitItemKind::Const(ty, Some(body_id)),
91 }) => (*body_id, ty.span, None),
92 Node::AnonConst(hir::AnonConst { body, hir_id, .. }) => {
93 (*body, tcx.hir().span(*hir_id), None)
96 _ => span_bug!(tcx.hir().span(id), "can't build MIR for {:?}", def.did),
99 // If we don't have a specialized span for the body, just use the
101 let span_with_body = span_with_body.unwrap_or_else(|| tcx.hir().span(id));
103 tcx.infer_ctxt().enter(|infcx| {
104 let body = if let Some(ErrorReported) = typeck_results.tainted_by_errors {
105 build::construct_error(&infcx, def, id, body_id, body_owner_kind)
106 } else if body_owner_kind.is_fn_or_closure() {
107 // fetch the fully liberated fn signature (that is, all bound
108 // types/lifetimes replaced)
109 let fn_sig = typeck_results.liberated_fn_sigs()[id];
110 let fn_def_id = tcx.hir().local_def_id(id);
112 let safety = match fn_sig.unsafety {
113 hir::Unsafety::Normal => Safety::Safe,
114 hir::Unsafety::Unsafe => Safety::FnUnsafe,
117 let body = tcx.hir().body(body_id);
118 let (thir, expr) = tcx.thir_body(def);
119 // We ran all queries that depended on THIR at the beginning
120 // of `mir_build`, so now we can steal it
121 let thir = thir.steal();
122 let ty = tcx.type_of(fn_def_id);
123 let mut abi = fn_sig.abi;
124 let implicit_argument = match ty.kind() {
126 // HACK(eddyb) Avoid having RustCall on closures,
127 // as it adds unnecessary (and wrong) auto-tupling.
129 vec![ArgInfo(liberated_closure_env_ty(tcx, id, body_id), None, None, None)]
131 ty::Generator(..) => {
132 let gen_ty = tcx.typeck_body(body_id).node_type(id);
134 // The resume argument may be missing, in that case we need to provide it here.
135 // It will always be `()` in this case.
136 if body.params.is_empty() {
138 ArgInfo(gen_ty, None, None, None),
139 ArgInfo(tcx.mk_unit(), None, None, None),
142 vec![ArgInfo(gen_ty, None, None, None)]
148 let explicit_arguments = body.params.iter().enumerate().map(|(index, arg)| {
149 let owner_id = tcx.hir().body_owner(body_id);
152 if let Some(ref fn_decl) = tcx.hir().fn_decl_by_hir_id(owner_id) {
153 opt_ty_info = fn_decl.inputs.get(index).map(|ty| ty.span);
154 self_arg = if index == 0 && fn_decl.implicit_self.has_implicit_self() {
155 match fn_decl.implicit_self {
156 hir::ImplicitSelfKind::Imm => Some(ImplicitSelfKind::Imm),
157 hir::ImplicitSelfKind::Mut => Some(ImplicitSelfKind::Mut),
158 hir::ImplicitSelfKind::ImmRef => Some(ImplicitSelfKind::ImmRef),
159 hir::ImplicitSelfKind::MutRef => Some(ImplicitSelfKind::MutRef),
170 // C-variadic fns also have a `VaList` input that's not listed in `fn_sig`
171 // (as it's created inside the body itself, not passed in from outside).
172 let ty = if fn_sig.c_variadic && index == fn_sig.inputs().len() {
173 let va_list_did = tcx.require_lang_item(LangItem::VaList, Some(arg.span));
175 tcx.type_of(va_list_did).subst(tcx, &[tcx.lifetimes.re_erased.into()])
177 fn_sig.inputs()[index]
180 ArgInfo(ty, opt_ty_info, Some(&arg), self_arg)
183 let arguments = implicit_argument.into_iter().chain(explicit_arguments);
185 let (yield_ty, return_ty) = if body.generator_kind.is_some() {
186 let gen_ty = tcx.typeck_body(body_id).node_type(id);
187 let gen_sig = match gen_ty.kind() {
188 ty::Generator(_, gen_substs, ..) => gen_substs.as_generator().sig(),
189 _ => span_bug!(tcx.hir().span(id), "generator w/o generator type: {:?}", ty),
191 (Some(gen_sig.yield_ty), gen_sig.return_ty)
193 (None, fn_sig.output())
196 let mut mir = build::construct_fn(
210 if yield_ty.is_some() {
211 mir.generator.as_mut().unwrap().yield_ty = yield_ty;
215 // Get the revealed type of this const. This is *not* the adjusted
216 // type of its body, which may be a subtype of this type. For
220 // static X: fn(&'static ()) = foo;
222 // The adjusted type of the body of X is `for<'a> fn(&'a ())` which
223 // is not the same as the type of X. We need the type of the return
224 // place to be the type of the constant because NLL typeck will
227 let return_ty = typeck_results.node_type(id);
229 let (thir, expr) = tcx.thir_body(def);
230 // We ran all queries that depended on THIR at the beginning
231 // of `mir_build`, so now we can steal it
232 let thir = thir.steal();
234 build::construct_const(&thir, &infcx, expr, def, id, return_ty, return_ty_span)
237 lints::check(tcx, &body);
239 // The borrow checker will replace all the regions here with its own
240 // inference variables. There's no point having non-erased regions here.
241 // The exception is `body.user_type_annotations`, which is used unmodified
242 // by borrow checking.
244 !(body.local_decls.has_free_regions()
245 || body.basic_blocks().has_free_regions()
246 || body.var_debug_info.has_free_regions()
247 || body.yield_ty().has_free_regions()),
248 "Unexpected free regions in MIR: {:?}",
256 ///////////////////////////////////////////////////////////////////////////
257 // BuildMir -- walks a crate, looking for fn items and methods to build MIR from
259 fn liberated_closure_env_ty(
261 closure_expr_id: hir::HirId,
262 body_id: hir::BodyId,
264 let closure_ty = tcx.typeck_body(body_id).node_type(closure_expr_id);
266 let (closure_def_id, closure_substs) = match *closure_ty.kind() {
267 ty::Closure(closure_def_id, closure_substs) => (closure_def_id, closure_substs),
268 _ => bug!("closure expr does not have closure type: {:?}", closure_ty),
272 tcx.mk_bound_variable_kinds(std::iter::once(ty::BoundVariableKind::Region(ty::BrEnv)));
274 ty::BoundRegion { var: ty::BoundVar::from_usize(bound_vars.len() - 1), kind: ty::BrEnv };
275 let env_region = ty::ReLateBound(ty::INNERMOST, br);
276 let closure_env_ty = tcx.closure_env_ty(closure_def_id, closure_substs, env_region).unwrap();
277 tcx.erase_late_bound_regions(ty::Binder::bind_with_vars(closure_env_ty, bound_vars))
280 #[derive(Debug, PartialEq, Eq)]
282 /// Evaluation is currently within a statement.
284 /// Examples include:
286 /// 2. `let _ = EXPR;`
287 /// 3. `let x = EXPR;`
289 /// If true, then statement discards result from evaluating
290 /// the expression (such as examples 1 and 2 above).
291 ignores_expr_result: bool,
294 /// Evaluation is currently within the tail expression of a block.
296 /// Example: `{ STMT_1; STMT_2; EXPR }`
298 /// If true, then the surrounding context of the block ignores
299 /// the result of evaluating the block's tail expression.
301 /// Example: `let _ = { STMT_1; EXPR };`
302 tail_result_is_ignored: bool,
304 /// `Span` of the tail expression.
308 /// Generic mark meaning that the block occurred as a subexpression
309 /// where the result might be used.
311 /// Examples: `foo(EXPR)`, `match EXPR { ... }`
316 fn is_tail_expr(&self) -> bool {
318 BlockFrame::TailExpr { .. } => true,
320 BlockFrame::Statement { .. } | BlockFrame::SubExpr => false,
323 fn is_statement(&self) -> bool {
325 BlockFrame::Statement { .. } => true,
327 BlockFrame::TailExpr { .. } | BlockFrame::SubExpr => false,
333 struct BlockContext(Vec<BlockFrame>);
335 struct Builder<'a, 'tcx> {
337 infcx: &'a InferCtxt<'a, 'tcx>,
338 typeck_results: &'tcx TypeckResults<'tcx>,
339 region_scope_tree: &'tcx region::ScopeTree,
340 param_env: ty::ParamEnv<'tcx>,
342 thir: &'a Thir<'tcx>,
347 check_overflow: bool,
350 generator_kind: Option<GeneratorKind>,
352 /// The current set of scopes, updated as we traverse;
353 /// see the `scope` module for more details.
354 scopes: scope::Scopes<'tcx>,
356 /// The block-context: each time we build the code within an thir::Block,
357 /// we push a frame here tracking whether we are building a statement or
358 /// if we are pushing the tail expression of the block. This is used to
359 /// embed information in generated temps about whether they were created
360 /// for a block tail expression or not.
362 /// It would be great if we could fold this into `self.scopes`
363 /// somehow, but right now I think that is very tightly tied to
364 /// the code generation in ways that we cannot (or should not)
365 /// start just throwing new entries onto that vector in order to
366 /// distinguish the context of EXPR1 from the context of EXPR2 in
367 /// `{ STMTS; EXPR1 } + EXPR2`.
368 block_context: BlockContext,
370 /// The current unsafe block in scope, even if it is hidden by
371 /// a `PushUnsafeBlock`.
372 unpushed_unsafe: Safety,
374 /// The number of `push_unsafe_block` levels in scope.
375 push_unsafe_count: usize,
377 /// The vector of all scopes that we have created thus far;
378 /// we track this for debuginfo later.
379 source_scopes: IndexVec<SourceScope, SourceScopeData<'tcx>>,
380 source_scope: SourceScope,
382 /// The guard-context: each time we build the guard expression for
383 /// a match arm, we push onto this stack, and then pop when we
384 /// finish building it.
385 guard_context: Vec<GuardFrame>,
387 /// Maps `HirId`s of variable bindings to the `Local`s created for them.
388 /// (A match binding can have two locals; the 2nd is for the arm's guard.)
389 var_indices: HirIdMap<LocalsForNode>,
390 local_decls: IndexVec<Local, LocalDecl<'tcx>>,
391 canonical_user_type_annotations: ty::CanonicalUserTypeAnnotations<'tcx>,
392 upvar_mutbls: Vec<Mutability>,
393 unit_temp: Option<Place<'tcx>>,
395 var_debug_info: Vec<VarDebugInfo<'tcx>>,
398 impl<'a, 'tcx> Builder<'a, 'tcx> {
399 fn is_bound_var_in_guard(&self, id: hir::HirId) -> bool {
400 self.guard_context.iter().any(|frame| frame.locals.iter().any(|local| local.id == id))
403 fn var_local_id(&self, id: hir::HirId, for_guard: ForGuard) -> Local {
404 self.var_indices[&id].local_id(for_guard)
412 fn push(&mut self, bf: BlockFrame) {
415 fn pop(&mut self) -> Option<BlockFrame> {
419 /// Traverses the frames on the `BlockContext`, searching for either
420 /// the first block-tail expression frame with no intervening
423 /// Notably, this skips over `SubExpr` frames; this method is
424 /// meant to be used in the context of understanding the
425 /// relationship of a temp (created within some complicated
426 /// expression) with its containing expression, and whether the
427 /// value of that *containing expression* (not the temp!) is
429 fn currently_in_block_tail(&self) -> Option<BlockTailInfo> {
430 for bf in self.0.iter().rev() {
432 BlockFrame::SubExpr => continue,
433 BlockFrame::Statement { .. } => break,
434 &BlockFrame::TailExpr { tail_result_is_ignored, span } => {
435 return Some(BlockTailInfo { tail_result_is_ignored, span });
443 /// Looks at the topmost frame on the BlockContext and reports
444 /// whether its one that would discard a block tail result.
446 /// Unlike `currently_within_ignored_tail_expression`, this does
447 /// *not* skip over `SubExpr` frames: here, we want to know
448 /// whether the block result itself is discarded.
449 fn currently_ignores_tail_results(&self) -> bool {
450 match self.0.last() {
451 // no context: conservatively assume result is read
454 // sub-expression: block result feeds into some computation
455 Some(BlockFrame::SubExpr) => false,
457 // otherwise: use accumulated is_ignored state.
459 BlockFrame::TailExpr { tail_result_is_ignored: ignored, .. }
460 | BlockFrame::Statement { ignores_expr_result: ignored },
468 /// In the usual case, a `HirId` for an identifier maps to at most
469 /// one `Local` declaration.
472 /// The exceptional case is identifiers in a match arm's pattern
473 /// that are referenced in a guard of that match arm. For these,
474 /// we have `2` Locals.
476 /// * `for_arm_body` is the Local used in the arm body (which is
477 /// just like the `One` case above),
479 /// * `ref_for_guard` is the Local used in the arm's guard (which
480 /// is a reference to a temp that is an alias of
482 ForGuard { ref_for_guard: Local, for_arm_body: Local },
486 struct GuardFrameLocal {
490 impl GuardFrameLocal {
491 fn new(id: hir::HirId, _binding_mode: BindingMode) -> Self {
492 GuardFrameLocal { id }
498 /// These are the id's of names that are bound by patterns of the
499 /// arm of *this* guard.
501 /// (Frames higher up the stack will have the id's bound in arms
502 /// further out, such as in a case like:
505 /// P1(id1) if (... (match E2 { P2(id2) if ... => B2 })) => B1,
508 /// here, when building for FIXME.
509 locals: Vec<GuardFrameLocal>,
512 /// `ForGuard` indicates whether we are talking about:
513 /// 1. The variable for use outside of guard expressions, or
514 /// 2. The temp that holds reference to (1.), which is actually what the
515 /// guard expressions see.
516 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
523 fn local_id(&self, for_guard: ForGuard) -> Local {
524 match (self, for_guard) {
525 (&LocalsForNode::One(local_id), ForGuard::OutsideGuard)
527 &LocalsForNode::ForGuard { ref_for_guard: local_id, .. },
528 ForGuard::RefWithinGuard,
530 | (&LocalsForNode::ForGuard { for_arm_body: local_id, .. }, ForGuard::OutsideGuard) => {
534 (&LocalsForNode::One(_), ForGuard::RefWithinGuard) => {
535 bug!("anything with one local should never be within a guard.")
542 basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
545 rustc_index::newtype_index! {
546 struct ScopeId { .. }
549 ///////////////////////////////////////////////////////////////////////////
550 /// The `BlockAnd` "monad" packages up the new basic block along with a
551 /// produced value (sometimes just unit, of course). The `unpack!`
552 /// macro (and methods below) makes working with `BlockAnd` much more
555 #[must_use = "if you don't use one of these results, you're leaving a dangling edge"]
556 struct BlockAnd<T>(BasicBlock, T);
558 trait BlockAndExtension {
559 fn and<T>(self, v: T) -> BlockAnd<T>;
560 fn unit(self) -> BlockAnd<()>;
563 impl BlockAndExtension for BasicBlock {
564 fn and<T>(self, v: T) -> BlockAnd<T> {
568 fn unit(self) -> BlockAnd<()> {
573 /// Update a block pointer and return the value.
574 /// Use it like `let x = unpack!(block = self.foo(block, foo))`.
575 macro_rules! unpack {
576 ($x:ident = $c:expr) => {{
577 let BlockAnd(b, v) = $c;
583 let BlockAnd(b, ()) = $c;
588 fn should_abort_on_panic(tcx: TyCtxt<'_>, fn_def_id: LocalDefId, abi: Abi) -> bool {
589 // Validate `#[unwind]` syntax regardless of platform-specific panic strategy.
590 let attrs = &tcx.get_attrs(fn_def_id.to_def_id());
591 let unwind_attr = attr::find_unwind_attr(&tcx.sess, attrs);
593 // We never unwind, so it's not relevant to stop an unwind.
594 if tcx.sess.panic_strategy() != PanicStrategy::Unwind {
599 // If an `#[unwind]` attribute was found, we should adhere to it.
600 Some(UnwindAttr::Allowed) => false,
601 Some(UnwindAttr::Aborts) => true,
602 // If no attribute was found and the panic strategy is `unwind`, then we should examine
603 // the function's ABI string to determine whether it should abort upon panic.
604 None if tcx.features().c_unwind => {
607 // In the case of ABI's that have an `-unwind` equivalent, check whether the ABI
608 // permits unwinding. If so, we should not abort. Otherwise, we should.
609 C { unwind } | Stdcall { unwind } | System { unwind } | Thiscall { unwind } => {
612 // Rust and `rust-call` functions are allowed to unwind, and should not abort.
613 Rust | RustCall => false,
614 // Other ABI's should abort.
627 | AvrNonBlockingInterrupt
632 | Unadjusted => true,
635 // If the `c_unwind` feature gate is not active, follow the behavior that was in place
636 // prior to #76570. This is a special case: some functions have a C ABI but are meant to
637 // unwind anyway. Don't stop them.
638 None => false, // FIXME(#58794); should be `!(abi == Abi::Rust || abi == Abi::RustCall)`
642 ///////////////////////////////////////////////////////////////////////////
643 /// the main entry point for building MIR for a function
645 struct ArgInfo<'tcx>(
648 Option<&'tcx hir::Param<'tcx>>,
649 Option<ImplicitSelfKind>,
652 fn construct_fn<'tcx, A>(
654 infcx: &InferCtxt<'_, 'tcx>,
655 fn_def: ty::WithOptConstParam<LocalDefId>,
661 return_ty_span: Span,
662 body: &'tcx hir::Body<'tcx>,
664 span_with_body: Span,
667 A: Iterator<Item = ArgInfo<'tcx>>,
669 let arguments: Vec<_> = arguments.collect();
672 let span = tcx.hir().span(fn_id);
674 let mut builder = Builder::new(
687 let call_site_scope =
688 region::Scope { id: body.value.hir_id.local_id, data: region::ScopeData::CallSite };
690 region::Scope { id: body.value.hir_id.local_id, data: region::ScopeData::Arguments };
691 let source_info = builder.source_info(span);
692 let call_site_s = (call_site_scope, source_info);
693 unpack!(builder.in_scope(call_site_s, LintLevel::Inherited, |builder| {
694 let arg_scope_s = (arg_scope, source_info);
695 // Attribute epilogue to function's closing brace
696 let fn_end = span_with_body.shrink_to_hi();
698 unpack!(builder.in_breakable_scope(None, Place::return_place(), fn_end, |builder| {
699 Some(builder.in_scope(arg_scope_s, LintLevel::Inherited, |builder| {
700 builder.args_and_body(
702 fn_def.did.to_def_id(),
709 let source_info = builder.source_info(fn_end);
710 builder.cfg.terminate(return_block, source_info, TerminatorKind::Return);
711 let should_abort = should_abort_on_panic(tcx, fn_def.did, abi);
712 builder.build_drop_trees(should_abort);
716 let spread_arg = if abi == Abi::RustCall {
717 // RustCall pseudo-ABI untuples the last argument.
718 Some(Local::new(arguments.len()))
722 debug!("fn_id {:?} has attrs {:?}", fn_def, tcx.get_attrs(fn_def.did.to_def_id()));
724 let mut body = builder.finish();
725 body.spread_arg = spread_arg;
729 fn construct_const<'a, 'tcx>(
730 thir: &'a Thir<'tcx>,
731 infcx: &'a InferCtxt<'a, 'tcx>,
733 def: ty::WithOptConstParam<LocalDefId>,
739 let span = tcx.hir().span(hir_id);
740 let mut builder = Builder::new(
753 let mut block = START_BLOCK;
754 unpack!(block = builder.expr_into_dest(Place::return_place(), block, &thir[expr]));
756 let source_info = builder.source_info(span);
757 builder.cfg.terminate(block, source_info, TerminatorKind::Return);
759 builder.build_drop_trees(false);
764 /// Construct MIR for a item that has had errors in type checking.
766 /// This is required because we may still want to run MIR passes on an item
767 /// with type errors, but normal MIR construction can't handle that in general.
768 fn construct_error<'a, 'tcx>(
769 infcx: &'a InferCtxt<'a, 'tcx>,
770 def: ty::WithOptConstParam<LocalDefId>,
772 body_id: hir::BodyId,
773 body_owner_kind: hir::BodyOwnerKind,
776 let span = tcx.hir().span(hir_id);
777 let ty = tcx.ty_error();
778 let generator_kind = tcx.hir().body(body_id).generator_kind;
779 let num_params = match body_owner_kind {
780 hir::BodyOwnerKind::Fn => tcx.hir().fn_decl_by_hir_id(hir_id).unwrap().inputs.len(),
781 hir::BodyOwnerKind::Closure => {
782 if generator_kind.is_some() {
783 // Generators have an implicit `self` parameter *and* a possibly
784 // implicit resume parameter.
787 // The implicit self parameter adds another local in MIR.
788 1 + tcx.hir().fn_decl_by_hir_id(hir_id).unwrap().inputs.len()
791 hir::BodyOwnerKind::Const => 0,
792 hir::BodyOwnerKind::Static(_) => 0,
794 let mut cfg = CFG { basic_blocks: IndexVec::new() };
795 let mut source_scopes = IndexVec::new();
796 let mut local_decls = IndexVec::from_elem_n(LocalDecl::new(ty, span), 1);
798 cfg.start_new_block();
799 source_scopes.push(SourceScopeData {
803 inlined_parent_scope: None,
804 local_data: ClearCrossCrate::Set(SourceScopeLocalData {
806 safety: Safety::Safe,
809 let source_info = SourceInfo { span, scope: OUTERMOST_SOURCE_SCOPE };
811 // Some MIR passes will expect the number of parameters to match the
812 // function declaration.
813 for _ in 0..num_params {
814 local_decls.push(LocalDecl::with_source_info(ty, source_info));
816 cfg.terminate(START_BLOCK, source_info, TerminatorKind::Unreachable);
818 let mut body = Body::new(
819 MirSource::item(def.did.to_def_id()),
829 body.generator.as_mut().map(|gen| gen.yield_ty = Some(ty));
833 impl<'a, 'tcx> Builder<'a, 'tcx> {
835 thir: &'a Thir<'tcx>,
836 infcx: &'a InferCtxt<'a, 'tcx>,
837 def: ty::WithOptConstParam<LocalDefId>,
844 generator_kind: Option<GeneratorKind>,
845 ) -> Builder<'a, 'tcx> {
847 let attrs = tcx.hir().attrs(hir_id);
848 // Some functions always have overflow checks enabled,
849 // however, they may not get codegen'd, depending on
850 // the settings for the crate they are codegened in.
851 let mut check_overflow = tcx.sess.contains_name(attrs, sym::rustc_inherit_overflow_checks);
852 // Respect -C overflow-checks.
853 check_overflow |= tcx.sess.overflow_checks();
854 // Constants always need overflow checks.
855 check_overflow |= matches!(
856 tcx.hir().body_owner_kind(hir_id),
857 hir::BodyOwnerKind::Const | hir::BodyOwnerKind::Static(_)
860 let lint_level = LintLevel::Explicit(hir_id);
861 let mut builder = Builder {
865 typeck_results: tcx.typeck_opt_const_arg(def),
866 region_scope_tree: tcx.region_scope_tree(def.did),
867 param_env: tcx.param_env(def.did),
868 def_id: def.did.to_def_id(),
871 cfg: CFG { basic_blocks: IndexVec::new() },
875 scopes: scope::Scopes::new(),
876 block_context: BlockContext::new(),
877 source_scopes: IndexVec::new(),
878 source_scope: OUTERMOST_SOURCE_SCOPE,
879 guard_context: vec![],
880 push_unsafe_count: 0,
881 unpushed_unsafe: safety,
882 local_decls: IndexVec::from_elem_n(LocalDecl::new(return_ty, return_span), 1),
883 canonical_user_type_annotations: IndexVec::new(),
884 upvar_mutbls: vec![],
885 var_indices: Default::default(),
887 var_debug_info: vec![],
890 assert_eq!(builder.cfg.start_new_block(), START_BLOCK);
892 builder.new_source_scope(span, lint_level, Some(safety)),
893 OUTERMOST_SOURCE_SCOPE
895 builder.source_scopes[OUTERMOST_SOURCE_SCOPE].parent_scope = None;
900 fn finish(self) -> Body<'tcx> {
901 for (index, block) in self.cfg.basic_blocks.iter().enumerate() {
902 if block.terminator.is_none() {
903 span_bug!(self.fn_span, "no terminator on block {:?}", index);
908 MirSource::item(self.def_id),
909 self.cfg.basic_blocks,
912 self.canonical_user_type_annotations,
922 mut block: BasicBlock,
924 arguments: &[ArgInfo<'tcx>],
925 argument_scope: region::Scope,
928 // Allocate locals for the function arguments
929 for &ArgInfo(ty, _, arg_opt, _) in arguments.iter() {
931 SourceInfo::outermost(arg_opt.map_or(self.fn_span, |arg| arg.pat.span));
932 let arg_local = self.local_decls.push(LocalDecl::with_source_info(ty, source_info));
934 // If this is a simple binding pattern, give debuginfo a nice name.
935 if let Some(arg) = arg_opt {
936 if let Some(ident) = arg.pat.simple_ident() {
937 self.var_debug_info.push(VarDebugInfo {
940 value: VarDebugInfoContents::Place(arg_local.into()),
947 let tcx_hir = tcx.hir();
948 let hir_typeck_results = self.typeck_results;
950 // In analyze_closure() in upvar.rs we gathered a list of upvars used by a
951 // indexed closure and we stored in a map called closure_min_captures in TypeckResults
952 // with the closure's DefId. Here, we run through that vec of UpvarIds for
953 // the given closure and use the necessary information to create upvar
954 // debuginfo and to fill `self.upvar_mutbls`.
955 if hir_typeck_results.closure_min_captures.get(&fn_def_id).is_some() {
956 let mut closure_env_projs = vec![];
957 let mut closure_ty = self.local_decls[ty::CAPTURE_STRUCT_LOCAL].ty;
958 if let ty::Ref(_, ty, _) = closure_ty.kind() {
959 closure_env_projs.push(ProjectionElem::Deref);
962 let upvar_substs = match closure_ty.kind() {
963 ty::Closure(_, substs) => ty::UpvarSubsts::Closure(substs),
964 ty::Generator(_, substs, _) => ty::UpvarSubsts::Generator(substs),
965 _ => span_bug!(self.fn_span, "upvars with non-closure env ty {:?}", closure_ty),
967 let capture_tys = upvar_substs.upvar_tys();
968 let captures_with_tys =
969 hir_typeck_results.closure_min_captures_flattened(fn_def_id).zip(capture_tys);
971 self.upvar_mutbls = captures_with_tys
973 .map(|(i, (captured_place, ty))| {
974 let capture = captured_place.info.capture_kind;
975 let var_id = match captured_place.place.base {
976 HirPlaceBase::Upvar(upvar_id) => upvar_id.var_path.hir_id,
977 _ => bug!("Expected an upvar"),
980 let mutability = captured_place.mutability;
982 // FIXME(project-rfc-2229#8): Store more precise information
983 let mut name = kw::Empty;
984 if let Some(Node::Binding(pat)) = tcx_hir.find(var_id) {
985 if let hir::PatKind::Binding(_, _, ident, _) = pat.kind {
990 let mut projs = closure_env_projs.clone();
991 projs.push(ProjectionElem::Field(Field::new(i), ty));
993 ty::UpvarCapture::ByValue(_) => {}
994 ty::UpvarCapture::ByRef(..) => {
995 projs.push(ProjectionElem::Deref);
999 self.var_debug_info.push(VarDebugInfo {
1001 source_info: SourceInfo::outermost(tcx_hir.span(var_id)),
1002 value: VarDebugInfoContents::Place(Place {
1003 local: ty::CAPTURE_STRUCT_LOCAL,
1004 projection: tcx.intern_place_elems(&projs),
1013 let mut scope = None;
1014 // Bind the argument patterns
1015 for (index, arg_info) in arguments.iter().enumerate() {
1016 // Function arguments always get the first Local indices after the return place
1017 let local = Local::new(index + 1);
1018 let place = Place::from(local);
1019 let &ArgInfo(_, opt_ty_info, arg_opt, ref self_binding) = arg_info;
1021 // Make sure we drop (parts of) the argument even when not matched on.
1023 arg_opt.as_ref().map_or(expr.span, |arg| arg.pat.span),
1029 if let Some(arg) = arg_opt {
1030 let pat = match tcx.hir().get(arg.pat.hir_id) {
1031 Node::Pat(pat) | Node::Binding(pat) => pat,
1032 node => bug!("pattern became {:?}", node),
1034 let pattern = pat_from_hir(tcx, self.param_env, self.typeck_results, pat);
1035 let original_source_scope = self.source_scope;
1036 let span = pattern.span;
1037 self.set_correct_source_scope_for_arg(arg.hir_id, original_source_scope, span);
1038 match *pattern.kind {
1039 // Don't introduce extra copies for simple bindings
1043 mode: BindingMode::ByValue,
1047 self.local_decls[local].mutability = mutability;
1048 self.local_decls[local].source_info.scope = self.source_scope;
1049 self.local_decls[local].local_info = if let Some(kind) = self_binding {
1050 Some(box LocalInfo::User(ClearCrossCrate::Set(
1051 BindingForm::ImplicitSelf(*kind),
1054 let binding_mode = ty::BindingMode::BindByValue(mutability);
1055 Some(box LocalInfo::User(ClearCrossCrate::Set(BindingForm::Var(
1059 opt_match_place: Some((Some(place), span)),
1064 self.var_indices.insert(var, LocalsForNode::One(local));
1067 scope = self.declare_bindings(
1071 matches::ArmHasGuard(false),
1072 Some((Some(&place), span)),
1074 let place_builder = PlaceBuilder::from(local);
1076 block = self.place_into_pattern(block, pattern, place_builder, false)
1080 self.source_scope = original_source_scope;
1084 // Enter the argument pattern bindings source scope, if it exists.
1085 if let Some(source_scope) = scope {
1086 self.source_scope = source_scope;
1089 self.expr_into_dest(Place::return_place(), block, &expr)
1092 fn set_correct_source_scope_for_arg(
1094 arg_hir_id: hir::HirId,
1095 original_source_scope: SourceScope,
1099 let current_root = tcx.maybe_lint_level_root_bounded(arg_hir_id, self.hir_id);
1100 let parent_root = tcx.maybe_lint_level_root_bounded(
1101 self.source_scopes[original_source_scope]
1104 .assert_crate_local()
1108 if current_root != parent_root {
1110 self.new_source_scope(pattern_span, LintLevel::Explicit(current_root), None);
1114 fn get_unit_temp(&mut self) -> Place<'tcx> {
1115 match self.unit_temp {
1118 let ty = self.tcx.mk_unit();
1119 let fn_span = self.fn_span;
1120 let tmp = self.temp(ty, fn_span);
1121 self.unit_temp = Some(tmp);
1128 ///////////////////////////////////////////////////////////////////////////
1129 // Builder methods are broken up into modules, depending on what kind
1130 // of thing is being lowered. Note that they use the `unpack` macro
1131 // above extensively.