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