Skip to main content

rustc_mir_transform/
impossible_clauses.rs

1//! Check if it's even possible to satisfy the 'where' clauses
2//! for this item.
3//!
4//! It's possible to `#!feature(trivial_bounds)]` to write
5//! a function with impossible to satisfy clauses, e.g.:
6//! `fn foo() where String: Copy {}`.
7//!
8//! We don't usually need to worry about this kind of case,
9//! since we would get a compilation error if the user tried
10//! to call it. However, since we optimize even without any
11//! calls to the function, we need to make sure that it even
12//! makes sense to try to evaluate the body.
13//!
14//! If there are unsatisfiable where clauses, then all bets are
15//! off, and we just give up.
16//!
17//! We manually filter the predicates, skipping anything that's not
18//! "global". We are in a potentially generic context
19//! (e.g. we are evaluating a function without instantiating generic
20//! parameters, so this filtering serves two purposes:
21//!
22//! 1. We skip evaluating any predicates that we would
23//!    never be able prove are unsatisfiable (e.g. `<T as Foo>`
24//! 2. We avoid trying to normalize predicates involving generic
25//!    parameters (e.g. `<T as Foo>::MyItem`). This can confuse
26//!    the normalization code (leading to cycle errors), since
27//!    it's usually never invoked in this way.
28
29use rustc_middle::mir::{Body, START_BLOCK, TerminatorKind};
30use rustc_middle::ty::{self, Ty, TyCtxt, TypeFlags, TypeVisitableExt, Unnormalized};
31use rustc_span::def_id::DefId;
32use rustc_trait_selection::traits;
33use tracing::trace;
34
35use crate::PassPolicy;
36use crate::pass_manager::MirPass;
37
38fn is_structurally_unsized<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> bool {
39    match ty.kind() {
40        ty::Str | ty::Slice(_) | ty::Dynamic(_, _) | ty::Foreign(_) => true,
41        ty::Tuple(tys) => tys.last().is_some_and(|ty| is_structurally_unsized(tcx, *ty)),
42        ty::Adt(def, args) => {
43            def.sizedness_constraint(tcx, ty::SizedTraitKind::Sized).is_some_and(|ty| {
44                is_structurally_unsized(tcx, ty.instantiate(tcx, args).skip_norm_wip())
45            })
46        }
47        _ => false,
48    }
49}
50
51fn has_structurally_impossible_sized_clause<'tcx>(
52    tcx: TyCtxt<'tcx>,
53    sized_trait: DefId,
54    predicate: ty::Clause<'tcx>,
55) -> bool {
56    let Some(trait_predicate) = predicate.as_trait_clause() else {
57        return false;
58    };
59    let trait_predicate = trait_predicate.skip_binder();
60
61    trait_predicate.polarity == ty::PredicatePolarity::Positive
62        && trait_predicate.def_id() == sized_trait
63        && is_structurally_unsized(tcx, trait_predicate.self_ty())
64}
65
66pub(crate) struct ImpossibleClauses;
67
68pub(crate) fn has_impossible_clauses<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId) -> bool {
69    let clauses = tcx.clauses_of(def_id).instantiate_identity(tcx);
70    tracing::trace!(?clauses);
71
72    // Some `Sized` clauses that mention local generics are still impossible
73    // for every instantiation, e.g. `dyn Trait<T>: Sized`.
74    if let Some(sized_trait) = tcx.lang_items().sized_trait() {
75        if clauses
76            .clauses
77            .iter()
78            .copied()
79            .map(Unnormalized::skip_norm_wip)
80            .any(|clause| has_structurally_impossible_sized_clause(tcx, sized_trait, clause))
81        {
82            return true;
83        }
84    }
85
86    let clauses = clauses.clauses.into_iter().map(Unnormalized::skip_norm_wip).filter(|c| {
87        !c.has_type_flags(
88            // Only consider global clauses to simplify.
89            TypeFlags::HAS_FREE_LOCAL_NAMES
90                // Clauses that refer to alias constants as they cause cycles.
91                | TypeFlags::HAS_CONST_ALIAS,
92        )
93    });
94    let clauses: Vec<_> = traits::elaborate(tcx, clauses).collect();
95    tracing::trace!(?clauses);
96    clauses.references_error() || traits::impossible_clauses(tcx, clauses)
97}
98
99impl<'tcx> MirPass<'tcx> for ImpossibleClauses {
100    #[tracing::instrument(level = "trace", skip(self, tcx, body))]
101    fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
102        tracing::trace!(def_id = ?body.source.def_id());
103        let impossible =
104            body.tainted_by_errors.is_some() || has_impossible_clauses(tcx, body.source.def_id());
105        if impossible {
106            trace!("found unsatisfiable clauses");
107            // Clear the body to only contain a single `unreachable` statement.
108            let bbs = body.basic_blocks.as_mut();
109            bbs.raw.truncate(1);
110            bbs[START_BLOCK].statements.clear();
111            bbs[START_BLOCK].terminator_mut().kind = TerminatorKind::Unreachable;
112            body.var_debug_info.clear();
113            body.local_decls.raw.truncate(body.arg_count + 1);
114        }
115    }
116
117    fn policy(&self, _sess: &rustc_session::Session) -> PassPolicy {
118        // This can only replace code proven unreachable with immediate UB, so it cannot remove UB.
119        PassPolicy::optional_non_optimization(true)
120    }
121}