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`.
67### SEME Regions
89When 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.
1516For 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.
2021### Not so SEME Regions
2223In 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.
2930Also 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.
3435### Drops
3637The 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:
4546```
47# let cond = true;
48loop {
49 let x = ..;
50 if cond { break; }
51 let y = ..;
52}
53```
5455When 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`.
5960### Early exit
6162There 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.
7071Panics 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`.
7576### Breakable scopes
7778In 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.
8182*/
8384use std::mem;
8586use interpret::ErrorHandled;
87use rustc_data_structures::fx::FxHashMap;
88use rustc_hir::HirId;
89use rustc_index::{IndexSlice, IndexVec};
90use rustc_middle::middle::region;
91use rustc_middle::mir::{self, *};
92use rustc_middle::thir::{AdtExpr, AdtExprBase, ArmId, ExprId, ExprKind};
93use rustc_middle::ty::{self, Ty, TyCtxt, TypeVisitableExt, ValTree};
94use rustc_middle::{bug, span_bug};
95use rustc_pattern_analysis::rustc::RustcPatCtxt;
96use rustc_session::lint::Level;
97use rustc_span::{DUMMY_SP, Span, Spanned};
98use tracing::{debug, instrument};
99100use super::matches::BuiltMatchTree;
101use crate::builder::{BlockAnd, BlockAndExtension, BlockFrame, Builder, CFG};
102use crate::errors::{
103ConstContinueBadConst, ConstContinueNotMonomorphicConst, ConstContinueUnknownJumpTarget,
104};
105106#[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>,
109110/// The current set of breakable scopes. See module comment for more details.
111breakable_scopes: Vec<BreakableScope<'tcx>>,
112113 const_continuable_scopes: Vec<ConstContinuableScope<'tcx>>,
114115/// The scope of the innermost if-then currently being lowered.
116if_then_scope: Option<IfThenScope>,
117118/// Drops that need to be done on unwind paths. See the comment on
119 /// [DropTree] for more details.
120unwind_drops: DropTree,
121122/// Drops that need to be done on paths to the `CoroutineDrop` terminator.
123coroutine_drops: DropTree,
124}
125126#[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.
129source_scope: SourceScope,
130131/// the region span of this scope within source code.
132region_scope: region::Scope,
133134/// 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.
138drops: Vec<DropData>,
139140 moved_locals: Vec<Local>,
141142/// The drop index that will drop everything in and below this scope on an
143 /// unwind path.
144cached_unwind_block: Option<DropIdx>,
145146/// The drop index that will drop everything in and below this scope on a
147 /// coroutine drop path.
148cached_coroutine_drop_block: Option<DropIdx>,
149}
150151#[derive(#[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)
155source_info: SourceInfo,
156157/// local to drop
158local: Local,
159160/// Whether this is a value Drop or a StorageDead.
161kind: DropKind,
162}
163164#[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]
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::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 {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {}
}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)]
165pub(crate) enum DropKind {
166 Value,
167 Storage,
168 ForLint,
169}
170171#[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
174region_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)
177break_destination: Place<'tcx>,
178/// Drops that happen on the `break`/`return` path.
179break_drops: DropTree,
180/// Drops that happen on the `continue` path.
181continue_drops: Option<DropTree>,
182}
183184#[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.
187region_scope: region::Scope,
188/// The place of the state of a `#[loop_match]`, which a `#[const_continue]` must update.
189state_place: Place<'tcx>,
190191 arms: Box<[ArmId]>,
192 built_match_tree: BuiltMatchTree<'tcx>,
193194/// Drops that happen on a `#[const_continue]`
195const_continue_drops: DropTree,
196}
197198#[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
201region_scope: region::Scope,
202/// Drops that happen on the `else` path.
203else_drops: DropTree,
204}
205206/// The target of an expression that breaks out of a scope
207#[derive(#[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}
213214impl ::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]
216struct DropIdx {}
217}218219const ROOT_NODE: DropIdx = DropIdx::ZERO;
220221/// 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.
233drop_nodes: IndexVec<DropIdx, DropNode>,
234/// Map for finding the index of an existing node, given its contents.
235existing_drops_map: FxHashMap<DropNodeKey, DropIdx>,
236/// Edges into the `DropTree` that need to be added once it's lowered.
237entry_points: Vec<(DropIdx, BasicBlock)>,
238}
239240/// 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.
244data: DropData,
245/// Index of the "next" drop to perform (in drop order, not declaration order).
246next: DropIdx,
247}
248249/// 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::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}
255256impl 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.
268fn needs_cleanup(&self) -> bool {
269self.drops.iter().any(|drop| match drop.kind {
270 DropKind::Value | DropKind::ForLint => true,
271 DropKind::Storage => false,
272 })
273 }
274275fn invalidate_cache(&mut self) {
276self.cached_unwind_block = None;
277self.cached_coroutine_drop_block = None;
278 }
279}
280281/// 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()`.
286fn make_block(cfg: &mut CFG<'tcx>) -> BasicBlock;
287288/// Links a block outside the drop tree, `from`, to the block `to` inside
289 /// the drop tree.
290fn link_entry_point(cfg: &mut CFG<'tcx>, from: BasicBlock, to: BasicBlock);
291}
292293impl DropTree {
294fn 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.
298let fake_source_info = SourceInfo::outermost(DUMMY_SP);
299let fake_data =
300DropData { source_info: fake_source_info, local: Local::MAX, kind: DropKind::Storage };
301let 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 }]);
302Self { drop_nodes, entry_points: Vec::new(), existing_drops_map: FxHashMap::default() }
303 }
304305/// 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.
310fn add_drop(&mut self, data: DropData, next: DropIdx) -> DropIdx {
311let drop_nodes = &mut self.drop_nodes;
312*self313 .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 }
318319/// 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.
323fn add_entry_point(&mut self, from: BasicBlock, to: DropIdx) {
324if 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());
325self.entry_points.push((to, from));
326 }
327328/// Builds the MIR for a given drop tree.
329fn 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 compiler/rustc_mir_build/src/builder/scope.rs:334",
"rustc_mir_build::builder::scope", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("DropTree::build_mir(drops = {0:#?})",
self) as &dyn Value))])
});
} else { ; }
};debug!("DropTree::build_mir(drops = {:#?})", self);
335336let mut blocks = self.assign_blocks::<T>(cfg, root_node);
337self.link_blocks(cfg, &mut blocks);
338339blocks340 }
341342/// Assign blocks for all of the drops in the drop tree that need them.
343fn 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]
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)]
352enum Block {
353// This drop is unreachable
354None,
355// This drop is only reachable through the `StorageDead` with the
356 // specified index.
357Shares(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.
361Own,
362 }
363364let mut blocks = IndexVec::from_elem(None, &self.drop_nodes);
365blocks[ROOT_NODE] = root_node;
366367let mut needs_block = IndexVec::from_elem(Block::None, &self.drop_nodes);
368if 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.
372needs_block[ROOT_NODE] = Block::Own;
373 }
374375// Sort so that we only need to check the last value.
376let entry_points = &mut self.entry_points;
377entry_points.sort();
378379for (drop_idx, drop_node) in self.drop_nodes.iter_enumerated().rev() {
380if entry_points.last().is_some_and(|entry_point| entry_point.0 == drop_idx) {
381let block = *blocks[drop_idx].get_or_insert_with(|| T::make_block(cfg));
382 needs_block[drop_idx] = Block::Own;
383while entry_points.last().is_some_and(|entry_point| entry_point.0 == drop_idx) {
384let entry_block = entry_points.pop().unwrap().1;
385 T::link_entry_point(cfg, entry_block, block);
386 }
387 }
388match 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 }
397if let DropKind::Value = drop_node.data.kind {
398 needs_block[drop_node.next] = Block::Own;
399 } else if drop_idx != ROOT_NODE {
400match &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 }
407408{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_mir_build/src/builder/scope.rs:408",
"rustc_mir_build::builder::scope", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("assign_blocks: blocks = {0:#?}",
blocks) as &dyn Value))])
});
} else { ; }
};debug!("assign_blocks: blocks = {:#?}", blocks);
409if !entry_points.is_empty() {
::core::panicking::panic("assertion failed: entry_points.is_empty()")
};assert!(entry_points.is_empty());
410411blocks412 }
413414fn link_blocks<'tcx>(
415&self,
416 cfg: &mut CFG<'tcx>,
417 blocks: &IndexSlice<DropIdx, Option<BasicBlock>>,
418 ) {
419for (drop_idx, drop_node) in self.drop_nodes.iter_enumerated().rev() {
420let Some(block) = blocks[drop_idx] else { continue };
421match drop_node.data.kind {
422 DropKind::Value => {
423let terminator = TerminatorKind::Drop {
424 target: blocks[drop_node.next].unwrap(),
425// The caller will handle this if needed.
426unwind: UnwindAction::Terminate(UnwindTerminateReason::InCleanup),
427 place: drop_node.data.local.into(),
428 replace: false,
429 drop: None,
430 async_fut: None,
431 };
432 cfg.terminate(block, drop_node.data.source_info, terminator);
433 }
434 DropKind::ForLint => {
435let stmt = Statement::new(
436 drop_node.data.source_info,
437 StatementKind::BackwardIncompatibleDropHint {
438 place: Box::new(drop_node.data.local.into()),
439 reason: BackwardIncompatibleDropReason::Edition2024,
440 },
441 );
442 cfg.push(block, stmt);
443let target = blocks[drop_node.next].unwrap();
444if target != block {
445// Diagnostics don't use this `Span` but debuginfo
446 // might. Since we don't want breakpoints to be placed
447 // here, especially when this is on an unwind path, we
448 // use `DUMMY_SP`.
449let source_info =
450 SourceInfo { span: DUMMY_SP, ..drop_node.data.source_info };
451let terminator = TerminatorKind::Goto { target };
452 cfg.terminate(block, source_info, terminator);
453 }
454 }
455// Root nodes don't correspond to a drop.
456DropKind::Storage if drop_idx == ROOT_NODE => {}
457 DropKind::Storage => {
458let stmt = Statement::new(
459 drop_node.data.source_info,
460 StatementKind::StorageDead(drop_node.data.local),
461 );
462 cfg.push(block, stmt);
463let target = blocks[drop_node.next].unwrap();
464if target != block {
465// Diagnostics don't use this `Span` but debuginfo
466 // might. Since we don't want breakpoints to be placed
467 // here, especially when this is on an unwind path, we
468 // use `DUMMY_SP`.
469let source_info =
470 SourceInfo { span: DUMMY_SP, ..drop_node.data.source_info };
471let terminator = TerminatorKind::Goto { target };
472 cfg.terminate(block, source_info, terminator);
473 }
474 }
475 }
476 }
477 }
478}
479480impl<'tcx> Scopes<'tcx> {
481pub(crate) fn new() -> Self {
482Self {
483 scopes: Vec::new(),
484 breakable_scopes: Vec::new(),
485 const_continuable_scopes: Vec::new(),
486 if_then_scope: None,
487 unwind_drops: DropTree::new(),
488 coroutine_drops: DropTree::new(),
489 }
490 }
491492fn push_scope(&mut self, region_scope: (region::Scope, SourceInfo), vis_scope: SourceScope) {
493{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_mir_build/src/builder/scope.rs:493",
"rustc_mir_build::builder::scope", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_mir_build/src/builder/scope.rs"),
::tracing_core::__macro_support::Option::Some(493u32),
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("push_scope({0:?})",
region_scope) as &dyn Value))])
});
} else { ; }
};debug!("push_scope({:?})", region_scope);
494self.scopes.push(Scope {
495 source_scope: vis_scope,
496 region_scope: region_scope.0,
497 drops: ::alloc::vec::Vec::new()vec![],
498 moved_locals: ::alloc::vec::Vec::new()vec![],
499 cached_unwind_block: None,
500 cached_coroutine_drop_block: None,
501 });
502 }
503504fn pop_scope(&mut self, region_scope: (region::Scope, SourceInfo)) -> Scope {
505let scope = self.scopes.pop().unwrap();
506match (&scope.region_scope, ®ion_scope.0) {
(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.0);
507scope508 }
509510fn scope_index(&self, region_scope: region::Scope, span: Span) -> usize {
511self.scopes
512 .iter()
513 .rposition(|scope| scope.region_scope == region_scope)
514 .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))
515 }
516517/// Returns the topmost active scope, which is known to be alive until
518 /// the next scope expression.
519fn topmost(&self) -> region::Scope {
520self.scopes.last().expect("topmost_scope: no scopes present").region_scope
521 }
522}
523524/// Used by [`Builder::in_scope`] to create source scopes mapping from MIR back to HIR at points
525/// where lint levels change.
526#[derive(#[automatically_derived]
impl ::core::marker::Copy for LintLevel { }Copy, #[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)]
527pub(crate) enum LintLevel {
528 Inherited,
529 Explicit(HirId),
530}
531532impl<'a, 'tcx> Builder<'a, 'tcx> {
533// Adding and removing scopes
534 // ==========================
535536/// Start a breakable scope, which tracks where `continue`, `break` and
537 /// `return` should branch to.
538pub(crate) fn in_breakable_scope<F>(
539&mut self,
540 loop_block: Option<BasicBlock>,
541 break_destination: Place<'tcx>,
542 span: Span,
543 f: F,
544 ) -> BlockAnd<()>
545where
546F: FnOnce(&mut Builder<'a, 'tcx>) -> Option<BlockAnd<()>>,
547 {
548let region_scope = self.scopes.topmost();
549let scope = BreakableScope {
550region_scope,
551break_destination,
552 break_drops: DropTree::new(),
553 continue_drops: loop_block.map(|_| DropTree::new()),
554 };
555self.scopes.breakable_scopes.push(scope);
556let normal_exit_block = f(self);
557let breakable_scope = self.scopes.breakable_scopes.pop().unwrap();
558if !(breakable_scope.region_scope == region_scope) {
::core::panicking::panic("assertion failed: breakable_scope.region_scope == region_scope")
};assert!(breakable_scope.region_scope == region_scope);
559let break_block =
560self.build_exit_tree(breakable_scope.break_drops, region_scope, span, None);
561if let Some(drops) = breakable_scope.continue_drops {
562self.build_exit_tree(drops, region_scope, span, loop_block);
563 }
564match (normal_exit_block, break_block) {
565 (Some(block), None) | (None, Some(block)) => block,
566 (None, None) => self.cfg.start_new_block().unit(),
567 (Some(normal_block), Some(exit_block)) => {
568let target = self.cfg.start_new_block();
569let source_info = self.source_info(span);
570self.cfg.terminate(
571normal_block.into_block(),
572source_info,
573 TerminatorKind::Goto { target },
574 );
575self.cfg.terminate(
576exit_block.into_block(),
577source_info,
578 TerminatorKind::Goto { target },
579 );
580target.unit()
581 }
582 }
583 }
584585/// Start a const-continuable scope, which tracks where `#[const_continue] break` should
586 /// branch to.
587pub(crate) fn in_const_continuable_scope<F>(
588&mut self,
589 arms: Box<[ArmId]>,
590 built_match_tree: BuiltMatchTree<'tcx>,
591 state_place: Place<'tcx>,
592 span: Span,
593 f: F,
594 ) -> BlockAnd<()>
595where
596F: FnOnce(&mut Builder<'a, 'tcx>) -> BlockAnd<()>,
597 {
598let region_scope = self.scopes.topmost();
599let scope = ConstContinuableScope {
600region_scope,
601state_place,
602 const_continue_drops: DropTree::new(),
603arms,
604built_match_tree,
605 };
606self.scopes.const_continuable_scopes.push(scope);
607let normal_exit_block = f(self);
608let const_continue_scope = self.scopes.const_continuable_scopes.pop().unwrap();
609if !(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);
610611let break_block = self.build_exit_tree(
612const_continue_scope.const_continue_drops,
613region_scope,
614span,
615None,
616 );
617618match (normal_exit_block, break_block) {
619 (block, None) => block,
620 (normal_block, Some(exit_block)) => {
621let target = self.cfg.start_new_block();
622let source_info = self.source_info(span);
623self.cfg.terminate(
624normal_block.into_block(),
625source_info,
626 TerminatorKind::Goto { target },
627 );
628self.cfg.terminate(
629exit_block.into_block(),
630source_info,
631 TerminatorKind::Goto { target },
632 );
633target.unit()
634 }
635 }
636 }
637638/// Start an if-then scope which tracks drop for `if` expressions and `if`
639 /// guards.
640 ///
641 /// For an if-let chain:
642 ///
643 /// if let Some(x) = a && let Some(y) = b && let Some(z) = c { ... }
644 ///
645 /// There are three possible ways the condition can be false and we may have
646 /// to drop `x`, `x` and `y`, or neither depending on which binding fails.
647 /// To handle this correctly we use a `DropTree` in a similar way to a
648 /// `loop` expression and 'break' out on all of the 'else' paths.
649 ///
650 /// Notes:
651 /// - We don't need to keep a stack of scopes in the `Builder` because the
652 /// 'else' paths will only leave the innermost scope.
653 /// - This is also used for match guards.
654pub(crate) fn in_if_then_scope<F>(
655&mut self,
656 region_scope: region::Scope,
657 span: Span,
658 f: F,
659 ) -> (BasicBlock, BasicBlock)
660where
661F: FnOnce(&mut Builder<'a, 'tcx>) -> BlockAnd<()>,
662 {
663let scope = IfThenScope { region_scope, else_drops: DropTree::new() };
664let previous_scope = mem::replace(&mut self.scopes.if_then_scope, Some(scope));
665666let then_block = f(self).into_block();
667668let if_then_scope = mem::replace(&mut self.scopes.if_then_scope, previous_scope).unwrap();
669if !(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);
670671let else_block =
672self.build_exit_tree(if_then_scope.else_drops, region_scope, span, None).map_or_else(
673 || self.cfg.start_new_block(),
674 |else_block_and| else_block_and.into_block(),
675 );
676677 (then_block, else_block)
678 }
679680/// 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("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(&["region_scope",
"lint_level"],
::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};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(®ion_scope)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&lint_level)
as &dyn 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(region_scope.1.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 compiler/rustc_mir_build/src/builder/scope.rs:703",
"rustc_mir_build::builder::scope", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("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(&["block"],
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&block) as
&dyn Value))])
});
} else { ; }
};
block.and(rv)
}
}
}#[instrument(skip(self, f), level = "debug")]683pub(crate) fn in_scope<F, R>(
684&mut self,
685 region_scope: (region::Scope, SourceInfo),
686 lint_level: LintLevel,
687 f: F,
688 ) -> BlockAnd<R>
689where
690F: FnOnce(&mut Builder<'a, 'tcx>) -> BlockAnd<R>,
691 {
692let source_scope = self.source_scope;
693if let LintLevel::Explicit(current_hir_id) = lint_level {
694let parent_id =
695self.source_scopes[source_scope].local_data.as_ref().unwrap_crate_local().lint_root;
696self.maybe_new_source_scope(region_scope.1.span, current_hir_id, parent_id);
697 }
698self.push_scope(region_scope);
699let mut block;
700let rv = unpack!(block = f(self));
701 block = self.pop_scope(region_scope, block).into_block();
702self.source_scope = source_scope;
703debug!(?block);
704 block.and(rv)
705 }
706707/// 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.
709pub(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> {
714if let Some(region_scope) = opt_region_scope {
715self.in_scope(region_scope, LintLevel::Inherited, f)
716 } else {
717f(self)
718 }
719 }
720721/// 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.
725pub(crate) fn push_scope(&mut self, region_scope: (region::Scope, SourceInfo)) {
726self.scopes.push_scope(region_scope, self.source_scope);
727 }
728729/// 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`.
732pub(crate) fn pop_scope(
733&mut self,
734 region_scope: (region::Scope, SourceInfo),
735mut 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 compiler/rustc_mir_build/src/builder/scope.rs:737",
"rustc_mir_build::builder::scope", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("pop_scope({0:?}, {1:?})",
region_scope, block) as &dyn Value))])
});
} else { ; }
};debug!("pop_scope({:?}, {:?})", region_scope, block);
738739block = self.leave_top_scope(block);
740741self.scopes.pop_scope(region_scope);
742743block.unit()
744 }
745746/// Sets up the drops for breaking from `block` to `target`.
747pub(crate) fn break_scope(
748&mut self,
749mut block: BasicBlock,
750 value: Option<ExprId>,
751 target: BreakableTarget,
752 source_info: SourceInfo,
753 ) -> BlockAnd<()> {
754let span = source_info.span;
755756let get_scope_index = |scope: region::Scope| {
757// find the loop-scope by its `region::Scope`.
758self.scopes
759 .breakable_scopes
760 .iter()
761 .rposition(|breakable_scope| breakable_scope.region_scope == scope)
762 .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"))
763 };
764let (break_index, destination) = match target {
765 BreakableTarget::Return => {
766let scope = &self.scopes.breakable_scopes[0];
767if scope.break_destination != Place::return_place() {
768::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");
769 }
770 (0, Some(scope.break_destination))
771 }
772 BreakableTarget::Break(scope) => {
773let break_index = get_scope_index(scope);
774let scope = &self.scopes.breakable_scopes[break_index];
775 (break_index, Some(scope.break_destination))
776 }
777 BreakableTarget::Continue(scope) => {
778let break_index = get_scope_index(scope);
779 (break_index, None)
780 }
781 };
782783match (destination, value) {
784 (Some(destination), Some(value)) => {
785{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_mir_build/src/builder/scope.rs:785",
"rustc_mir_build::builder::scope", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_mir_build/src/builder/scope.rs"),
::tracing_core::__macro_support::Option::Some(785u32),
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("stmt_expr Break val block_context.push(SubExpr)")
as &dyn Value))])
});
} else { ; }
};debug!("stmt_expr Break val block_context.push(SubExpr)");
786self.block_context.push(BlockFrame::SubExpr);
787block = self.expr_into_dest(destination, block, value).into_block();
788self.block_context.pop();
789 }
790 (Some(destination), None) => {
791self.cfg.push_assign_unit(block, source_info, destination, self.tcx)
792 }
793 (None, Some(_)) => {
794{
::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")795 }
796 (None, None) => {
797if self.tcx.sess.instrument_coverage() {
798// Normally we wouldn't build any MIR in this case, but that makes it
799 // harder for coverage instrumentation to extract a relevant span for
800 // `continue` expressions. So here we inject a dummy statement with the
801 // desired span.
802self.cfg.push_coverage_span_marker(block, source_info);
803 }
804 }
805 }
806807let region_scope = self.scopes.breakable_scopes[break_index].region_scope;
808let scope_index = self.scopes.scope_index(region_scope, span);
809let drops = if destination.is_some() {
810&mut self.scopes.breakable_scopes[break_index].break_drops
811 } else {
812let Some(drops) = self.scopes.breakable_scopes[break_index].continue_drops.as_mut()
813else {
814self.tcx.dcx().span_delayed_bug(
815source_info.span,
816"unlabelled `continue` within labelled block",
817 );
818self.cfg.terminate(block, source_info, TerminatorKind::Unreachable);
819820return self.cfg.start_new_block().unit();
821 };
822drops823 };
824825let mut drop_idx = ROOT_NODE;
826for scope in &self.scopes.scopes[scope_index + 1..] {
827for drop in &scope.drops {
828 drop_idx = drops.add_drop(*drop, drop_idx);
829 }
830 }
831drops.add_entry_point(block, drop_idx);
832833// `build_drop_trees` doesn't have access to our source_info, so we
834 // create a dummy terminator now. `TerminatorKind::UnwindResume` is used
835 // because MIR type checking will panic if it hasn't been overwritten.
836 // (See `<ExitScopes as DropTreeBuilder>::link_entry_point`.)
837self.cfg.terminate(block, source_info, TerminatorKind::UnwindResume);
838839self.cfg.start_new_block().unit()
840 }
841842/// Based on `FunctionCx::eval_unevaluated_mir_constant_to_valtree`.
843fn eval_unevaluated_mir_constant_to_valtree(
844&self,
845 constant: ConstOperand<'tcx>,
846 ) -> Result<(ty::ValTree<'tcx>, Ty<'tcx>), interpret::ErrorHandled> {
847if !!constant.const_.ty().has_param() {
::core::panicking::panic("assertion failed: !constant.const_.ty().has_param()")
};assert!(!constant.const_.ty().has_param());
848let (uv, ty) = match constant.const_ {
849 mir::Const::Unevaluated(uv, ty) => (uv.shrink(), ty),
850 mir::Const::Ty(_, c) => match c.kind() {
851// A constant that came from a const generic but was then used as an argument to
852 // old-style simd_shuffle (passing as argument instead of as a generic param).
853ty::ConstKind::Value(cv) => return Ok((cv.valtree, cv.ty)),
854 other => ::rustc_middle::util::bug::span_bug_fmt(constant.span,
format_args!("{0:#?}", other))span_bug!(constant.span, "{other:#?}"),
855 },
856 mir::Const::Val(mir::ConstValue::Scalar(mir::interpret::Scalar::Int(val)), ty) => {
857return Ok((ValTree::from_scalar_int(self.tcx, val), ty));
858 }
859// We should never encounter `Const::Val` unless MIR opts (like const prop) evaluate
860 // a constant and write that value back into `Operand`s. This could happen, but is
861 // unlikely. Also: all users of `simd_shuffle` are on unstable and already need to take
862 // a lot of care around intrinsics. For an issue to happen here, it would require a
863 // macro expanding to a `simd_shuffle` call without wrapping the constant argument in a
864 // `const {}` block, but the user pass through arbitrary expressions.
865866 // FIXME(oli-obk): Replace the magic const generic argument of `simd_shuffle` with a
867 // real const generic, and get rid of this entire function.
868 other => ::rustc_middle::util::bug::span_bug_fmt(constant.span,
format_args!("{0:#?}", other))span_bug!(constant.span, "{other:#?}"),
869 };
870871match self.tcx.const_eval_resolve_for_typeck(self.typing_env(), uv, constant.span) {
872Ok(Ok(valtree)) => Ok((valtree, ty)),
873Ok(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"),
874Err(e) => Err(e),
875 }
876 }
877878/// Sets up the drops for jumping from `block` to `scope`.
879pub(crate) fn break_const_continuable_scope(
880&mut self,
881mut block: BasicBlock,
882 value: ExprId,
883 scope: region::Scope,
884 source_info: SourceInfo,
885 ) -> BlockAnd<()> {
886let span = source_info.span;
887888// A break can only break out of a scope, so the value should be a scope.
889let rustc_middle::thir::ExprKind::Scope { value, .. } = self.thir[value].kind else {
890::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")891 };
892893let expr = &self.thir[value];
894let constant = match &expr.kind {
895 ExprKind::Adt(box AdtExpr { variant_index, fields, base, .. }) => {
896if !#[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));
897if !fields.is_empty() {
::core::panicking::panic("assertion failed: fields.is_empty()")
};assert!(fields.is_empty());
898ConstOperand {
899 span: self.thir[value].span,
900 user_ty: None,
901 const_: Const::Ty(
902self.thir[value].ty,
903 ty::Const::new_value(
904self.tcx,
905ValTree::from_branches(
906self.tcx,
907 [ty::Const::new_value(
908self.tcx,
909ValTree::from_scalar_int(
910self.tcx,
911variant_index.as_u32().into(),
912 ),
913self.tcx.types.u32,
914 )],
915 ),
916self.thir[value].ty,
917 ),
918 ),
919 }
920 }
921922 ExprKind::Literal { .. }
923 | ExprKind::NonHirLiteral { .. }
924 | ExprKind::ZstLiteral { .. }
925 | ExprKind::NamedConst { .. } => self.as_constant(&self.thir[value]),
926927 other => {
928use crate::errors::ConstContinueNotMonomorphicConstReasonas Reason;
929930let span = expr.span;
931let reason = match other {
932 ExprKind::ConstParam { .. } => Reason::ConstantParameter { span },
933 ExprKind::ConstBlock { .. } => Reason::ConstBlock { span },
934_ => Reason::Other { span },
935 };
936937self.tcx
938 .dcx()
939 .emit_err(ConstContinueNotMonomorphicConst { span: expr.span, reason });
940return block.unit();
941 }
942 };
943944let break_index = self945 .scopes
946 .const_continuable_scopes
947 .iter()
948 .rposition(|const_continuable_scope| const_continuable_scope.region_scope == scope)
949 .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"));
950951let scope = &self.scopes.const_continuable_scopes[break_index];
952953let state_decl = &self.local_decls[scope.state_place.as_local().unwrap()];
954let state_ty = state_decl.ty;
955let (discriminant_ty, rvalue) = match state_ty.kind() {
956 ty::Adt(adt_def, _) if adt_def.is_enum() => {
957 (state_ty.discriminant_ty(self.tcx), Rvalue::Discriminant(scope.state_place))
958 }
959 ty::Uint(_) | ty::Int(_) | ty::Float(_) | ty::Bool | ty::Char => {
960 (state_ty, Rvalue::Use(Operand::Copy(scope.state_place)))
961 }
962_ => ::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"),
963 };
964965// The `PatCtxt` is normally used in pattern exhaustiveness checking, but reused
966 // here because it performs normalization and const evaluation.
967let dropless_arena = rustc_arena::DroplessArena::default();
968let typeck_results = self.tcx.typeck(self.def_id);
969let cx = RustcPatCtxt {
970 tcx: self.tcx,
971typeck_results,
972 module: self.tcx.parent_module(self.hir_id).to_def_id(),
973// FIXME(#132279): We're in a body, should handle opaques.
974typing_env: rustc_middle::ty::TypingEnv::non_body_analysis(self.tcx, self.def_id),
975 dropless_arena: &dropless_arena,
976 match_lint_level: self.hir_id,
977 whole_match_span: Some(rustc_span::Span::default()),
978 scrut_span: rustc_span::Span::default(),
979 refutable: true,
980 known_valid_scrutinee: true,
981 internal_state: Default::default(),
982 };
983984let valtree = match self.eval_unevaluated_mir_constant_to_valtree(constant) {
985Ok((valtree, ty)) => {
986// Defensively check that the type is monomorphic.
987if !!ty.has_param() {
::core::panicking::panic("assertion failed: !ty.has_param()")
};assert!(!ty.has_param());
988989valtree990 }
991Err(ErrorHandled::Reported(..)) => {
992return block.unit();
993 }
994Err(ErrorHandled::TooGeneric(_)) => {
995self.tcx.dcx().emit_fatal(ConstContinueBadConst { span: constant.span });
996 }
997 };
998999let Some(real_target) =
1000self.static_pattern_match(&cx, valtree, &*scope.arms, &scope.built_match_tree)
1001else {
1002self.tcx.dcx().emit_fatal(ConstContinueUnknownJumpTarget { span })
1003 };
10041005self.block_context.push(BlockFrame::SubExpr);
1006let state_place = scope.state_place;
1007block = self.expr_into_dest(state_place, block, value).into_block();
1008self.block_context.pop();
10091010let discr = self.temp(discriminant_ty, source_info.span);
1011let scope_index = self1012 .scopes
1013 .scope_index(self.scopes.const_continuable_scopes[break_index].region_scope, span);
1014let scope = &mut self.scopes.const_continuable_scopes[break_index];
1015self.cfg.push_assign(block, source_info, discr, rvalue);
1016let drop_and_continue_block = self.cfg.start_new_block();
1017let imaginary_target = self.cfg.start_new_block();
1018self.cfg.terminate(
1019block,
1020source_info,
1021 TerminatorKind::FalseEdge { real_target: drop_and_continue_block, imaginary_target },
1022 );
10231024let drops = &mut scope.const_continue_drops;
10251026let drop_idx = self.scopes.scopes[scope_index + 1..]
1027 .iter()
1028 .flat_map(|scope| &scope.drops)
1029 .fold(ROOT_NODE, |drop_idx, &drop| drops.add_drop(drop, drop_idx));
10301031drops.add_entry_point(imaginary_target, drop_idx);
10321033self.cfg.terminate(imaginary_target, source_info, TerminatorKind::UnwindResume);
10341035let region_scope = scope.region_scope;
1036let scope_index = self.scopes.scope_index(region_scope, span);
1037let mut drops = DropTree::new();
10381039let drop_idx = self.scopes.scopes[scope_index + 1..]
1040 .iter()
1041 .flat_map(|scope| &scope.drops)
1042 .fold(ROOT_NODE, |drop_idx, &drop| drops.add_drop(drop, drop_idx));
10431044drops.add_entry_point(drop_and_continue_block, drop_idx);
10451046// `build_drop_trees` doesn't have access to our source_info, so we
1047 // create a dummy terminator now. `TerminatorKind::UnwindResume` is used
1048 // because MIR type checking will panic if it hasn't been overwritten.
1049 // (See `<ExitScopes as DropTreeBuilder>::link_entry_point`.)
1050self.cfg.terminate(drop_and_continue_block, source_info, TerminatorKind::UnwindResume);
10511052self.build_exit_tree(drops, region_scope, span, Some(real_target));
10531054return self.cfg.start_new_block().unit();
1055 }
10561057/// Sets up the drops for breaking from `block` due to an `if` condition
1058 /// that turned out to be false.
1059 ///
1060 /// Must be called in the context of [`Builder::in_if_then_scope`], so that
1061 /// there is an if-then scope to tell us what the target scope is.
1062pub(crate) fn break_for_else(&mut self, block: BasicBlock, source_info: SourceInfo) {
1063let if_then_scope = self1064 .scopes
1065 .if_then_scope
1066 .as_ref()
1067 .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"));
10681069let target = if_then_scope.region_scope;
1070let scope_index = self.scopes.scope_index(target, source_info.span);
10711072// Upgrade `if_then_scope` to `&mut`.
1073let if_then_scope = self.scopes.if_then_scope.as_mut().expect("upgrading & to &mut");
10741075let mut drop_idx = ROOT_NODE;
1076let drops = &mut if_then_scope.else_drops;
1077for scope in &self.scopes.scopes[scope_index + 1..] {
1078for drop in &scope.drops {
1079 drop_idx = drops.add_drop(*drop, drop_idx);
1080 }
1081 }
1082drops.add_entry_point(block, drop_idx);
10831084// `build_drop_trees` doesn't have access to our source_info, so we
1085 // create a dummy terminator now. `TerminatorKind::UnwindResume` is used
1086 // because MIR type checking will panic if it hasn't been overwritten.
1087 // (See `<ExitScopes as DropTreeBuilder>::link_entry_point`.)
1088self.cfg.terminate(block, source_info, TerminatorKind::UnwindResume);
1089 }
10901091/// Sets up the drops for explicit tail calls.
1092 ///
1093 /// Unlike other kinds of early exits, tail calls do not go through the drop tree.
1094 /// Instead, all scheduled drops are immediately added to the CFG.
1095pub(crate) fn break_for_tail_call(
1096&mut self,
1097mut block: BasicBlock,
1098 args: &[Spanned<Operand<'tcx>>],
1099 source_info: SourceInfo,
1100 ) -> BlockAnd<()> {
1101let arg_drops: Vec<_> = args1102 .iter()
1103 .rev()
1104 .filter_map(|arg| match &arg.node {
1105 Operand::Copy(_) => ::rustc_middle::util::bug::bug_fmt(format_args!("copy op in tail call args"))bug!("copy op in tail call args"),
1106 Operand::Move(place) => {
1107let local =
1108place.as_local().unwrap_or_else(|| ::rustc_middle::util::bug::bug_fmt(format_args!("projection in tail call args"))bug!("projection in tail call args"));
11091110if !self.local_decls[local].ty.needs_drop(self.tcx, self.typing_env()) {
1111return None;
1112 }
11131114Some(DropData { source_info, local, kind: DropKind::Value })
1115 }
1116 Operand::Constant(_) | Operand::RuntimeChecks(_) => None,
1117 })
1118 .collect();
11191120let mut unwind_to = self.diverge_cleanup_target(
1121self.scopes.scopes.iter().rev().nth(1).unwrap().region_scope,
1122DUMMY_SP,
1123 );
1124let typing_env = self.typing_env();
1125let unwind_drops = &mut self.scopes.unwind_drops;
11261127// the innermost scope contains only the destructors for the tail call arguments
1128 // we only want to drop these in case of a panic, so we skip it
1129for scope in self.scopes.scopes[1..].iter().rev().skip(1) {
1130// FIXME(explicit_tail_calls) code duplication with `build_scope_drops`
1131for drop_data in scope.drops.iter().rev() {
1132let source_info = drop_data.source_info;
1133let local = drop_data.local;
11341135if !self.local_decls[local].ty.needs_drop(self.tcx, typing_env) {
1136continue;
1137 }
11381139match drop_data.kind {
1140 DropKind::Value => {
1141// `unwind_to` should drop the value that we're about to
1142 // schedule. If dropping this value panics, then we continue
1143 // with the *next* value on the unwind path.
1144if 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!(
1145 unwind_drops.drop_nodes[unwind_to].data.local,
1146 drop_data.local
1147 );
1148if 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!(
1149 unwind_drops.drop_nodes[unwind_to].data.kind,
1150 drop_data.kind
1151 );
1152 unwind_to = unwind_drops.drop_nodes[unwind_to].next;
11531154let mut unwind_entry_point = unwind_to;
11551156// the tail call arguments must be dropped if any of these drops panic
1157for drop in arg_drops.iter().copied() {
1158 unwind_entry_point = unwind_drops.add_drop(drop, unwind_entry_point);
1159 }
11601161 unwind_drops.add_entry_point(block, unwind_entry_point);
11621163let next = self.cfg.start_new_block();
1164self.cfg.terminate(
1165 block,
1166 source_info,
1167 TerminatorKind::Drop {
1168 place: local.into(),
1169 target: next,
1170 unwind: UnwindAction::Continue,
1171 replace: false,
1172 drop: None,
1173 async_fut: None,
1174 },
1175 );
1176 block = next;
1177 }
1178 DropKind::ForLint => {
1179self.cfg.push(
1180 block,
1181 Statement::new(
1182 source_info,
1183 StatementKind::BackwardIncompatibleDropHint {
1184 place: Box::new(local.into()),
1185 reason: BackwardIncompatibleDropReason::Edition2024,
1186 },
1187 ),
1188 );
1189 }
1190 DropKind::Storage => {
1191// Only temps and vars need their storage dead.
1192if !(local.index() > self.arg_count) {
::core::panicking::panic("assertion failed: local.index() > self.arg_count")
};assert!(local.index() > self.arg_count);
1193self.cfg.push(
1194 block,
1195 Statement::new(source_info, StatementKind::StorageDead(local)),
1196 );
1197 }
1198 }
1199 }
1200 }
12011202block.unit()
1203 }
12041205fn is_async_drop_impl(
1206 tcx: TyCtxt<'tcx>,
1207 local_decls: &IndexVec<Local, LocalDecl<'tcx>>,
1208 typing_env: ty::TypingEnv<'tcx>,
1209 local: Local,
1210 ) -> bool {
1211let ty = local_decls[local].ty;
1212if ty.is_async_drop(tcx, typing_env) || ty.is_coroutine() {
1213return true;
1214 }
1215ty.needs_async_drop(tcx, typing_env)
1216 }
1217fn is_async_drop(&self, local: Local) -> bool {
1218Self::is_async_drop_impl(self.tcx, &self.local_decls, self.typing_env(), local)
1219 }
12201221fn leave_top_scope(&mut self, block: BasicBlock) -> BasicBlock {
1222// If we are emitting a `drop` statement, we need to have the cached
1223 // diverge cleanup pads ready in case that drop panics.
1224let needs_cleanup = self.scopes.scopes.last().is_some_and(|scope| scope.needs_cleanup());
1225let is_coroutine = self.coroutine.is_some();
1226let unwind_to = if needs_cleanup { self.diverge_cleanup() } else { DropIdx::MAX };
12271228let scope = self.scopes.scopes.last().expect("leave_top_scope called with no scopes");
1229let has_async_drops = is_coroutine1230 && scope.drops.iter().any(|v| v.kind == DropKind::Value && self.is_async_drop(v.local));
1231let dropline_to = if has_async_drops { Some(self.diverge_dropline()) } else { None };
1232let scope = self.scopes.scopes.last().expect("leave_top_scope called with no scopes");
1233let typing_env = self.typing_env();
1234build_scope_drops(
1235&mut self.cfg,
1236&mut self.scopes.unwind_drops,
1237&mut self.scopes.coroutine_drops,
1238scope,
1239block,
1240unwind_to,
1241dropline_to,
1242is_coroutine && needs_cleanup,
1243self.arg_count,
1244 |v: Local| Self::is_async_drop_impl(self.tcx, &self.local_decls, typing_env, v),
1245 )
1246 .into_block()
1247 }
12481249/// Possibly creates a new source scope if `current_root` and `parent_root`
1250 /// are different, or if -Zmaximal-hir-to-mir-coverage is enabled.
1251pub(crate) fn maybe_new_source_scope(
1252&mut self,
1253 span: Span,
1254 current_id: HirId,
1255 parent_id: HirId,
1256 ) {
1257let (current_root, parent_root) =
1258if self.tcx.sess.opts.unstable_opts.maximal_hir_to_mir_coverage {
1259// Some consumers of rustc need to map MIR locations back to HIR nodes. Currently
1260 // the only part of rustc that tracks MIR -> HIR is the
1261 // `SourceScopeLocalData::lint_root` field that tracks lint levels for MIR
1262 // locations. Normally the number of source scopes is limited to the set of nodes
1263 // with lint annotations. The -Zmaximal-hir-to-mir-coverage flag changes this
1264 // behavior to maximize the number of source scopes, increasing the granularity of
1265 // the MIR->HIR mapping.
1266(current_id, parent_id)
1267 } else {
1268// Use `maybe_lint_level_root_bounded` to avoid adding Hir dependencies on our
1269 // parents. We estimate the true lint roots here to avoid creating a lot of source
1270 // scopes.
1271(
1272self.maybe_lint_level_root_bounded(current_id),
1273if parent_id == self.hir_id {
1274parent_id// this is very common
1275} else {
1276self.maybe_lint_level_root_bounded(parent_id)
1277 },
1278 )
1279 };
12801281if current_root != parent_root {
1282let lint_level = LintLevel::Explicit(current_root);
1283self.source_scope = self.new_source_scope(span, lint_level);
1284 }
1285 }
12861287/// Walks upwards from `orig_id` to find a node which might change lint levels with attributes.
1288 /// It stops at `self.hir_id` and just returns it if reached.
1289fn maybe_lint_level_root_bounded(&mut self, orig_id: HirId) -> HirId {
1290// This assertion lets us just store `ItemLocalId` in the cache, rather
1291 // than the full `HirId`.
1292match (&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);
12931294let mut id = orig_id;
1295loop {
1296if id == self.hir_id {
1297// This is a moderately common case, mostly hit for previously unseen nodes.
1298break;
1299 }
13001301if self.tcx.hir_attrs(id).iter().any(|attr| Level::from_attr(attr).is_some()) {
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.
1304return id;
1305 }
13061307let next = self.tcx.parent_hir_id(id);
1308if 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 }
1311id = next;
13121313// 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.
1318if self.lint_level_roots_cache.contains(id.local_id) {
1319break;
1320 }
1321 }
13221323// `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.
1326self.lint_level_roots_cache.insert(orig_id.local_id);
1327self.hir_id
1328 }
13291330/// Creates a new source scope, nested in the current one.
1331pub(crate) fn new_source_scope(&mut self, span: Span, lint_level: LintLevel) -> SourceScope {
1332let 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 compiler/rustc_mir_build/src/builder/scope.rs:1333",
"rustc_mir_build::builder::scope", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::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 Value))])
});
} else { ; }
};debug!(
1334"new_source_scope({:?}, {:?}) - parent({:?})={:?}",
1335 span,
1336 lint_level,
1337 parent,
1338self.source_scopes.get(parent)
1339 );
1340let scope_local_data = SourceScopeLocalData {
1341 lint_root: if let LintLevel::Explicit(lint_root) = lint_level {
1342lint_root1343 } else {
1344self.source_scopes[parent].local_data.as_ref().unwrap_crate_local().lint_root
1345 },
1346 };
1347self.source_scopes.push(SourceScopeData {
1348span,
1349 parent_scope: Some(parent),
1350 inlined: None,
1351 inlined_parent_scope: None,
1352 local_data: ClearCrossCrate::Set(scope_local_data),
1353 })
1354 }
13551356/// Given a span and the current source scope, make a SourceInfo.
1357pub(crate) fn source_info(&self, span: Span) -> SourceInfo {
1358SourceInfo { span, scope: self.source_scope }
1359 }
13601361// Finding scopes
1362 // ==============
13631364/// 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.
1383pub(crate) fn local_scope(&self) -> region::Scope {
1384self.scopes.topmost()
1385 }
13861387// Scheduling drops
1388 // ================
13891390pub(crate) fn schedule_drop_storage_and_value(
1391&mut self,
1392 span: Span,
1393 region_scope: region::Scope,
1394 local: Local,
1395 ) {
1396self.schedule_drop(span, region_scope, local, DropKind::Storage);
1397self.schedule_drop(span, region_scope, local, DropKind::Value);
1398 }
13991400/// Indicates that `place` should be dropped on exit from `region_scope`.
1401 ///
1402 /// When called with `DropKind::Storage`, `place` shouldn't be the return
1403 /// place, or a function parameter.
1404pub(crate) fn schedule_drop(
1405&mut self,
1406 span: Span,
1407 region_scope: region::Scope,
1408 local: Local,
1409 drop_kind: DropKind,
1410 ) {
1411let needs_drop = match drop_kind {
1412 DropKind::Value | DropKind::ForLint => {
1413if !self.local_decls[local].ty.needs_drop(self.tcx, self.typing_env()) {
1414return;
1415 }
1416true
1417}
1418 DropKind::Storage => {
1419if local.index() <= self.arg_count {
1420::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!(
1421span,
1422"`schedule_drop` called with body argument {:?} \
1423 but its storage does not require a drop",
1424 local,
1425 )1426 }
1427false
1428}
1429 };
14301431// When building drops, we try to cache chains of drops to reduce the
1432 // number of `DropTree::add_drop` calls. This, however, means that
1433 // whenever we add a drop into a scope which already had some entries
1434 // in the drop tree built (and thus, cached) for it, we must invalidate
1435 // all caches which might branch into the scope which had a drop just
1436 // added to it. This is necessary, because otherwise some other code
1437 // might use the cache to branch into already built chain of drops,
1438 // essentially ignoring the newly added drop.
1439 //
1440 // For example consider there’s two scopes with a drop in each. These
1441 // are built and thus the caches are filled:
1442 //
1443 // +--------------------------------------------------------+
1444 // | +---------------------------------+ |
1445 // | | +--------+ +-------------+ | +---------------+ |
1446 // | | | return | <-+ | drop(outer) | <-+ | drop(middle) | |
1447 // | | +--------+ +-------------+ | +---------------+ |
1448 // | +------------|outer_scope cache|--+ |
1449 // +------------------------------|middle_scope cache|------+
1450 //
1451 // Now, a new, innermost scope is added along with a new drop into
1452 // both innermost and outermost scopes:
1453 //
1454 // +------------------------------------------------------------+
1455 // | +----------------------------------+ |
1456 // | | +--------+ +-------------+ | +---------------+ | +-------------+
1457 // | | | return | <+ | drop(new) | <-+ | drop(middle) | <--+| drop(inner) |
1458 // | | +--------+ | | drop(outer) | | +---------------+ | +-------------+
1459 // | | +-+ +-------------+ | |
1460 // | +---|invalid outer_scope cache|----+ |
1461 // +----=----------------|invalid middle_scope cache|-----------+
1462 //
1463 // If, when adding `drop(new)` we do not invalidate the cached blocks for both
1464 // outer_scope and middle_scope, then, when building drops for the inner (rightmost)
1465 // scope, the old, cached blocks, without `drop(new)` will get used, producing the
1466 // wrong results.
1467 //
1468 // Note that this code iterates scopes from the innermost to the outermost,
1469 // invalidating caches of each scope visited. This way bare minimum of the
1470 // caches gets invalidated. i.e., if a new drop is added into the middle scope, the
1471 // cache of outer scope stays intact.
1472 //
1473 // Since we only cache drops for the unwind path and the coroutine drop
1474 // path, we only need to invalidate the cache for drops that happen on
1475 // the unwind or coroutine drop paths. This means that for
1476 // non-coroutines we don't need to invalidate caches for `DropKind::Storage`.
1477let invalidate_caches = needs_drop || self.coroutine.is_some();
1478for scope in self.scopes.scopes.iter_mut().rev() {
1479if invalidate_caches {
1480 scope.invalidate_cache();
1481 }
14821483if scope.region_scope == region_scope {
1484let region_scope_span = region_scope.span(self.tcx, self.region_scope_tree);
1485// Attribute scope exit drops to scope's closing brace.
1486let scope_end = self.tcx.sess.source_map().end_point(region_scope_span);
14871488 scope.drops.push(DropData {
1489 source_info: SourceInfo { span: scope_end, scope: scope.source_scope },
1490 local,
1491 kind: drop_kind,
1492 });
14931494return;
1495 }
1496 }
14971498::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);
1499 }
15001501/// Schedule emission of a backwards incompatible drop lint hint.
1502 /// Applicable only to temporary values for now.
1503#[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("compiler/rustc_mir_build/src/builder/scope.rs"),
::tracing_core::__macro_support::Option::Some(1503u32),
::tracing_core::__macro_support::Option::Some("rustc_mir_build::builder::scope"),
::tracing_core::field::FieldSet::new(&["span",
"region_scope", "local"],
::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};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&span)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(®ion_scope)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&local)
as &dyn 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;
}
{
for scope in self.scopes.scopes.iter_mut().rev() {
scope.invalidate_cache();
if scope.region_scope == region_scope {
let region_scope_span =
region_scope.span(self.tcx, self.region_scope_tree);
let scope_end =
self.tcx.sess.source_map().end_point(region_scope_span);
scope.drops.push(DropData {
source_info: SourceInfo {
span: scope_end,
scope: scope.source_scope,
},
local,
kind: DropKind::ForLint,
});
return;
}
}
::rustc_middle::util::bug::span_bug_fmt(span,
format_args!("region scope {0:?} not in scope to drop {1:?} for linting",
region_scope, local));
}
}
}#[instrument(level = "debug", skip(self))]1504pub(crate) fn schedule_backwards_incompatible_drop(
1505&mut self,
1506 span: Span,
1507 region_scope: region::Scope,
1508 local: Local,
1509 ) {
1510// Note that we are *not* gating BIDs here on whether they have significant destructor.
1511 // We need to know all of them so that we can capture potential borrow-checking errors.
1512for scope in self.scopes.scopes.iter_mut().rev() {
1513// Since we are inserting linting MIR statement, we have to invalidate the caches
1514scope.invalidate_cache();
1515if scope.region_scope == region_scope {
1516let region_scope_span = region_scope.span(self.tcx, self.region_scope_tree);
1517let scope_end = self.tcx.sess.source_map().end_point(region_scope_span);
15181519 scope.drops.push(DropData {
1520 source_info: SourceInfo { span: scope_end, scope: scope.source_scope },
1521 local,
1522 kind: DropKind::ForLint,
1523 });
15241525return;
1526 }
1527 }
1528span_bug!(
1529 span,
1530"region scope {:?} not in scope to drop {:?} for linting",
1531 region_scope,
1532 local
1533 );
1534 }
15351536/// Indicates that the "local operand" stored in `local` is
1537 /// *moved* at some point during execution (see `local_scope` for
1538 /// more information about what a "local operand" is -- in short,
1539 /// it's an intermediate operand created as part of preparing some
1540 /// MIR instruction). We use this information to suppress
1541 /// redundant drops on the non-unwind paths. This results in less
1542 /// MIR, but also avoids spurious borrow check errors
1543 /// (c.f. #64391).
1544 ///
1545 /// Example: when compiling the call to `foo` here:
1546 ///
1547 /// ```ignore (illustrative)
1548 /// foo(bar(), ...)
1549 /// ```
1550 ///
1551 /// we would evaluate `bar()` to an operand `_X`. We would also
1552 /// schedule `_X` to be dropped when the expression scope for
1553 /// `foo(bar())` is exited. This is relevant, for example, if the
1554 /// later arguments should unwind (it would ensure that `_X` gets
1555 /// dropped). However, if no unwind occurs, then `_X` will be
1556 /// unconditionally consumed by the `call`:
1557 ///
1558 /// ```ignore (illustrative)
1559 /// bb {
1560 /// ...
1561 /// _R = CALL(foo, _X, ...)
1562 /// }
1563 /// ```
1564 ///
1565 /// However, `_X` is still registered to be dropped, and so if we
1566 /// do nothing else, we would generate a `DROP(_X)` that occurs
1567 /// after the call. This will later be optimized out by the
1568 /// drop-elaboration code, but in the meantime it can lead to
1569 /// spurious borrow-check errors -- the problem, ironically, is
1570 /// not the `DROP(_X)` itself, but the (spurious) unwind pathways
1571 /// that it creates. See #64391 for an example.
1572pub(crate) fn record_operands_moved(&mut self, operands: &[Spanned<Operand<'tcx>>]) {
1573let local_scope = self.local_scope();
1574let scope = self.scopes.scopes.last_mut().unwrap();
15751576match (&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!",);
15771578// look for moves of a local variable, like `MOVE(_X)`
1579let locals_moved = operands.iter().flat_map(|operand| match operand.node {
1580 Operand::Copy(_) | Operand::Constant(_) | Operand::RuntimeChecks(_) => None,
1581 Operand::Move(place) => place.as_local(),
1582 });
15831584for local in locals_moved {
1585// check if we have a Drop for this operand and -- if so
1586 // -- add it to the list of moved operands. Note that this
1587 // local might not have been an operand created for this
1588 // call, it could come from other places too.
1589if scope.drops.iter().any(|drop| drop.local == local && drop.kind == DropKind::Value) {
1590 scope.moved_locals.push(local);
1591 }
1592 }
1593 }
15941595// Other
1596 // =====
15971598/// Returns the [DropIdx] for the innermost drop if the function unwound at
1599 /// this point. The `DropIdx` will be created if it doesn't already exist.
1600fn diverge_cleanup(&mut self) -> DropIdx {
1601// It is okay to use dummy span because the getting scope index on the topmost scope
1602 // must always succeed.
1603self.diverge_cleanup_target(self.scopes.topmost(), DUMMY_SP)
1604 }
16051606/// This is similar to [diverge_cleanup](Self::diverge_cleanup) except its target is set to
1607 /// some ancestor scope instead of the current scope.
1608 /// It is possible to unwind to some ancestor scope if some drop panics as
1609 /// the program breaks out of a if-then scope.
1610fn diverge_cleanup_target(&mut self, target_scope: region::Scope, span: Span) -> DropIdx {
1611let target = self.scopes.scope_index(target_scope, span);
1612let (uncached_scope, mut cached_drop) = self.scopes.scopes[..=target]
1613 .iter()
1614 .enumerate()
1615 .rev()
1616 .find_map(|(scope_idx, scope)| {
1617scope.cached_unwind_block.map(|cached_block| (scope_idx + 1, cached_block))
1618 })
1619 .unwrap_or((0, ROOT_NODE));
16201621if uncached_scope > target {
1622return cached_drop;
1623 }
16241625let is_coroutine = self.coroutine.is_some();
1626for scope in &mut self.scopes.scopes[uncached_scope..=target] {
1627for drop in &scope.drops {
1628if is_coroutine || drop.kind == DropKind::Value {
1629 cached_drop = self.scopes.unwind_drops.add_drop(*drop, cached_drop);
1630 }
1631 }
1632 scope.cached_unwind_block = Some(cached_drop);
1633 }
16341635cached_drop1636 }
16371638/// Prepares to create a path that performs all required cleanup for a
1639 /// terminator that can unwind at the given basic block.
1640 ///
1641 /// This path terminates in Resume. The path isn't created until after all
1642 /// of the non-unwind paths in this item have been lowered.
1643pub(crate) fn diverge_from(&mut self, start: BasicBlock) {
1644if 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!(
1645matches!(
1646self.cfg.block_data(start).terminator().kind,
1647 TerminatorKind::Assert { .. }
1648 | TerminatorKind::Call { .. }
1649 | TerminatorKind::Drop { .. }
1650 | TerminatorKind::FalseUnwind { .. }
1651 | TerminatorKind::InlineAsm { .. }
1652 ),
1653"diverge_from called on block with terminator that cannot unwind."
1654);
16551656let next_drop = self.diverge_cleanup();
1657self.scopes.unwind_drops.add_entry_point(start, next_drop);
1658 }
16591660/// Returns the [DropIdx] for the innermost drop for dropline (coroutine drop path).
1661 /// The `DropIdx` will be created if it doesn't already exist.
1662fn diverge_dropline(&mut self) -> DropIdx {
1663// It is okay to use dummy span because the getting scope index on the topmost scope
1664 // must always succeed.
1665self.diverge_dropline_target(self.scopes.topmost(), DUMMY_SP)
1666 }
16671668/// Similar to diverge_cleanup_target, but for dropline (coroutine drop path)
1669fn diverge_dropline_target(&mut self, target_scope: region::Scope, span: Span) -> DropIdx {
1670if true {
if !self.coroutine.is_some() {
{
::core::panicking::panic_fmt(format_args!("diverge_dropline_target is valid only for coroutine"));
}
};
};debug_assert!(
1671self.coroutine.is_some(),
1672"diverge_dropline_target is valid only for coroutine"
1673);
1674let target = self.scopes.scope_index(target_scope, span);
1675let (uncached_scope, mut cached_drop) = self.scopes.scopes[..=target]
1676 .iter()
1677 .enumerate()
1678 .rev()
1679 .find_map(|(scope_idx, scope)| {
1680scope.cached_coroutine_drop_block.map(|cached_block| (scope_idx + 1, cached_block))
1681 })
1682 .unwrap_or((0, ROOT_NODE));
16831684if uncached_scope > target {
1685return cached_drop;
1686 }
16871688for scope in &mut self.scopes.scopes[uncached_scope..=target] {
1689for drop in &scope.drops {
1690 cached_drop = self.scopes.coroutine_drops.add_drop(*drop, cached_drop);
1691 }
1692 scope.cached_coroutine_drop_block = Some(cached_drop);
1693 }
16941695cached_drop1696 }
16971698/// Sets up a path that performs all required cleanup for dropping a
1699 /// coroutine, starting from the given block that ends in
1700 /// [TerminatorKind::Yield].
1701 ///
1702 /// This path terminates in CoroutineDrop.
1703pub(crate) fn coroutine_drop_cleanup(&mut self, yield_block: BasicBlock) {
1704if 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!(
1705matches!(
1706self.cfg.block_data(yield_block).terminator().kind,
1707 TerminatorKind::Yield { .. }
1708 ),
1709"coroutine_drop_cleanup called on block with non-yield terminator."
1710);
1711let cached_drop = self.diverge_dropline();
1712self.scopes.coroutine_drops.add_entry_point(yield_block, cached_drop);
1713 }
17141715/// Utility function for *non*-scope code to build their own drops
1716 /// Force a drop at this point in the MIR by creating a new block.
1717pub(crate) fn build_drop_and_replace(
1718&mut self,
1719 block: BasicBlock,
1720 span: Span,
1721 place: Place<'tcx>,
1722 value: Rvalue<'tcx>,
1723 ) -> BlockAnd<()> {
1724let source_info = self.source_info(span);
17251726// create the new block for the assignment
1727let assign = self.cfg.start_new_block();
1728self.cfg.push_assign(assign, source_info, place, value.clone());
17291730// create the new block for the assignment in the case of unwinding
1731let assign_unwind = self.cfg.start_new_cleanup_block();
1732self.cfg.push_assign(assign_unwind, source_info, place, value.clone());
17331734self.cfg.terminate(
1735block,
1736source_info,
1737 TerminatorKind::Drop {
1738place,
1739 target: assign,
1740 unwind: UnwindAction::Cleanup(assign_unwind),
1741 replace: true,
1742 drop: None,
1743 async_fut: None,
1744 },
1745 );
1746self.diverge_from(block);
17471748assign.unit()
1749 }
17501751/// Creates an `Assert` terminator and return the success block.
1752 /// If the boolean condition operand is not the expected value,
1753 /// a runtime panic will be caused with the given message.
1754pub(crate) fn assert(
1755&mut self,
1756 block: BasicBlock,
1757 cond: Operand<'tcx>,
1758 expected: bool,
1759 msg: AssertMessage<'tcx>,
1760 span: Span,
1761 ) -> BasicBlock {
1762let source_info = self.source_info(span);
1763let success_block = self.cfg.start_new_block();
17641765self.cfg.terminate(
1766block,
1767source_info,
1768 TerminatorKind::Assert {
1769cond,
1770expected,
1771 msg: Box::new(msg),
1772 target: success_block,
1773 unwind: UnwindAction::Continue,
1774 },
1775 );
1776self.diverge_from(block);
17771778success_block1779 }
17801781/// Unschedules any drops in the top two scopes.
1782 ///
1783 /// This is only needed for pattern-matches combining guards and or-patterns: or-patterns lead
1784 /// to guards being lowered multiple times before lowering the arm body, so we unschedle drops
1785 /// for guards' temporaries and bindings between lowering each instance of an match arm's guard.
1786pub(crate) fn clear_match_arm_and_guard_scopes(&mut self, region_scope: region::Scope) {
1787let [.., arm_scope, guard_scope] = &mut *self.scopes.scopes else {
1788::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");
1789 };
17901791match (&arm_scope.region_scope, ®ion_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);
1792match (&guard_scope.region_scope.data, ®ion::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);
1793match (&guard_scope.region_scope.local_id, ®ion_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);
17941795arm_scope.drops.clear();
1796arm_scope.invalidate_cache();
1797guard_scope.drops.clear();
1798guard_scope.invalidate_cache();
1799 }
1800}
18011802/// Builds drops for `pop_scope` and `leave_top_scope`.
1803///
1804/// # Parameters
1805///
1806/// * `unwind_drops`, the drop tree data structure storing what needs to be cleaned up if unwind occurs
1807/// * `scope`, describes the drops that will occur on exiting the scope in regular execution
1808/// * `block`, the block to branch to once drops are complete (assuming no unwind occurs)
1809/// * `unwind_to`, describes the drops that would occur at this point in the code if a
1810/// panic occurred (a subset of the drops in `scope`, since we sometimes elide StorageDead and other
1811/// instructions on unwinding)
1812/// * `dropline_to`, describes the drops that would occur at this point in the code if a
1813/// coroutine drop occurred.
1814/// * `storage_dead_on_unwind`, if true, then we should emit `StorageDead` even when unwinding
1815/// * `arg_count`, number of MIR local variables corresponding to fn arguments (used to assert that we don't drop those)
1816fn build_scope_drops<'tcx, F>(
1817 cfg: &mut CFG<'tcx>,
1818 unwind_drops: &mut DropTree,
1819 coroutine_drops: &mut DropTree,
1820 scope: &Scope,
1821 block: BasicBlock,
1822 unwind_to: DropIdx,
1823 dropline_to: Option<DropIdx>,
1824 storage_dead_on_unwind: bool,
1825 arg_count: usize,
1826 is_async_drop: F,
1827) -> BlockAnd<()>
1828where
1829F: Fn(Local) -> bool,
1830{
1831{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_mir_build/src/builder/scope.rs:1831",
"rustc_mir_build::builder::scope", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_mir_build/src/builder/scope.rs"),
::tracing_core::__macro_support::Option::Some(1831u32),
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("build_scope_drops({0:?} -> {1:?}), dropline_to={2:?}",
block, scope, dropline_to) as &dyn Value))])
});
} else { ; }
};debug!("build_scope_drops({:?} -> {:?}), dropline_to={:?}", block, scope, dropline_to);
18321833// Build up the drops in evaluation order. The end result will
1834 // look like:
1835 //
1836 // [SDs, drops[n]] --..> [SDs, drop[1]] -> [SDs, drop[0]] -> [[SDs]]
1837 // | | |
1838 // : | |
1839 // V V
1840 // [drop[n]] -...-> [drop[1]] ------> [drop[0]] ------> [last_unwind_to]
1841 //
1842 // The horizontal arrows represent the execution path when the drops return
1843 // successfully. The downwards arrows represent the execution path when the
1844 // drops panic (panicking while unwinding will abort, so there's no need for
1845 // another set of arrows).
1846 //
1847 // For coroutines, we unwind from a drop on a local to its StorageDead
1848 // statement. For other functions we don't worry about StorageDead. The
1849 // drops for the unwind path should have already been generated by
1850 // `diverge_cleanup_gen`.
18511852 // `unwind_to` indicates what needs to be dropped should unwinding occur.
1853 // This is a subset of what needs to be dropped when exiting the scope.
1854 // As we unwind the scope, we will also move `unwind_to` backwards to match,
1855 // so that we can use it should a destructor panic.
1856let mut unwind_to = unwind_to;
18571858// The block that we should jump to after drops complete. We start by building the final drop (`drops[n]`
1859 // in the diagram above) and then build the drops (e.g., `drop[1]`, `drop[0]`) that come before it.
1860 // block begins as the successor of `drops[n]` and then becomes `drops[n]` so that `drops[n-1]`
1861 // will branch to `drops[n]`.
1862let mut block = block;
18631864// `dropline_to` indicates what needs to be dropped should coroutine drop occur.
1865let mut dropline_to = dropline_to;
18661867for drop_data in scope.drops.iter().rev() {
1868let source_info = drop_data.source_info;
1869let local = drop_data.local;
18701871match drop_data.kind {
1872 DropKind::Value => {
1873// `unwind_to` should drop the value that we're about to
1874 // schedule. If dropping this value panics, then we continue
1875 // with the *next* value on the unwind path.
1876 //
1877 // We adjust this BEFORE we create the drop (e.g., `drops[n]`)
1878 // because `drops[n]` should unwind to `drops[n-1]`.
1879if 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);
1880if 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);
1881 unwind_to = unwind_drops.drop_nodes[unwind_to].next;
18821883if let Some(idx) = dropline_to {
1884if 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);
1885if 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);
1886 dropline_to = Some(coroutine_drops.drop_nodes[idx].next);
1887 }
18881889// If the operand has been moved, and we are not on an unwind
1890 // path, then don't generate the drop. (We only take this into
1891 // account for non-unwind paths so as not to disturb the
1892 // caching mechanism.)
1893if scope.moved_locals.contains(&local) {
1894continue;
1895 }
18961897 unwind_drops.add_entry_point(block, unwind_to);
1898if let Some(to) = dropline_to
1899 && is_async_drop(local)
1900 {
1901 coroutine_drops.add_entry_point(block, to);
1902 }
19031904let next = cfg.start_new_block();
1905 cfg.terminate(
1906 block,
1907 source_info,
1908 TerminatorKind::Drop {
1909 place: local.into(),
1910 target: next,
1911 unwind: UnwindAction::Continue,
1912 replace: false,
1913 drop: None,
1914 async_fut: None,
1915 },
1916 );
1917 block = next;
1918 }
1919 DropKind::ForLint => {
1920// As in the `DropKind::Storage` case below:
1921 // normally lint-related drops are not emitted for unwind,
1922 // so we can just leave `unwind_to` unmodified, but in some
1923 // cases we emit things ALSO on the unwind path, so we need to adjust
1924 // `unwind_to` in that case.
1925if storage_dead_on_unwind {
1926if 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!(
1927 unwind_drops.drop_nodes[unwind_to].data.local,
1928 drop_data.local
1929 );
1930if 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);
1931 unwind_to = unwind_drops.drop_nodes[unwind_to].next;
1932 }
19331934// If the operand has been moved, and we are not on an unwind
1935 // path, then don't generate the drop. (We only take this into
1936 // account for non-unwind paths so as not to disturb the
1937 // caching mechanism.)
1938if scope.moved_locals.contains(&local) {
1939continue;
1940 }
19411942 cfg.push(
1943 block,
1944 Statement::new(
1945 source_info,
1946 StatementKind::BackwardIncompatibleDropHint {
1947 place: Box::new(local.into()),
1948 reason: BackwardIncompatibleDropReason::Edition2024,
1949 },
1950 ),
1951 );
1952 }
1953 DropKind::Storage => {
1954// Ordinarily, storage-dead nodes are not emitted on unwind, so we don't
1955 // need to adjust `unwind_to` on this path. However, in some specific cases
1956 // we *do* emit storage-dead nodes on the unwind path, and in that case now that
1957 // the storage-dead has completed, we need to adjust the `unwind_to` pointer
1958 // so that any future drops we emit will not register storage-dead.
1959if storage_dead_on_unwind {
1960if 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!(
1961 unwind_drops.drop_nodes[unwind_to].data.local,
1962 drop_data.local
1963 );
1964if 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);
1965 unwind_to = unwind_drops.drop_nodes[unwind_to].next;
1966 }
1967if let Some(idx) = dropline_to {
1968if 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);
1969if 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);
1970 dropline_to = Some(coroutine_drops.drop_nodes[idx].next);
1971 }
1972// Only temps and vars need their storage dead.
1973if !(local.index() > arg_count) {
::core::panicking::panic("assertion failed: local.index() > arg_count")
};assert!(local.index() > arg_count);
1974 cfg.push(block, Statement::new(source_info, StatementKind::StorageDead(local)));
1975 }
1976 }
1977 }
1978block.unit()
1979}
19801981impl<'a, 'tcx: 'a> Builder<'a, 'tcx> {
1982/// Build a drop tree for a breakable scope.
1983 ///
1984 /// If `continue_block` is `Some`, then the tree is for `continue` inside a
1985 /// loop. Otherwise this is for `break` or `return`.
1986fn build_exit_tree(
1987&mut self,
1988mut drops: DropTree,
1989 else_scope: region::Scope,
1990 span: Span,
1991 continue_block: Option<BasicBlock>,
1992 ) -> Option<BlockAnd<()>> {
1993let blocks = drops.build_mir::<ExitScopes>(&mut self.cfg, continue_block);
1994let is_coroutine = self.coroutine.is_some();
19951996// Link the exit drop tree to unwind drop tree.
1997if drops.drop_nodes.iter().any(|drop_node| drop_node.data.kind == DropKind::Value) {
1998let unwind_target = self.diverge_cleanup_target(else_scope, span);
1999let mut unwind_indices = IndexVec::from_elem_n(unwind_target, 1);
2000for (drop_idx, drop_node) in drops.drop_nodes.iter_enumerated().skip(1) {
2001match drop_node.data.kind {
2002 DropKind::Storage | DropKind::ForLint => {
2003if is_coroutine {
2004let unwind_drop = self
2005.scopes
2006 .unwind_drops
2007 .add_drop(drop_node.data, unwind_indices[drop_node.next]);
2008 unwind_indices.push(unwind_drop);
2009 } else {
2010 unwind_indices.push(unwind_indices[drop_node.next]);
2011 }
2012 }
2013 DropKind::Value => {
2014let unwind_drop = self
2015.scopes
2016 .unwind_drops
2017 .add_drop(drop_node.data, unwind_indices[drop_node.next]);
2018self.scopes.unwind_drops.add_entry_point(
2019 blocks[drop_idx].unwrap(),
2020 unwind_indices[drop_node.next],
2021 );
2022 unwind_indices.push(unwind_drop);
2023 }
2024 }
2025 }
2026 }
2027// Link the exit drop tree to dropline drop tree (coroutine drop path) for async drops
2028if is_coroutine2029 && drops.drop_nodes.iter().any(|DropNode { data, next: _ }| {
2030data.kind == DropKind::Value && self.is_async_drop(data.local)
2031 })
2032 {
2033let dropline_target = self.diverge_dropline_target(else_scope, span);
2034let mut dropline_indices = IndexVec::from_elem_n(dropline_target, 1);
2035for (drop_idx, drop_data) in drops.drop_nodes.iter_enumerated().skip(1) {
2036let coroutine_drop = self
2037.scopes
2038 .coroutine_drops
2039 .add_drop(drop_data.data, dropline_indices[drop_data.next]);
2040match drop_data.data.kind {
2041 DropKind::Storage | DropKind::ForLint => {}
2042 DropKind::Value => {
2043if self.is_async_drop(drop_data.data.local) {
2044self.scopes.coroutine_drops.add_entry_point(
2045 blocks[drop_idx].unwrap(),
2046 dropline_indices[drop_data.next],
2047 );
2048 }
2049 }
2050 }
2051 dropline_indices.push(coroutine_drop);
2052 }
2053 }
2054blocks[ROOT_NODE].map(BasicBlock::unit)
2055 }
20562057/// Build the unwind and coroutine drop trees.
2058pub(crate) fn build_drop_trees(&mut self) {
2059if self.coroutine.is_some() {
2060self.build_coroutine_drop_trees();
2061 } else {
2062Self::build_unwind_tree(
2063&mut self.cfg,
2064&mut self.scopes.unwind_drops,
2065self.fn_span,
2066&mut None,
2067 );
2068 }
2069 }
20702071fn build_coroutine_drop_trees(&mut self) {
2072// Build the drop tree for dropping the coroutine while it's suspended.
2073let drops = &mut self.scopes.coroutine_drops;
2074let cfg = &mut self.cfg;
2075let fn_span = self.fn_span;
2076let blocks = drops.build_mir::<CoroutineDrop>(cfg, None);
2077if let Some(root_block) = blocks[ROOT_NODE] {
2078cfg.terminate(
2079root_block,
2080SourceInfo::outermost(fn_span),
2081 TerminatorKind::CoroutineDrop,
2082 );
2083 }
20842085// Build the drop tree for unwinding in the normal control flow paths.
2086let resume_block = &mut None;
2087let unwind_drops = &mut self.scopes.unwind_drops;
2088Self::build_unwind_tree(cfg, unwind_drops, fn_span, resume_block);
20892090// Build the drop tree for unwinding when dropping a suspended
2091 // coroutine.
2092 //
2093 // This is a different tree to the standard unwind paths here to
2094 // prevent drop elaboration from creating drop flags that would have
2095 // to be captured by the coroutine. I'm not sure how important this
2096 // optimization is, but it is here.
2097for (drop_idx, drop_node) in drops.drop_nodes.iter_enumerated() {
2098if let DropKind::Value = drop_node.data.kind
2099 && let Some(bb) = blocks[drop_idx]
2100 {
2101if 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());
2102 drops.entry_points.push((drop_node.next, bb));
2103 }
2104 }
2105Self::build_unwind_tree(cfg, drops, fn_span, resume_block);
2106 }
21072108fn build_unwind_tree(
2109 cfg: &mut CFG<'tcx>,
2110 drops: &mut DropTree,
2111 fn_span: Span,
2112 resume_block: &mut Option<BasicBlock>,
2113 ) {
2114let blocks = drops.build_mir::<Unwind>(cfg, *resume_block);
2115if let (None, Some(resume)) = (*resume_block, blocks[ROOT_NODE]) {
2116cfg.terminate(resume, SourceInfo::outermost(fn_span), TerminatorKind::UnwindResume);
21172118*resume_block = blocks[ROOT_NODE];
2119 }
2120 }
2121}
21222123// DropTreeBuilder implementations.
21242125struct ExitScopes;
21262127impl<'tcx> DropTreeBuilder<'tcx> for ExitScopes {
2128fn make_block(cfg: &mut CFG<'tcx>) -> BasicBlock {
2129cfg.start_new_block()
2130 }
2131fn link_entry_point(cfg: &mut CFG<'tcx>, from: BasicBlock, to: BasicBlock) {
2132// There should be an existing terminator with real source info and a
2133 // dummy TerminatorKind. Replace it with a proper goto.
2134 // (The dummy is added by `break_scope` and `break_for_else`.)
2135let term = cfg.block_data_mut(from).terminator_mut();
2136if let TerminatorKind::UnwindResume = term.kind {
2137term.kind = TerminatorKind::Goto { target: to };
2138 } else {
2139::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);
2140 }
2141 }
2142}
21432144struct CoroutineDrop;
21452146impl<'tcx> DropTreeBuilder<'tcx> for CoroutineDrop {
2147fn make_block(cfg: &mut CFG<'tcx>) -> BasicBlock {
2148cfg.start_new_block()
2149 }
2150fn link_entry_point(cfg: &mut CFG<'tcx>, from: BasicBlock, to: BasicBlock) {
2151let term = cfg.block_data_mut(from).terminator_mut();
2152if let TerminatorKind::Yield { ref mut drop, .. } = term.kind {
2153*drop = Some(to);
2154 } else if let TerminatorKind::Drop { ref mut drop, .. } = term.kind {
2155*drop = Some(to);
2156 } else {
2157::rustc_middle::util::bug::span_bug_fmt(term.source_info.span,
format_args!("cannot enter coroutine drop tree from {0:?}", term.kind))span_bug!(
2158term.source_info.span,
2159"cannot enter coroutine drop tree from {:?}",
2160 term.kind
2161 )2162 }
2163 }
2164}
21652166struct Unwind;
21672168impl<'tcx> DropTreeBuilder<'tcx> for Unwind {
2169fn make_block(cfg: &mut CFG<'tcx>) -> BasicBlock {
2170cfg.start_new_cleanup_block()
2171 }
2172fn link_entry_point(cfg: &mut CFG<'tcx>, from: BasicBlock, to: BasicBlock) {
2173let term = &mut cfg.block_data_mut(from).terminator_mut();
2174match &mut term.kind {
2175 TerminatorKind::Drop { unwind, .. } => {
2176if let UnwindAction::Cleanup(unwind) = *unwind {
2177let source_info = term.source_info;
2178cfg.terminate(unwind, source_info, TerminatorKind::Goto { target: to });
2179 } else {
2180*unwind = UnwindAction::Cleanup(to);
2181 }
2182 }
2183 TerminatorKind::FalseUnwind { unwind, .. }
2184 | TerminatorKind::Call { unwind, .. }
2185 | TerminatorKind::Assert { unwind, .. }
2186 | TerminatorKind::InlineAsm { unwind, .. } => {
2187*unwind = UnwindAction::Cleanup(to);
2188 }
2189 TerminatorKind::Goto { .. }
2190 | TerminatorKind::SwitchInt { .. }
2191 | TerminatorKind::UnwindResume2192 | TerminatorKind::UnwindTerminate(_)
2193 | TerminatorKind::Return2194 | TerminatorKind::TailCall { .. }
2195 | TerminatorKind::Unreachable2196 | TerminatorKind::Yield { .. }
2197 | TerminatorKind::CoroutineDrop2198 | TerminatorKind::FalseEdge { .. } => {
2199::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)2200 }
2201 }
2202 }
2203}