frontend 0.4.0

rustc's frontend with no LLVM and no std: parsing through MIR, as a library
//! This pass replaces a drop of a type that does not need dropping, with a goto.
//!
//! When the MIR is built, we check `needs_drop` before emitting a `Drop` for a place. This pass is
//! useful because (unlike MIR building) it runs after type checking, so it can make use of
//! `TypingMode::PostAnalysis` to provide more precise type information, especially about opaque
//! types.

// `#![no_std]`: these arrive with the standard prelude and name no path, so a `std::`
// search cannot see them - and a `#[derive]` can use them without the name appearing
// in this file at all, which is why they are not trimmed by inspection.
use alloc::borrow::ToOwned;
use alloc::boxed::Box;
use alloc::format;
use alloc::string::{String, ToString};
use alloc::vec;
use alloc::vec::Vec;

use crate::rustc_middle::mir::*;
use crate::rustc_middle::ty::TyCtxt;
use tracing::{debug, trace};

use super::simplify::simplify_cfg;
use crate::rustc_mir_transform::PassPolicy;

pub(super) struct RemoveUnneededDrops;

impl<'tcx> crate::rustc_mir_transform::MirPass<'tcx> for RemoveUnneededDrops {
    fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
        trace!("Running RemoveUnneededDrops on {:?}", body.source);

        let typing_env = body.typing_env(tcx);
        let mut should_simplify = false;
        for block in body.basic_blocks.as_mut() {
            let terminator = block.terminator_mut();
            let TerminatorKind::Drop { place, target, .. } = terminator.kind else { continue };
            let ty = place.ty(&body.local_decls, tcx).ty;

            if ty.needs_drop(tcx, typing_env) {
                continue;
            }
            debug!("SUCCESS: replacing `drop` with goto({:?})", target);
            terminator.kind = TerminatorKind::Goto { target };
            should_simplify = true;
        }

        // if we applied optimizations, we potentially have some cfg to cleanup to
        // make it easier for further passes
        if should_simplify {
            simplify_cfg(tcx, body);
        }
    }

    fn policy(&self, _sess: &crate::rustc_session::Session) -> PassPolicy {
        PassPolicy::optional_non_optimization(true)
    }
}