Skip to main content

rustc_mir_build/builder/
mod.rs

1//! This module used to be named `build`, but that was causing GitHub's
2//! "Go to file" feature to silently ignore all files in the module, probably
3//! because it assumes that "build" is a build-output directory.
4//! See <https://github.com/rust-lang/rust/pull/134365>.
5//!
6//! ## The `let this = self;` idiom (LET_THIS_SELF)
7//!
8//! Throughout MIR building there are several places where a `Builder` method
9//! needs to borrow `self`, and then re-expose it to a closure as `|this|`.
10//!
11//! In complex builder methods, potentially with multiple levels of nesting, it
12//! would thus become necessary to mentally keep track of whether the builder
13//! is `self` (at the top level) or `this` (nested in a closure), or to replace
14//! one with the other when moving code in or out of a closure.
15//!
16//! (The borrow checker will prevent incorrect usage, but having to go back and
17//! satisfy the borrow checker still creates contributor friction.)
18//!
19//! To reduce that friction, some builder methods therefore start with
20//! `let this = self;` or similar, allowing subsequent code to uniformly refer
21//! to the builder as `this` (and never `self`), even when not nested.
22
23use itertools::Itertools;
24use rustc_abi::{ExternAbi, FieldIdx};
25use rustc_apfloat::Float;
26use rustc_apfloat::ieee::{Double, Half, Quad, Single};
27use rustc_data_structures::fx::FxHashMap;
28use rustc_data_structures::sorted_map::SortedIndexMultiMap;
29use rustc_errors::ErrorGuaranteed;
30use rustc_hir::def::DefKind;
31use rustc_hir::def_id::{DefId, LocalDefId};
32use rustc_hir::{self as hir, BindingMode, ByRef, HirId, ItemLocalId, Node, find_attr};
33use rustc_index::bit_set::GrowableBitSet;
34use rustc_index::{Idx, IndexSlice, IndexVec};
35use rustc_infer::infer::{InferCtxt, TyCtxtInferExt};
36use rustc_middle::hir::place::PlaceBase as HirPlaceBase;
37use rustc_middle::middle::region;
38use rustc_middle::mir::*;
39use rustc_middle::thir::{self, ExprId, LocalVarId, Param, ParamId, PatKind, Thir};
40use rustc_middle::ty::{self, ScalarInt, Ty, TyCtxt, TypeVisitableExt, TypingMode};
41use rustc_middle::{bug, span_bug};
42use rustc_session::lint;
43use rustc_span::{Span, Symbol};
44
45use crate::builder::expr::as_place::PlaceBuilder;
46use crate::builder::scope::{DropKind, LintLevel};
47use crate::errors;
48
49pub(crate) fn closure_saved_names_of_captured_variables<'tcx>(
50    tcx: TyCtxt<'tcx>,
51    def_id: LocalDefId,
52) -> IndexVec<FieldIdx, Symbol> {
53    tcx.closure_captures(def_id)
54        .iter()
55        .map(|captured_place| {
56            let name = captured_place.to_symbol();
57            match captured_place.info.capture_kind {
58                ty::UpvarCapture::ByValue | ty::UpvarCapture::ByUse => name,
59                ty::UpvarCapture::ByRef(..) => Symbol::intern(&::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("_ref__{0}", name))
    })format!("_ref__{name}")),
60            }
61        })
62        .collect()
63}
64
65/// Create the MIR for a given `DefId`, including unreachable code.
66///
67/// This is the implementation of hook `build_mir_inner_impl`, which should only
68/// be called by the query `mir_built`.
69pub(crate) fn build_mir_inner_impl<'tcx>(tcx: TyCtxt<'tcx>, def: LocalDefId) -> Body<'tcx> {
70    tcx.ensure_done().thir_abstract_const(def);
71    if let Err(e) = tcx.ensure_result().check_match(def) {
72        return construct_error(tcx, def, e);
73    }
74
75    if let Err(err) = tcx.ensure_result().check_tail_calls(def) {
76        return construct_error(tcx, def, err);
77    }
78
79    let body = match tcx.thir_body(def) {
80        Err(error_reported) => construct_error(tcx, def, error_reported),
81        Ok((thir, expr)) => {
82            let build_mir = |thir: &Thir<'tcx>| match thir.body_type {
83                thir::BodyTy::Fn(fn_sig) => construct_fn(tcx, def, thir, expr, fn_sig),
84                thir::BodyTy::Const(ty) | thir::BodyTy::GlobalAsm(ty) => {
85                    construct_const(tcx, def, thir, expr, ty)
86                }
87            };
88
89            // Don't steal here, instead steal in unsafeck. This is so that
90            // pattern inline constants can be evaluated as part of building the
91            // THIR of the parent function without a cycle.
92            build_mir(&thir.borrow())
93        }
94    };
95
96    // The borrow checker will replace all the regions here with its own
97    // inference variables. There's no point having non-erased regions here.
98    // The exception is `body.user_type_annotations`, which is used unmodified
99    // by borrow checking.
100    if true {
    if !!(body.local_decls.has_free_regions() ||
                                body.basic_blocks.has_free_regions() ||
                            body.var_debug_info.has_free_regions() ||
                        body.yield_ty().has_free_regions()) {
        {
            ::core::panicking::panic_fmt(format_args!("Unexpected free regions in MIR: {0:?}",
                    body));
        }
    };
};debug_assert!(
101        !(body.local_decls.has_free_regions()
102            || body.basic_blocks.has_free_regions()
103            || body.var_debug_info.has_free_regions()
104            || body.yield_ty().has_free_regions()),
105        "Unexpected free regions in MIR: {body:?}",
106    );
107
108    body
109}
110
111///////////////////////////////////////////////////////////////////////////
112// BuildMir -- walks a crate, looking for fn items and methods to build MIR from
113
114#[derive(#[automatically_derived]
impl ::core::fmt::Debug for BlockFrame {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            BlockFrame::Statement { ignores_expr_result: __self_0 } =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "Statement", "ignores_expr_result", &__self_0),
            BlockFrame::TailExpr { info: __self_0 } =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "TailExpr", "info", &__self_0),
            BlockFrame::SubExpr =>
                ::core::fmt::Formatter::write_str(f, "SubExpr"),
        }
    }
}Debug, #[automatically_derived]
impl ::core::cmp::PartialEq for BlockFrame {
    #[inline]
    fn eq(&self, other: &BlockFrame) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr &&
            match (self, other) {
                (BlockFrame::Statement { ignores_expr_result: __self_0 },
                    BlockFrame::Statement { ignores_expr_result: __arg1_0 }) =>
                    __self_0 == __arg1_0,
                (BlockFrame::TailExpr { info: __self_0 },
                    BlockFrame::TailExpr { info: __arg1_0 }) =>
                    __self_0 == __arg1_0,
                _ => true,
            }
    }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for BlockFrame {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<bool>;
        let _: ::core::cmp::AssertParamIsEq<BlockTailInfo>;
    }
}Eq)]
115enum BlockFrame {
116    /// Evaluation is currently within a statement.
117    ///
118    /// Examples include:
119    /// 1. `EXPR;`
120    /// 2. `let _ = EXPR;`
121    /// 3. `let x = EXPR;`
122    Statement {
123        /// If true, then statement discards result from evaluating
124        /// the expression (such as examples 1 and 2 above).
125        ignores_expr_result: bool,
126    },
127
128    /// Evaluation is currently within the tail expression of a block.
129    ///
130    /// Example: `{ STMT_1; STMT_2; EXPR }`
131    TailExpr { info: BlockTailInfo },
132
133    /// Generic mark meaning that the block occurred as a subexpression
134    /// where the result might be used.
135    ///
136    /// Examples: `foo(EXPR)`, `match EXPR { ... }`
137    SubExpr,
138}
139
140impl BlockFrame {
141    fn is_tail_expr(&self) -> bool {
142        match *self {
143            BlockFrame::TailExpr { .. } => true,
144
145            BlockFrame::Statement { .. } | BlockFrame::SubExpr => false,
146        }
147    }
148    fn is_statement(&self) -> bool {
149        match *self {
150            BlockFrame::Statement { .. } => true,
151
152            BlockFrame::TailExpr { .. } | BlockFrame::SubExpr => false,
153        }
154    }
155}
156
157#[derive(#[automatically_derived]
impl ::core::fmt::Debug for BlockContext {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_tuple_field1_finish(f, "BlockContext",
            &&self.0)
    }
}Debug)]
158struct BlockContext(Vec<BlockFrame>);
159
160struct Builder<'a, 'tcx> {
161    tcx: TyCtxt<'tcx>,
162    // FIXME(@lcnr): Why does this use an `infcx`, there should be
163    // no shared type inference going on here. I feel like it would
164    // clearer to manually construct one where necessary or to provide
165    // a nice API for non-type inference trait system checks.
166    infcx: InferCtxt<'tcx>,
167    region_scope_tree: &'tcx region::ScopeTree,
168    param_env: ty::ParamEnv<'tcx>,
169
170    thir: &'a Thir<'tcx>,
171    cfg: CFG<'tcx>,
172
173    def_id: LocalDefId,
174    hir_id: HirId,
175    parent_module: DefId,
176    check_overflow: bool,
177    fn_span: Span,
178    arg_count: usize,
179    coroutine: Option<Box<CoroutineInfo<'tcx>>>,
180
181    /// The current set of scopes, updated as we traverse;
182    /// see the `scope` module for more details.
183    scopes: scope::Scopes<'tcx>,
184
185    /// The block-context: each time we build the code within an thir::Block,
186    /// we push a frame here tracking whether we are building a statement or
187    /// if we are pushing the tail expression of the block. This is used to
188    /// embed information in generated temps about whether they were created
189    /// for a block tail expression or not.
190    ///
191    /// It would be great if we could fold this into `self.scopes`
192    /// somehow, but right now I think that is very tightly tied to
193    /// the code generation in ways that we cannot (or should not)
194    /// start just throwing new entries onto that vector in order to
195    /// distinguish the context of EXPR1 from the context of EXPR2 in
196    /// `{ STMTS; EXPR1 } + EXPR2`.
197    block_context: BlockContext,
198
199    /// The vector of all scopes that we have created thus far;
200    /// we track this for debuginfo later.
201    source_scopes: IndexVec<SourceScope, SourceScopeData<'tcx>>,
202    source_scope: SourceScope,
203
204    /// The guard-context: each time we build the guard expression for
205    /// a match arm, we push onto this stack, and then pop when we
206    /// finish building it.
207    guard_context: Vec<GuardFrame>,
208
209    /// Temporaries with fixed indexes. Used so that if-let guards on arms
210    /// with an or-pattern are only created once.
211    fixed_temps: FxHashMap<ExprId, Local>,
212    /// Scope of temporaries that should be deduplicated using [Self::fixed_temps].
213    fixed_temps_scope: Option<region::Scope>,
214
215    /// Maps `HirId`s of variable bindings to the `Local`s created for them.
216    /// (A match binding can have two locals; the 2nd is for the arm's guard.)
217    var_indices: FxHashMap<LocalVarId, LocalsForNode>,
218    local_decls: IndexVec<Local, LocalDecl<'tcx>>,
219    canonical_user_type_annotations: ty::CanonicalUserTypeAnnotations<'tcx>,
220    upvars: CaptureMap<'tcx>,
221    unit_temp: Option<Place<'tcx>>,
222
223    var_debug_info: Vec<VarDebugInfo<'tcx>>,
224
225    // A cache for `maybe_lint_level_roots_bounded`. That function is called
226    // repeatedly, and each time it effectively traces a path through a tree
227    // structure from a node towards the root, doing an attribute check on each
228    // node along the way. This cache records which nodes trace all the way to
229    // the root (most of them do) and saves us from retracing many sub-paths
230    // many times, and rechecking many nodes.
231    lint_level_roots_cache: GrowableBitSet<hir::ItemLocalId>,
232
233    /// Collects additional coverage information during MIR building.
234    /// Only present if coverage is enabled and this function is eligible.
235    coverage_info: Option<coverageinfo::CoverageInfoBuilder>,
236}
237
238type CaptureMap<'tcx> = SortedIndexMultiMap<usize, ItemLocalId, Capture<'tcx>>;
239
240#[derive(#[automatically_derived]
impl<'tcx> ::core::fmt::Debug for Capture<'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field3_finish(f, "Capture",
            "captured_place", &self.captured_place, "use_place",
            &self.use_place, "mutability", &&self.mutability)
    }
}Debug)]
241struct Capture<'tcx> {
242    captured_place: &'tcx ty::CapturedPlace<'tcx>,
243    use_place: Place<'tcx>,
244    mutability: Mutability,
245}
246
247impl<'a, 'tcx> Builder<'a, 'tcx> {
248    fn typing_env(&self) -> ty::TypingEnv<'tcx> {
249        self.infcx.typing_env(self.param_env)
250    }
251
252    fn is_bound_var_in_guard(&self, id: LocalVarId) -> bool {
253        self.guard_context.iter().any(|frame| frame.locals.iter().any(|local| local.id == id))
254    }
255
256    fn var_local_id(&self, id: LocalVarId, for_guard: ForGuard) -> Local {
257        self.var_indices[&id].local_id(for_guard)
258    }
259}
260
261impl BlockContext {
262    fn new() -> Self {
263        BlockContext(::alloc::vec::Vec::new()vec![])
264    }
265    fn push(&mut self, bf: BlockFrame) {
266        self.0.push(bf);
267    }
268    fn pop(&mut self) -> Option<BlockFrame> {
269        self.0.pop()
270    }
271
272    /// Traverses the frames on the `BlockContext`, searching for either
273    /// the first block-tail expression frame with no intervening
274    /// statement frame.
275    ///
276    /// Notably, this skips over `SubExpr` frames; this method is
277    /// meant to be used in the context of understanding the
278    /// relationship of a temp (created within some complicated
279    /// expression) with its containing expression, and whether the
280    /// value of that *containing expression* (not the temp!) is
281    /// ignored.
282    fn currently_in_block_tail(&self) -> Option<BlockTailInfo> {
283        for bf in self.0.iter().rev() {
284            match bf {
285                BlockFrame::SubExpr => continue,
286                BlockFrame::Statement { .. } => break,
287                &BlockFrame::TailExpr { info } => return Some(info),
288            }
289        }
290
291        None
292    }
293
294    /// Looks at the topmost frame on the BlockContext and reports
295    /// whether its one that would discard a block tail result.
296    ///
297    /// Unlike `currently_within_ignored_tail_expression`, this does
298    /// *not* skip over `SubExpr` frames: here, we want to know
299    /// whether the block result itself is discarded.
300    fn currently_ignores_tail_results(&self) -> bool {
301        match self.0.last() {
302            // no context: conservatively assume result is read
303            None => false,
304
305            // sub-expression: block result feeds into some computation
306            Some(BlockFrame::SubExpr) => false,
307
308            // otherwise: use accumulated is_ignored state.
309            Some(
310                BlockFrame::TailExpr { info: BlockTailInfo { tail_result_is_ignored: ign, .. } }
311                | BlockFrame::Statement { ignores_expr_result: ign },
312            ) => *ign,
313        }
314    }
315}
316
317#[derive(#[automatically_derived]
impl ::core::fmt::Debug for LocalsForNode {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            LocalsForNode::One(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "One",
                    &__self_0),
            LocalsForNode::ForGuard {
                ref_for_guard: __self_0, for_arm_body: __self_1 } =>
                ::core::fmt::Formatter::debug_struct_field2_finish(f,
                    "ForGuard", "ref_for_guard", __self_0, "for_arm_body",
                    &__self_1),
        }
    }
}Debug)]
318enum LocalsForNode {
319    /// In the usual case, a `HirId` for an identifier maps to at most
320    /// one `Local` declaration.
321    One(Local),
322
323    /// The exceptional case is identifiers in a match arm's pattern
324    /// that are referenced in a guard of that match arm. For these,
325    /// we have `2` Locals.
326    ///
327    /// * `for_arm_body` is the Local used in the arm body (which is
328    ///   just like the `One` case above),
329    ///
330    /// * `ref_for_guard` is the Local used in the arm's guard (which
331    ///   is a reference to a temp that is an alias of
332    ///   `for_arm_body`).
333    ForGuard { ref_for_guard: Local, for_arm_body: Local },
334}
335
336#[derive(#[automatically_derived]
impl ::core::fmt::Debug for GuardFrameLocal {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field1_finish(f,
            "GuardFrameLocal", "id", &&self.id)
    }
}Debug)]
337struct GuardFrameLocal {
338    id: LocalVarId,
339}
340
341impl GuardFrameLocal {
342    fn new(id: LocalVarId) -> Self {
343        GuardFrameLocal { id }
344    }
345}
346
347#[derive(#[automatically_derived]
impl ::core::fmt::Debug for GuardFrame {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field1_finish(f, "GuardFrame",
            "locals", &&self.locals)
    }
}Debug)]
348struct GuardFrame {
349    /// These are the id's of names that are bound by patterns of the
350    /// arm of *this* guard.
351    ///
352    /// (Frames higher up the stack will have the id's bound in arms
353    /// further out, such as in a case like:
354    ///
355    /// match E1 {
356    ///      P1(id1) if (... (match E2 { P2(id2) if ... => B2 })) => B1,
357    /// }
358    ///
359    /// here, when building for FIXME.
360    locals: Vec<GuardFrameLocal>,
361}
362
363/// `ForGuard` indicates whether we are talking about:
364///   1. The variable for use outside of guard expressions, or
365///   2. The temp that holds reference to (1.), which is actually what the
366///      guard expressions see.
367#[derive(#[automatically_derived]
impl ::core::marker::Copy for ForGuard { }Copy, #[automatically_derived]
impl ::core::clone::Clone for ForGuard {
    #[inline]
    fn clone(&self) -> ForGuard { *self }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for ForGuard {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                ForGuard::RefWithinGuard => "RefWithinGuard",
                ForGuard::OutsideGuard => "OutsideGuard",
            })
    }
}Debug, #[automatically_derived]
impl ::core::cmp::PartialEq for ForGuard {
    #[inline]
    fn eq(&self, other: &ForGuard) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr
    }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for ForGuard {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {}
}Eq)]
368enum ForGuard {
369    RefWithinGuard,
370    OutsideGuard,
371}
372
373impl LocalsForNode {
374    fn local_id(&self, for_guard: ForGuard) -> Local {
375        match (self, for_guard) {
376            (&LocalsForNode::One(local_id), ForGuard::OutsideGuard)
377            | (
378                &LocalsForNode::ForGuard { ref_for_guard: local_id, .. },
379                ForGuard::RefWithinGuard,
380            )
381            | (&LocalsForNode::ForGuard { for_arm_body: local_id, .. }, ForGuard::OutsideGuard) => {
382                local_id
383            }
384
385            (&LocalsForNode::One(_), ForGuard::RefWithinGuard) => {
386                ::rustc_middle::util::bug::bug_fmt(format_args!("anything with one local should never be within a guard."))bug!("anything with one local should never be within a guard.")
387            }
388        }
389    }
390}
391
392struct CFG<'tcx> {
393    basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
394}
395
396impl ::std::fmt::Debug for ScopeId {
    fn fmt(&self, fmt: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
        fmt.write_fmt(format_args!("{0}", self.as_u32()))
    }
}rustc_index::newtype_index! {
397    struct ScopeId {}
398}
399
400#[derive(#[automatically_derived]
impl ::core::fmt::Debug for NeedsTemporary {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                NeedsTemporary::No => "No",
                NeedsTemporary::Maybe => "Maybe",
            })
    }
}Debug)]
401enum NeedsTemporary {
402    /// Use this variant when whatever you are converting with `as_operand`
403    /// is the last thing you are converting. This means that if we introduced
404    /// an intermediate temporary, we'd only read it immediately after, so we can
405    /// also avoid it.
406    No,
407    /// For all cases where you aren't sure or that are too expensive to compute
408    /// for now. It is always safe to fall back to this.
409    Maybe,
410}
411
412/// The `BlockAnd` "monad" packages up the new basic block along with a
413/// produced value (sometimes just unit, of course). The `unpack!`
414/// macro (and methods below) makes working with `BlockAnd` much more
415/// convenient.
416#[must_use = "if you don't use one of these results, you're leaving a dangling edge"]
417struct BlockAnd<T>(BasicBlock, T);
418
419impl BlockAnd<()> {
420    /// Unpacks `BlockAnd<()>` into a [`BasicBlock`].
421    #[must_use]
422    fn into_block(self) -> BasicBlock {
423        let Self(block, ()) = self;
424        block
425    }
426}
427
428trait BlockAndExtension {
429    fn and<T>(self, v: T) -> BlockAnd<T>;
430    fn unit(self) -> BlockAnd<()>;
431}
432
433impl BlockAndExtension for BasicBlock {
434    fn and<T>(self, v: T) -> BlockAnd<T> {
435        BlockAnd(self, v)
436    }
437
438    fn unit(self) -> BlockAnd<()> {
439        BlockAnd(self, ())
440    }
441}
442
443/// Update a block pointer and return the value.
444/// Use it like `let x = unpack!(block = self.foo(block, foo))`.
445macro_rules! unpack {
446    ($x:ident = $c:expr) => {{
447        let BlockAnd(b, v) = $c;
448        $x = b;
449        v
450    }};
451}
452
453/// The main entry point for building MIR for a function.
454fn construct_fn<'tcx>(
455    tcx: TyCtxt<'tcx>,
456    fn_def: LocalDefId,
457    thir: &Thir<'tcx>,
458    expr: ExprId,
459    fn_sig: ty::FnSig<'tcx>,
460) -> Body<'tcx> {
461    let span = tcx.def_span(fn_def);
462    let fn_id = tcx.local_def_id_to_hir_id(fn_def);
463
464    // Figure out what primary body this item has.
465    let body = tcx.hir_body_owned_by(fn_def);
466    let span_with_body = tcx.hir_span_with_body(fn_id);
467    let return_ty_span = tcx
468        .hir_fn_decl_by_hir_id(fn_id)
469        .unwrap_or_else(|| ::rustc_middle::util::bug::span_bug_fmt(span,
    format_args!("can\'t build MIR for {0:?}", fn_def))span_bug!(span, "can't build MIR for {:?}", fn_def))
