Skip to main content

rustc_mir_build/builder/
scope.rs

1/*!
2Managing the scope stack. The scopes are tied to lexical scopes, so as
3we descend the THIR, we push a scope on the stack, build its
4contents, and then pop it off. Every scope is named by a
5`region::Scope`.
6
7### SEME Regions
8
9When pushing a new [Scope], we record the current point in the graph (a
10basic block); this marks the entry to the scope. We then generate more
11stuff in the control-flow graph. Whenever the scope is exited, either
12via a `break` or `return` or just by fallthrough, that marks an exit
13from the scope. Each lexical scope thus corresponds to a single-entry,
14multiple-exit (SEME) region in the control-flow graph.
15
16For now, we record the `region::Scope` to each SEME region for later reference
17(see caveat in next paragraph). This is because destruction scopes are tied to
18them. This may change in the future so that MIR lowering determines its own
19destruction scopes.
20
21### Not so SEME Regions
22
23In the course of building matches, it sometimes happens that certain code
24(namely guards) gets executed multiple times. This means that the scope lexical
25scope may in fact correspond to multiple, disjoint SEME regions. So in fact our
26mapping is from one scope to a vector of SEME regions. Since the SEME regions
27are disjoint, the mapping is still one-to-one for the set of SEME regions that
28we're currently in.
29
30Also in matches, the scopes assigned to arms are not always even SEME regions!
31Each arm has a single region with one entry for each pattern. We manually
32manipulate the scheduled drops in this scope to avoid dropping things multiple
33times.
34
35### Drops
36
37The primary purpose for scopes is to insert drops: while building
38the contents, we also accumulate places that need to be dropped upon
39exit from each scope. This is done by calling `schedule_drop`. Once a
40drop is scheduled, whenever we branch out we will insert drops of all
41those places onto the outgoing edge. Note that we don't know the full
42set of scheduled drops up front, and so whenever we exit from the
43scope we only drop the values scheduled thus far. For example, consider
44the scope S corresponding to this loop:
45
46```
47# let cond = true;
48loop {
49    let x = ..;
50    if cond { break; }
51    let y = ..;
52}
53```
54
55When processing the `let x`, we will add one drop to the scope for
56`x`. The break will then insert a drop for `x`. When we process `let
57y`, we will add another drop (in fact, to a subscope, but let's ignore
58that for now); any later drops would also drop `y`.
59
60### Early exit
61
62There are numerous "normal" ways to early exit a scope: `break`,
63`continue`, `return` (panics are handled separately). Whenever an
64early exit occurs, the method `break_scope` is called. It is given the
65current point in execution where the early exit occurs, as well as the
66scope you want to branch to (note that all early exits from to some
67other enclosing scope). `break_scope` will record the set of drops currently
68scheduled in a [DropTree]. Later, before `in_breakable_scope` exits, the drops
69will be added to the CFG.
70
71Panics are handled in a similar fashion, except that the drops are added to the
72MIR once the rest of the function has finished being lowered. If a terminator
73can panic, call `diverge_from(block)` with the block containing the terminator
74`block`.
75
76### Breakable scopes
77
78In addition to the normal scope stack, we track a loop scope stack
79that contains only loops and breakable blocks. It tracks where a `break`,
80`continue` or `return` should go to.
81
82*/
83
84use std::mem;
85
86use interpret::ErrorHandled;
87use rustc_data_structures::fx::FxHashMap;
88use rustc_hir::HirId;
89use rustc_index::{IndexSlice, IndexVec};
90use rustc_lint_defs::Level;
91use rustc_middle::middle::region;
92use rustc_middle::mir::{self, *};
93use rustc_middle::thir::{AdtExpr, AdtExprBase, ArmId, ExprId, ExprKind};
94use rustc_middle::ty::{self, Ty, TyCtxt, TypeVisitableExt, ValTree};
95use rustc_middle::{bug, span_bug};
96use rustc_pattern_analysis::rustc::RustcPatCtxt;
97use rustc_span::{DUMMY_SP, Span, Spanned};
98use tracing::{debug, instrument};
99
100use super::matches::BuiltMatchTree;
101use crate::builder::{BlockAnd, BlockAndExtension, BlockFrame, Builder, CFG};
102use crate::diagnostics::{
103    ConstContinueBadConst, ConstContinueNotMonomorphicConst, ConstContinueUnknownJumpTarget,
104};
105
106#[derive(#[automatically_derived]
impl<'tcx> ::core::fmt::Debug for Scopes<'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        let names: &'static _ =
            &["scopes", "breakable_scopes", "const_continuable_scopes",
                        "if_then_scope", "unwind_drops", "coroutine_drops"];
        let values: &[&dyn ::core::fmt::Debug] =
            &[&self.scopes, &self.breakable_scopes,
                        &self.const_continuable_scopes, &self.if_then_scope,
                        &self.unwind_drops, &&self.coroutine_drops];
        ::core::fmt::Formatter::debug_struct_fields_finish(f, "Scopes", names,
            values)
    }
}Debug)]
107pub(crate) struct Scopes<'tcx> {
108    scopes: Vec<Scope>,
109
110    /// The current set of breakable scopes. See module comment for more details.
111    breakable_scopes: Vec<BreakableScope<'tcx>>,
112
113    const_continuable_scopes: Vec<ConstContinuableScope<'tcx>>,
114
115    /// The scope of the innermost if-then currently being lowered.
116    if_then_scope: Option<IfThenScope>,
117
118    /// Drops that need to be done on unwind paths. See the comment on
119    /// [DropTree] for more details.
120    unwind_drops: DropTree,
121
122    /// Drops that need to be done on paths to the `CoroutineDrop` terminator.
123    coroutine_drops: DropTree,
124}
125
126#[derive(#[automatically_derived]
impl ::core::fmt::Debug for Scope {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        let names: &'static _ =
            &["source_scope", "region_scope", "drops", "moved_locals",
                        "cached_unwind_block", "cached_coroutine_drop_block"];
        let values: &[&dyn ::core::fmt::Debug] =
            &[&self.source_scope, &self.region_scope, &self.drops,
                        &self.moved_locals, &self.cached_unwind_block,
                        &&self.cached_coroutine_drop_block];
        ::core::fmt::Formatter::debug_struct_fields_finish(f, "Scope", names,
            values)
    }
}Debug)]
127struct Scope {
128    /// The source scope this scope was created in.
129    source_scope: SourceScope,
130
131    /// the region span of this scope within source code.
132    region_scope: region::Scope,
133
134    /// set of places to drop when exiting this scope. This starts
135    /// out empty but grows as variables are declared during the
136    /// building process. This is a stack, so we always drop from the
137    /// end of the vector (top of the stack) first.
138    drops: Vec<DropData>,
139
140    moved_locals: Vec<Local>,
141
142    /// The drop index that will drop everything in and below this scope on an
143    /// unwind path.
144    cached_unwind_block: Option<DropIdx>,
145
146    /// The drop index that will drop everything in and below this scope on a
147    /// coroutine drop path.
148    cached_coroutine_drop_block: Option<DropIdx>,
149}
150
151#[derive(#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for DropData { }
#[automatically_derived]
impl ::core::clone::Clone for DropData {
    #[inline]
    fn clone(&self) -> DropData {
        let _: ::core::clone::AssertParamIsClone<SourceInfo>;
        let _: ::core::clone::AssertParamIsClone<Local>;
        let _: ::core::clone::AssertParamIsClone<DropKind>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for DropData { }Copy, #[automatically_derived]
impl ::core::fmt::Debug for DropData {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field3_finish(f, "DropData",
            "source_info", &self.source_info, "local", &self.local, "kind",
            &&self.kind)
    }
}Debug)]
152struct DropData {
153    /// The `Span` where drop obligation was incurred (typically where place was
154    /// declared)
155    source_info: SourceInfo,
156
157    /// local to drop
158    local: Local,
159
160    /// Whether this is a value Drop or a StorageDead.
161    kind: DropKind,
162}
163
164#[derive(#[automatically_derived]
impl ::core::fmt::Debug for DropKind {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                DropKind::Value => "Value",
                DropKind::Storage => "Storage",
                DropKind::ForLint => "ForLint",
            })
    }
}Debug, #[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for DropKind { }
#[automatically_derived]
impl ::core::clone::Clone for DropKind {
    #[inline]
    fn clone(&self) -> DropKind { *self }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for DropKind { }Copy, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for DropKind { }
#[automatically_derived]
impl ::core::cmp::PartialEq for DropKind {
    #[inline]
    fn eq(&self, other: &DropKind) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr
    }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for DropKind { }Eq, #[automatically_derived]
impl ::core::hash::Hash for DropKind {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        ::core::hash::Hash::hash(&__self_discr, state)
    }
}Hash)]
165enum DropKind {
166    Value,
167    Storage,
168    ForLint,
169}
170
171#[derive(#[automatically_derived]
impl<'tcx> ::core::fmt::Debug for BreakableScope<'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field4_finish(f,
            "BreakableScope", "region_scope", &self.region_scope,
            "break_destination", &self.break_destination, "break_drops",
            &self.break_drops, "continue_drops", &&self.continue_drops)
    }
}Debug)]
172struct BreakableScope<'tcx> {
173    /// Region scope of the loop
174    region_scope: region::Scope,
175    /// The destination of the loop/block expression itself (i.e., where to put
176    /// the result of a `break` or `return` expression)
177    break_destination: Place<'tcx>,
178    /// Drops that happen on the `break`/`return` path.
179    break_drops: DropTree,
180    /// Drops that happen on the `continue` path.
181    continue_drops: Option<DropTree>,
182}
183
184#[derive(#[automatically_derived]
impl<'tcx> ::core::fmt::Debug for ConstContinuableScope<'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field5_finish(f,
            "ConstContinuableScope", "region_scope", &self.region_scope,
            "state_place", &self.state_place, "arms", &self.arms,
            "built_match_tree", &self.built_match_tree,
            "const_continue_drops", &&self.const_continue_drops)
    }
}Debug)]
185struct ConstContinuableScope<'tcx> {
186    /// The scope for the `#[loop_match]` which its `#[const_continue]`s will jump to.
187    region_scope: region::Scope,
188    /// The place of the state of a `#[loop_match]`, which a `#[const_continue]` must update.
189    state_place: Place<'tcx>,
190
191    arms: Box<[ArmId]>,
192    built_match_tree: BuiltMatchTree<'tcx>,
193
194    /// Drops that happen on a `#[const_continue]`
195    const_continue_drops: DropTree,
196}
197
198#[derive(#[automatically_derived]
impl ::core::fmt::Debug for IfThenScope {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f, "IfThenScope",
            "region_scope", &self.region_scope, "else_drops",
            &&self.else_drops)
    }
}Debug)]
199struct IfThenScope {
200    /// The if-then scope or arm scope
201    region_scope: region::Scope,
202    /// Drops that happen on the `else` path.
203    else_drops: DropTree,
204}
205
206/// The target of an expression that breaks out of a scope
207#[derive(#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for BreakableTarget { }
#[automatically_derived]
impl ::core::clone::Clone for BreakableTarget {
    #[inline]
    fn clone(&self) -> BreakableTarget {
        let _: ::core::clone::AssertParamIsClone<region::Scope>;
        let _: ::core::clone::AssertParamIsClone<region::Scope>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for BreakableTarget { }Copy, #[automatically_derived]
impl ::core::fmt::Debug for BreakableTarget {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            BreakableTarget::Continue(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "Continue", &__self_0),
            BreakableTarget::Break(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Break",
                    &__self_0),
            BreakableTarget::Return =>
                ::core::fmt::Formatter::write_str(f, "Return"),
        }
    }
}Debug)]
208pub(crate) enum BreakableTarget {
209    Continue(region::Scope),
210    Break(region::Scope),
211    Return,
212}
213
214#[automatically_derived]
impl ::core::marker::Copy for DropIdx { }
impl DropIdx {
    #[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 DropIdx {
    type Output = Self;
    #[inline]
    fn add(self, other: usize) -> Self {
        Self::from_usize(self.index() + other)
    }
}
impl std::ops::AddAssign<usize> for DropIdx {
    #[inline]
    fn add_assign(&mut self, other: usize) { *self = *self + other; }
}
impl rustc_index::Idx for DropIdx {
    #[inline]
    fn new(value: usize) -> Self { Self::from_usize(value) }
    #[inline]
    fn index(self) -> usize { self.as_usize() }
}
impl ::std::iter::Step for DropIdx {
    #[inline]
    fn steps_between(start: &Self, end: &Self) -> (usize, Option<usize>) {
        <usize as
                ::std::iter::Step>::steps_between(&Self::index(*start),
            &Self::index(*end))
    }
    #[inline]
    fn forward_checked(start: Self, u: usize) -> Option<Self> {
        Self::index(start).checked_add(u).map(Self::from_usize)
    }
    #[inline]
    fn backward_checked(start: Self, u: usize) -> Option<Self> {
        Self::index(start).checked_sub(u).map(Self::from_usize)
    }
    #[inline]
    fn forward_overflowing(start: Self, u: usize) -> (Self, bool) {
        let (s, o) = Self::index(start).overflowing_add(u);
        (Self::from_usize(s), o)
    }
    #[inline]
    fn backward_overflowing(start: Self, u: usize) -> (Self, bool) {
        let (s, o) = Self::index(start).overflowing_sub(u);
        (Self::from_usize(s), o)
    }
}
impl ::std::cmp::Ord for DropIdx {
    #[inline]
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        self.as_u32().cmp(&other.as_u32())
    }
}
impl ::std::cmp::PartialOrd for DropIdx {
    #[inline]
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}
impl From<DropIdx> for u32 {
    #[inline]
    fn from(v: DropIdx) -> u32 { v.as_u32() }
}
impl From<DropIdx> for usize {
    #[inline]
    fn from(v: DropIdx) -> usize { v.as_usize() }
}
impl From<usize> for DropIdx {
    #[inline]
    fn from(value: usize) -> Self { Self::from_usize(value) }
}
impl From<u32> for DropIdx {
    #[inline]
    fn from(value: u32) -> Self { Self::from_u32(value) }
}
impl ::std::cmp::Eq for DropIdx {}
impl ::std::cmp::PartialEq for DropIdx {
    fn eq(&self, other: &Self) -> bool { self.as_u32().eq(&other.as_u32()) }
}
impl ::std::marker::StructuralPartialEq for DropIdx {}
impl ::std::hash::Hash for DropIdx {
    fn hash<H: ::std::hash::Hasher>(&self, state: &mut H) {
        self.as_u32().hash(state)
    }
}
impl ::std::fmt::Debug for DropIdx {
    fn fmt(&self, fmt: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
        fmt.write_fmt(format_args!("{0}", self.as_u32()))
    }
}rustc_index::newtype_index! {
215    #[orderable]
216    struct DropIdx {}
217}
218
219const ROOT_NODE: DropIdx = DropIdx::ZERO;
220
221/// A tree of drops that we have deferred lowering. It's used for:
222///
223/// * Drops on unwind paths
224/// * Drops on coroutine drop paths (when a suspended coroutine is dropped)
225/// * Drops on return and loop exit paths
226/// * Drops on the else path in an `if let` chain
227///
228/// Once no more nodes could be added to the tree, we lower it to MIR in one go
229/// in `build_mir`.
230#[derive(#[automatically_derived]
impl ::core::fmt::Debug for DropTree {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field3_finish(f, "DropTree",
            "drop_nodes", &self.drop_nodes, "existing_drops_map",
            &self.existing_drops_map, "entry_points", &&self.entry_points)
    }
}Debug)]
231struct DropTree {
232    /// Nodes in the drop tree, containing drop data and a link to the next node.
233    drop_nodes: IndexVec<DropIdx, DropNode>,
234    /// Map for finding the index of an existing node, given its contents.
235    existing_drops_map: FxHashMap<DropNodeKey, DropIdx>,
236    /// Edges into the `DropTree` that need to be added once it's lowered.
237    entry_points: Vec<(DropIdx, BasicBlock)>,
238}
239
240/// A single node in the drop tree.
241#[derive(#[automatically_derived]
impl ::core::fmt::Debug for DropNode {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f, "DropNode",
            "data", &self.data, "next", &&self.next)
    }
}Debug)]
242struct DropNode {
243    /// Info about the drop to be performed at this node in the drop tree.
244    data: DropData,
245    /// Index of the "next" drop to perform (in drop order, not declaration order).
246    next: DropIdx,
247}
248
249/// Subset of [`DropNode`] used for reverse lookup in a hash table.
250#[derive(#[automatically_derived]
impl ::core::fmt::Debug for DropNodeKey {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f, "DropNodeKey",
            "next", &self.next, "local", &&self.local)
    }
}Debug, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for DropNodeKey { }
#[automatically_derived]
impl ::core::cmp::PartialEq for DropNodeKey {
    #[inline]
    fn eq(&self, other: &DropNodeKey) -> bool {
        self.next == other.next && self.local == other.local
    }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for DropNodeKey {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<DropIdx>;
        let _: ::core::cmp::AssertParamIsEq<Local>;
    }
}Eq, #[automatically_derived]
impl ::core::hash::Hash for DropNodeKey {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
        ::core::hash::Hash::hash(&self.next, state);
        ::core::hash::Hash::hash(&self.local, state)
    }
}Hash)]
251struct DropNodeKey {
252    next: DropIdx,
253    local: Local,
254}
255
256impl Scope {
257    /// Whether there's anything to do for the cleanup path, that is,
258    /// when unwinding through this scope. This includes destructors,
259    /// but not StorageDead statements, which don't get emitted at all
260    /// for unwinding, for several reasons:
261    ///  * clang doesn't emit llvm.lifetime.end for C++ unwinding
262    ///  * LLVM's memory dependency analysis can't handle it atm
263    ///  * polluting the cleanup MIR with StorageDead creates
264    ///    landing pads even though there's no actual destructors
265    ///  * freeing up stack space has no effect during unwinding
266    /// Note that for coroutines we do emit StorageDeads, for the
267    /// use of optimizations in the MIR coroutine transform.
268    fn needs_cleanup(&self) -> bool {
269        self.drops.iter().any(|drop| match drop.kind {
270            DropKind::Value | DropKind::ForLint => true,
271            DropKind::Storage => false,
272        })
273    }
274
275    fn invalidate_cache(&mut self) {
276        self.cached_unwind_block = None;
277        self.cached_coroutine_drop_block = None;
278    }
279}
280
281/// A trait that determined how [DropTree] creates its blocks and
282/// links to any entry nodes.
283trait DropTreeBuilder<'tcx> {
284    /// Create a new block for the tree. This should call either
285    /// `cfg.start_new_block()` or `cfg.start_new_cleanup_block()`.
286    fn make_block(cfg: &mut CFG<'tcx>) -> BasicBlock;
287
288    /// Links a block outside the drop tree, `from`, to the block `to` inside
289    /// the drop tree.
290    fn link_entry_point(cfg: &mut CFG<'tcx>, from: BasicBlock, to: BasicBlock);
291}
292
293impl DropTree {
294    fn new() -> Self {
295        // The root node of the tree doesn't represent a drop, but instead
296        // represents the block in the tree that should be jumped to once all
297        // of the required drops have been performed.
298        let fake_source_info = SourceInfo::outermost(DUMMY_SP);
299        let fake_data =
300            DropData { source_info: fake_source_info, local: Local::MAX, kind: DropKind::Storage };
301        let drop_nodes = IndexVec::from_raw(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [DropNode { data: fake_data, next: DropIdx::MAX }]))vec![DropNode { data: fake_data, next: DropIdx::MAX }]);
302        Self { drop_nodes, entry_points: Vec::new(), existing_drops_map: FxHashMap::default() }
303    }
304
305    /// Adds a node to the drop tree, consisting of drop data and the index of
306    /// the "next" drop (in drop order), which could be the sentinel [`ROOT_NODE`].
307    ///
308    /// If there is already an equivalent node in the tree, nothing is added, and
309    /// that node's index is returned. Otherwise, the new node's index is returned.
310    fn add_drop(&mut self, data: DropData, next: DropIdx) -> DropIdx {
311        let drop_nodes = &mut self.drop_nodes;
312        *self
313            .existing_drops_map
314            .entry(DropNodeKey { next, local: data.local })
315            // Create a new node, and also add its index to the map.
316            .or_insert_with(|| drop_nodes.push(DropNode { data, next }))
317    }
318
319    /// Registers `from` as an entry point to this drop tree, at `to`.
320    ///
321    /// During [`Self::build_mir`], `from` will be linked to the corresponding
322    /// block within the drop tree.
323    fn add_entry_point(&mut self, from: BasicBlock, to: DropIdx) {
324        if true {
    if !(to < self.drop_nodes.next_index()) {
        ::core::panicking::panic("assertion failed: to < self.drop_nodes.next_index()")
    };
};debug_assert!(to < self.drop_nodes.next_index());
325        self.entry_points.push((to, from));
326    }
327
328    /// Builds the MIR for a given drop tree.
329    fn build_mir<'tcx, T: DropTreeBuilder<'tcx>>(
330        &mut self,
331        cfg: &mut CFG<'tcx>,
332        root_node: Option<BasicBlock>,
333    ) -> IndexVec<DropIdx, Option<BasicBlock>> {
334        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/4b6d04e706108ccfeafe2547fbe857dfe8972bad/compiler/rustc_mir_build/src/builder/scope.rs:334",
                        "rustc_mir_build::builder::scope", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/4b6d04e706108ccfeafe2547fbe857dfe8972bad/compiler/rustc_mir_build/src/builder/scope.rs"),
                        ::tracing_core::__macro_support::Option::Some(334u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_mir_build::builder::scope"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("DropTree::build_mir(drops = {0:#?})",
                                                    self) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("DropTree::build_mir(drops = {:#?})", self);
335
336        let mut blocks = self.assign_blocks::<T>(cfg, root_node);
337        self.link_blocks(cfg, &mut blocks);
338
339        blocks
340    }
341
342    /// Assign blocks for all of the drops in the drop tree that need them.
343    fn assign_blocks<'tcx, T: DropTreeBuilder<'tcx>>(
344        &mut self,
345        cfg: &mut CFG<'tcx>,
346        root_node: Option<BasicBlock>,
347    ) -> IndexVec<DropIdx, Option<BasicBlock>> {
348        // StorageDead statements can share blocks with each other and also with
349        // a Drop terminator. We iterate through the drops to find which drops
350        // need their own block.
351        #[derive(#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for Block { }
#[automatically_derived]
impl ::core::clone::Clone for Block {
    #[inline]
    fn clone(&self) -> Block {
        let _: ::core::clone::AssertParamIsClone<DropIdx>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for Block { }Copy)]
352        enum Block {
353            // This drop is unreachable
354            None,
355            // This drop is only reachable through the `StorageDead` with the
356            // specified index.
357            Shares(DropIdx),
358            // This drop has more than one way of being reached, or it is
359            // branched to from outside the tree, or its predecessor is a
360            // `Value` drop.
361            Own,
362        }
363
364        let mut blocks = IndexVec::from_elem(None, &self.drop_nodes);
365        blocks[ROOT_NODE] = root_node;
366
367        let mut needs_block = IndexVec::from_elem(Block::None, &self.drop_nodes);
368        if root_node.is_some() {
369            // In some cases (such as drops for `continue`) the root node
370            // already has a block. In this case, make sure that we don't
371            // override it.
372            needs_block[ROOT_NODE] = Block::Own;
373        }
374
375        // Sort so that we only need to check the last value.
376        let entry_points = &mut self.entry_points;
377        entry_points.sort();
378
379        for (drop_idx, drop_node) in self.drop_nodes.iter_enumerated().rev() {
380            if entry_points.last().is_some_and(|entry_point| entry_point.0 == drop_idx) {
381                let block = *blocks[drop_idx].get_or_insert_with(|| T::make_block(cfg));
382                needs_block[drop_idx] = Block::Own;
383                while entry_points.last().is_some_and(|entry_point| entry_point.0 == drop_idx) {
384                    let entry_block = entry_points.pop().unwrap().1;
385                    T::link_entry_point(cfg, entry_block, block);
386                }
387            }
388            match needs_block[drop_idx] {
389                Block::None => continue,
390                Block::Own => {
391                    blocks[drop_idx].get_or_insert_with(|| T::make_block(cfg));
392                }
393                Block::Shares(pred) => {
394                    blocks[drop_idx] = blocks[pred];
395                }
396            }
397            if let DropKind::Value = drop_node.data.kind {
398                needs_block[drop_node.next] = Block::Own;
399            } else if drop_idx != ROOT_NODE {
400                match &mut needs_block[drop_node.next] {
401                    pred @ Block::None => *pred = Block::Shares(drop_idx),
402                    pred @ Block::Shares(_) => *pred = Block::Own,
403                    Block::Own => (),
404                }
405            }
406        }
407
408        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/4b6d04e706108ccfeafe2547fbe857dfe8972bad/compiler/rustc_mir_build/src/builder/scope.rs:408",
                        "rustc_mir_build::builder::scope", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/4b6d04e706108ccfeafe2547fbe857dfe8972bad/compiler/rustc_mir_build/src/builder/scope.rs"),
                        ::tracing_core::__macro_support::Option::Some(408u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_mir_build::builder::scope"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("assign_blocks: blocks = {0:#?}",
                                                    blocks) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("assign_blocks: blocks = {:#?}", blocks);
409        if !entry_points.is_empty() {
    ::core::panicking::panic("assertion failed: entry_points.is_empty()")
};assert!(entry_points.is_empty());
410
411        blocks
412    }
413
414    fn link_blocks<'tcx>(
415        &self,
416        cfg: &mut CFG<'tcx>,
417        blocks: &IndexSlice<DropIdx, Option<BasicBlock>>,
418    ) {
419        for (drop_idx, drop_node) in self.drop_nodes.iter_enumerated().rev() {
420            let Some(block) = blocks[drop_idx] else { continue };
421            match drop_node.data.kind {
422                DropKind::Value => {
423                    let terminator = TerminatorKind::Drop {
424                        target: blocks[drop_node.next].unwrap(),
425                        // The caller will handle this if needed.
426                        unwind: UnwindAction::Terminate(UnwindTerminateReason::InCleanup),
427                        place: drop_node.data.local.into(),
428                        replace: false,
429                        drop: None,
430                    };
431                    cfg.terminate(block, drop_node.data.source_info, terminator);
432                }
433                DropKind::ForLint => {
434                    let stmt = Statement::new(
435                        drop_node.data.source_info,
436                        StatementKind::BackwardIncompatibleDropHint {
437                            place: Box::new(drop_node.data.local.into()),
438                            reason: BackwardIncompatibleDropReason::Edition2024,
439                        },
440                    );
441                    cfg.push(block, stmt);
442                    let target = blocks[drop_node.next].unwrap();
443                    if target != block {
444                        // Diagnostics don't use this `Span` but debuginfo
445                        // might. Since we don't want breakpoints to be placed
446                        // here, especially when this is on an unwind path, we
447                        // use `DUMMY_SP`.
448                        let source_info =
449                            SourceInfo { span: DUMMY_SP, ..drop_node.data.source_info };
450                        let terminator = TerminatorKind::Goto { target };
451                        cfg.terminate(block, source_info, terminator);
452                    }
453                }
454                // Root nodes don't correspond to a drop.
455                DropKind::Storage if drop_idx == ROOT_NODE => {}
456                DropKind::Storage => {
457                    let stmt = Statement::new(
458                        drop_node.data.source_info,
459                        StatementKind::StorageDead(drop_node.data.local),
460                    );
461                    cfg.push(block, stmt);
462                    let target = blocks[drop_node.next].unwrap();
463                    if target != block {
464                        // Diagnostics don't use this `Span` but debuginfo
465                        // might. Since we don't want breakpoints to be placed
466                        // here, especially when this is on an unwind path, we
467                        // use `DUMMY_SP`.
468                        let source_info =
469                            SourceInfo { span: DUMMY_SP, ..drop_node.data.source_info };
470                        let terminator = TerminatorKind::Goto { target };
471                        cfg.terminate(block, source_info, terminator);
472                    }
473                }
474            }
475        }
476    }
477}
478
479impl<'tcx> Scopes<'tcx> {
480    pub(crate) fn new() -> Self {
481        Self {
482            scopes: Vec::new(),
483            breakable_scopes: Vec::new(),
484            const_continuable_scopes: Vec::new(),
485            if_then_scope: None,
486            unwind_drops: DropTree::new(),
487            coroutine_drops: DropTree::new(),
488        }
489    }
490
491    fn push_scope(&mut self, region_scope: region::Scope, vis_scope: SourceScope) {
492        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/4b6d04e706108ccfeafe2547fbe857dfe8972bad/compiler/rustc_mir_build/src/builder/scope.rs:492",
                        "rustc_mir_build::builder::scope", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/4b6d04e706108ccfeafe2547fbe857dfe8972bad/compiler/rustc_mir_build/src/builder/scope.rs"),
                        ::tracing_core::__macro_support::Option::Some(492u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_mir_build::builder::scope"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("push_scope({0:?})",
                                                    region_scope) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("push_scope({:?})", region_scope);
493        self.scopes.push(Scope {
494            source_scope: vis_scope,
495            region_scope,
496            drops: ::alloc::vec::Vec::new()vec![],
497            moved_locals: ::alloc::vec::Vec::new()vec![],
498            cached_unwind_block: None,
499            cached_coroutine_drop_block: None,
500        });
501    }
502
503    fn pop_scope(&mut self, region_scope: region::Scope) {
504        let scope = self.scopes.pop().unwrap();
505        {
    match (&scope.region_scope, &region_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!(scope.region_scope, region_scope);
506    }
507
508    /// Returns the position in the scope stack of `region_scope`.
509    fn stack_index(&self, region_scope: region::Scope, span: Span) -> usize {
510        self.scopes
511            .iter()
512            .rposition(|scope| scope.region_scope == region_scope)
513            .unwrap_or_else(|| ::rustc_middle::util::bug::span_bug_fmt(span,
    format_args!("region_scope {0:?} does not enclose", region_scope))span_bug!(span, "region_scope {:?} does not enclose", region_scope))
514    }
515
516    /// Returns the topmost active scope, which is known to be alive until
517    /// the next scope expression.
518    fn topmost(&self) -> region::Scope {
519        self.scopes.last().expect("topmost_scope: no scopes present").region_scope
520    }
521}
522
523/// Used by [`Builder::in_scope`] to create source scopes mapping from MIR back to HIR at points
524/// where lint levels change.
525#[derive(#[automatically_derived]
impl ::core::marker::Copy for LintLevel { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for LintLevel { }
#[automatically_derived]
impl ::core::clone::Clone for LintLevel {
    #[inline]
    fn clone(&self) -> LintLevel {
        let _: ::core::clone::AssertParamIsClone<HirId>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for LintLevel {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            LintLevel::Inherited =>
                ::core::fmt::Formatter::write_str(f, "Inherited"),
            LintLevel::Explicit(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "Explicit", &__self_0),
        }
    }
}Debug)]
526pub(crate) enum LintLevel {
527    Inherited,
528    Explicit(HirId),
529}
530
531impl<'a, 'tcx> Builder<'a, 'tcx> {
532    // Adding and removing scopes
533    // ==========================
534
535    ///  Start a breakable scope, which tracks where `continue`, `break` and
536    ///  `return` should branch to.
537    pub(crate) fn in_breakable_scope<F>(
538        &mut self,
539        loop_block: Option<BasicBlock>,
540        break_destination: Place<'tcx>,
541        span: Span,
542        f: F,
543    ) -> BlockAnd<()>
544    where
545        F: FnOnce(&mut Builder<'a, 'tcx>) -> Option<BlockAnd<()>>,
546    {
547        let region_scope = self.scopes.topmost();
548        let scope = BreakableScope {
549            region_scope,
550            break_destination,
551            break_drops: DropTree::new(),
552            continue_drops: loop_block.map(|_| DropTree::new()),
553        };
554        self.scopes.breakable_scopes.push(scope);
555        let normal_exit_block = f(self);
556        let breakable_scope = self.scopes.breakable_scopes.pop().unwrap();
557        if !(breakable_scope.region_scope == region_scope) {
    ::core::panicking::panic("assertion failed: breakable_scope.region_scope == region_scope")
};assert!(breakable_scope.region_scope == region_scope);
558        let break_block =
559            self.build_exit_tree(breakable_scope.break_drops, region_scope, span, None);
560        if let Some(drops) = breakable_scope.continue_drops {
561            self.build_exit_tree(drops, region_scope, span, loop_block);
562        }
563        match (normal_exit_block, break_block) {
564            (Some(block), None) | (None, Some(block)) => block,
565            (None, None) => self.cfg.start_new_block().unit(),
566            (Some(normal_block), Some(exit_block)) => {
567                let target = self.cfg.start_new_block();
568                let source_info = self.source_info(span);
569                self.cfg.terminate(
570                    normal_block.into_block(),
571                    source_info,
572                    TerminatorKind::Goto { target },
573                );
574                self.cfg.terminate(
575                    exit_block.into_block(),
576                    source_info,
577                    TerminatorKind::Goto { target },
578                );
579                target.unit()
580            }
581        }
582    }
583
584    /// Start a const-continuable scope, which tracks where `#[const_continue] break` should
585    /// branch to.
586    pub(crate) fn in_const_continuable_scope<F>(
587        &mut self,
588        arms: Box<[ArmId]>,
589        built_match_tree: BuiltMatchTree<'tcx>,
590        state_place: Place<'tcx>,
591        span: Span,
592        f: F,
593    ) -> BlockAnd<()>
594    where
595        F: FnOnce(&mut Builder<'a, 'tcx>) -> BlockAnd<()>,
596    {
597        let region_scope = self.scopes.topmost();
598        let scope = ConstContinuableScope {
599            region_scope,
600            state_place,
601            const_continue_drops: DropTree::new(),
602            arms,
603            built_match_tree,
604        };
605        self.scopes.const_continuable_scopes.push(scope);
606        let normal_exit_block = f(self);
607        let const_continue_scope = self.scopes.const_continuable_scopes.pop().unwrap();
608        if !(const_continue_scope.region_scope == region_scope) {
    ::core::panicking::panic("assertion failed: const_continue_scope.region_scope == region_scope")
};assert!(const_continue_scope.region_scope == region_scope);
609
610        let break_block = self.build_exit_tree(
611            const_continue_scope.const_continue_drops,
612            region_scope,
613            span,
614            None,
615        );
616
617        match (normal_exit_block, break_block) {
618            (block, None) => block,
619            (normal_block, Some(exit_block)) => {
620                let target = self.cfg.start_new_block();
621                let source_info = self.source_info(span);
622                self.cfg.terminate(
623                    normal_block.into_block(),
624                    source_info,
625                    TerminatorKind::Goto { target },
626                );
627                self.cfg.terminate(
628                    exit_block.into_block(),
629                    source_info,
630                    TerminatorKind::Goto { target },
631                );
632                target.unit()
633            }
634        }
635    }
636
637    /// Start an if-then scope which tracks drop for `if` expressions and `if`
638    /// guards.
639    ///
640    /// For an if-let chain:
641    /// ```rust,ignore(illustrative)
642    ///     if let Some(x) = a && let Some(y) = b && let Some(z) = c { ... }
643    /// ```
644    /// There are three possible ways the condition can be false and we may have
645    /// to drop `x`, `x` and `y`, or neither depending on which binding fails.
646    /// To handle this correctly we use a `DropTree` in a similar way to a
647    /// `loop` expression and 'break' out on all of the 'else' paths.
648    ///
649    /// Notes:
650    /// - We don't need to keep a stack of scopes in the `Builder` because the
651    ///   'else' paths will only leave the innermost scope.
652    /// - This is also used for match guards.
653    ///
654    /// Returns blocks for the two condition outcomes, `(true_block, false_block)`.
655    pub(crate) fn in_if_then_scope(
656        &mut self,
657        region_scope: region::Scope,
658        span: Span,
659        // Closure that will lower the condition(s), register breaks, and return `true_block`.
660        f: impl FnOnce(&mut Builder<'a, 'tcx>) -> BlockAnd<()>,
661    ) -> (BasicBlock, BasicBlock) {
662        let scope = IfThenScope { region_scope, else_drops: DropTree::new() };
663        let previous_scope = mem::replace(&mut self.scopes.if_then_scope, Some(scope));
664
665        let true_block = f(self).into_block();
666
667        let if_then_scope = mem::replace(&mut self.scopes.if_then_scope, previous_scope).unwrap();
668        if !(if_then_scope.region_scope == region_scope) {
    ::core::panicking::panic("assertion failed: if_then_scope.region_scope == region_scope")
};assert!(if_then_scope.region_scope == region_scope);
669
670        // Lower any break paths (where the condition was false)
671        // into a drop tree that ends in `false_block`.
672        let false_block = self
673            .build_exit_tree(if_then_scope.else_drops, region_scope, span, None)
674            .map(|false_block: BlockAnd<()>| false_block.into_block())
675            .unwrap_or_else(|| self.cfg.start_new_block());
676
677        (true_block, false_block)
678    }
679
680    /// Convenience wrapper that pushes a scope and then executes `f`
681    /// to build its contents, popping the scope afterwards.
682    {}
#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("in_scope",
                                    "rustc_mir_build::builder::scope", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/4b6d04e706108ccfeafe2547fbe857dfe8972bad/compiler/rustc_mir_build/src/builder/scope.rs"),
                                    ::tracing_core::__macro_support::Option::Some(682u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_mir_build::builder::scope"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("region_scope")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("region_scope");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("source_info")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("source_info");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("lint_level")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("lint_level");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&region_scope)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&source_info)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&lint_level)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: BlockAnd<R> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let source_scope = self.source_scope;
            if let LintLevel::Explicit(current_hir_id) = lint_level {
                let parent_id =
                    self.source_scopes[source_scope].local_data.as_ref().unwrap_crate_local().lint_root;
                self.maybe_new_source_scope(source_info.span, current_hir_id,
                    parent_id);
            }
            self.push_scope(region_scope);
            let mut block;
            let rv = { let BlockAnd(b, v) = f(self); block = b; v };
            block = self.pop_scope(region_scope, block).into_block();
            self.source_scope = source_scope;
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event /rustc-dev/4b6d04e706108ccfeafe2547fbe857dfe8972bad/compiler/rustc_mir_build/src/builder/scope.rs:703",
                                    "rustc_mir_build::builder::scope", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/4b6d04e706108ccfeafe2547fbe857dfe8972bad/compiler/rustc_mir_build/src/builder/scope.rs"),
                                    ::tracing_core::__macro_support::Option::Some(703u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_mir_build::builder::scope"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("block")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("block");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&block)
                                                        as &dyn ::tracing::field::Value))])
                        });
                } else { ; }
            };
            block.and(rv)
        }
    }
}#[instrument(skip(self, f), level = "debug")]
683    pub(crate) fn in_scope<F, R>(
684        &mut self,
685        (region_scope, source_info): (region::Scope, SourceInfo),
686        lint_level: LintLevel,
687        f: F,
688    ) -> BlockAnd<R>
689    where
690        F: FnOnce(&mut Builder<'a, 'tcx>) -> BlockAnd<R>,
691    {
692        let source_scope = self.source_scope;
693        if let LintLevel::Explicit(current_hir_id) = lint_level {
694            let parent_id =
695                self.source_scopes[source_scope].local_data.as_ref().unwrap_crate_local().lint_root;
696            self.maybe_new_source_scope(source_info.span, current_hir_id, parent_id);
697        }
698        self.push_scope(region_scope);
699        let mut block;
700        let rv = unpack!(block = f(self));
701        block = self.pop_scope(region_scope, block).into_block();
702        self.source_scope = source_scope;
703        debug!(?block);
704        block.and(rv)
705    }
706
707    /// Convenience wrapper that executes `f` either within the current scope or a new scope.
708    /// Used for pattern matching, which introduces an additional scope for patterns with guards.
709    pub(crate) fn opt_in_scope<R>(
710        &mut self,
711        opt_region_scope: Option<(region::Scope, SourceInfo)>,
712        f: impl FnOnce(&mut Builder<'a, 'tcx>) -> BlockAnd<R>,
713    ) -> BlockAnd<R> {
714        if let Some(region_scope) = opt_region_scope {
715            self.in_scope(region_scope, LintLevel::Inherited, f)
716        } else {
717            f(self)
718        }
719    }
720
721    /// Push a scope onto the stack. You can then build code in this
722    /// scope and call `pop_scope` afterwards. Note that these two
723    /// calls must be paired; using `in_scope` as a convenience
724    /// wrapper maybe preferable.
725    pub(crate) fn push_scope(&mut self, region_scope: region::Scope) {
726        self.scopes.push_scope(region_scope, self.source_scope);
727    }
728
729    /// Pops a scope, which should have region scope `region_scope`,
730    /// adding any drops onto the end of `block` that are needed.
731    /// This must match 1-to-1 with `push_scope`.
732    pub(crate) fn pop_scope(
733        &mut self,
734        region_scope: region::Scope,
735        mut block: BasicBlock,
736    ) -> BlockAnd<()> {
737        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/4b6d04e706108ccfeafe2547fbe857dfe8972bad/compiler/rustc_mir_build/src/builder/scope.rs:737",
                        "rustc_mir_build::builder::scope", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/4b6d04e706108ccfeafe2547fbe857dfe8972bad/compiler/rustc_mir_build/src/builder/scope.rs"),
                        ::tracing_core::__macro_support::Option::Some(737u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_mir_build::builder::scope"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("pop_scope({0:?}, {1:?})",
                                                    region_scope, block) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("pop_scope({:?}, {:?})", region_scope, block);
738
739        block = self.leave_top_scope(block);
740        self.scopes.pop_scope(region_scope);
741
742        block.unit()
743    }
744
745    /// Sets up the drops for breaking from `block` to `target`.
746    pub(crate) fn break_scope(
747        &mut self,
748        mut block: BasicBlock,
749        value: Option<ExprId>,
750        target: BreakableTarget,
751        source_info: SourceInfo,
752    ) -> BlockAnd<()> {
753        let span = source_info.span;
754
755        let get_scope_index = |scope: region::Scope| {
756            // find the loop-scope by its `region::Scope`.
757            self.scopes
758                .breakable_scopes
759                .iter()
760                .rposition(|breakable_scope| breakable_scope.region_scope == scope)
761                .unwrap_or_else(|| ::rustc_middle::util::bug::span_bug_fmt(span,
    format_args!("no enclosing breakable scope found"))span_bug!(span, "no enclosing breakable scope found"))
762        };
763        let (break_index, destination) = match target {
764            BreakableTarget::Return => {
765                let scope = &self.scopes.breakable_scopes[0];
766                if scope.break_destination != Place::return_place() {
767                    ::rustc_middle::util::bug::span_bug_fmt(span,
    format_args!("`return` in item with no return scope"));span_bug!(span, "`return` in item with no return scope");
768                }
769                (0, Some(scope.break_destination))
770            }
771            BreakableTarget::Break(scope) => {
772                let break_index = get_scope_index(scope);
773                let scope = &self.scopes.breakable_scopes[break_index];
774                (break_index, Some(scope.break_destination))
775            }
776            BreakableTarget::Continue(scope) => {
777                let break_index = get_scope_index(scope);
778                (break_index, None)
779            }
780        };
781
782        match (destination, value) {
783            (Some(destination), Some(value)) => {
784                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/4b6d04e706108ccfeafe2547fbe857dfe8972bad/compiler/rustc_mir_build/src/builder/scope.rs:784",
                        "rustc_mir_build::builder::scope", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/4b6d04e706108ccfeafe2547fbe857dfe8972bad/compiler/rustc_mir_build/src/builder/scope.rs"),
                        ::tracing_core::__macro_support::Option::Some(784u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_mir_build::builder::scope"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("stmt_expr Break val block_context.push(SubExpr)")
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("stmt_expr Break val block_context.push(SubExpr)");
785                self.block_context.push(BlockFrame::SubExpr);
786                block = self.expr_into_dest(destination, block, value).into_block();
787                self.block_context.pop();
788            }
789            (Some(destination), None) => {
790                self.cfg.push_assign_unit(block, source_info, destination, self.tcx)
791            }
792            (None, Some(_)) => {
793                {
    ::core::panicking::panic_fmt(format_args!("`return`, `become` and `break` with value and must have a destination"));
}panic!("`return`, `become` and `break` with value and must have a destination")
794            }
795            (None, None) => {}
796        }
797
798        let region_scope = self.scopes.breakable_scopes[break_index].region_scope;
799        let stack_index = self.scopes.stack_index(region_scope, span);
800        let drops = if destination.is_some() {
801            &mut self.scopes.breakable_scopes[break_index].break_drops
802        } else {
803            let Some(drops) = self.scopes.breakable_scopes[break_index].continue_drops.as_mut()
804            else {
805                self.tcx.dcx().span_delayed_bug(
806                    source_info.span,
807                    "unlabelled `continue` within labelled block",
808                );
809                self.cfg.terminate(block, source_info, TerminatorKind::Unreachable);
810
811                return self.cfg.start_new_block().unit();
812            };
813            drops
814        };
815
816        let mut drop_idx = ROOT_NODE;
817        for scope in &self.scopes.scopes[stack_index + 1..] {
818            for drop in &scope.drops {
819                drop_idx = drops.add_drop(*drop, drop_idx);
820            }
821        }
822        drops.add_entry_point(block, drop_idx);
823
824        // `build_drop_trees` doesn't have access to our source_info, so we
825        // create a dummy terminator now. `TerminatorKind::UnwindResume` is used
826        // because MIR type checking will panic if it hasn't been overwritten.
827        // (See `<ExitScopes as DropTreeBuilder>::link_entry_point`.)
828        self.cfg.terminate(block, source_info, TerminatorKind::UnwindResume);
829
830        self.cfg.start_new_block().unit()
831    }
832
833    /// Based on `FunctionCx::eval_unevaluated_mir_constant_to_valtree`.
834    fn eval_unevaluated_mir_constant_to_valtree(
835        &self,
836        constant: ConstOperand<'tcx>,
837    ) -> Result<(ty::ValTree<'tcx>, Ty<'tcx>), interpret::ErrorHandled> {
838        if !!constant.const_.ty().has_param() {
    ::core::panicking::panic("assertion failed: !constant.const_.ty().has_param()")
};assert!(!constant.const_.ty().has_param());
839        let (uv, ty) = match constant.const_ {
840            mir::Const::Unevaluated(uv, ty) => (uv.shrink(self.tcx), ty),
841            mir::Const::Ty(_, c) => match c.kind() {
842                // A constant that came from a const generic but was then used as an argument to
843                // old-style simd_shuffle (passing as argument instead of as a generic param).
844                ty::ConstKind::Value(cv) => return Ok((cv.valtree, cv.ty)),
845                other => ::rustc_middle::util::bug::span_bug_fmt(constant.span,
    format_args!("{0:#?}", other))span_bug!(constant.span, "{other:#?}"),
846            },
847            mir::Const::Val(mir::ConstValue::Scalar(mir::interpret::Scalar::Int(val)), ty) => {
848                return Ok((ValTree::from_scalar_int(self.tcx, val), ty));
849            }
850            // We should never encounter `Const::Val` unless MIR opts (like const prop) evaluate
851            // a constant and write that value back into `Operand`s. This could happen, but is
852            // unlikely. Also: all users of `simd_shuffle` are on unstable and already need to take
853            // a lot of care around intrinsics. For an issue to happen here, it would require a
854            // macro expanding to a `simd_shuffle` call without wrapping the constant argument in a
855            // `const {}` block, but the user pass through arbitrary expressions.
856
857            // FIXME(oli-obk): Replace the magic const generic argument of `simd_shuffle` with a
858            // real const generic, and get rid of this entire function.
859            other => ::rustc_middle::util::bug::span_bug_fmt(constant.span,
    format_args!("{0:#?}", other))span_bug!(constant.span, "{other:#?}"),
860        };
861
862        match self.tcx.const_eval_resolve_for_typeck(self.typing_env(), uv, constant.span) {
863            Ok(Ok(valtree)) => Ok((valtree, ty)),
864            Ok(Err(ty)) => ::rustc_middle::util::bug::span_bug_fmt(constant.span,
    format_args!("could not convert {0:?} to a valtree", ty))span_bug!(constant.span, "could not convert {ty:?} to a valtree"),
865            Err(e) => Err(e),
866        }
867    }
868
869    /// Sets up the drops for jumping from `block` to `scope`.
870    pub(crate) fn break_const_continuable_scope(
871        &mut self,
872        mut block: BasicBlock,
873        value: ExprId,
874        scope: region::Scope,
875        source_info: SourceInfo,
876    ) -> BlockAnd<()> {
877        let span = source_info.span;
878
879        // A break can only break out of a scope, so the value should be a scope.
880        let rustc_middle::thir::ExprKind::Scope { value, .. } = self.thir[value].kind else {
881            ::rustc_middle::util::bug::span_bug_fmt(span,
    format_args!("break value must be a scope"))span_bug!(span, "break value must be a scope")
882        };
883
884        let expr = &self.thir[value];
885        let constant = match &expr.kind {
886            ExprKind::Adt(AdtExpr { variant_index, fields, base, .. }) => {
887                if !#[allow(non_exhaustive_omitted_patterns)] match base {
            AdtExprBase::None => true,
            _ => false,
        } {
    ::core::panicking::panic("assertion failed: matches!(base, AdtExprBase::None)")
};assert!(matches!(base, AdtExprBase::None));
888                if !fields.is_empty() {
    ::core::panicking::panic("assertion failed: fields.is_empty()")
};assert!(fields.is_empty());
889                ConstOperand {
890                    span: self.thir[value].span,
891                    user_ty: None,
892                    const_: Const::Ty(
893                        self.thir[value].ty,
894                        ty::Const::new_value(
895                            self.tcx,
896                            ValTree::from_branches(
897                                self.tcx,
898                                [ty::Const::new_value(
899                                    self.tcx,
900                                    ValTree::from_scalar_int(
901                                        self.tcx,
902                                        variant_index.as_u32().into(),
903                                    ),
904                                    self.tcx.types.u32,
905                                )],
906                            ),
907                            self.thir[value].ty,
908                        ),
909                    ),
910                }
911            }
912
913            ExprKind::Literal { .. }
914            | ExprKind::NonHirLiteral { .. }
915            | ExprKind::ZstLiteral { .. }
916            | ExprKind::NamedConst { .. } => self.as_constant(&self.thir[value]),
917
918            other => {
919                use crate::diagnostics::ConstContinueNotMonomorphicConstReason as Reason;
920
921                let span = expr.span;
922                let reason = match other {
923                    ExprKind::ConstParam { .. } => Reason::ConstantParameter { span },
924                    ExprKind::ConstBlock { .. } => Reason::ConstBlock { span },
925                    _ => Reason::Other { span },
926                };
927
928                self.tcx
929                    .dcx()
930                    .emit_err(ConstContinueNotMonomorphicConst { span: expr.span, reason });
931                return block.unit();
932            }
933        };
934
935        let break_index = self
936            .scopes
937            .const_continuable_scopes
938            .iter()
939            .rposition(|const_continuable_scope| const_continuable_scope.region_scope == scope)
940            .unwrap_or_else(|| ::rustc_middle::util::bug::span_bug_fmt(span,
    format_args!("no enclosing const-continuable scope found"))span_bug!(span, "no enclosing const-continuable scope found"));
941
942        let scope = &self.scopes.const_continuable_scopes[break_index];
943
944        let state_decl = &self.local_decls[scope.state_place.as_local().unwrap()];
945        let state_ty = state_decl.ty;
946        let (discriminant_ty, rvalue) = match state_ty.kind() {
947            ty::Adt(adt_def, _) if adt_def.is_enum() => {
948                (state_ty.discriminant_ty(self.tcx), Rvalue::Discriminant(scope.state_place))
949            }
950            ty::Uint(_) | ty::Int(_) | ty::Float(_) | ty::Bool | ty::Char => {
951                (state_ty, Rvalue::Use(Operand::Copy(scope.state_place), WithRetag::Yes))
952            }
953            _ => ::rustc_middle::util::bug::span_bug_fmt(state_decl.source_info.span,
    format_args!("unsupported #[loop_match] state"))span_bug!(state_decl.source_info.span, "unsupported #[loop_match] state"),
954        };
955
956        // The `PatCtxt` is normally used in pattern exhaustiveness checking, but reused
957        // here because it performs normalization and const evaluation.
958        let dropless_arena = rustc_arena::DroplessArena::default();
959        let typeck_results = self.tcx.typeck(self.def_id);
960        let cx = RustcPatCtxt {
961            tcx: self.tcx,
962            typeck_results,
963            module: self.tcx.parent_module(self.hir_id),
964            typing_env: ty::TypingEnv::post_typeck_until_borrowck_for_mir_build(
965                self.tcx,
966                self.def_id,
967            ),
968            dropless_arena: &dropless_arena,
969            match_lint_level: self.hir_id,
970            whole_match_span: Some(rustc_span::Span::default()),
971            scrut_span: rustc_span::Span::default(),
972            refutable: true,
973            known_valid_scrutinee: true,
974            internal_state: Default::default(),
975        };
976
977        let valtree = match self.eval_unevaluated_mir_constant_to_valtree(constant) {
978            Ok((valtree, ty)) => {
979                // Defensively check that the type is monomorphic.
980                if !!ty.has_param() {
    ::core::panicking::panic("assertion failed: !ty.has_param()")
};assert!(!ty.has_param());
981
982                valtree
983            }
984            Err(ErrorHandled::Reported(..)) => {
985                return block.unit();
986            }
987            Err(ErrorHandled::TooGeneric(_)) => {
988                self.tcx.dcx().emit_fatal(ConstContinueBadConst { span: constant.span });
989            }
990        };
991
992        let Some(real_target) =
993            self.static_pattern_match(&cx, valtree, &*scope.arms, &scope.built_match_tree)
994        else {
995            self.tcx.dcx().emit_fatal(ConstContinueUnknownJumpTarget { span })
996        };
997
998        self.block_context.push(BlockFrame::SubExpr);
999        let state_place = scope.state_place;
1000        block = self.expr_into_dest(state_place, block, value).into_block();
1001        self.block_context.pop();
1002
1003        let discr = self.temp(discriminant_ty, source_info.span);
1004        let stack_index = self
1005            .scopes
1006            .stack_index(self.scopes.const_continuable_scopes[break_index].region_scope, span);
1007        let scope = &mut self.scopes.const_continuable_scopes[break_index];
1008        self.cfg.push_assign(block, source_info, discr, rvalue);
1009        let drop_and_continue_block = self.cfg.start_new_block();
1010        let imaginary_target = self.cfg.start_new_block();
1011        self.cfg.terminate(
1012            block,
1013            source_info,
1014            TerminatorKind::FalseEdge { real_target: drop_and_continue_block, imaginary_target },
1015        );
1016
1017        let drops = &mut scope.const_continue_drops;
1018
1019        let drop_idx = self.scopes.scopes[stack_index + 1..]
1020            .iter()
1021            .flat_map(|scope| &scope.drops)
1022            .fold(ROOT_NODE, |drop_idx, &drop| drops.add_drop(drop, drop_idx));
1023
1024        drops.add_entry_point(imaginary_target, drop_idx);
1025
1026        self.cfg.terminate(imaginary_target, source_info, TerminatorKind::UnwindResume);
1027
1028        let region_scope = scope.region_scope;
1029        let stack_index = self.scopes.stack_index(region_scope, span);
1030        let mut drops = DropTree::new();
1031
1032        let drop_idx = self.scopes.scopes[stack_index + 1..]
1033            .iter()
1034            .flat_map(|scope| &scope.drops)
1035            .fold(ROOT_NODE, |drop_idx, &drop| drops.add_drop(drop, drop_idx));
1036
1037        drops.add_entry_point(drop_and_continue_block, drop_idx);
1038
1039        // `build_drop_trees` doesn't have access to our source_info, so we
1040        // create a dummy terminator now. `TerminatorKind::UnwindResume` is used
1041        // because MIR type checking will panic if it hasn't been overwritten.
1042        // (See `<ExitScopes as DropTreeBuilder>::link_entry_point`.)
1043        self.cfg.terminate(drop_and_continue_block, source_info, TerminatorKind::UnwindResume);
1044
1045        self.build_exit_tree(drops, region_scope, span, Some(real_target));
1046
1047        return self.cfg.start_new_block().unit();
1048    }
1049
1050    /// Breaks out of the enclosing [`Builder::in_if_then_scope`] due to a
1051    /// condition being false.
1052    ///
1053    /// This adds relevant drops in the drop tree, and adds a dummy terminator
1054    /// that will become a real `goto` when the scope's drop tree is built.
1055    ///
1056    /// Must be called in the context of [`Builder::in_if_then_scope`], so that
1057    /// there is an if-then scope to tell us what the target scope is.
1058    pub(crate) fn break_from_if_then_scope(&mut self, block: BasicBlock, source_info: SourceInfo) {
1059        let if_then_scope = self
1060            .scopes
1061            .if_then_scope
1062            .as_ref()
1063            .unwrap_or_else(|| ::rustc_middle::util::bug::span_bug_fmt(source_info.span,
    format_args!("no if-then scope found"))span_bug!(source_info.span, "no if-then scope found"));
1064
1065        let target = if_then_scope.region_scope;
1066        let stack_index = self.scopes.stack_index(target, source_info.span);
1067
1068        // Upgrade `if_then_scope` to `&mut`.
1069        let if_then_scope = self.scopes.if_then_scope.as_mut().expect("upgrading & to &mut");
1070
1071        let mut drop_idx = ROOT_NODE;
1072        let drops = &mut if_then_scope.else_drops;
1073        for scope in &self.scopes.scopes[stack_index + 1..] {
1074            for drop in &scope.drops {
1075                drop_idx = drops.add_drop(*drop, drop_idx);
1076            }
1077        }
1078        drops.add_entry_point(block, drop_idx);
1079
1080        // `build_drop_trees` doesn't have access to our source_info, so we
1081        // create a dummy terminator now. `TerminatorKind::UnwindResume` is used
1082        // because MIR type checking will panic if it hasn't been overwritten.
1083        // (See `<ExitScopes as DropTreeBuilder>::link_entry_point`.)
1084        self.cfg.terminate(block, source_info, TerminatorKind::UnwindResume);
1085    }
1086
1087    /// Sets up the drops for explicit tail calls.
1088    ///
1089    /// Unlike other kinds of early exits, tail calls do not go through the drop tree.
1090    /// Instead, all scheduled drops are immediately added to the CFG.
1091    pub(crate) fn break_for_tail_call(
1092        &mut self,
1093        mut block: BasicBlock,
1094        args: &[Spanned<Operand<'tcx>>],
1095        source_info: SourceInfo,
1096    ) -> BlockAnd<()> {
1097        let arg_drops: Vec<_> = args
1098            .iter()
1099            .rev()
1100            .filter_map(|arg| match &arg.node {
1101                Operand::Copy(_) => ::rustc_middle::util::bug::bug_fmt(format_args!("copy op in tail call args"))bug!("copy op in tail call args"),
1102                Operand::Move(place) => {
1103                    let local =
1104                        place.as_local().unwrap_or_else(|| ::rustc_middle::util::bug::bug_fmt(format_args!("projection in tail call args"))bug!("projection in tail call args"));
1105
1106                    if !self.local_decls[local].ty.needs_drop(self.tcx, self.typing_env()) {
1107                        return None;
1108                    }
1109
1110                    Some(DropData { source_info, local, kind: DropKind::Value })
1111                }
1112                Operand::Constant(_) | Operand::RuntimeChecks(_) => None,
1113            })
1114            .collect();
1115
1116        let mut unwind_to = self.diverge_cleanup_target(
1117            self.scopes.scopes.iter().rev().nth(1).unwrap().region_scope,
1118            DUMMY_SP,
1119        );
1120        let typing_env = self.typing_env();
1121        let unwind_drops = &mut self.scopes.unwind_drops;
1122
1123        // the innermost scope contains only the destructors for the tail call arguments
1124        // we only want to drop these in case of a panic, so we skip it
1125        for scope in self.scopes.scopes[1..].iter().rev().skip(1) {
1126            // FIXME(explicit_tail_calls) code duplication with `build_scope_drops`
1127            for drop_data in scope.drops.iter().rev() {
1128                let source_info = drop_data.source_info;
1129                let local = drop_data.local;
1130
1131                if !self.local_decls[local].ty.needs_drop(self.tcx, typing_env) {
1132                    continue;
1133                }
1134
1135                match drop_data.kind {
1136                    DropKind::Value => {
1137                        // `unwind_to` should drop the value that we're about to
1138                        // schedule. If dropping this value panics, then we continue
1139                        // with the *next* value on the unwind path.
1140                        if true {
    {
        match (&unwind_drops.drop_nodes[unwind_to].data.local,
                &drop_data.local) {
            (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);
                }
            }
        }
    };
};debug_assert_eq!(
1141                            unwind_drops.drop_nodes[unwind_to].data.local,
1142                            drop_data.local
1143                        );
1144                        if true {
    {
        match (&unwind_drops.drop_nodes[unwind_to].data.kind, &drop_data.kind)
            {
            (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);
                }
            }
        }
    };
};debug_assert_eq!(
1145                            unwind_drops.drop_nodes[unwind_to].data.kind,
1146                            drop_data.kind
1147                        );
1148                        unwind_to = unwind_drops.drop_nodes[unwind_to].next;
1149
1150                        let mut unwind_entry_point = unwind_to;
1151
1152                        // the tail call arguments must be dropped if any of these drops panic
1153                        for drop in arg_drops.iter().copied() {
1154                            unwind_entry_point = unwind_drops.add_drop(drop, unwind_entry_point);
1155                        }
1156
1157                        unwind_drops.add_entry_point(block, unwind_entry_point);
1158
1159                        let next = self.cfg.start_new_block();
1160                        self.cfg.terminate(
1161                            block,
1162                            source_info,
1163                            TerminatorKind::Drop {
1164                                place: local.into(),
1165                                target: next,
1166                                unwind: UnwindAction::Continue,
1167                                replace: false,
1168                                drop: None,
1169                            },
1170                        );
1171                        block = next;
1172                    }
1173                    DropKind::ForLint => {
1174                        self.cfg.push(
1175                            block,
1176                            Statement::new(
1177                                source_info,
1178                                StatementKind::BackwardIncompatibleDropHint {
1179                                    place: Box::new(local.into()),
1180                                    reason: BackwardIncompatibleDropReason::Edition2024,
1181                                },
1182                            ),
1183                        );
1184                    }
1185                    DropKind::Storage => {
1186                        // Only temps and vars need their storage dead.
1187                        if !(local.index() > self.arg_count) {
    ::core::panicking::panic("assertion failed: local.index() > self.arg_count")
};assert!(local.index() > self.arg_count);
1188                        self.cfg.push(
1189                            block,
1190                            Statement::new(source_info, StatementKind::StorageDead(local)),
1191                        );
1192                    }
1193                }
1194            }
1195        }
1196
1197        block.unit()
1198    }
1199
1200    fn is_async_drop_impl(
1201        tcx: TyCtxt<'tcx>,
1202        local_decls: &IndexVec<Local, LocalDecl<'tcx>>,
1203        typing_env: ty::TypingEnv<'tcx>,
1204        local: Local,
1205    ) -> bool {
1206        let ty = local_decls[local].ty;
1207        if ty.is_async_drop(tcx, typing_env) || ty.is_coroutine() {
1208            return true;
1209        }
1210        ty.needs_async_drop(tcx, typing_env)
1211    }
1212    fn is_async_drop(&self, local: Local) -> bool {
1213        Self::is_async_drop_impl(self.tcx, &self.local_decls, self.typing_env(), local)
1214    }
1215
1216    fn leave_top_scope(&mut self, block: BasicBlock) -> BasicBlock {
1217        // If we are emitting a `drop` statement, we need to have the cached
1218        // diverge cleanup pads ready in case that drop panics.
1219        let needs_cleanup = self.scopes.scopes.last().is_some_and(|scope| scope.needs_cleanup());
1220        let is_coroutine = self.coroutine.is_some();
1221        let unwind_to = if needs_cleanup { self.diverge_cleanup() } else { DropIdx::MAX };
1222
1223        let scope = self.scopes.scopes.last().expect("leave_top_scope called with no scopes");
1224        let has_async_drops = is_coroutine
1225            && scope.drops.iter().any(|v| v.kind == DropKind::Value && self.is_async_drop(v.local));
1226        let dropline_to = if has_async_drops { Some(self.diverge_dropline()) } else { None };
1227        let scope = self.scopes.scopes.last().expect("leave_top_scope called with no scopes");
1228        let typing_env = self.typing_env();
1229        build_scope_drops(
1230            &mut self.cfg,
1231            &mut self.scopes.unwind_drops,
1232            &mut self.scopes.coroutine_drops,
1233            scope,
1234            block,
1235            unwind_to,
1236            dropline_to,
1237            is_coroutine && needs_cleanup,
1238            self.arg_count,
1239            |v: Local| Self::is_async_drop_impl(self.tcx, &self.local_decls, typing_env, v),
1240        )
1241        .into_block()
1242    }
1243
1244    /// Possibly creates a new source scope if `current_root` and `parent_root`
1245    /// are different, or if -Zmaximal-hir-to-mir-coverage is enabled.
1246    pub(crate) fn maybe_new_source_scope(
1247        &mut self,
1248        span: Span,
1249        current_id: HirId,
1250        parent_id: HirId,
1251    ) {
1252        let (current_root, parent_root) =
1253            if self.tcx.sess.opts.unstable_opts.maximal_hir_to_mir_coverage {
1254                // Some consumers of rustc need to map MIR locations back to HIR nodes. Currently
1255                // the only part of rustc that tracks MIR -> HIR is the
1256                // `SourceScopeLocalData::lint_root` field that tracks lint levels for MIR
1257                // locations. Normally the number of source scopes is limited to the set of nodes
1258                // with lint annotations. The -Zmaximal-hir-to-mir-coverage flag changes this
1259                // behavior to maximize the number of source scopes, increasing the granularity of
1260                // the MIR->HIR mapping.
1261                (current_id, parent_id)
1262            } else {
1263                // Use `maybe_lint_level_root_bounded` to avoid adding Hir dependencies on our
1264                // parents. We estimate the true lint roots here to avoid creating a lot of source
1265                // scopes.
1266                (
1267                    self.maybe_lint_level_root_bounded(current_id),
1268                    if parent_id == self.hir_id {
1269                        parent_id // this is very common
1270                    } else {
1271                        self.maybe_lint_level_root_bounded(parent_id)
1272                    },
1273                )
1274            };
1275
1276        if current_root != parent_root {
1277            let lint_level = LintLevel::Explicit(current_root);
1278            self.source_scope = self.new_source_scope(span, lint_level);
1279        }
1280    }
1281
1282    /// Walks upwards from `orig_id` to find a node which might change lint levels with attributes.
1283    /// It stops at `self.hir_id` and just returns it if reached.
1284    fn maybe_lint_level_root_bounded(&mut self, orig_id: HirId) -> HirId {
1285        // This assertion lets us just store `ItemLocalId` in the cache, rather
1286        // than the full `HirId`.
1287        {
    match (&orig_id.owner, &self.hir_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!(orig_id.owner, self.hir_id.owner);
1288
1289        let mut id = orig_id;
1290        loop {
1291            if id == self.hir_id {
1292                // This is a moderately common case, mostly hit for previously unseen nodes.
1293                break;
1294            }
1295
1296            if self
1297                .tcx
1298                .hir_attrs(id)
1299                .iter()
1300                .any(|attr| Level::from_opt_symbol(attr.name()).is_some())
1301            {
1302                // This is a rare case. It's for a node path that doesn't reach the root due to an
1303                // intervening lint level attribute. This result doesn't get cached.
1304                return id;
1305            }
1306
1307            let next = self.tcx.parent_hir_id(id);
1308            if next == id {
1309                ::rustc_middle::util::bug::bug_fmt(format_args!("lint traversal reached the root of the crate"));bug!("lint traversal reached the root of the crate");
1310            }
1311            id = next;
1312
1313            // This lookup is just an optimization; it can be removed without affecting
1314            // functionality. It might seem strange to see this at the end of this loop, but the
1315            // `orig_id` passed in to this function is almost always previously unseen, for which a
1316            // lookup will be a miss. So we only do lookups for nodes up the parent chain, where
1317            // cache lookups have a very high hit rate.
1318            if self.lint_level_roots_cache.contains(id.local_id) {
1319                break;
1320            }
1321        }
1322
1323        // `orig_id` traced to `self_id`; record this fact. If `orig_id` is a leaf node it will
1324        // rarely (never?) subsequently be searched for, but it's hard to know if that is the case.
1325        // The performance wins from the cache all come from caching non-leaf nodes.
1326        self.lint_level_roots_cache.insert(orig_id.local_id);
1327        self.hir_id
1328    }
1329
1330    /// Creates a new source scope, nested in the current one.
1331    pub(crate) fn new_source_scope(&mut self, span: Span, lint_level: LintLevel) -> SourceScope {
1332        let parent = self.source_scope;
1333        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/4b6d04e706108ccfeafe2547fbe857dfe8972bad/compiler/rustc_mir_build/src/builder/scope.rs:1333",
                        "rustc_mir_build::builder::scope", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/4b6d04e706108ccfeafe2547fbe857dfe8972bad/compiler/rustc_mir_build/src/builder/scope.rs"),
                        ::tracing_core::__macro_support::Option::Some(1333u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_mir_build::builder::scope"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("new_source_scope({0:?}, {1:?}) - parent({2:?})={3:?}",
                                                    span, lint_level, parent, self.source_scopes.get(parent)) as
                                            &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(
1334            "new_source_scope({:?}, {:?}) - parent({:?})={:?}",
1335            span,
1336            lint_level,
1337            parent,
1338            self.source_scopes.get(parent)
1339        );
1340        let scope_local_data = SourceScopeLocalData {
1341            lint_root: if let LintLevel::Explicit(lint_root) = lint_level {
1342                lint_root
1343            } else {
1344                self.source_scopes[parent].local_data.as_ref().unwrap_crate_local().lint_root
1345            },
1346        };
1347        self.source_scopes.push(SourceScopeData {
1348            span,
1349            parent_scope: Some(parent),
1350            inlined: None,
1351            inlined_parent_scope: None,
1352            local_data: ClearCrossCrate::Set(scope_local_data),
1353        })
1354    }
1355
1356    /// Given a span and the current source scope, make a SourceInfo.
1357    pub(crate) fn source_info(&self, span: Span) -> SourceInfo {
1358        SourceInfo { span, scope: self.source_scope }
1359    }
1360
1361    // Finding scopes
1362    // ==============
1363
1364    /// Returns the scope that we should use as the lifetime of an
1365    /// operand. Basically, an operand must live until it is consumed.
1366    /// This is similar to, but not quite the same as, the temporary
1367    /// scope (which can be larger or smaller).
1368    ///
1369    /// Consider:
1370    /// ```ignore (illustrative)
1371    /// let x = foo(bar(X, Y));
1372    /// ```
1373    /// We wish to pop the storage for X and Y after `bar()` is
1374    /// called, not after the whole `let` is completed.
1375    ///
1376    /// As another example, if the second argument diverges:
1377    /// ```ignore (illustrative)
1378    /// foo(Box::new(2), panic!())
1379    /// ```
1380    /// We would allocate the box but then free it on the unwinding
1381    /// path; we would also emit a free on the 'success' path from
1382    /// panic, but that will turn out to be removed as dead-code.
1383    pub(crate) fn local_scope(&self) -> region::Scope {
1384        self.scopes.topmost()
1385    }
1386
1387    // Scheduling drops
1388    // ================
1389
1390    /// Indicates that `place` should be dropped on exit from `region_scope`.
1391    ///
1392    /// When called with `DropKind::Storage`, `place` shouldn't be the return
1393    /// place, or a function parameter.
1394    fn schedule_drop(
1395        &mut self,
1396        span: Span,
1397        region_scope: region::Scope,
1398        local: Local,
1399        drop_kind: DropKind,
1400    ) {
1401        // When building drops, we try to cache chains of drops to reduce the
1402        // number of `DropTree::add_drop` calls. This, however, means that
1403        // whenever we add a drop into a scope which already had some entries
1404        // in the drop tree built (and thus, cached) for it, we must invalidate
1405        // all caches which might branch into the scope which had a drop just
1406        // added to it. This is necessary, because otherwise some other code
1407        // might use the cache to branch into already built chain of drops,
1408        // essentially ignoring the newly added drop.
1409        //
1410        // For example consider there’s two scopes with a drop in each. These
1411        // are built and thus the caches are filled:
1412        //
1413        // +--------------------------------------------------------+
1414        // | +---------------------------------+                    |
1415        // | | +--------+     +-------------+  |  +---------------+ |
1416        // | | | return | <-+ | drop(outer) | <-+ |  drop(middle) | |
1417        // | | +--------+     +-------------+  |  +---------------+ |
1418        // | +------------|outer_scope cache|--+                    |
1419        // +------------------------------|middle_scope cache|------+
1420        //
1421        // Now, a new, innermost scope is added along with a new drop into
1422        // both innermost and outermost scopes:
1423        //
1424        // +------------------------------------------------------------+
1425        // | +----------------------------------+                       |
1426        // | | +--------+      +-------------+  |   +---------------+   | +-------------+
1427        // | | | return | <+   | drop(new)   | <-+  |  drop(middle) | <--+| drop(inner) |
1428        // | | +--------+  |   | drop(outer) |  |   +---------------+   | +-------------+
1429        // | |             +-+ +-------------+  |                       |
1430        // | +---|invalid outer_scope cache|----+                       |
1431        // +----=----------------|invalid middle_scope cache|-----------+
1432        //
1433        // If, when adding `drop(new)` we do not invalidate the cached blocks for both
1434        // outer_scope and middle_scope, then, when building drops for the inner (rightmost)
1435        // scope, the old, cached blocks, without `drop(new)` will get used, producing the
1436        // wrong results.
1437        //
1438        // Note that this code iterates scopes from the innermost to the outermost,
1439        // invalidating caches of each scope visited. This way bare minimum of the
1440        // caches gets invalidated. i.e., if a new drop is added into the middle scope, the
1441        // cache of outer scope stays intact.
1442        //
1443        // Since we only cache drops for the unwind path and the coroutine drop
1444        // path, we only need to invalidate the cache for drops that happen on
1445        // the unwind or coroutine drop paths. This means that for
1446        // non-coroutines we don't need to invalidate caches for `DropKind::Storage`.
1447        let invalidate_caches = match drop_kind {
1448            DropKind::Value | DropKind::ForLint => true,
1449            DropKind::Storage => self.coroutine.is_some(),
1450        };
1451        for scope in self.scopes.scopes.iter_mut().rev() {
1452            if invalidate_caches {
1453                scope.invalidate_cache();
1454            }
1455
1456            if scope.region_scope == region_scope {
1457                let region_scope_span = region_scope.span(self.tcx, self.region_scope_tree);
1458                // Attribute scope exit drops to scope's closing brace.
1459                let scope_end = self.tcx.sess.source_map().end_point(region_scope_span);
1460
1461                scope.drops.push(DropData {
1462                    source_info: SourceInfo { span: scope_end, scope: scope.source_scope },
1463                    local,
1464                    kind: drop_kind,
1465                });
1466
1467                return;
1468            }
1469        }
1470
1471        ::rustc_middle::util::bug::span_bug_fmt(span,
    format_args!("region scope {0:?} not in scope to drop {1:?}",
        region_scope, local));span_bug!(span, "region scope {:?} not in scope to drop {:?}", region_scope, local);
1472    }
1473
1474    /// Indicates that `place` should be marked `StorageDead` on exit from `region_scope`.
1475    ///
1476    /// `place` must not be the return place, or a function parameter.
1477    pub(crate) fn schedule_drop_storage(
1478        &mut self,
1479        span: Span,
1480        region_scope: region::Scope,
1481        local: Local,
1482    ) {
1483        if local.index() <= self.arg_count {
1484            ::rustc_middle::util::bug::span_bug_fmt(span,
    format_args!("`schedule_drop` called with body argument {0:?} but its storage does not require a drop",
        local))span_bug!(
1485                span,
1486                "`schedule_drop` called with body argument {:?} \
1487                but its storage does not require a drop",
1488                local,
1489            )
1490        }
1491        self.schedule_drop(span, region_scope, local, DropKind::Storage);
1492    }
1493
1494    /// Indicates that `place` should be dropped on exit from `region_scope`.
1495    pub(crate) fn schedule_drop_value(
1496        &mut self,
1497        span: Span,
1498        region_scope: region::Scope,
1499        local: Local,
1500    ) {
1501        if !self.local_decls[local].ty.needs_drop(self.tcx, self.typing_env()) {
1502            return;
1503        }
1504        self.schedule_drop(span, region_scope, local, DropKind::Value);
1505    }
1506
1507    /// Schedule emission of a backwards incompatible drop lint hint.
1508    /// Applicable only to temporary values for now.
1509    {}
#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("schedule_backwards_incompatible_drop",
                                    "rustc_mir_build::builder::scope", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/4b6d04e706108ccfeafe2547fbe857dfe8972bad/compiler/rustc_mir_build/src/builder/scope.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1509u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_mir_build::builder::scope"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("span")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("span");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("region_scope")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("region_scope");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("local")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("local");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&span)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&region_scope)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&local)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        { self.schedule_drop(span, region_scope, local, DropKind::ForLint); }
    }
}#[instrument(level = "debug", skip(self))]
1510    pub(crate) fn schedule_backwards_incompatible_drop(
1511        &mut self,
1512        span: Span,
1513        region_scope: region::Scope,
1514        local: Local,
1515    ) {
1516        // Note that we are *not* gating BIDs here on whether they have significant destructor.
1517        // We need to know all of them so that we can capture potential borrow-checking errors.
1518        self.schedule_drop(span, region_scope, local, DropKind::ForLint);
1519    }
1520
1521    /// Indicates that the "local operand" stored in `local` is
1522    /// *moved* at some point during execution (see `local_scope` for
1523    /// more information about what a "local operand" is -- in short,
1524    /// it's an intermediate operand created as part of preparing some
1525    /// MIR instruction). We use this information to suppress
1526    /// redundant drops on the non-unwind paths. This results in less
1527    /// MIR, but also avoids spurious borrow check errors
1528    /// (c.f. #64391).
1529    ///
1530    /// Example: when compiling the call to `foo` here:
1531    ///
1532    /// ```ignore (illustrative)
1533    /// foo(bar(), ...)
1534    /// ```
1535    ///
1536    /// we would evaluate `bar()` to an operand `_X`. We would also
1537    /// schedule `_X` to be dropped when the expression scope for
1538    /// `foo(bar())` is exited. This is relevant, for example, if the
1539    /// later arguments should unwind (it would ensure that `_X` gets
1540    /// dropped). However, if no unwind occurs, then `_X` will be
1541    /// unconditionally consumed by the `call`:
1542    ///
1543    /// ```ignore (illustrative)
1544    /// bb {
1545    ///   ...
1546    ///   _R = CALL(foo, _X, ...)
1547    /// }
1548    /// ```
1549    ///
1550    /// However, `_X` is still registered to be dropped, and so if we
1551    /// do nothing else, we would generate a `DROP(_X)` that occurs
1552    /// after the call. This will later be optimized out by the
1553    /// drop-elaboration code, but in the meantime it can lead to
1554    /// spurious borrow-check errors -- the problem, ironically, is
1555    /// not the `DROP(_X)` itself, but the (spurious) unwind pathways
1556    /// that it creates. See #64391 for an example.
1557    pub(crate) fn record_operands_moved(&mut self, operands: &[Spanned<Operand<'tcx>>]) {
1558        let local_scope = self.local_scope();
1559        let scope = self.scopes.scopes.last_mut().unwrap();
1560
1561        {
    match (&scope.region_scope, &local_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::Some(format_args!("local scope is not the topmost scope!")));
            }
        }
    }
};assert_eq!(scope.region_scope, local_scope, "local scope is not the topmost scope!",);
1562
1563        // look for moves of a local variable, like `MOVE(_X)`
1564        let locals_moved = operands.iter().flat_map(|operand| match operand.node {
1565            Operand::Copy(_) | Operand::Constant(_) | Operand::RuntimeChecks(_) => None,
1566            Operand::Move(place) => place.as_local(),
1567        });
1568
1569        for local in locals_moved {
1570            // check if we have a Drop for this operand and -- if so
1571            // -- add it to the list of moved operands. Note that this
1572            // local might not have been an operand created for this
1573            // call, it could come from other places too.
1574            if scope.drops.iter().any(|drop| drop.local == local && drop.kind == DropKind::Value) {
1575                scope.moved_locals.push(local);
1576            }
1577        }
1578    }
1579
1580    // Other
1581    // =====
1582
1583    /// Returns the [DropIdx] for the innermost drop if the function unwound at
1584    /// this point. The `DropIdx` will be created if it doesn't already exist.
1585    fn diverge_cleanup(&mut self) -> DropIdx {
1586        // It is okay to use dummy span because the getting scope index on the topmost scope
1587        // must always succeed.
1588        self.diverge_cleanup_target(self.scopes.topmost(), DUMMY_SP)
1589    }
1590
1591    /// This is similar to [diverge_cleanup](Self::diverge_cleanup) except its target is set to
1592    /// some ancestor scope instead of the current scope.
1593    /// It is possible to unwind to some ancestor scope if some drop panics as
1594    /// the program breaks out of a if-then scope.
1595    fn diverge_cleanup_target(&mut self, target_scope: region::Scope, span: Span) -> DropIdx {
1596        let target = self.scopes.stack_index(target_scope, span);
1597        let (uncached_scope, mut cached_drop) = self.scopes.scopes[..=target]
1598            .iter()
1599            .enumerate()
1600            .rev()
1601            .find_map(|(scope_idx, scope)| {
1602                scope.cached_unwind_block.map(|cached_block| (scope_idx + 1, cached_block))
1603            })
1604            .unwrap_or((0, ROOT_NODE));
1605
1606        if uncached_scope > target {
1607            return cached_drop;
1608        }
1609
1610        let is_coroutine = self.coroutine.is_some();
1611        for scope in &mut self.scopes.scopes[uncached_scope..=target] {
1612            for drop in &scope.drops {
1613                if is_coroutine || drop.kind == DropKind::Value {
1614                    cached_drop = self.scopes.unwind_drops.add_drop(*drop, cached_drop);
1615                }
1616            }
1617            scope.cached_unwind_block = Some(cached_drop);
1618        }
1619
1620        cached_drop
1621    }
1622
1623    /// Prepares to create a path that performs all required cleanup for a
1624    /// terminator that can unwind at the given basic block.
1625    ///
1626    /// This path terminates in Resume. The path isn't created until after all
1627    /// of the non-unwind paths in this item have been lowered.
1628    pub(crate) fn diverge_from(&mut self, start: BasicBlock) {
1629        if true {
    if !#[allow(non_exhaustive_omitted_patterns)] match self.cfg.block_data(start).terminator().kind
                {
                TerminatorKind::Assert { .. } | TerminatorKind::Call { .. } |
                    TerminatorKind::Drop { .. } | TerminatorKind::FalseUnwind {
                    .. } | TerminatorKind::InlineAsm { .. } => true,
                _ => false,
            } {
        {
            ::core::panicking::panic_fmt(format_args!("diverge_from called on block with terminator that cannot unwind."));
        }
    };
};debug_assert!(
1630            matches!(
1631                self.cfg.block_data(start).terminator().kind,
1632                TerminatorKind::Assert { .. }
1633                    | TerminatorKind::Call { .. }
1634                    | TerminatorKind::Drop { .. }
1635                    | TerminatorKind::FalseUnwind { .. }
1636                    | TerminatorKind::InlineAsm { .. }
1637            ),
1638            "diverge_from called on block with terminator that cannot unwind."
1639        );
1640
1641        let next_drop = self.diverge_cleanup();
1642        self.scopes.unwind_drops.add_entry_point(start, next_drop);
1643    }
1644
1645    /// Returns the [DropIdx] for the innermost drop for dropline (coroutine drop path).
1646    /// The `DropIdx` will be created if it doesn't already exist.
1647    fn diverge_dropline(&mut self) -> DropIdx {
1648        // It is okay to use dummy span because the getting scope index on the topmost scope
1649        // must always succeed.
1650        self.diverge_dropline_target(self.scopes.topmost(), DUMMY_SP)
1651    }
1652
1653    /// Similar to diverge_cleanup_target, but for dropline (coroutine drop path)
1654    fn diverge_dropline_target(&mut self, target_scope: region::Scope, span: Span) -> DropIdx {
1655        if true {
    if !self.coroutine.is_some() {
        {
            ::core::panicking::panic_fmt(format_args!("diverge_dropline_target is valid only for coroutine"));
        }
    };
};debug_assert!(
1656            self.coroutine.is_some(),
1657            "diverge_dropline_target is valid only for coroutine"
1658        );
1659        let target = self.scopes.stack_index(target_scope, span);
1660        let (uncached_scope, mut cached_drop) = self.scopes.scopes[..=target]
1661            .iter()
1662            .enumerate()
1663            .rev()
1664            .find_map(|(scope_idx, scope)| {
1665                scope.cached_coroutine_drop_block.map(|cached_block| (scope_idx + 1, cached_block))
1666            })
1667            .unwrap_or((0, ROOT_NODE));
1668
1669        if uncached_scope > target {
1670            return cached_drop;
1671        }
1672
1673        for scope in &mut self.scopes.scopes[uncached_scope..=target] {
1674            for drop in &scope.drops {
1675                cached_drop = self.scopes.coroutine_drops.add_drop(*drop, cached_drop);
1676            }
1677            scope.cached_coroutine_drop_block = Some(cached_drop);
1678        }
1679
1680        cached_drop
1681    }
1682
1683    /// Sets up a path that performs all required cleanup for dropping a
1684    /// coroutine, starting from the given block that ends in
1685    /// [TerminatorKind::Yield].
1686    ///
1687    /// This path terminates in CoroutineDrop.
1688    pub(crate) fn coroutine_drop_cleanup(&mut self, yield_block: BasicBlock) {
1689        if true {
    if !#[allow(non_exhaustive_omitted_patterns)] match self.cfg.block_data(yield_block).terminator().kind
                {
                TerminatorKind::Yield { .. } => true,
                _ => false,
            } {
        {
            ::core::panicking::panic_fmt(format_args!("coroutine_drop_cleanup called on block with non-yield terminator."));
        }
    };
};debug_assert!(
1690            matches!(
1691                self.cfg.block_data(yield_block).terminator().kind,
1692                TerminatorKind::Yield { .. }
1693            ),
1694            "coroutine_drop_cleanup called on block with non-yield terminator."
1695        );
1696        let cached_drop = self.diverge_dropline();
1697        self.scopes.coroutine_drops.add_entry_point(yield_block, cached_drop);
1698    }
1699
1700    /// Utility function for *non*-scope code to build their own drops
1701    /// Force a drop at this point in the MIR by creating a new block.
1702    pub(crate) fn build_drop_and_replace(
1703        &mut self,
1704        block: BasicBlock,
1705        span: Span,
1706        place: Place<'tcx>,
1707        value: Rvalue<'tcx>,
1708    ) -> BlockAnd<()> {
1709        let source_info = self.source_info(span);
1710
1711        // create the new block for the assignment
1712        let assign = self.cfg.start_new_block();
1713        self.cfg.push_assign(assign, source_info, place, value.clone());
1714
1715        // create the new block for the assignment in the case of unwinding
1716        let assign_unwind = self.cfg.start_new_cleanup_block();
1717        self.cfg.push_assign(assign_unwind, source_info, place, value.clone());
1718
1719        self.cfg.terminate(
1720            block,
1721            source_info,
1722            TerminatorKind::Drop {
1723                place,
1724                target: assign,
1725                unwind: UnwindAction::Cleanup(assign_unwind),
1726                replace: true,
1727                drop: None,
1728            },
1729        );
1730        self.diverge_from(block);
1731
1732        assign.unit()
1733    }
1734
1735    /// Creates an `Assert` terminator and return the success block.
1736    /// If the boolean condition operand is not the expected value,
1737    /// a runtime panic will be caused with the given message.
1738    pub(crate) fn assert(
1739        &mut self,
1740        block: BasicBlock,
1741        cond: Operand<'tcx>,
1742        expected: bool,
1743        msg: AssertMessage<'tcx>,
1744        span: Span,
1745    ) -> BasicBlock {
1746        let source_info = self.source_info(span);
1747        let success_block = self.cfg.start_new_block();
1748
1749        self.cfg.terminate(
1750            block,
1751            source_info,
1752            TerminatorKind::Assert {
1753                cond,
1754                expected,
1755                msg: Box::new(msg),
1756                target: success_block,
1757                unwind: UnwindAction::Continue,
1758            },
1759        );
1760        self.diverge_from(block);
1761
1762        success_block
1763    }
1764
1765    /// Unschedules any drops in the top two scopes.
1766    ///
1767    /// This is only needed for pattern-matches combining guards and or-patterns: or-patterns lead
1768    /// to guards being lowered multiple times before lowering the arm body, so we unschedle drops
1769    /// for guards' temporaries and bindings between lowering each instance of an match arm's guard.
1770    pub(crate) fn clear_match_arm_and_guard_scopes(&mut self, region_scope: region::Scope) {
1771        let [.., arm_scope, guard_scope] = &mut *self.scopes.scopes else {
1772            ::rustc_middle::util::bug::bug_fmt(format_args!("matches with guards should introduce separate scopes for the pattern and guard"));bug!("matches with guards should introduce separate scopes for the pattern and guard");
1773        };
1774
1775        {
    match (&arm_scope.region_scope, &region_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!(arm_scope.region_scope, region_scope);
1776        {
    match (&guard_scope.region_scope.data, &region::ScopeData::MatchGuard) {
        (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!(guard_scope.region_scope.data, region::ScopeData::MatchGuard);
1777        {
    match (&guard_scope.region_scope.local_id, &region_scope.local_id) {
        (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!(guard_scope.region_scope.local_id, region_scope.local_id);
1778
1779        arm_scope.drops.clear();
1780        arm_scope.invalidate_cache();
1781        guard_scope.drops.clear();
1782        guard_scope.invalidate_cache();
1783    }
1784}
1785
1786/// Builds drops for `pop_scope` and `leave_top_scope`.
1787///
1788/// # Parameters
1789///
1790/// * `unwind_drops`, the drop tree data structure storing what needs to be cleaned up if unwind occurs
1791/// * `scope`, describes the drops that will occur on exiting the scope in regular execution
1792/// * `block`, the block to branch to once drops are complete (assuming no unwind occurs)
1793/// * `unwind_to`, describes the drops that would occur at this point in the code if a
1794///   panic occurred (a subset of the drops in `scope`, since we sometimes elide StorageDead and other
1795///   instructions on unwinding)
1796/// * `dropline_to`, describes the drops that would occur at this point in the code if a
1797///    coroutine drop occurred.
1798/// * `storage_dead_on_unwind`, if true, then we should emit `StorageDead` even when unwinding
1799/// * `arg_count`, number of MIR local variables corresponding to fn arguments (used to assert that we don't drop those)
1800fn build_scope_drops<'tcx, F>(
1801    cfg: &mut CFG<'tcx>,
1802    unwind_drops: &mut DropTree,
1803    coroutine_drops: &mut DropTree,
1804    scope: &Scope,
1805    block: BasicBlock,
1806    unwind_to: DropIdx,
1807    dropline_to: Option<DropIdx>,
1808    storage_dead_on_unwind: bool,
1809    arg_count: usize,
1810    is_async_drop: F,
1811) -> BlockAnd<()>
1812where
1813    F: Fn(Local) -> bool,
1814{
1815    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/4b6d04e706108ccfeafe2547fbe857dfe8972bad/compiler/rustc_mir_build/src/builder/scope.rs:1815",
                        "rustc_mir_build::builder::scope", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/4b6d04e706108ccfeafe2547fbe857dfe8972bad/compiler/rustc_mir_build/src/builder/scope.rs"),
                        ::tracing_core::__macro_support::Option::Some(1815u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_mir_build::builder::scope"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("build_scope_drops({0:?} -> {1:?}), dropline_to={2:?}",
                                                    block, scope, dropline_to) as
                                            &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("build_scope_drops({:?} -> {:?}), dropline_to={:?}", block, scope, dropline_to);
1816
1817    // Build up the drops in evaluation order. The end result will
1818    // look like:
1819    //
1820    // [SDs, drops[n]] --..> [SDs, drop[1]] -> [SDs, drop[0]] -> [[SDs]]
1821    //               |                    |                 |
1822    //               :                    |                 |
1823    //                                    V                 V
1824    // [drop[n]] -...-> [drop[1]] ------> [drop[0]] ------> [last_unwind_to]
1825    //
1826    // The horizontal arrows represent the execution path when the drops return
1827    // successfully. The downwards arrows represent the execution path when the
1828    // drops panic (panicking while unwinding will abort, so there's no need for
1829    // another set of arrows).
1830    //
1831    // For coroutines, we unwind from a drop on a local to its StorageDead
1832    // statement. For other functions we don't worry about StorageDead. The
1833    // drops for the unwind path should have already been generated by
1834    // `diverge_cleanup_gen`.
1835
1836    // `unwind_to` indicates what needs to be dropped should unwinding occur.
1837    // This is a subset of what needs to be dropped when exiting the scope.
1838    // As we unwind the scope, we will also move `unwind_to` backwards to match,
1839    // so that we can use it should a destructor panic.
1840    let mut unwind_to = unwind_to;
1841
1842    // The block that we should jump to after drops complete. We start by building the final drop (`drops[n]`
1843    // in the diagram above) and then build the drops (e.g., `drop[1]`, `drop[0]`) that come before it.
1844    // block begins as the successor of `drops[n]` and then becomes `drops[n]` so that `drops[n-1]`
1845    // will branch to `drops[n]`.
1846    let mut block = block;
1847
1848    // `dropline_to` indicates what needs to be dropped should coroutine drop occur.
1849    let mut dropline_to = dropline_to;
1850
1851    for drop_data in scope.drops.iter().rev() {
1852        let source_info = drop_data.source_info;
1853        let local = drop_data.local;
1854
1855        match drop_data.kind {
1856            DropKind::Value => {
1857                // `unwind_to` should drop the value that we're about to
1858                // schedule. If dropping this value panics, then we continue
1859                // with the *next* value on the unwind path.
1860                //
1861                // We adjust this BEFORE we create the drop (e.g., `drops[n]`)
1862                // because `drops[n]` should unwind to `drops[n-1]`.
1863                if true {
    {
        match (&unwind_drops.drop_nodes[unwind_to].data.local,
                &drop_data.local) {
            (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);
                }
            }
        }
    };
};debug_assert_eq!(unwind_drops.drop_nodes[unwind_to].data.local, drop_data.local);
1864                if true {
    {
        match (&unwind_drops.drop_nodes[unwind_to].data.kind, &drop_data.kind)
            {
            (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);
                }
            }
        }
    };
};debug_assert_eq!(unwind_drops.drop_nodes[unwind_to].data.kind, drop_data.kind);
1865                unwind_to = unwind_drops.drop_nodes[unwind_to].next;
1866
1867                if let Some(idx) = dropline_to {
1868                    if true {
    {
        match (&coroutine_drops.drop_nodes[idx].data.local, &drop_data.local)
            {
            (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);
                }
            }
        }
    };
};debug_assert_eq!(coroutine_drops.drop_nodes[idx].data.local, drop_data.local);
1869                    if true {
    {
        match (&coroutine_drops.drop_nodes[idx].data.kind, &drop_data.kind) {
            (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);
                }
            }
        }
    };
};debug_assert_eq!(coroutine_drops.drop_nodes[idx].data.kind, drop_data.kind);
1870                    dropline_to = Some(coroutine_drops.drop_nodes[idx].next);
1871                }
1872
1873                // If the operand has been moved, and we are not on an unwind
1874                // path, then don't generate the drop. (We only take this into
1875                // account for non-unwind paths so as not to disturb the
1876                // caching mechanism.)
1877                if scope.moved_locals.contains(&local) {
1878                    continue;
1879                }
1880
1881                unwind_drops.add_entry_point(block, unwind_to);
1882                if let Some(to) = dropline_to
1883                    && is_async_drop(local)
1884                {
1885                    coroutine_drops.add_entry_point(block, to);
1886                }
1887
1888                let next = cfg.start_new_block();
1889                cfg.terminate(
1890                    block,
1891                    source_info,
1892                    TerminatorKind::Drop {
1893                        place: local.into(),
1894                        target: next,
1895                        unwind: UnwindAction::Continue,
1896                        replace: false,
1897                        drop: None,
1898                    },
1899                );
1900                block = next;
1901            }
1902            DropKind::ForLint => {
1903                // As in the `DropKind::Storage` case below:
1904                // normally lint-related drops are not emitted for unwind,
1905                // so we can just leave `unwind_to` unmodified, but in some
1906                // cases we emit things ALSO on the unwind path, so we need to adjust
1907                // `unwind_to` in that case.
1908                if storage_dead_on_unwind {
1909                    if true {
    {
        match (&unwind_drops.drop_nodes[unwind_to].data.local,
                &drop_data.local) {
            (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);
                }
            }
        }
    };
};debug_assert_eq!(
1910                        unwind_drops.drop_nodes[unwind_to].data.local,
1911                        drop_data.local
1912                    );
1913                    if true {
    {
        match (&unwind_drops.drop_nodes[unwind_to].data.kind, &drop_data.kind)
            {
            (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);
                }
            }
        }
    };
};debug_assert_eq!(unwind_drops.drop_nodes[unwind_to].data.kind, drop_data.kind);
1914                    unwind_to = unwind_drops.drop_nodes[unwind_to].next;
1915                }
1916
1917                // If the operand has been moved, and we are not on an unwind
1918                // path, then don't generate the drop. (We only take this into
1919                // account for non-unwind paths so as not to disturb the
1920                // caching mechanism.)
1921                if scope.moved_locals.contains(&local) {
1922                    continue;
1923                }
1924
1925                cfg.push(
1926                    block,
1927                    Statement::new(
1928                        source_info,
1929                        StatementKind::BackwardIncompatibleDropHint {
1930                            place: Box::new(local.into()),
1931                            reason: BackwardIncompatibleDropReason::Edition2024,
1932                        },
1933                    ),
1934                );
1935            }
1936            DropKind::Storage => {
1937                // Ordinarily, storage-dead nodes are not emitted on unwind, so we don't
1938                // need to adjust `unwind_to` on this path. However, in some specific cases
1939                // we *do* emit storage-dead nodes on the unwind path, and in that case now that
1940                // the storage-dead has completed, we need to adjust the `unwind_to` pointer
1941                // so that any future drops we emit will not register storage-dead.
1942                if storage_dead_on_unwind {
1943                    if true {
    {
        match (&unwind_drops.drop_nodes[unwind_to].data.local,
                &drop_data.local) {
            (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);
                }
            }
        }
    };
};debug_assert_eq!(
1944                        unwind_drops.drop_nodes[unwind_to].data.local,
1945                        drop_data.local
1946                    );
1947                    if true {
    {
        match (&unwind_drops.drop_nodes[unwind_to].data.kind, &drop_data.kind)
            {
            (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);
                }
            }
        }
    };
};debug_assert_eq!(unwind_drops.drop_nodes[unwind_to].data.kind, drop_data.kind);
1948                    unwind_to = unwind_drops.drop_nodes[unwind_to].next;
1949                }
1950                if let Some(idx) = dropline_to {
1951                    if true {
    {
        match (&coroutine_drops.drop_nodes[idx].data.local, &drop_data.local)
            {
            (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);
                }
            }
        }
    };
};debug_assert_eq!(coroutine_drops.drop_nodes[idx].data.local, drop_data.local);
1952                    if true {
    {
        match (&coroutine_drops.drop_nodes[idx].data.kind, &drop_data.kind) {
            (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);
                }
            }
        }
    };
};debug_assert_eq!(coroutine_drops.drop_nodes[idx].data.kind, drop_data.kind);
1953                    dropline_to = Some(coroutine_drops.drop_nodes[idx].next);
1954                }
1955                // Only temps and vars need their storage dead.
1956                if !(local.index() > arg_count) {
    ::core::panicking::panic("assertion failed: local.index() > arg_count")
};assert!(local.index() > arg_count);
1957                cfg.push(block, Statement::new(source_info, StatementKind::StorageDead(local)));
1958            }
1959        }
1960    }
1961    block.unit()
1962}
1963
1964impl<'a, 'tcx: 'a> Builder<'a, 'tcx> {
1965    /// Build a drop tree for a breakable scope.
1966    ///
1967    /// If `continue_block` is `Some`, then the tree is for `continue` inside a
1968    /// loop. Otherwise this is for `break`, `return`, or `if`.
1969    fn build_exit_tree(
1970        &mut self,
1971        mut drops: DropTree,
1972        else_scope: region::Scope,
1973        span: Span,
1974        continue_block: Option<BasicBlock>,
1975    ) -> Option<BlockAnd<()>> {
1976        let blocks = drops.build_mir::<ExitScopes>(&mut self.cfg, continue_block);
1977        let is_coroutine = self.coroutine.is_some();
1978
1979        // Link the exit drop tree to unwind drop tree.
1980        if drops.drop_nodes.iter().any(|drop_node| drop_node.data.kind == DropKind::Value) {
1981            let unwind_target = self.diverge_cleanup_target(else_scope, span);
1982            let mut unwind_indices = IndexVec::from_elem_n(unwind_target, 1);
1983            for (drop_idx, drop_node) in drops.drop_nodes.iter_enumerated().skip(1) {
1984                match drop_node.data.kind {
1985                    DropKind::Storage | DropKind::ForLint => {
1986                        if is_coroutine {
1987                            let unwind_drop = self
1988                                .scopes
1989                                .unwind_drops
1990                                .add_drop(drop_node.data, unwind_indices[drop_node.next]);
1991                            unwind_indices.push(unwind_drop);
1992                        } else {
1993                            unwind_indices.push(unwind_indices[drop_node.next]);
1994                        }
1995                    }
1996                    DropKind::Value => {
1997                        let unwind_drop = self
1998                            .scopes
1999                            .unwind_drops
2000                            .add_drop(drop_node.data, unwind_indices[drop_node.next]);
2001                        self.scopes.unwind_drops.add_entry_point(
2002                            blocks[drop_idx].unwrap(),
2003                            unwind_indices[drop_node.next],
2004                        );
2005                        unwind_indices.push(unwind_drop);
2006                    }
2007                }
2008            }
2009        }
2010        // Link the exit drop tree to dropline drop tree (coroutine drop path) for async drops
2011        if is_coroutine
2012            && drops.drop_nodes.iter().any(|DropNode { data, next: _ }| {
2013                data.kind == DropKind::Value && self.is_async_drop(data.local)
2014            })
2015        {
2016            let dropline_target = self.diverge_dropline_target(else_scope, span);
2017            let mut dropline_indices = IndexVec::from_elem_n(dropline_target, 1);
2018            for (drop_idx, drop_data) in drops.drop_nodes.iter_enumerated().skip(1) {
2019                let coroutine_drop = self
2020                    .scopes
2021                    .coroutine_drops
2022                    .add_drop(drop_data.data, dropline_indices[drop_data.next]);
2023                match drop_data.data.kind {
2024                    DropKind::Storage | DropKind::ForLint => {}
2025                    DropKind::Value => {
2026                        if self.is_async_drop(drop_data.data.local) {
2027                            self.scopes.coroutine_drops.add_entry_point(
2028                                blocks[drop_idx].unwrap(),
2029                                dropline_indices[drop_data.next],
2030                            );
2031                        }
2032                    }
2033                }
2034                dropline_indices.push(coroutine_drop);
2035            }
2036        }
2037        blocks[ROOT_NODE].map(BasicBlock::unit)
2038    }
2039
2040    /// Build the unwind and coroutine drop trees.
2041    pub(crate) fn build_drop_trees(&mut self) {
2042        if self.coroutine.is_some() {
2043            self.build_coroutine_drop_trees();
2044        } else {
2045            Self::build_unwind_tree(
2046                &mut self.cfg,
2047                &mut self.scopes.unwind_drops,
2048                self.fn_span,
2049                &mut None,
2050            );
2051        }
2052    }
2053
2054    fn build_coroutine_drop_trees(&mut self) {
2055        // Build the drop tree for dropping the coroutine while it's suspended.
2056        let drops = &mut self.scopes.coroutine_drops;
2057        let cfg = &mut self.cfg;
2058        let fn_span = self.fn_span;
2059        let blocks = drops.build_mir::<CoroutineDrop>(cfg, None);
2060        if let Some(root_block) = blocks[ROOT_NODE] {
2061            cfg.terminate(
2062                root_block,
2063                SourceInfo::outermost(fn_span),
2064                TerminatorKind::CoroutineDrop,
2065            );
2066        }
2067
2068        // Build the drop tree for unwinding in the normal control flow paths.
2069        let resume_block = &mut None;
2070        let unwind_drops = &mut self.scopes.unwind_drops;
2071        Self::build_unwind_tree(cfg, unwind_drops, fn_span, resume_block);
2072
2073        // Build the drop tree for unwinding when dropping a suspended
2074        // coroutine.
2075        //
2076        // This is a different tree to the standard unwind paths here to
2077        // prevent drop elaboration from creating drop flags that would have
2078        // to be captured by the coroutine. I'm not sure how important this
2079        // optimization is, but it is here.
2080        for (drop_idx, drop_node) in drops.drop_nodes.iter_enumerated() {
2081            if let DropKind::Value = drop_node.data.kind
2082                && let Some(bb) = blocks[drop_idx]
2083            {
2084                if true {
    if !(drop_node.next < drops.drop_nodes.next_index()) {
        ::core::panicking::panic("assertion failed: drop_node.next < drops.drop_nodes.next_index()")
    };
};debug_assert!(drop_node.next < drops.drop_nodes.next_index());
2085                drops.entry_points.push((drop_node.next, bb));
2086            }
2087        }
2088        Self::build_unwind_tree(cfg, drops, fn_span, resume_block);
2089    }
2090
2091    fn build_unwind_tree(
2092        cfg: &mut CFG<'tcx>,
2093        drops: &mut DropTree,
2094        fn_span: Span,
2095        resume_block: &mut Option<BasicBlock>,
2096    ) {
2097        let blocks = drops.build_mir::<Unwind>(cfg, *resume_block);
2098        if let (None, Some(resume)) = (*resume_block, blocks[ROOT_NODE]) {
2099            cfg.terminate(resume, SourceInfo::outermost(fn_span), TerminatorKind::UnwindResume);
2100
2101            *resume_block = blocks[ROOT_NODE];
2102        }
2103    }
2104}
2105
2106// DropTreeBuilder implementations.
2107
2108struct ExitScopes;
2109
2110impl<'tcx> DropTreeBuilder<'tcx> for ExitScopes {
2111    fn make_block(cfg: &mut CFG<'tcx>) -> BasicBlock {
2112        cfg.start_new_block()
2113    }
2114    fn link_entry_point(cfg: &mut CFG<'tcx>, from: BasicBlock, to: BasicBlock) {
2115        // There should be an existing terminator with real source info and a
2116        // dummy TerminatorKind. Replace it with a proper goto.
2117        // (The dummy is added by `break_scope` and `break_from_if_then_scope`.)
2118        let term = cfg.block_data_mut(from).terminator_mut();
2119        if let TerminatorKind::UnwindResume = term.kind {
2120            term.kind = TerminatorKind::Goto { target: to };
2121        } else {
2122            ::rustc_middle::util::bug::span_bug_fmt(term.source_info.span,
    format_args!("unexpected dummy terminator kind: {0:?}", term.kind));span_bug!(term.source_info.span, "unexpected dummy terminator kind: {:?}", term.kind);
2123        }
2124    }
2125}
2126
2127struct CoroutineDrop;
2128
2129impl<'tcx> DropTreeBuilder<'tcx> for CoroutineDrop {
2130    fn make_block(cfg: &mut CFG<'tcx>) -> BasicBlock {
2131        cfg.start_new_block()
2132    }
2133    fn link_entry_point(cfg: &mut CFG<'tcx>, from: BasicBlock, to: BasicBlock) {
2134        let term = cfg.block_data_mut(from).terminator_mut();
2135        if let TerminatorKind::Yield { ref mut drop, .. } = term.kind {
2136            *drop = Some(to);
2137        } else if let TerminatorKind::Drop { ref mut drop, .. } = term.kind {
2138            *drop = Some(to);
2139        } else {
2140            ::rustc_middle::util::bug::span_bug_fmt(term.source_info.span,
    format_args!("cannot enter coroutine drop tree from {0:?}", term.kind))span_bug!(
2141                term.source_info.span,
2142                "cannot enter coroutine drop tree from {:?}",
2143                term.kind
2144            )
2145        }
2146    }
2147}
2148
2149struct Unwind;
2150
2151impl<'tcx> DropTreeBuilder<'tcx> for Unwind {
2152    fn make_block(cfg: &mut CFG<'tcx>) -> BasicBlock {
2153        cfg.start_new_cleanup_block()
2154    }
2155    fn link_entry_point(cfg: &mut CFG<'tcx>, from: BasicBlock, to: BasicBlock) {
2156        let term = &mut cfg.block_data_mut(from).terminator_mut();
2157        match &mut term.kind {
2158            TerminatorKind::Drop { unwind, .. } => {
2159                if let UnwindAction::Cleanup(unwind) = *unwind {
2160                    let source_info = term.source_info;
2161                    cfg.terminate(unwind, source_info, TerminatorKind::Goto { target: to });
2162                } else {
2163                    *unwind = UnwindAction::Cleanup(to);
2164                }
2165            }
2166            TerminatorKind::FalseUnwind { unwind, .. }
2167            | TerminatorKind::Call { unwind, .. }
2168            | TerminatorKind::Assert { unwind, .. }
2169            | TerminatorKind::InlineAsm { unwind, .. } => {
2170                *unwind = UnwindAction::Cleanup(to);
2171            }
2172            TerminatorKind::Goto { .. }
2173            | TerminatorKind::SwitchInt { .. }
2174            | TerminatorKind::UnwindResume
2175            | TerminatorKind::UnwindTerminate(_)
2176            | TerminatorKind::Return
2177            | TerminatorKind::TailCall { .. }
2178            | TerminatorKind::Unreachable
2179            | TerminatorKind::Yield { .. }
2180            | TerminatorKind::CoroutineDrop
2181            | TerminatorKind::FalseEdge { .. } => {
2182                ::rustc_middle::util::bug::span_bug_fmt(term.source_info.span,
    format_args!("cannot unwind from {0:?}", term.kind))span_bug!(term.source_info.span, "cannot unwind from {:?}", term.kind)
2183            }
2184        }
2185    }
2186}