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