470        .output
471        .span();
472
473    let mut abi = fn_sig.abi();
474    if let DefKind::Closure = tcx.def_kind(fn_def) {
475        // HACK(eddyb) Avoid having RustCall on closures,
476        // as it adds unnecessary (and wrong) auto-tupling.
477        abi = ExternAbi::Rust;
478    }
479
480    let arguments = &thir.params;
481
482    let return_ty = fn_sig.output();
483    let coroutine = match tcx.type_of(fn_def).instantiate_identity().skip_norm_wip().kind() {
484        ty::Coroutine(_, args) => Some(Box::new(CoroutineInfo::initial(
485            tcx.coroutine_kind(fn_def).unwrap(),
486            args.as_coroutine().yield_ty(),
487            args.as_coroutine().resume_ty(),
488        ))),
489        ty::Closure(..) | ty::CoroutineClosure(..) | ty::FnDef(..) => None,
490        ty => ::rustc_middle::util::bug::span_bug_fmt(span_with_body,
    format_args!("unexpected type of body: {0:?}", ty))span_bug!(span_with_body, "unexpected type of body: {ty:?}"),
491    };
492
493    if let Some((dialect, phase)) =
494        {
    {
        'done:
            {
            for i in ::rustc_hir::attrs::HasAttrs::get_attrs(fn_id, &tcx) {
                #[allow(unused_imports)]
                use rustc_hir::attrs::AttributeKind::*;
                let i: &rustc_hir::Attribute = i;
                match i {
                    rustc_hir::Attribute::Parsed(CustomMir(dialect, phase)) => {
                        break 'done Some((dialect, phase));
                    }
                    rustc_hir::Attribute::Unparsed(..) =>
                        {}
                        #[deny(unreachable_patterns)]
                        _ => {}
                }
            }
            None
        }
    }
}find_attr!(tcx, fn_id, CustomMir(dialect, phase) => (dialect, phase))
495    {
496        return custom::build_custom_mir(
497            tcx,
498            fn_def.to_def_id(),
499            fn_id,
500            thir,
501            expr,
502            arguments,
503            return_ty,
504            return_ty_span,
505            span_with_body,
506            dialect.as_ref().map(|(d, _)| *d),
507            phase.as_ref().map(|(p, _)| *p),
508        );
509    }
510
511    // FIXME(#132279): This should be able to reveal opaque
512    // types defined during HIR typeck.
513    let infcx = tcx.infer_ctxt().build(TypingMode::non_body_analysis());
514    let mut builder = Builder::new(
515        thir,
516        infcx,
517        fn_def,
518        fn_id,
519        span_with_body,
520        arguments.len(),
521        return_ty,
522        return_ty_span,
523        coroutine,
524    );
525
526    let call_site_scope =
527        region::Scope { local_id: body.id().hir_id.local_id, data: region::ScopeData::CallSite };
528    let arg_scope =
529        region::Scope { local_id: body.id().hir_id.local_id, data: region::ScopeData::Arguments };
530    let source_info = builder.source_info(span);
531    let call_site_s = (call_site_scope, source_info);
532    let _: BlockAnd<()> = builder.in_scope(call_site_s, LintLevel::Inherited, |builder| {
533        let arg_scope_s = (arg_scope, source_info);
534        // Attribute epilogue to function's closing brace
535        let fn_end = span_with_body.shrink_to_hi();
536        let return_block = builder
537            .in_breakable_scope(None, Place::return_place(), fn_end, |builder| {
538                Some(builder.in_scope(arg_scope_s, LintLevel::Inherited, |builder| {
539                    builder.args_and_body(START_BLOCK, arguments, arg_scope, expr)
540                }))
541            })
542            .into_block();
543        let source_info = builder.source_info(fn_end);
544        builder.cfg.terminate(return_block, source_info, TerminatorKind::Return);
545        builder.build_drop_trees();
546        return_block.unit()
547    });
548
549    builder.lint_and_remove_uninhabited();
550    let mut body = builder.finish();
551
552    body.spread_arg = if abi == ExternAbi::RustCall {
553        // RustCall pseudo-ABI untuples the last argument.
554        Some(Local::new(arguments.len()))
555    } else {
556        None
557    };
558
559    body
560}
561
562fn construct_const<'a, 'tcx>(
563    tcx: TyCtxt<'tcx>,
564    def: LocalDefId,
565    thir: &'a Thir<'tcx>,
566    expr: ExprId,
567    const_ty: Ty<'tcx>,
568) -> Body<'tcx> {
569    let hir_id = tcx.local_def_id_to_hir_id(def);
570
571    // Figure out what primary body this item has.
572    let (span, const_ty_span) = match tcx.hir_node(hir_id) {
573        Node::Item(hir::Item {
574            kind: hir::ItemKind::Static(_, _, ty, _) | hir::ItemKind::Const(_, _, ty, _),
575            span,
576            ..
577        })
578        | Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Const(ty, _), span, .. })
579        | Node::TraitItem(hir::TraitItem {
580            kind: hir::TraitItemKind::Const(ty, Some(_), _),
581            span,
582            ..
583        }) => (*span, ty.span),
584        Node::AnonConst(ct) => (ct.span, ct.span),
585        Node::ConstBlock(_) => {
586            let span = tcx.def_span(def);
587            (span, span)
588        }
589        Node::Item(hir::Item { kind: hir::ItemKind::GlobalAsm { .. }, span, .. }) => (*span, *span),
590        _ => ::rustc_middle::util::bug::span_bug_fmt(tcx.def_span(def),
    format_args!("can\'t build MIR for {0:?}", def))span_bug!(tcx.def_span(def), "can't build MIR for {:?}", def),
