2 use crate::build::expr::as_place::PlaceBuilder;
3 use crate::build::scope::DropKind;
4 use crate::thir::{build_thir, BindingMode, Expr, ExprId, LintLevel, Pat, PatKind, Thir};
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::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;
21 use rustc_target::spec::PanicStrategy;
25 crate fn mir_built<'tcx>(
27 def: ty::WithOptConstParam<LocalDefId>,
28 ) -> &'tcx rustc_data_structures::steal::Steal<Body<'tcx>> {
29 if let Some(def) = def.try_upgrade(tcx) {
30 return tcx.mir_built(def);
33 let mut body = mir_build(tcx, def);
34 if def.const_param_did.is_some() {
35 assert!(matches!(body.source.instance, ty::InstanceDef::Item(_)));
36 body.source = MirSource::from_instance(ty::InstanceDef::Item(def.to_global()));
39 tcx.alloc_steal_mir(body)
42 /// Construct the MIR for a given `DefId`.
43 fn mir_build(tcx: TyCtxt<'_>, def: ty::WithOptConstParam<LocalDefId>) -> Body<'_> {
44 let id = tcx.hir().local_def_id_to_hir_id(def.did);
45 let body_owner_kind = tcx.hir().body_owner_kind(id);
46 let typeck_results = tcx.typeck_opt_const_arg(def);
48 // Figure out what primary body this item has.
49 let (body_id, return_ty_span, span_with_body) = match tcx.hir().get(id) {
50 Node::Expr(hir::Expr { kind: hir::ExprKind::Closure(_, decl, body_id, _, _), .. }) => {
51 (*body_id, decl.output.span(), None)
53 Node::Item(hir::Item {
54 kind: hir::ItemKind::Fn(hir::FnSig { decl, .. }, _, body_id),
58 | Node::ImplItem(hir::ImplItem {
59 kind: hir::ImplItemKind::Fn(hir::FnSig { decl, .. }, body_id),
63 | Node::TraitItem(hir::TraitItem {
64 kind: hir::TraitItemKind::Fn(hir::FnSig { decl, .. }, hir::TraitFn::Provided(body_id)),
68 // Use the `Span` of the `Item/ImplItem/TraitItem` as the body span,
69 // since the def span of a function does not include the body
70 (*body_id, decl.output.span(), Some(*span))
72 Node::Item(hir::Item {
73 kind: hir::ItemKind::Static(ty, _, body_id) | hir::ItemKind::Const(ty, body_id),
76 | Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Const(ty, body_id), .. })
77 | Node::TraitItem(hir::TraitItem {
78 kind: hir::TraitItemKind::Const(ty, Some(body_id)),
80 }) => (*body_id, ty.span, None),
81 Node::AnonConst(hir::AnonConst { body, hir_id, .. }) => {
82 (*body, tcx.hir().span(*hir_id), None)
85 _ => span_bug!(tcx.hir().span(id), "can't build MIR for {:?}", def.did),
88 // If we don't have a specialized span for the body, just use the
90 let span_with_body = span_with_body.unwrap_or_else(|| tcx.hir().span(id));
92 tcx.infer_ctxt().enter(|infcx| {
93 let body = if let Some(ErrorReported) = typeck_results.tainted_by_errors {
94 build::construct_error(&infcx, def, id, body_id, body_owner_kind)
95 } else if body_owner_kind.is_fn_or_closure() {
96 // fetch the fully liberated fn signature (that is, all bound
97 // types/lifetimes replaced)
98 let fn_sig = typeck_results.liberated_fn_sigs()[id];
99 let fn_def_id = tcx.hir().local_def_id(id);
101 let safety = match fn_sig.unsafety {
102 hir::Unsafety::Normal => Safety::Safe,
103 hir::Unsafety::Unsafe => Safety::FnUnsafe,
106 let body = tcx.hir().body(body_id);
107 let (thir, expr) = build_thir(tcx, def, &body.value);
108 let ty = tcx.type_of(fn_def_id);
109 let mut abi = fn_sig.abi;
110 let implicit_argument = match ty.kind() {
112 // HACK(eddyb) Avoid having RustCall on closures,
113 // as it adds unnecessary (and wrong) auto-tupling.
115 vec![ArgInfo(liberated_closure_env_ty(tcx, id, body_id), None, None, None)]
117 ty::Generator(..) => {
118 let gen_ty = tcx.typeck_body(body_id).node_type(id);
120 // The resume argument may be missing, in that case we need to provide it here.
121 // It will always be `()` in this case.
122 if body.params.is_empty() {
124 ArgInfo(gen_ty, None, None, None),
125 ArgInfo(tcx.mk_unit(), None, None, None),
128 vec![ArgInfo(gen_ty, None, None, None)]
134 let explicit_arguments = body.params.iter().enumerate().map(|(index, arg)| {
135 let owner_id = tcx.hir().body_owner(body_id);
138 if let Some(ref fn_decl) = tcx.hir().fn_decl_by_hir_id(owner_id) {
139 opt_ty_info = fn_decl.inputs.get(index).map(|ty| ty.span);
140 self_arg = if index == 0 && fn_decl.implicit_self.has_implicit_self() {
141 match fn_decl.implicit_self {
142 hir::ImplicitSelfKind::Imm => Some(ImplicitSelfKind::Imm),
143 hir::ImplicitSelfKind::Mut => Some(ImplicitSelfKind::Mut),
144 hir::ImplicitSelfKind::ImmRef => Some(ImplicitSelfKind::ImmRef),
145 hir::ImplicitSelfKind::MutRef => Some(ImplicitSelfKind::MutRef),
156 // C-variadic fns also have a `VaList` input that's not listed in `fn_sig`
157 // (as it's created inside the body itself, not passed in from outside).
158 let ty = if fn_sig.c_variadic && index == fn_sig.inputs().len() {
159 let va_list_did = tcx.require_lang_item(LangItem::VaList, Some(arg.span));
161 tcx.type_of(va_list_did).subst(tcx, &[tcx.lifetimes.re_erased.into()])
163 fn_sig.inputs()[index]
166 ArgInfo(ty, opt_ty_info, Some(&arg), self_arg)
169 let arguments = implicit_argument.into_iter().chain(explicit_arguments);
171 let (yield_ty, return_ty) = if body.generator_kind.is_some() {
172 let gen_ty = tcx.typeck_body(body_id).node_type(id);
173 let gen_sig = match gen_ty.kind() {
174 ty::Generator(_, gen_substs, ..) => gen_substs.as_generator().sig(),
175 _ => span_bug!(tcx.hir().span(id), "generator w/o generator type: {:?}", ty),
177 (Some(gen_sig.yield_ty), gen_sig.return_ty)
179 (None, fn_sig.output())
182 let mut mir = build::construct_fn(
196 if yield_ty.is_some() {
197 mir.generator.as_mut().unwrap().yield_ty = yield_ty;
201 // Get the revealed type of this const. This is *not* the adjusted
202 // type of its body, which may be a subtype of this type. For
206 // static X: fn(&'static ()) = foo;
208 // The adjusted type of the body of X is `for<'a> fn(&'a ())` which
209 // is not the same as the type of X. We need the type of the return
210 // place to be the type of the constant because NLL typeck will
213 let return_ty = typeck_results.node_type(id);
215 let ast_expr = &tcx.hir().body(body_id).value;
216 let (thir, expr) = build_thir(tcx, def, ast_expr);
218 build::construct_const(&thir, &infcx, expr, def, id, return_ty, return_ty_span)
221 lints::check(tcx, &body);
223 // The borrow checker will replace all the regions here with its own
224 // inference variables. There's no point having non-erased regions here.
225 // The exception is `body.user_type_annotations`, which is used unmodified
226 // by borrow checking.
228 !(body.local_decls.has_free_regions()
229 || body.basic_blocks().has_free_regions()
230 || body.var_debug_info.has_free_regions()
231 || body.yield_ty().has_free_regions()),
232 "Unexpected free regions in MIR: {:?}",
240 ///////////////////////////////////////////////////////////////////////////
241 // BuildMir -- walks a crate, looking for fn items and methods to build MIR from
243 fn liberated_closure_env_ty(
245 closure_expr_id: hir::HirId,
246 body_id: hir::BodyId,
248 let closure_ty = tcx.typeck_body(body_id).node_type(closure_expr_id);
250 let (closure_def_id, closure_substs) = match *closure_ty.kind() {
251 ty::Closure(closure_def_id, closure_substs) => (closure_def_id, closure_substs),
252 _ => bug!("closure expr does not have closure type: {:?}", closure_ty),
256 tcx.mk_bound_variable_kinds(std::iter::once(ty::BoundVariableKind::Region(ty::BrEnv)));
258 ty::BoundRegion { var: ty::BoundVar::from_usize(bound_vars.len() - 1), kind: ty::BrEnv };
259 let env_region = ty::ReLateBound(ty::INNERMOST, br);
260 let closure_env_ty = tcx.closure_env_ty(closure_def_id, closure_substs, env_region).unwrap();
261 tcx.erase_late_bound_regions(ty::Binder::bind_with_vars(closure_env_ty, bound_vars))
264 #[derive(Debug, PartialEq, Eq)]
266 /// Evaluation is currently within a statement.
268 /// Examples include:
270 /// 2. `let _ = EXPR;`
271 /// 3. `let x = EXPR;`
273 /// If true, then statement discards result from evaluating
274 /// the expression (such as examples 1 and 2 above).
275 ignores_expr_result: bool,
278 /// Evaluation is currently within the tail expression of a block.
280 /// Example: `{ STMT_1; STMT_2; EXPR }`
282 /// If true, then the surrounding context of the block ignores
283 /// the result of evaluating the block's tail expression.
285 /// Example: `let _ = { STMT_1; EXPR };`
286 tail_result_is_ignored: bool,
288 /// `Span` of the tail expression.
292 /// Generic mark meaning that the block occurred as a subexpression
293 /// where the result might be used.
295 /// Examples: `foo(EXPR)`, `match EXPR { ... }`
300 fn is_tail_expr(&self) -> bool {
302 BlockFrame::TailExpr { .. } => true,
304 BlockFrame::Statement { .. } | BlockFrame::SubExpr => false,
307 fn is_statement(&self) -> bool {
309 BlockFrame::Statement { .. } => true,
311 BlockFrame::TailExpr { .. } | BlockFrame::SubExpr => false,
317 struct BlockContext(Vec<BlockFrame>);
319 struct Builder<'a, 'tcx> {
321 infcx: &'a InferCtxt<'a, 'tcx>,
322 typeck_results: &'tcx TypeckResults<'tcx>,
323 region_scope_tree: &'tcx region::ScopeTree,
324 param_env: ty::ParamEnv<'tcx>,
326 thir: &'a Thir<'tcx>,
331 check_overflow: bool,
334 generator_kind: Option<GeneratorKind>,
336 /// The current set of scopes, updated as we traverse;
337 /// see the `scope` module for more details.
338 scopes: scope::Scopes<'tcx>,
340 /// The block-context: each time we build the code within an thir::Block,
341 /// we push a frame here tracking whether we are building a statement or
342 /// if we are pushing the tail expression of the block. This is used to
343 /// embed information in generated temps about whether they were created
344 /// for a block tail expression or not.
346 /// It would be great if we could fold this into `self.scopes`
347 /// somehow, but right now I think that is very tightly tied to
348 /// the code generation in ways that we cannot (or should not)
349 /// start just throwing new entries onto that vector in order to
350 /// distinguish the context of EXPR1 from the context of EXPR2 in
351 /// `{ STMTS; EXPR1 } + EXPR2`.
352 block_context: BlockContext,
354 /// The current unsafe block in scope, even if it is hidden by
355 /// a `PushUnsafeBlock`.
356 unpushed_unsafe: Safety,
358 /// The number of `push_unsafe_block` levels in scope.
359 push_unsafe_count: usize,
361 /// The vector of all scopes that we have created thus far;
362 /// we track this for debuginfo later.
363 source_scopes: IndexVec<SourceScope, SourceScopeData<'tcx>>,
364 source_scope: SourceScope,
366 /// The guard-context: each time we build the guard expression for
367 /// a match arm, we push onto this stack, and then pop when we
368 /// finish building it.
369 guard_context: Vec<GuardFrame>,
371 /// Maps `HirId`s of variable bindings to the `Local`s created for them.
372 /// (A match binding can have two locals; the 2nd is for the arm's guard.)
373 var_indices: HirIdMap<LocalsForNode>,
374 local_decls: IndexVec<Local, LocalDecl<'tcx>>,
375 canonical_user_type_annotations: ty::CanonicalUserTypeAnnotations<'tcx>,
376 upvar_mutbls: Vec<Mutability>,
377 unit_temp: Option<Place<'tcx>>,
379 var_debug_info: Vec<VarDebugInfo<'tcx>>,
382 impl<'a, 'tcx> Builder<'a, 'tcx> {
383 fn is_bound_var_in_guard(&self, id: hir::HirId) -> bool {
384 self.guard_context.iter().any(|frame| frame.locals.iter().any(|local| local.id == id))
387 fn var_local_id(&self, id: hir::HirId, for_guard: ForGuard) -> Local {
388 self.var_indices[&id].local_id(for_guard)
396 fn push(&mut self, bf: BlockFrame) {
399 fn pop(&mut self) -> Option<BlockFrame> {
403 /// Traverses the frames on the `BlockContext`, searching for either
404 /// the first block-tail expression frame with no intervening
407 /// Notably, this skips over `SubExpr` frames; this method is
408 /// meant to be used in the context of understanding the
409 /// relationship of a temp (created within some complicated
410 /// expression) with its containing expression, and whether the
411 /// value of that *containing expression* (not the temp!) is
413 fn currently_in_block_tail(&self) -> Option<BlockTailInfo> {
414 for bf in self.0.iter().rev() {
416 BlockFrame::SubExpr => continue,
417 BlockFrame::Statement { .. } => break,
418 &BlockFrame::TailExpr { tail_result_is_ignored, span } => {
419 return Some(BlockTailInfo { tail_result_is_ignored, span });
427 /// Looks at the topmost frame on the BlockContext and reports
428 /// whether its one that would discard a block tail result.
430 /// Unlike `currently_within_ignored_tail_expression`, this does
431 /// *not* skip over `SubExpr` frames: here, we want to know
432 /// whether the block result itself is discarded.
433 fn currently_ignores_tail_results(&self) -> bool {
434 match self.0.last() {
435 // no context: conservatively assume result is read
438 // sub-expression: block result feeds into some computation
439 Some(BlockFrame::SubExpr) => false,
441 // otherwise: use accumulated is_ignored state.
443 BlockFrame::TailExpr { tail_result_is_ignored: ignored, .. }
444 | BlockFrame::Statement { ignores_expr_result: ignored },
452 /// In the usual case, a `HirId` for an identifier maps to at most
453 /// one `Local` declaration.
456 /// The exceptional case is identifiers in a match arm's pattern
457 /// that are referenced in a guard of that match arm. For these,
458 /// we have `2` Locals.
460 /// * `for_arm_body` is the Local used in the arm body (which is
461 /// just like the `One` case above),
463 /// * `ref_for_guard` is the Local used in the arm's guard (which
464 /// is a reference to a temp that is an alias of
466 ForGuard { ref_for_guard: Local, for_arm_body: Local },
470 struct GuardFrameLocal {
474 impl GuardFrameLocal {
475 fn new(id: hir::HirId, _binding_mode: BindingMode) -> Self {
476 GuardFrameLocal { id }
482 /// These are the id's of names that are bound by patterns of the
483 /// arm of *this* guard.
485 /// (Frames higher up the stack will have the id's bound in arms
486 /// further out, such as in a case like:
489 /// P1(id1) if (... (match E2 { P2(id2) if ... => B2 })) => B1,
492 /// here, when building for FIXME.
493 locals: Vec<GuardFrameLocal>,
496 /// `ForGuard` indicates whether we are talking about:
497 /// 1. The variable for use outside of guard expressions, or
498 /// 2. The temp that holds reference to (1.), which is actually what the
499 /// guard expressions see.
500 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
507 fn local_id(&self, for_guard: ForGuard) -> Local {
508 match (self, for_guard) {
509 (&LocalsForNode::One(local_id), ForGuard::OutsideGuard)
511 &LocalsForNode::ForGuard { ref_for_guard: local_id, .. },
512 ForGuard::RefWithinGuard,
514 | (&LocalsForNode::ForGuard { for_arm_body: local_id, .. }, ForGuard::OutsideGuard) => {
518 (&LocalsForNode::One(_), ForGuard::RefWithinGuard) => {
519 bug!("anything with one local should never be within a guard.")
526 basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
529 rustc_index::newtype_index! {
530 struct ScopeId { .. }
533 ///////////////////////////////////////////////////////////////////////////
534 /// The `BlockAnd` "monad" packages up the new basic block along with a
535 /// produced value (sometimes just unit, of course). The `unpack!`
536 /// macro (and methods below) makes working with `BlockAnd` much more
539 #[must_use = "if you don't use one of these results, you're leaving a dangling edge"]
540 struct BlockAnd<T>(BasicBlock, T);
542 trait BlockAndExtension {
543 fn and<T>(self, v: T) -> BlockAnd<T>;
544 fn unit(self) -> BlockAnd<()>;
547 impl BlockAndExtension for BasicBlock {
548 fn and<T>(self, v: T) -> BlockAnd<T> {
552 fn unit(self) -> BlockAnd<()> {
557 /// Update a block pointer and return the value.
558 /// Use it like `let x = unpack!(block = self.foo(block, foo))`.
559 macro_rules! unpack {
560 ($x:ident = $c:expr) => {{
561 let BlockAnd(b, v) = $c;
567 let BlockAnd(b, ()) = $c;
572 fn should_abort_on_panic(tcx: TyCtxt<'_>, fn_def_id: LocalDefId, abi: Abi) -> bool {
573 // Validate `#[unwind]` syntax regardless of platform-specific panic strategy.
574 let attrs = &tcx.get_attrs(fn_def_id.to_def_id());
575 let unwind_attr = attr::find_unwind_attr(&tcx.sess, attrs);
577 // We never unwind, so it's not relevant to stop an unwind.
578 if tcx.sess.panic_strategy() != PanicStrategy::Unwind {
583 // If an `#[unwind]` attribute was found, we should adhere to it.
584 Some(UnwindAttr::Allowed) => false,
585 Some(UnwindAttr::Aborts) => true,
586 // If no attribute was found and the panic strategy is `unwind`, then we should examine
587 // the function's ABI string to determine whether it should abort upon panic.
588 None if tcx.features().c_unwind => {
591 // In the case of ABI's that have an `-unwind` equivalent, check whether the ABI
592 // permits unwinding. If so, we should not abort. Otherwise, we should.
593 C { unwind } | Stdcall { unwind } | System { unwind } | Thiscall { unwind } => {
596 // Rust and `rust-call` functions are allowed to unwind, and should not abort.
597 Rust | RustCall => false,
598 // Other ABI's should abort.
611 | AvrNonBlockingInterrupt
616 | Unadjusted => true,
619 // If the `c_unwind` feature gate is not active, follow the behavior that was in place
620 // prior to #76570. This is a special case: some functions have a C ABI but are meant to
621 // unwind anyway. Don't stop them.
622 None => false, // FIXME(#58794); should be `!(abi == Abi::Rust || abi == Abi::RustCall)`
626 ///////////////////////////////////////////////////////////////////////////
627 /// the main entry point for building MIR for a function
629 struct ArgInfo<'tcx>(
632 Option<&'tcx hir::Param<'tcx>>,
633 Option<ImplicitSelfKind>,
636 fn construct_fn<'tcx, A>(
638 infcx: &InferCtxt<'_, 'tcx>,
639 fn_def: ty::WithOptConstParam<LocalDefId>,
645 return_ty_span: Span,
646 body: &'tcx hir::Body<'tcx>,
648 span_with_body: Span,
651 A: Iterator<Item = ArgInfo<'tcx>>,
653 let arguments: Vec<_> = arguments.collect();
656 let span = tcx.hir().span(fn_id);
658 let mut builder = Builder::new(
671 let call_site_scope =
672 region::Scope { id: body.value.hir_id.local_id, data: region::ScopeData::CallSite };
674 region::Scope { id: body.value.hir_id.local_id, data: region::ScopeData::Arguments };
675 let source_info = builder.source_info(span);
676 let call_site_s = (call_site_scope, source_info);
677 unpack!(builder.in_scope(call_site_s, LintLevel::Inherited, |builder| {
678 let arg_scope_s = (arg_scope, source_info);
679 // Attribute epilogue to function's closing brace
680 let fn_end = span_with_body.shrink_to_hi();
682 unpack!(builder.in_breakable_scope(None, Place::return_place(), fn_end, |builder| {
683 Some(builder.in_scope(arg_scope_s, LintLevel::Inherited, |builder| {
684 builder.args_and_body(
686 fn_def.did.to_def_id(),
693 let source_info = builder.source_info(fn_end);
694 builder.cfg.terminate(return_block, source_info, TerminatorKind::Return);
695 let should_abort = should_abort_on_panic(tcx, fn_def.did, abi);
696 builder.build_drop_trees(should_abort);
700 let spread_arg = if abi == Abi::RustCall {
701 // RustCall pseudo-ABI untuples the last argument.
702 Some(Local::new(arguments.len()))
706 debug!("fn_id {:?} has attrs {:?}", fn_def, tcx.get_attrs(fn_def.did.to_def_id()));
708 let mut body = builder.finish();
709 body.spread_arg = spread_arg;
713 fn construct_const<'a, 'tcx>(
714 thir: &'a Thir<'tcx>,
715 infcx: &'a InferCtxt<'a, 'tcx>,
717 def: ty::WithOptConstParam<LocalDefId>,
723 let span = tcx.hir().span(hir_id);
724 let mut builder = Builder::new(
737 let mut block = START_BLOCK;
738 unpack!(block = builder.expr_into_dest(Place::return_place(), block, &thir[expr]));
740 let source_info = builder.source_info(span);
741 builder.cfg.terminate(block, source_info, TerminatorKind::Return);
743 builder.build_drop_trees(false);
748 /// Construct MIR for a item that has had errors in type checking.
750 /// This is required because we may still want to run MIR passes on an item
751 /// with type errors, but normal MIR construction can't handle that in general.
752 fn construct_error<'a, 'tcx>(
753 infcx: &'a InferCtxt<'a, 'tcx>,
754 def: ty::WithOptConstParam<LocalDefId>,
756 body_id: hir::BodyId,
757 body_owner_kind: hir::BodyOwnerKind,
760 let span = tcx.hir().span(hir_id);
761 let ty = tcx.ty_error();
762 let generator_kind = tcx.hir().body(body_id).generator_kind;
763 let num_params = match body_owner_kind {
764 hir::BodyOwnerKind::Fn => tcx.hir().fn_decl_by_hir_id(hir_id).unwrap().inputs.len(),
765 hir::BodyOwnerKind::Closure => {
766 if generator_kind.is_some() {
767 // Generators have an implicit `self` parameter *and* a possibly
768 // implicit resume parameter.
771 // The implicit self parameter adds another local in MIR.
772 1 + tcx.hir().fn_decl_by_hir_id(hir_id).unwrap().inputs.len()
775 hir::BodyOwnerKind::Const => 0,
776 hir::BodyOwnerKind::Static(_) => 0,
778 let mut cfg = CFG { basic_blocks: IndexVec::new() };
779 let mut source_scopes = IndexVec::new();
780 let mut local_decls = IndexVec::from_elem_n(LocalDecl::new(ty, span), 1);
782 cfg.start_new_block();
783 source_scopes.push(SourceScopeData {
787 inlined_parent_scope: None,
788 local_data: ClearCrossCrate::Set(SourceScopeLocalData {
790 safety: Safety::Safe,
793 let source_info = SourceInfo { span, scope: OUTERMOST_SOURCE_SCOPE };
795 // Some MIR passes will expect the number of parameters to match the
796 // function declaration.
797 for _ in 0..num_params {
798 local_decls.push(LocalDecl::with_source_info(ty, source_info));
800 cfg.terminate(START_BLOCK, source_info, TerminatorKind::Unreachable);
802 let mut body = Body::new(
803 MirSource::item(def.did.to_def_id()),
813 body.generator.as_mut().map(|gen| gen.yield_ty = Some(ty));
817 impl<'a, 'tcx> Builder<'a, 'tcx> {
819 thir: &'a Thir<'tcx>,
820 infcx: &'a InferCtxt<'a, 'tcx>,
821 def: ty::WithOptConstParam<LocalDefId>,
828 generator_kind: Option<GeneratorKind>,
829 ) -> Builder<'a, 'tcx> {
831 let attrs = tcx.hir().attrs(hir_id);
832 // Some functions always have overflow checks enabled,
833 // however, they may not get codegen'd, depending on
834 // the settings for the crate they are codegened in.
835 let mut check_overflow = tcx.sess.contains_name(attrs, sym::rustc_inherit_overflow_checks);
836 // Respect -C overflow-checks.
837 check_overflow |= tcx.sess.overflow_checks();
838 // Constants always need overflow checks.
839 check_overflow |= matches!(
840 tcx.hir().body_owner_kind(hir_id),
841 hir::BodyOwnerKind::Const | hir::BodyOwnerKind::Static(_)
844 let lint_level = LintLevel::Explicit(hir_id);
845 let mut builder = Builder {
849 typeck_results: tcx.typeck_opt_const_arg(def),
850 region_scope_tree: tcx.region_scope_tree(def.did),
851 param_env: tcx.param_env(def.did),
852 def_id: def.did.to_def_id(),
855 cfg: CFG { basic_blocks: IndexVec::new() },
859 scopes: scope::Scopes::new(),
860 block_context: BlockContext::new(),
861 source_scopes: IndexVec::new(),
862 source_scope: OUTERMOST_SOURCE_SCOPE,
863 guard_context: vec![],
864 push_unsafe_count: 0,
865 unpushed_unsafe: safety,
866 local_decls: IndexVec::from_elem_n(LocalDecl::new(return_ty, return_span), 1),
867 canonical_user_type_annotations: IndexVec::new(),
868 upvar_mutbls: vec![],
869 var_indices: Default::default(),
871 var_debug_info: vec![],
874 assert_eq!(builder.cfg.start_new_block(), START_BLOCK);
876 builder.new_source_scope(span, lint_level, Some(safety)),
877 OUTERMOST_SOURCE_SCOPE
879 builder.source_scopes[OUTERMOST_SOURCE_SCOPE].parent_scope = None;
884 fn finish(self) -> Body<'tcx> {
885 for (index, block) in self.cfg.basic_blocks.iter().enumerate() {
886 if block.terminator.is_none() {
887 span_bug!(self.fn_span, "no terminator on block {:?}", index);
892 MirSource::item(self.def_id),
893 self.cfg.basic_blocks,
896 self.canonical_user_type_annotations,
906 mut block: BasicBlock,
908 arguments: &[ArgInfo<'tcx>],
909 argument_scope: region::Scope,
912 // Allocate locals for the function arguments
913 for &ArgInfo(ty, _, arg_opt, _) in arguments.iter() {
915 SourceInfo::outermost(arg_opt.map_or(self.fn_span, |arg| arg.pat.span));
916 let arg_local = self.local_decls.push(LocalDecl::with_source_info(ty, source_info));
918 // If this is a simple binding pattern, give debuginfo a nice name.
919 if let Some(arg) = arg_opt {
920 if let Some(ident) = arg.pat.simple_ident() {
921 self.var_debug_info.push(VarDebugInfo {
924 value: VarDebugInfoContents::Place(arg_local.into()),
931 let tcx_hir = tcx.hir();
932 let hir_typeck_results = self.typeck_results;
934 // In analyze_closure() in upvar.rs we gathered a list of upvars used by a
935 // indexed closure and we stored in a map called closure_min_captures in TypeckResults
936 // with the closure's DefId. Here, we run through that vec of UpvarIds for
937 // the given closure and use the necessary information to create upvar
938 // debuginfo and to fill `self.upvar_mutbls`.
939 if hir_typeck_results.closure_min_captures.get(&fn_def_id).is_some() {
940 let closure_env_arg = Local::new(1);
941 let mut closure_env_projs = vec![];
942 let mut closure_ty = self.local_decls[closure_env_arg].ty;
943 if let ty::Ref(_, ty, _) = closure_ty.kind() {
944 closure_env_projs.push(ProjectionElem::Deref);
947 let upvar_substs = match closure_ty.kind() {
948 ty::Closure(_, substs) => ty::UpvarSubsts::Closure(substs),
949 ty::Generator(_, substs, _) => ty::UpvarSubsts::Generator(substs),
950 _ => span_bug!(self.fn_span, "upvars with non-closure env ty {:?}", closure_ty),
952 let capture_tys = upvar_substs.upvar_tys();
953 let captures_with_tys =
954 hir_typeck_results.closure_min_captures_flattened(fn_def_id).zip(capture_tys);
956 self.upvar_mutbls = captures_with_tys
958 .map(|(i, (captured_place, ty))| {
959 let capture = captured_place.info.capture_kind;
960 let var_id = match captured_place.place.base {
961 HirPlaceBase::Upvar(upvar_id) => upvar_id.var_path.hir_id,
962 _ => bug!("Expected an upvar"),
965 let mutability = captured_place.mutability;
967 // FIXME(project-rfc-2229#8): Store more precise information
968 let mut name = kw::Empty;
969 if let Some(Node::Binding(pat)) = tcx_hir.find(var_id) {
970 if let hir::PatKind::Binding(_, _, ident, _) = pat.kind {
975 let mut projs = closure_env_projs.clone();
976 projs.push(ProjectionElem::Field(Field::new(i), ty));
978 ty::UpvarCapture::ByValue(_) => {}
979 ty::UpvarCapture::ByRef(..) => {
980 projs.push(ProjectionElem::Deref);
984 self.var_debug_info.push(VarDebugInfo {
986 source_info: SourceInfo::outermost(tcx_hir.span(var_id)),
987 value: VarDebugInfoContents::Place(Place {
988 local: closure_env_arg,
989 projection: tcx.intern_place_elems(&projs),
998 let mut scope = None;
999 // Bind the argument patterns
1000 for (index, arg_info) in arguments.iter().enumerate() {
1001 // Function arguments always get the first Local indices after the return place
1002 let local = Local::new(index + 1);
1003 let place = Place::from(local);
1004 let &ArgInfo(_, opt_ty_info, arg_opt, ref self_binding) = arg_info;
1006 // Make sure we drop (parts of) the argument even when not matched on.
1008 arg_opt.as_ref().map_or(expr.span, |arg| arg.pat.span),
1014 if let Some(arg) = arg_opt {
1015 let pat = match tcx.hir().get(arg.pat.hir_id) {
1016 Node::Pat(pat) | Node::Binding(pat) => pat,
1017 node => bug!("pattern became {:?}", node),
1019 let pattern = Pat::from_hir(tcx, self.param_env, self.typeck_results, pat);
1020 let original_source_scope = self.source_scope;
1021 let span = pattern.span;
1022 self.set_correct_source_scope_for_arg(arg.hir_id, original_source_scope, span);
1023 match *pattern.kind {
1024 // Don't introduce extra copies for simple bindings
1028 mode: BindingMode::ByValue,
1032 self.local_decls[local].mutability = mutability;
1033 self.local_decls[local].source_info.scope = self.source_scope;
1034 self.local_decls[local].local_info = if let Some(kind) = self_binding {
1035 Some(box LocalInfo::User(ClearCrossCrate::Set(
1036 BindingForm::ImplicitSelf(*kind),
1039 let binding_mode = ty::BindingMode::BindByValue(mutability);
1040 Some(box LocalInfo::User(ClearCrossCrate::Set(BindingForm::Var(
1044 opt_match_place: Some((Some(place), span)),
1049 self.var_indices.insert(var, LocalsForNode::One(local));
1052 scope = self.declare_bindings(
1056 matches::ArmHasGuard(false),
1057 Some((Some(&place), span)),
1059 let place_builder = PlaceBuilder::from(local);
1061 block = self.place_into_pattern(block, pattern, place_builder, false)
1065 self.source_scope = original_source_scope;
1069 // Enter the argument pattern bindings source scope, if it exists.
1070 if let Some(source_scope) = scope {
1071 self.source_scope = source_scope;
1074 self.expr_into_dest(Place::return_place(), block, &expr)
1077 fn set_correct_source_scope_for_arg(
1079 arg_hir_id: hir::HirId,
1080 original_source_scope: SourceScope,
1084 let current_root = tcx.maybe_lint_level_root_bounded(arg_hir_id, self.hir_id);
1085 let parent_root = tcx.maybe_lint_level_root_bounded(
1086 self.source_scopes[original_source_scope]
1089 .assert_crate_local()
1093 if current_root != parent_root {
1095 self.new_source_scope(pattern_span, LintLevel::Explicit(current_root), None);
1099 fn get_unit_temp(&mut self) -> Place<'tcx> {
1100 match self.unit_temp {
1103 let ty = self.tcx.mk_unit();
1104 let fn_span = self.fn_span;
1105 let tmp = self.temp(ty, fn_span);
1106 self.unit_temp = Some(tmp);
1113 ///////////////////////////////////////////////////////////////////////////
1114 // Builder methods are broken up into modules, depending on what kind
1115 // of thing is being lowered. Note that they use the `unpack` macro
1116 // above extensively.