1 //! Structural const qualification.
2 //!
3 //! See the `Qualif` trait for more info.
4 
5 use rustc_errors::ErrorReported;
6 use rustc_hir as hir;
7 use rustc_infer::infer::TyCtxtInferExt;
8 use rustc_middle::mir::*;
9 use rustc_middle::ty::{self, subst::SubstsRef, AdtDef, Ty};
10 use rustc_span::DUMMY_SP;
11 use rustc_trait_selection::traits::{
12     self, ImplSource, Obligation, ObligationCause, SelectionContext,
13 };
14 
15 use super::ConstCx;
16 
in_any_value_of_ty( cx: &ConstCx<'_, 'tcx>, ty: Ty<'tcx>, error_occured: Option<ErrorReported>, ) -> ConstQualifs17 pub fn in_any_value_of_ty(
18     cx: &ConstCx<'_, 'tcx>,
19     ty: Ty<'tcx>,
20     error_occured: Option<ErrorReported>,
21 ) -> ConstQualifs {
22     ConstQualifs {
23         has_mut_interior: HasMutInterior::in_any_value_of_ty(cx, ty),
24         needs_drop: NeedsDrop::in_any_value_of_ty(cx, ty),
25         needs_non_const_drop: NeedsNonConstDrop::in_any_value_of_ty(cx, ty),
26         custom_eq: CustomEq::in_any_value_of_ty(cx, ty),
27         error_occured,
28     }
29 }
30 
31 /// A "qualif"(-ication) is a way to look for something "bad" in the MIR that would disqualify some
32 /// code for promotion or prevent it from evaluating at compile time.
33 ///
34 /// Normally, we would determine what qualifications apply to each type and error when an illegal
35 /// operation is performed on such a type. However, this was found to be too imprecise, especially
36 /// in the presence of `enum`s. If only a single variant of an enum has a certain qualification, we
37 /// needn't reject code unless it actually constructs and operates on the qualified variant.
38 ///
39 /// To accomplish this, const-checking and promotion use a value-based analysis (as opposed to a
40 /// type-based one). Qualifications propagate structurally across variables: If a local (or a
41 /// projection of a local) is assigned a qualified value, that local itself becomes qualified.
42 pub trait Qualif {
43     /// The name of the file used to debug the dataflow analysis that computes this qualif.
44     const ANALYSIS_NAME: &'static str;
45 
46     /// Whether this `Qualif` is cleared when a local is moved from.
47     const IS_CLEARED_ON_MOVE: bool = false;
48 
49     /// Whether this `Qualif` might be evaluated after the promotion and can encounter a promoted.
50     const ALLOW_PROMOTED: bool = false;
51 
52     /// Extracts the field of `ConstQualifs` that corresponds to this `Qualif`.
in_qualifs(qualifs: &ConstQualifs) -> bool53     fn in_qualifs(qualifs: &ConstQualifs) -> bool;
54 
55     /// Returns `true` if *any* value of the given type could possibly have this `Qualif`.
56     ///
57     /// This function determines `Qualif`s when we cannot do a value-based analysis. Since qualif
58     /// propagation is context-insenstive, this includes function arguments and values returned
59     /// from a call to another function.
60     ///
61     /// It also determines the `Qualif`s for primitive types.
in_any_value_of_ty(cx: &ConstCx<'_, 'tcx>, ty: Ty<'tcx>) -> bool62     fn in_any_value_of_ty(cx: &ConstCx<'_, 'tcx>, ty: Ty<'tcx>) -> bool;
63 
64     /// Returns `true` if this `Qualif` is inherent to the given struct or enum.
65     ///
66     /// By default, `Qualif`s propagate into ADTs in a structural way: An ADT only becomes
67     /// qualified if part of it is assigned a value with that `Qualif`. However, some ADTs *always*
68     /// have a certain `Qualif`, regardless of whether their fields have it. For example, a type
69     /// with a custom `Drop` impl is inherently `NeedsDrop`.
70     ///
71     /// Returning `true` for `in_adt_inherently` but `false` for `in_any_value_of_ty` is unsound.
in_adt_inherently( cx: &ConstCx<'_, 'tcx>, adt: &'tcx AdtDef, substs: SubstsRef<'tcx>, ) -> bool72     fn in_adt_inherently(
73         cx: &ConstCx<'_, 'tcx>,
74         adt: &'tcx AdtDef,
75         substs: SubstsRef<'tcx>,
76     ) -> bool;
77 }
78 
79 /// Constant containing interior mutability (`UnsafeCell<T>`).
80 /// This must be ruled out to make sure that evaluating the constant at compile-time
81 /// and at *any point* during the run-time would produce the same result. In particular,
82 /// promotion of temporaries must not change program behavior; if the promoted could be
83 /// written to, that would be a problem.
84 pub struct HasMutInterior;
85 
86 impl Qualif for HasMutInterior {
87     const ANALYSIS_NAME: &'static str = "flow_has_mut_interior";
88 
in_qualifs(qualifs: &ConstQualifs) -> bool89     fn in_qualifs(qualifs: &ConstQualifs) -> bool {
90         qualifs.has_mut_interior
91     }
92 
in_any_value_of_ty(cx: &ConstCx<'_, 'tcx>, ty: Ty<'tcx>) -> bool93     fn in_any_value_of_ty(cx: &ConstCx<'_, 'tcx>, ty: Ty<'tcx>) -> bool {
94         !ty.is_freeze(cx.tcx.at(DUMMY_SP), cx.param_env)
95     }
96 
in_adt_inherently(cx: &ConstCx<'_, 'tcx>, adt: &'tcx AdtDef, _: SubstsRef<'tcx>) -> bool97     fn in_adt_inherently(cx: &ConstCx<'_, 'tcx>, adt: &'tcx AdtDef, _: SubstsRef<'tcx>) -> bool {
98         // Exactly one type, `UnsafeCell`, has the `HasMutInterior` qualif inherently.
99         // It arises structurally for all other types.
100         Some(adt.did) == cx.tcx.lang_items().unsafe_cell_type()
101     }
102 }
103 
104 /// Constant containing an ADT that implements `Drop`.
105 /// This must be ruled out because implicit promotion would remove side-effects
106 /// that occur as part of dropping that value. N.B., the implicit promotion has
107 /// to reject const Drop implementations because even if side-effects are ruled
108 /// out through other means, the execution of the drop could diverge.
109 pub struct NeedsDrop;
110 
111 impl Qualif for NeedsDrop {
112     const ANALYSIS_NAME: &'static str = "flow_needs_drop";
113     const IS_CLEARED_ON_MOVE: bool = true;
114 
in_qualifs(qualifs: &ConstQualifs) -> bool115     fn in_qualifs(qualifs: &ConstQualifs) -> bool {
116         qualifs.needs_drop
117     }
118 
in_any_value_of_ty(cx: &ConstCx<'_, 'tcx>, ty: Ty<'tcx>) -> bool119     fn in_any_value_of_ty(cx: &ConstCx<'_, 'tcx>, ty: Ty<'tcx>) -> bool {
120         ty.needs_drop(cx.tcx, cx.param_env)
121     }
122 
in_adt_inherently(cx: &ConstCx<'_, 'tcx>, adt: &'tcx AdtDef, _: SubstsRef<'tcx>) -> bool123     fn in_adt_inherently(cx: &ConstCx<'_, 'tcx>, adt: &'tcx AdtDef, _: SubstsRef<'tcx>) -> bool {
124         adt.has_dtor(cx.tcx)
125     }
126 }
127 
128 /// Constant containing an ADT that implements non-const `Drop`.
129 /// This must be ruled out because we cannot run `Drop` during compile-time.
130 pub struct NeedsNonConstDrop;
131 
132 impl Qualif for NeedsNonConstDrop {
133     const ANALYSIS_NAME: &'static str = "flow_needs_nonconst_drop";
134     const IS_CLEARED_ON_MOVE: bool = true;
135     const ALLOW_PROMOTED: bool = true;
136 
in_qualifs(qualifs: &ConstQualifs) -> bool137     fn in_qualifs(qualifs: &ConstQualifs) -> bool {
138         qualifs.needs_non_const_drop
139     }
140 
in_any_value_of_ty(cx: &ConstCx<'_, 'tcx>, mut ty: Ty<'tcx>) -> bool141     fn in_any_value_of_ty(cx: &ConstCx<'_, 'tcx>, mut ty: Ty<'tcx>) -> bool {
142         // Avoid selecting for simple cases.
143         match ty::util::needs_drop_components(ty, &cx.tcx.data_layout).as_deref() {
144             Ok([]) => return false,
145             Err(ty::util::AlwaysRequiresDrop) => return true,
146             // If we've got a single component, select with that
147             // to increase the chance that we hit the selection cache.
148             Ok([t]) => ty = t,
149             Ok([..]) => {}
150         }
151 
152         let Some(drop_trait) = cx.tcx.lang_items().drop_trait() else {
153             // there is no way to define a type that needs non-const drop
154             // without having the lang item present.
155             return false;
156         };
157         let trait_ref =
158             ty::TraitRef { def_id: drop_trait, substs: cx.tcx.mk_substs_trait(ty, &[]) };
159         let obligation = Obligation::new(
160             ObligationCause::dummy(),
161             cx.param_env,
162             ty::Binder::dummy(ty::TraitPredicate {
163                 trait_ref,
164                 constness: ty::BoundConstness::ConstIfConst,
165                 polarity: ty::ImplPolarity::Positive,
166             }),
167         );
168 
169         let implsrc = cx.tcx.infer_ctxt().enter(|infcx| {
170             let mut selcx = SelectionContext::with_constness(&infcx, hir::Constness::Const);
171             selcx.select(&obligation)
172         });
173         !matches!(
174             implsrc,
175             Ok(Some(
176                 ImplSource::ConstDrop(_) | ImplSource::Param(_, ty::BoundConstness::ConstIfConst)
177             ))
178         )
179     }
180 
in_adt_inherently(cx: &ConstCx<'_, 'tcx>, adt: &'tcx AdtDef, _: SubstsRef<'tcx>) -> bool181     fn in_adt_inherently(cx: &ConstCx<'_, 'tcx>, adt: &'tcx AdtDef, _: SubstsRef<'tcx>) -> bool {
182         adt.has_non_const_dtor(cx.tcx)
183     }
184 }
185 
186 /// A constant that cannot be used as part of a pattern in a `match` expression.
187 pub struct CustomEq;
188 
189 impl Qualif for CustomEq {
190     const ANALYSIS_NAME: &'static str = "flow_custom_eq";
191 
in_qualifs(qualifs: &ConstQualifs) -> bool192     fn in_qualifs(qualifs: &ConstQualifs) -> bool {
193         qualifs.custom_eq
194     }
195 
in_any_value_of_ty(cx: &ConstCx<'_, 'tcx>, ty: Ty<'tcx>) -> bool196     fn in_any_value_of_ty(cx: &ConstCx<'_, 'tcx>, ty: Ty<'tcx>) -> bool {
197         // If *any* component of a composite data type does not implement `Structural{Partial,}Eq`,
198         // we know that at least some values of that type are not structural-match. I say "some"
199         // because that component may be part of an enum variant (e.g.,
200         // `Option::<NonStructuralMatchTy>::Some`), in which case some values of this type may be
201         // structural-match (`Option::None`).
202         let id = cx.tcx.hir().local_def_id_to_hir_id(cx.def_id());
203         traits::search_for_structural_match_violation(id, cx.body.span, cx.tcx, ty).is_some()
204     }
205 
in_adt_inherently( cx: &ConstCx<'_, 'tcx>, adt: &'tcx AdtDef, substs: SubstsRef<'tcx>, ) -> bool206     fn in_adt_inherently(
207         cx: &ConstCx<'_, 'tcx>,
208         adt: &'tcx AdtDef,
209         substs: SubstsRef<'tcx>,
210     ) -> bool {
211         let ty = cx.tcx.mk_ty(ty::Adt(adt, substs));
212         !ty.is_structural_eq_shallow(cx.tcx)
213     }
214 }
215 
216 // FIXME: Use `mir::visit::Visitor` for the `in_*` functions if/when it supports early return.
217 
218 /// Returns `true` if this `Rvalue` contains qualif `Q`.
in_rvalue<Q, F>(cx: &ConstCx<'_, 'tcx>, in_local: &mut F, rvalue: &Rvalue<'tcx>) -> bool where Q: Qualif, F: FnMut(Local) -> bool,219 pub fn in_rvalue<Q, F>(cx: &ConstCx<'_, 'tcx>, in_local: &mut F, rvalue: &Rvalue<'tcx>) -> bool
220 where
221     Q: Qualif,
222     F: FnMut(Local) -> bool,
223 {
224     match rvalue {
225         Rvalue::ThreadLocalRef(_) | Rvalue::NullaryOp(..) => {
226             Q::in_any_value_of_ty(cx, rvalue.ty(cx.body, cx.tcx))
227         }
228 
229         Rvalue::Discriminant(place) | Rvalue::Len(place) => {
230             in_place::<Q, _>(cx, in_local, place.as_ref())
231         }
232 
233         Rvalue::Use(operand)
234         | Rvalue::Repeat(operand, _)
235         | Rvalue::UnaryOp(_, operand)
236         | Rvalue::Cast(_, operand, _)
237         | Rvalue::ShallowInitBox(operand, _) => in_operand::<Q, _>(cx, in_local, operand),
238 
239         Rvalue::BinaryOp(_, box (lhs, rhs)) | Rvalue::CheckedBinaryOp(_, box (lhs, rhs)) => {
240             in_operand::<Q, _>(cx, in_local, lhs) || in_operand::<Q, _>(cx, in_local, rhs)
241         }
242 
243         Rvalue::Ref(_, _, place) | Rvalue::AddressOf(_, place) => {
244             // Special-case reborrows to be more like a copy of the reference.
245             if let Some((place_base, ProjectionElem::Deref)) = place.as_ref().last_projection() {
246                 let base_ty = place_base.ty(cx.body, cx.tcx).ty;
247                 if let ty::Ref(..) = base_ty.kind() {
248                     return in_place::<Q, _>(cx, in_local, place_base);
249                 }
250             }
251 
252             in_place::<Q, _>(cx, in_local, place.as_ref())
253         }
254 
255         Rvalue::Aggregate(kind, operands) => {
256             // Return early if we know that the struct or enum being constructed is always
257             // qualified.
258             if let AggregateKind::Adt(def, _, substs, ..) = **kind {
259                 if Q::in_adt_inherently(cx, def, substs) {
260                     return true;
261                 }
262                 if def.is_union() && Q::in_any_value_of_ty(cx, rvalue.ty(cx.body, cx.tcx)) {
263                     return true;
264                 }
265             }
266 
267             // Otherwise, proceed structurally...
268             operands.iter().any(|o| in_operand::<Q, _>(cx, in_local, o))
269         }
270     }
271 }
272 
273 /// Returns `true` if this `Place` contains qualif `Q`.
in_place<Q, F>(cx: &ConstCx<'_, 'tcx>, in_local: &mut F, place: PlaceRef<'tcx>) -> bool where Q: Qualif, F: FnMut(Local) -> bool,274 pub fn in_place<Q, F>(cx: &ConstCx<'_, 'tcx>, in_local: &mut F, place: PlaceRef<'tcx>) -> bool
275 where
276     Q: Qualif,
277     F: FnMut(Local) -> bool,
278 {
279     let mut place = place;
280     while let Some((place_base, elem)) = place.last_projection() {
281         match elem {
282             ProjectionElem::Index(index) if in_local(index) => return true,
283 
284             ProjectionElem::Deref
285             | ProjectionElem::Field(_, _)
286             | ProjectionElem::ConstantIndex { .. }
287             | ProjectionElem::Subslice { .. }
288             | ProjectionElem::Downcast(_, _)
289             | ProjectionElem::Index(_) => {}
290         }
291 
292         let base_ty = place_base.ty(cx.body, cx.tcx);
293         let proj_ty = base_ty.projection_ty(cx.tcx, elem).ty;
294         if !Q::in_any_value_of_ty(cx, proj_ty) {
295             return false;
296         }
297 
298         place = place_base;
299     }
300 
301     assert!(place.projection.is_empty());
302     in_local(place.local)
303 }
304 
305 /// Returns `true` if this `Operand` contains qualif `Q`.
in_operand<Q, F>(cx: &ConstCx<'_, 'tcx>, in_local: &mut F, operand: &Operand<'tcx>) -> bool where Q: Qualif, F: FnMut(Local) -> bool,306 pub fn in_operand<Q, F>(cx: &ConstCx<'_, 'tcx>, in_local: &mut F, operand: &Operand<'tcx>) -> bool
307 where
308     Q: Qualif,
309     F: FnMut(Local) -> bool,
310 {
311     let constant = match operand {
312         Operand::Copy(place) | Operand::Move(place) => {
313             return in_place::<Q, _>(cx, in_local, place.as_ref());
314         }
315 
316         Operand::Constant(c) => c,
317     };
318 
319     // Check the qualifs of the value of `const` items.
320     if let Some(ct) = constant.literal.const_for_ty() {
321         if let ty::ConstKind::Unevaluated(ty::Unevaluated { def, substs_: _, promoted }) = ct.val {
322             // Use qualifs of the type for the promoted. Promoteds in MIR body should be possible
323             // only for `NeedsNonConstDrop` with precise drop checking. This is the only const
324             // check performed after the promotion. Verify that with an assertion.
325             assert!(promoted.is_none() || Q::ALLOW_PROMOTED);
326             // Don't peek inside trait associated constants.
327             if promoted.is_none() && cx.tcx.trait_of_item(def.did).is_none() {
328                 let qualifs = if let Some((did, param_did)) = def.as_const_arg() {
329                     cx.tcx.at(constant.span).mir_const_qualif_const_arg((did, param_did))
330                 } else {
331                     cx.tcx.at(constant.span).mir_const_qualif(def.did)
332                 };
333 
334                 if !Q::in_qualifs(&qualifs) {
335                     return false;
336                 }
337 
338                 // Just in case the type is more specific than
339                 // the definition, e.g., impl associated const
340                 // with type parameters, take it into account.
341             }
342         }
343     }
344     // Otherwise use the qualifs of the type.
345     Q::in_any_value_of_ty(cx, constant.literal.ty())
346 }
347