591    };
592
593    // FIXME(#132279): We likely want to be able to use the hidden types of
594    // opaques used by this function here.
595    let infcx = tcx.infer_ctxt().build(TypingMode::non_body_analysis());
596    let mut builder =
597        Builder::new(thir, infcx, def, hir_id, span, 0, const_ty, const_ty_span, None);
598
599    let mut block = START_BLOCK;
600    block = builder.expr_into_dest(Place::return_place(), block, expr).into_block();
601
602    let source_info = builder.source_info(span);
603    builder.cfg.terminate(block, source_info, TerminatorKind::Return);
604
605    builder.build_drop_trees();
606
607    builder.lint_and_remove_uninhabited();
608    builder.finish()
609}
610
611/// Construct MIR for an item that has had errors in type checking.
612///
613/// This is required because we may still want to run MIR passes on an item
614/// with type errors, but normal MIR construction can't handle that in general.
615fn construct_error(tcx: TyCtxt<'_>, def_id: LocalDefId, guar: ErrorGuaranteed) -> Body<'_> {
616    let span = tcx.def_span(def_id);
617    let hir_id = tcx.local_def_id_to_hir_id(def_id);
618
619    let (inputs, output, coroutine) = match tcx.def_kind(def_id) {
620        DefKind::Const { .. }
621        | DefKind::AssocConst { .. }
622        | DefKind::AnonConst
623        | DefKind::InlineConst
624        | DefKind::Static { .. }
625        | DefKind::GlobalAsm => {
626            (::alloc::vec::Vec::new()vec![], tcx.type_of(def_id).instantiate_identity().skip_norm_wip(), None)
627        }
628        DefKind::Ctor(..) | DefKind::Fn | DefKind::AssocFn => {
629            let sig = tcx.liberate_late_bound_regions(
630                def_id.to_def_id(),
631                tcx.fn_sig(def_id).instantiate_identity().skip_norm_wip(),
632            );
633            (sig.inputs().to_vec(), sig.output(), None)
634        }
635        DefKind::Closure => {
636            let closure_ty = tcx.type_of(def_id).instantiate_identity().skip_norm_wip();
637            match closure_ty.kind() {
638                ty::Closure(_, args) => {
639                    let args = args.as_closure();
640                    let sig = tcx.liberate_late_bound_regions(def_id.to_def_id(), args.sig());
641                    let self_ty = match args.kind() {
642                        ty::ClosureKind::Fn => {
643                            Ty::new_imm_ref(tcx, tcx.lifetimes.re_erased, closure_ty)
644                        }
645                        ty::ClosureKind::FnMut => {
646                            Ty::new_mut_ref(tcx, tcx.lifetimes.re_erased, closure_ty)
647                        }
648                        ty::ClosureKind::FnOnce => closure_ty,
649                    };
650                    (
651                        [self_ty].into_iter().chain(sig.inputs()[0].tuple_fields()).collect(),
652                        sig.output(),
653                        None,
654                    )
655                }
656                ty::Coroutine(_, args) => {
657                    let args = args.as_coroutine();
658                    let resume_ty = args.resume_ty();
659                    let yield_ty = args.yield_ty();
660                    let return_ty = args.return_ty();
661                    (
662                        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [closure_ty, resume_ty]))vec![closure_ty, resume_ty],
663                        return_ty,
664                        Some(Box::new(CoroutineInfo::initial(
665                            tcx.coroutine_kind(def_id).unwrap(),
666                            yield_ty,
667                            resume_ty,
668                        ))),
669                    )
670                }
671                ty::CoroutineClosure(did, args) => {
672                    let args = args.as_coroutine_closure();
673                    let sig = tcx.liberate_late_bound_regions(
674                        def_id.to_def_id(),
675                        args.coroutine_closure_sig(),
676                    );
677                    let self_ty = match args.kind() {
678                        ty::ClosureKind::Fn => {
679                            Ty::new_imm_ref(tcx, tcx.lifetimes.re_erased, closure_ty)
680                        }
681                        ty::ClosureKind::FnMut => {
682                            Ty::new_mut_ref(tcx, tcx.lifetimes.re_erased, closure_ty)
683                        }
684                        ty::ClosureKind::FnOnce => closure_ty,
685                    };
686                    (
687                        [self_ty].into_iter().chain(sig.tupled_inputs_ty.tuple_fields()).collect(),
688                        sig.to_coroutine(
689                            tcx,
690                            args.parent_args(),
691                            args.kind_ty(),
692                            tcx.coroutine_for_closure(*did),
693                            Ty::new_error(tcx, guar),
694                        ),
695                        None,
696                    )
697                }
698                ty::Error(_) => (::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [closure_ty, closure_ty]))vec![closure_ty, closure_ty], closure_ty, None),
699                kind => {
700                    ::rustc_middle::util::bug::span_bug_fmt(span,
    format_args!("expected type of closure body to be a closure or coroutine, got {0:?}",
        kind));span_bug!(
701                        span,
702                        "expected type of closure body to be a closure or coroutine, got {kind:?}"
703                    );
704                }
705            }
706        }
707        dk => ::rustc_middle::util::bug::span_bug_fmt(span,
    format_args!("{0:?} is not a body: {1:?}", def_id, dk))span_bug!(span, "{:?} is not a body: {:?}", def_id, dk),
708    };
709
710    let source_info = SourceInfo { span, scope: OUTERMOST_SOURCE_SCOPE };
711    let local_decls = IndexVec::from_iter(
712        [output].iter().chain(&inputs).map(|ty| LocalDecl::with_source_info(*ty, source_info)),
713    );
714    let mut cfg = CFG { basic_blocks: IndexVec::new() };
715    let mut source_scopes = IndexVec::new();
716
717    cfg.start_new_block();
718    source_scopes.push(SourceScopeData {
719        span,
720        parent_scope: None,
721        inlined: None,
722        inlined_parent_scope: None,
723        local_data: ClearCrossCrate::Set(SourceScopeLocalData { lint_root: hir_id }),
724    });
725
726    cfg.terminate(START_BLOCK, source_info, TerminatorKind::Unreachable);
727
728    Body::new(
729        MirSource::item(def_id.to_def_id()),
730        cfg.basic_blocks,
731        source_scopes,
732        local_decls,
733        IndexVec::new(),
734        inputs.len(),
735        ::alloc::vec::Vec::new()vec![],
736        span,
737        coroutine,
738        Some(guar),
739    )
740}
741
742impl<'a, 'tcx> Builder<'a, 'tcx> {
743    fn new(
744        thir: &'a Thir<'tcx>,
745        infcx: InferCtxt<'tcx>,
746        def: LocalDefId,
747        hir_id: HirId,
748        span: Span,
749        arg_count: usize,
750        return_ty: Ty<'tcx>,
751        return_span: Span,
752        coroutine: Option<Box<CoroutineInfo<'tcx>>>,
753    ) -> Builder<'a, 'tcx> {
754        let tcx = infcx.tcx;
755        // Some functions always have overflow checks enabled,
756        // however, they may not get codegen'd, depending on
757        // the settings for the crate they are codegened in.
758        let mut check_overflow = {
    {
            'done:
                {
                for i in tcx.hir_attrs(hir_id) {
                    #[allow(unused_imports)]
                    use rustc_hir::attrs::AttributeKind::*;
                    let i: &rustc_hir::Attribute = i;
                    match i {
                        rustc_hir::Attribute::Parsed(RustcInheritOverflowChecks) =>
                            {
                            break 'done Some(());
                        }
                        rustc_hir::Attribute::Unparsed(..) =>
                            {}
                            #[deny(unreachable_patterns)]
                            _ => {}
                    }
                }
                None
            }
        }.is_some()
}find_attr!(tcx.hir_attrs(hir_id), RustcInheritOverflowChecks);
759        // Respect -C overflow-checks.
760        check_overflow |= tcx.sess.overflow_checks();
761        // Constants always need overflow checks.
762        check_overflow |= #[allow(non_exhaustive_omitted_patterns)] match tcx.hir_body_owner_kind(def) {
    hir::BodyOwnerKind::Const { .. } | hir::BodyOwnerKind::Static(_) => true,
    _ => false,
}matches!(
763            tcx.hir_body_owner_kind(def),
764            hir::BodyOwnerKind::Const { .. } | hir::BodyOwnerKind::Static(_)
765        );
766
767        let lint_level = LintLevel::Explicit(hir_id);
768        let param_env = tcx.param_env(def);
769        let mut builder = Builder {
770            thir,
771            tcx,
772            infcx,
773            region_scope_tree: tcx.region_scope_tree(def),
774            param_env,
775            def_id: def,
776            hir_id,
777            parent_module: tcx.parent_module(hir_id).to_def_id(),
778            check_overflow,
779            cfg: CFG { basic_blocks: IndexVec::new() },
780            fn_span: span,
781            arg_count,
782            coroutine,
783            scopes: scope::Scopes::new(),
784            block_context: BlockContext::new(),
785            source_scopes: IndexVec::new(),
786            source_scope: OUTERMOST_SOURCE_SCOPE,
787            guard_context: ::alloc::vec::Vec::new()vec![],
788            fixed_temps: Default::default(),
789            fixed_temps_scope: None,
790            local_decls: IndexVec::from_elem_n(LocalDecl::new(return_ty, return_span), 1),
791            canonical_user_type_annotations: IndexVec::new(),
792            upvars: CaptureMap::new(),
793            var_indices: Default::default(),
794            unit_temp: None,
795            var_debug_info: ::alloc::vec::Vec::new()vec![],
796            lint_level_roots_cache: GrowableBitSet::new_empty(),
797            coverage_info: coverageinfo::CoverageInfoBuilder::new_if_enabled(tcx, def),
798        };
799
800        match (&builder.cfg.start_new_block(), &START_BLOCK) {
    (left_val, right_val) => {
        if !(*left_val == *right_val) {
            let kind = ::core::panicking::AssertKind::Eq;
            ::core::panicking::assert_failed(kind, &*left_val, &*right_val,
                ::core::option::Option::None);
        }
    }
};assert_eq!(builder.cfg.start_new_block(), START_BLOCK);
801        match (&builder.new_source_scope(span, lint_level), &OUTERMOST_SOURCE_SCOPE) {
    (left_val, right_val) => {
        if !(*left_val == *right_val) {
            let kind = ::core::panicking::AssertKind::Eq;
            ::core::panicking::assert_failed(kind, &*left_val, &*right_val,
                ::core::option::Option::None);
        }
    }
};assert_eq!(builder.new_source_scope(span, lint_level), OUTERMOST_SOURCE_SCOPE);
802        builder.source_scopes[OUTERMOST_SOURCE_SCOPE].parent_scope = None;
803
804        builder
805    }
806
807    #[allow(dead_code)]
808    fn dump_for_debugging(&self) {
809        let mut body = Body::new(
810            MirSource::item(self.def_id.to_def_id()),
811            self.cfg.basic_blocks.clone(),
812            self.source_scopes.clone(),
813            self.local_decls.clone(),
814            self.canonical_user_type_annotations.clone(),
815            self.arg_count.clone(),
816            self.var_debug_info.clone(),
817            self.fn_span.clone(),
818            self.coroutine.clone(),
819            None,
820        );
821        body.coverage_info_hi = self.coverage_info.as_ref().map(|b| b.as_done());
822
823        let writer = pretty::MirWriter::new(self.tcx);
824        writer.write_mir_fn(&body, &mut std::io::stdout()).unwrap();
825    }
826
827    fn lint_and_remove_uninhabited(&mut self) {
828        let mut lints = ::alloc::vec::Vec::new()vec![];
829
830        for bbdata in self.cfg.basic_blocks.iter_mut() {
831            let term = bbdata.terminator_mut();
832            let TerminatorKind::Call { ref mut target, destination, .. } = term.kind else {
833                continue;
834            };
835            let Some(target_bb) = *target else { continue };
836
837            let ty = destination.ty(&self.local_decls, self.tcx).ty;
838            let ty_is_inhabited = ty.is_inhabited_from(
839                self.tcx,
840                self.parent_module,
841                self.infcx.typing_env(self.param_env),
842            );
843            if !ty_is_inhabited {
844                // Unreachable code warnings are already emitted during type checking.
845                // However, during type checking, full type information is being
846                // calculated but not yet available, so the check for diverging
847                // expressions due to uninhabited result types is pretty crude and
848                // only checks whether ty.is_never(). Here, we have full type
849                // information available and can issue warnings for less obviously
850                // uninhabited types (e.g. empty enums). The check above is used so
851                // that we do not emit the same warning twice if the uninhabited type
852                // is indeed `!`.
853                if !ty.is_never()
854                    && #[allow(non_exhaustive_omitted_patterns)] match self.tcx.def_kind(self.def_id)
    {
    DefKind::Fn | DefKind::AssocFn => true,
    _ => false,
}matches!(self.tcx.def_kind(self.def_id), DefKind::Fn | DefKind::AssocFn)
855                // check if the function's return type is inhabited
856                // this was added here because of this regression
857                // https://github.com/rust-lang/rust/issues/149571
858                    && self
859                        .tcx
860                        .fn_sig(self.def_id).instantiate_identity().skip_binder()
861                        .output()
862                        .is_inhabited_from(
863                            self.tcx,
864                            self.parent_module,
865                            self.infcx.typing_env(self.param_env),
866                        )
867                {
868                    lints.push((target_bb, ty, term.source_info.span));
869                }
870
871                // The presence or absence of a return edge affects control-flow sensitive
872                // MIR checks and ultimately whether code is accepted or not. We can only
873                // omit the return edge if a return type is visibly uninhabited to a module
874                // that makes the call.
875                *target = None;
876            }
877        }
878
879        /// Starting at a target unreachable block, find some user code to lint as unreachable
880        fn find_unreachable_code_from(
881            bb: BasicBlock,
882            bbs: &IndexVec<BasicBlock, BasicBlockData<'_>>,
883        ) -> Option<(SourceInfo, &'static str)> {
884            let bb = &bbs[bb];
885            for stmt in &bb.statements {
886                match &stmt.kind {
887                    // Ignore the implicit `()` return place assignment for unit functions/blocks
888                    StatementKind::Assign((_, Rvalue::Use(Operand::Constant(const_), _)))
889                        if const_.ty().is_unit() =>
890                    {
891                        continue;
892                    }
893                    // Ignore return value plumbing. After a call returning a non-`!`
894                    // uninhabited type, a tail expression can be unreachable while
895                    // still being needed to satisfy the surrounding return type.
896                    StatementKind::Assign((place, _)) if place.as_local() == Some(RETURN_PLACE) => {
897                        continue;
898                    }
899                    StatementKind::StorageLive(_) | StatementKind::StorageDead(_) => {
900                        continue;
901                    }
902                    StatementKind::FakeRead(..) => return Some((stmt.source_info, "definition")),
903                    _ => return Some((stmt.source_info, "expression")),
904                }
905            }
906
907            let term = bb.terminator();
908            match term.kind {
909                // No user code in this bb, and our goto target may be reachable via other paths
910                TerminatorKind::Goto { .. } | TerminatorKind::Return => None,
911                _ => Some((term.source_info, "expression")),
912            }
913        }
914
915        for (target_bb, orig_ty, orig_span) in lints {
916            if orig_span.in_external_macro(self.tcx.sess.source_map()) {
917                continue;
918            }
919
920            let Some((target_loc, descr)) =
921                find_unreachable_code_from(target_bb, &self.cfg.basic_blocks)
922            else {
923                continue;
924            };
925            let lint_root = self.source_scopes[target_loc.scope]
926                .local_data
927                .as_ref()
928                .unwrap_crate_local()
929                .lint_root;
930            self.tcx.emit_node_span_lint(
931                lint::builtin::UNREACHABLE_CODE,
932                lint_root,
933                target_loc.span,
934                errors::UnreachableDueToUninhabited {
935                    expr: target_loc.span,
936                    orig: orig_span,
937                    descr,
938                    ty: orig_ty,
939                },
940            );
941        }
942    }
943
944    fn finish(self) -> Body<'tcx> {
945        let mut body = Body::new(
946            MirSource::item(self.def_id.to_def_id()),
947            self.cfg.basic_blocks,
948            self.source_scopes,
949            self.local_decls,
950            self.canonical_user_type_annotations,
951            self.arg_count,
952            self.var_debug_info,
953            self.fn_span,
954            self.coroutine,
955            None,
956        );
957        body.coverage_info_hi = self.coverage_info.map(|b| b.into_done());
958
959        let writer = pretty::MirWriter::new(self.tcx);
960        for (index, block) in body.basic_blocks.iter().enumerate() {
961            if block.terminator.is_none() {
962                writer.write_mir_fn(&body, &mut std::io::stdout()).unwrap();
963                ::rustc_middle::util::bug::span_bug_fmt(self.fn_span,
    format_args!("no terminator on block {0:?}", index));span_bug!(self.fn_span, "no terminator on block {:?}", index);
964            }
965        }
966
967        body
968    }
969
970    fn insert_upvar_arg(&mut self) {
971        let Some(closure_arg) = self.local_decls.get(ty::CAPTURE_STRUCT_LOCAL) else { return };
972
973        let mut closure_ty = closure_arg.ty;
974        let mut closure_env_projs = ::alloc::vec::Vec::new()vec![];
975        if let ty::Ref(_, ty, _) = closure_ty.kind() {
976            closure_env_projs.push(ProjectionElem::Deref);
977            closure_ty = *ty;
978        }
979
980        let upvar_args = match closure_ty.kind() {
981            ty::Closure(_, args) => ty::UpvarArgs::Closure(args),
982            ty::Coroutine(_, args) => ty::UpvarArgs::Coroutine(args),
983            ty::CoroutineClosure(_, args) => ty::UpvarArgs::CoroutineClosure(args),
984            _ => return,
985        };
986
987        // In analyze_closure() in upvar.rs we gathered a list of upvars used by an
988        // indexed closure and we stored in a map called closure_min_captures in TypeckResults
989        // with the closure's DefId. Here, we run through that vec of UpvarIds for
990        // the given closure and use the necessary information to create upvar
991        // debuginfo and to fill `self.upvars`.
992        let capture_tys = upvar_args.upvar_tys();
993
994        let tcx = self.tcx;
995        let mut upvar_owner = None;
996        self.upvars = tcx
997            .closure_captures(self.def_id)
998            .iter()
999            .zip_eq(capture_tys)
1000            .enumerate()
1001            .map(|(i, (captured_place, ty))| {
1002                let name = captured_place.to_symbol();
1003
1004                let capture = captured_place.info.capture_kind;
1005                let var_id = match captured_place.place.base {
1006                    HirPlaceBase::Upvar(upvar_id) => upvar_id.var_path.hir_id,
1007                    _ => ::rustc_middle::util::bug::bug_fmt(format_args!("Expected an upvar"))bug!("Expected an upvar"),
1008                };
1009                let upvar_base = upvar_owner.get_or_insert(var_id.owner);
1010                match (&*upvar_base, &var_id.owner) {
    (left_val, right_val) => {
        if !(*left_val == *right_val) {
            let kind = ::core::panicking::AssertKind::Eq;
            ::core::panicking::assert_failed(kind, &*left_val, &*right_val,
                ::core::option::Option::None);
        }
    }
};assert_eq!(*upvar_base, var_id.owner);
1011                let var_id = var_id.local_id;
1012
1013                let mutability = captured_place.mutability;
1014
1015                let mut projs = closure_env_projs.clone();
1016                projs.push(ProjectionElem::Field(FieldIdx::new(i), ty));
1017                match capture {
1018                    ty::UpvarCapture::ByValue | ty::UpvarCapture::ByUse => {}
1019                    ty::UpvarCapture::ByRef(..) => {
1020                        projs.push(ProjectionElem::Deref);
1021                    }
1022                };
1023
1024                let use_place = Place {
1025                    local: ty::CAPTURE_STRUCT_LOCAL,
1026                    projection: tcx.mk_place_elems(&projs),
1027                };
1028                self.var_debug_info.push(VarDebugInfo {
1029                    name,
1030                    source_info: SourceInfo::outermost(captured_place.var_ident.span),
1031                    value: VarDebugInfoContents::Place(use_place),
1032                    composite: None,
1033                    argument_index: None,
1034                });
1035
1036                let capture = Capture { captured_place, use_place, mutability };
1037                (var_id, capture)
1038            })
1039            .collect();
1040    }
1041
1042    fn args_and_body(
1043        &mut self,
1044        mut block: BasicBlock,
1045        arguments: &IndexSlice<ParamId, Param<'tcx>>,
1046        argument_scope: region::Scope,
1047        expr_id: ExprId,
1048    ) -> BlockAnd<()> {
1049        let expr_span = self.thir[expr_id].span;
1050        // Allocate locals for the function arguments
1051        for (argument_index, param) in arguments.iter().enumerate() {
1052            let source_info =
1053                SourceInfo::outermost(param.pat.as_ref().map_or(self.fn_span, |pat| pat.span));
1054            let arg_local =
1055                self.local_decls.push(LocalDecl::with_source_info(param.ty, source_info));
1056
1057            // If this is a simple binding pattern, give debuginfo a nice name.
1058            if let Some(ref pat) = param.pat
1059                && let Some(name) = pat.simple_ident()
1060            {
1061                self.var_debug_info.push(VarDebugInfo {
1062                    name,
1063                    source_info,
1064                    value: VarDebugInfoContents::Place(arg_local.into()),
1065                    composite: None,
1066                    argument_index: Some(argument_index as u16 + 1),
1067                });
1068            }
1069        }
1070
1071        self.insert_upvar_arg();
1072
1073        let mut scope = None;
1074        // Bind the argument patterns
1075        for (index, param) in arguments.iter().enumerate() {
1076            // Function arguments always get the first Local indices after the return place
1077            let local = Local::arg(index);
1078            let place = Place::from(local);
1079
1080            // Make sure we drop (parts of) the argument even when not matched on.
1081            self.schedule_drop(
1082                param.pat.as_ref().map_or(expr_span, |pat| pat.span),
1083                argument_scope,
1084                local,
1085                DropKind::Value,
1086            );
1087
1088            let Some(ref pat) = param.pat else {
1089                continue;
1090            };
1091            let original_source_scope = self.source_scope;
1092            let span = pat.span;
1093            if let Some(arg_hir_id) = param.hir_id {
1094                self.set_correct_source_scope_for_arg(arg_hir_id, original_source_scope, span);
1095            }
1096            match pat.kind {
1097                // Don't introduce extra copies for simple bindings
1098                PatKind::Binding {
1099                    var,
1100                    mode: BindingMode(ByRef::No, mutability),
1101                    subpattern: None,
1102                    ..
1103                } => {
1104                    self.local_decls[local].mutability = mutability;
1105                    self.local_decls[local].source_info.scope = self.source_scope;
1106                    **self.local_decls[local].local_info.as_mut().unwrap_crate_local() =
1107                        if let Some(kind) = param.self_kind {
1108                            LocalInfo::User(BindingForm::ImplicitSelf(kind))
1109                        } else {
1110                            let binding_mode = BindingMode(ByRef::No, mutability);
1111                            LocalInfo::User(BindingForm::Var(VarBindingForm {
1112                                binding_mode,
1113                                opt_ty_info: param.ty_span,
1114                                opt_match_place: Some((None, span)),
1115                                pat_span: span,
1116                                introductions: ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [VarBindingIntroduction { span, is_shorthand: false }]))vec![VarBindingIntroduction {
1117                                    span,
1118                                    is_shorthand: false,
1119                                }],
1120                            }))
1121                        };
1122                    self.var_indices.insert(var, LocalsForNode::One(local));
1123                }
1124                _ => {
1125                    scope = self.declare_bindings(
1126                        scope,
1127                        expr_span,
1128                        &pat,
1129                        None,
1130                        Some((Some(&place), span)),
1131                    );
1132                    let place_builder = PlaceBuilder::from(local);
1133                    block = self.place_into_pattern(block, pat, place_builder, false).into_block();
1134                }
1135            }
1136            self.source_scope = original_source_scope;
1137        }
1138
1139        // Enter the argument pattern bindings source scope, if it exists.
1140        if let Some(source_scope) = scope {
1141            self.source_scope = source_scope;
1142        }
1143
1144        if self.tcx.intrinsic(self.def_id).is_some_and(|i| i.must_be_overridden)
1145            || self.tcx.is_sdylib_interface_build()
1146        {
1147            let source_info = self.source_info(rustc_span::DUMMY_SP);
1148            self.cfg.terminate(block, source_info, TerminatorKind::Unreachable);
1149            self.cfg.start_new_block().unit()
1150        } else {
1151            // Ensure we don't silently codegen functions with fake bodies.
1152            match self.tcx.hir_node(self.hir_id) {
1153                hir::Node::Item(hir::Item {
1154                    kind: hir::ItemKind::Fn { has_body: false, .. },
1155                    ..
1156                }) => {
1157                    self.tcx.dcx().span_delayed_bug(
1158                        expr_span,
1159                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("fn item without body has reached MIR building: {0:?}",
                self.def_id))
    })format!("fn item without body has reached MIR building: {:?}", self.def_id),
1160                    );
1161                }
1162                _ => {}
1163            }
1164            self.expr_into_dest(Place::return_place(), block, expr_id)
1165        }
1166    }
1167
1168    fn set_correct_source_scope_for_arg(
1169        &mut self,
1170        arg_hir_id: HirId,
1171        original_source_scope: SourceScope,
1172        pattern_span: Span,
1173    ) {
1174        let parent_id = self.source_scopes[original_source_scope]
1175            .local_data
1176            .as_ref()
1177            .unwrap_crate_local()
1178            .lint_root;
1179        self.maybe_new_source_scope(pattern_span, arg_hir_id, parent_id);
1180    }
1181
1182    fn get_unit_temp(&mut self) -> Place<'tcx> {
1183        match self.unit_temp {
1184            Some(tmp) => tmp,
1185            None => {
1186                let ty = self.tcx.types.unit;
1187                let fn_span = self.fn_span;
1188                let tmp = self.temp(ty, fn_span);
1189                self.unit_temp = Some(tmp);
1190                tmp
1191            }
1192        }
1193    }
1194}
1195
1196fn parse_float_into_constval(num: Symbol, float_ty: ty::FloatTy, neg: bool) -> Option<ConstValue> {
1197    parse_float_into_scalar(num, float_ty, neg).map(|s| ConstValue::Scalar(s.into()))
1198}
1199
1200pub(crate) fn parse_float_into_scalar(
1201    num: Symbol,
1202    float_ty: ty::FloatTy,
1203    neg: bool,
1204) -> Option<ScalarInt> {
1205    let num = num.as_str();
1206    match float_ty {
1207        // FIXME(f16_f128): When available, compare to the library parser as with `f32` and `f64`
1208        ty::FloatTy::F16 => {
1209            let mut f = num.parse::<Half>().ok()?;
1210            if neg {
1211                f = -f;
1212            }
1213            Some(ScalarInt::from(f))
1214        }
1215        ty::FloatTy::F32 => {
1216            let Ok(rust_f) = num.parse::<f32>() else { return None };
1217            let mut f = num
1218                .parse::<Single>()
1219                .unwrap_or_else(|e| {
    ::core::panicking::panic_fmt(format_args!("apfloat::ieee::Single failed to parse `{0}`: {1:?}",
            num, e));
}panic!("apfloat::ieee::Single failed to parse `{num}`: {e:?}"));
1220
1221            if !(u128::from(rust_f.to_bits()) == f.to_bits()) {
    {
        ::core::panicking::panic_fmt(format_args!("apfloat::ieee::Single gave different result for `{0}`: {1}({2:#x}) vs Rust\'s {3}({4:#x})",
                rust_f, f, f.to_bits(),
                Single::from_bits(rust_f.to_bits().into()),
                rust_f.to_bits()));
    }
};assert!(
1222                u128::from(rust_f.to_bits()) == f.to_bits(),
1223                "apfloat::ieee::Single gave different result for `{}`: \
1224                 {}({:#x}) vs Rust's {}({:#x})",
1225                rust_f,
1226                f,
1227                f.to_bits(),
1228                Single::from_bits(rust_f.to_bits().into()),
1229                rust_f.to_bits()
1230            );
1231
1232            if neg {
1233                f = -f;
1234            }
1235
1236            Some(ScalarInt::from(f))
1237        }
1238        ty::FloatTy::F64 => {
1239            let Ok(rust_f) = num.parse::<f64>() else { return None };
1240            let mut f = num
1241                .parse::<Double>()
1242                .unwrap_or_else(|e| {
    ::core::panicking::panic_fmt(format_args!("apfloat::ieee::Double failed to parse `{0}`: {1:?}",
            num, e));
}panic!("apfloat::ieee::Double failed to parse `{num}`: {e:?}"));
1243
1244            if !(u128::from(rust_f.to_bits()) == f.to_bits()) {
    {
        ::core::panicking::panic_fmt(format_args!("apfloat::ieee::Double gave different result for `{0}`: {1}({2:#x}) vs Rust\'s {3}({4:#x})",
                rust_f, f, f.to_bits(),
                Double::from_bits(rust_f.to_bits().into()),
                rust_f.to_bits()));
    }
};assert!(
1245                u128::from(rust_f.to_bits()) == f.to_bits(),
1246                "apfloat::ieee::Double gave different result for `{}`: \
1247                 {}({:#x}) vs Rust's {}({:#x})",
1248                rust_f,
1249                f,
1250                f.to_bits(),
1251                Double::from_bits(rust_f.to_bits().into()),
1252                rust_f.to_bits()
1253            );
1254
1255            if neg {
1256                f = -f;
1257            }
1258
1259            Some(ScalarInt::from(f))
1260        }
1261        // FIXME(f16_f128): When available, compare to the library parser as with `f32` and `f64`
1262        ty::FloatTy::F128 => {
1263            let mut f = num.parse::<Quad>().ok()?;
1264            if neg {
1265                f = -f;
1266            }
1267            Some(ScalarInt::from(f))
1268        }
1269    }
1270}
1271
1272///////////////////////////////////////////////////////////////////////////
1273// Builder methods are broken up into modules, depending on what kind
1274// of thing is being lowered. Note that they use the `unpack` macro
1275// above extensively.
1276
1277mod block;
1278mod cfg;
1279mod coverageinfo;
1280mod custom;
1281mod expr;
1282mod matches;
1283mod misc;
1284mod scope;