rustc_const_eval/check_consts/qualifs.rs
1//! Structural const qualification.
2//!
3//! See the `Qualif` trait for more info.
4
5// FIXME(const_trait_impl): This API should be really reworked. It's dangerously general for
6// having basically only two use-cases that act in different ways.
7
8use rustc_errors::ErrorGuaranteed;
9use rustc_hir::attrs::AttributeKind;
10use rustc_hir::def::DefKind;
11use rustc_hir::{LangItem, find_attr};
12use rustc_infer::infer::TyCtxtInferExt;
13use rustc_middle::mir::*;
14use rustc_middle::ty::{self, AdtDef, Ty};
15use rustc_middle::{bug, mir};
16use rustc_trait_selection::traits::{Obligation, ObligationCause, ObligationCtxt};
17use tracing::instrument;
18
19use super::ConstCx;
20
21pub fn in_any_value_of_ty<'tcx>(
22 cx: &ConstCx<'_, 'tcx>,
23 ty: Ty<'tcx>,
24 tainted_by_errors: Option<ErrorGuaranteed>,
25) -> ConstQualifs {
26 ConstQualifs {
27 has_mut_interior: HasMutInterior::in_any_value_of_ty(cx, ty),
28 needs_drop: NeedsDrop::in_any_value_of_ty(cx, ty),
29 needs_non_const_drop: NeedsNonConstDrop::in_any_value_of_ty(cx, ty),
30 tainted_by_errors,
31 }
32}
33
34/// A "qualif"(-ication) is a way to look for something "bad" in the MIR that would disqualify some
35/// code for promotion or prevent it from evaluating at compile time.
36///
37/// Normally, we would determine what qualifications apply to each type and error when an illegal
38/// operation is performed on such a type. However, this was found to be too imprecise, especially
39/// in the presence of `enum`s. If only a single variant of an enum has a certain qualification, we
40/// needn't reject code unless it actually constructs and operates on the qualified variant.
41///
42/// To accomplish this, const-checking and promotion use a value-based analysis (as opposed to a
43/// type-based one). Qualifications propagate structurally across variables: If a local (or a
44/// projection of a local) is assigned a qualified value, that local itself becomes qualified.
45pub trait Qualif {
46 /// The name of the file used to debug the dataflow analysis that computes this qualif.
47 const ANALYSIS_NAME: &'static str;
48
49 /// Whether this `Qualif` is cleared when a local is moved from.
50 const IS_CLEARED_ON_MOVE: bool = false;
51
52 /// Whether this `Qualif` might be evaluated after the promotion and can encounter a promoted.
53 const ALLOW_PROMOTED: bool = false;
54
55 /// Extracts the field of `ConstQualifs` that corresponds to this `Qualif`.
56 fn in_qualifs(qualifs: &ConstQualifs) -> bool;
57
58 /// Returns `true` if *any* value of the given type could possibly have this `Qualif`.
59 ///
60 /// This function determines `Qualif`s when we cannot do a value-based analysis. Since qualif
61 /// propagation is context-insensitive, this includes function arguments and values returned
62 /// from a call to another function.
63 ///
64 /// It also determines the `Qualif`s for primitive types.
65 fn in_any_value_of_ty<'tcx>(cx: &ConstCx<'_, 'tcx>, ty: Ty<'tcx>) -> bool;
66
67 /// Returns `true` if the `Qualif` is structural in an ADT's fields, i.e. if we may
68 /// recurse into an operand *value* to determine whether it has this `Qualif`.
69 ///
70 /// If this returns false, `in_any_value_of_ty` will be invoked to determine the
71 /// final qualif for this ADT.
72 fn is_structural_in_adt_value<'tcx>(cx: &ConstCx<'_, 'tcx>, adt: AdtDef<'tcx>) -> bool;
73}
74
75/// Constant containing interior mutability (`UnsafeCell<T>`).
76/// This must be ruled out to make sure that evaluating the constant at compile-time
77/// and at *any point* during the run-time would produce the same result. In particular,
78/// promotion of temporaries must not change program behavior; if the promoted could be
79/// written to, that would be a problem.
80pub struct HasMutInterior;
81
82impl Qualif for HasMutInterior {
83 const ANALYSIS_NAME: &'static str = "flow_has_mut_interior";
84
85 fn in_qualifs(qualifs: &ConstQualifs) -> bool {
86 qualifs.has_mut_interior
87 }
88
89 fn in_any_value_of_ty<'tcx>(cx: &ConstCx<'_, 'tcx>, ty: Ty<'tcx>) -> bool {
90 // Avoid selecting for simple cases, such as builtin types.
91 if ty.is_trivially_freeze() {
92 return false;
93 }
94
95 // Avoid selecting for `UnsafeCell` either.
96 if ty.ty_adt_def().is_some_and(|adt| adt.is_unsafe_cell()) {
97 return true;
98 }
99
100 // We do not use `ty.is_freeze` here, because that requires revealing opaque types, which
101 // requires borrowck, which in turn will invoke mir_const_qualifs again, causing a cycle error.
102 // Instead we invoke an obligation context manually, and provide the opaque type inference settings
103 // that allow the trait solver to just error out instead of cycling.
104 let freeze_def_id = cx.tcx.require_lang_item(LangItem::Freeze, cx.body.span);
105 // FIXME(#132279): Once we've got a typing mode which reveals opaque types using the HIR
106 // typeck results without causing query cycles, we should use this here instead of defining
107 // opaque types.
108 let typing_env = ty::TypingEnv {
109 typing_mode: ty::TypingMode::analysis_in_body(
110 cx.tcx,
111 cx.body.source.def_id().expect_local(),
112 ),
113 param_env: cx.typing_env.param_env,
114 };
115 let (infcx, param_env) = cx.tcx.infer_ctxt().build_with_typing_env(typing_env);
116 let ocx = ObligationCtxt::new(&infcx);
117 let obligation = Obligation::new(
118 cx.tcx,
119 ObligationCause::dummy_with_span(cx.body.span),
120 param_env,
121 ty::TraitRef::new(cx.tcx, freeze_def_id, [ty::GenericArg::from(ty)]),
122 );
123 ocx.register_obligation(obligation);
124 let errors = ocx.evaluate_obligations_error_on_ambiguity();
125 !errors.is_empty()
126 }
127
128 fn is_structural_in_adt_value<'tcx>(_cx: &ConstCx<'_, 'tcx>, adt: AdtDef<'tcx>) -> bool {
129 // Exactly one type, `UnsafeCell`, has the `HasMutInterior` qualif inherently.
130 // It arises structurally for all other types.
131 !adt.is_unsafe_cell()
132 }
133}
134
135/// Constant containing an ADT that implements `Drop`.
136/// This must be ruled out because implicit promotion would remove side-effects
137/// that occur as part of dropping that value. N.B., the implicit promotion has
138/// to reject const Drop implementations because even if side-effects are ruled
139/// out through other means, the execution of the drop could diverge.
140pub struct NeedsDrop;
141
142impl Qualif for NeedsDrop {
143 const ANALYSIS_NAME: &'static str = "flow_needs_drop";
144 const IS_CLEARED_ON_MOVE: bool = true;
145 const ALLOW_PROMOTED: bool = true;
146
147 fn in_qualifs(qualifs: &ConstQualifs) -> bool {
148 qualifs.needs_drop
149 }
150
151 fn in_any_value_of_ty<'tcx>(cx: &ConstCx<'_, 'tcx>, ty: Ty<'tcx>) -> bool {
152 ty.needs_drop(cx.tcx, cx.typing_env)
153 }
154
155 fn is_structural_in_adt_value<'tcx>(cx: &ConstCx<'_, 'tcx>, adt: AdtDef<'tcx>) -> bool {
156 !adt.has_dtor(cx.tcx)
157 }
158}
159
160/// Constant containing an ADT that implements non-const `Drop`.
161/// This must be ruled out because we cannot run `Drop` during compile-time.
162pub struct NeedsNonConstDrop;
163
164impl Qualif for NeedsNonConstDrop {
165 const ANALYSIS_NAME: &'static str = "flow_needs_nonconst_drop";
166 const IS_CLEARED_ON_MOVE: bool = true;
167 const ALLOW_PROMOTED: bool = true;
168
169 fn in_qualifs(qualifs: &ConstQualifs) -> bool {
170 qualifs.needs_non_const_drop
171 }
172
173 #[instrument(level = "trace", skip(cx), ret)]
174 fn in_any_value_of_ty<'tcx>(cx: &ConstCx<'_, 'tcx>, ty: Ty<'tcx>) -> bool {
175 // If this doesn't need drop at all, then don't select `[const] Destruct`.
176 if !ty.needs_drop(cx.tcx, cx.typing_env) {
177 return false;
178 }
179
180 // We check that the type is `[const] Destruct` since that will verify that
181 // the type is both `[const] Drop` (if a drop impl exists for the adt), *and*
182 // that the components of this type are also `[const] Destruct`. This
183 // amounts to verifying that there are no values in this ADT that may have
184 // a non-const drop.
185 let destruct_def_id = cx.tcx.require_lang_item(LangItem::Destruct, cx.body.span);
186 let (infcx, param_env) = cx.tcx.infer_ctxt().build_with_typing_env(cx.typing_env);
187 let ocx = ObligationCtxt::new(&infcx);
188 ocx.register_obligation(Obligation::new(
189 cx.tcx,
190 ObligationCause::misc(cx.body.span, cx.def_id()),
191 param_env,
192 ty::Binder::dummy(ty::TraitRef::new(cx.tcx, destruct_def_id, [ty]))
193 .to_host_effect_clause(
194 cx.tcx,
195 match cx.const_kind() {
196 rustc_hir::ConstContext::ConstFn => ty::BoundConstness::Maybe,
197 rustc_hir::ConstContext::Static(_)
198 | rustc_hir::ConstContext::Const { .. } => ty::BoundConstness::Const,
199 },
200 ),
201 ));
202 !ocx.evaluate_obligations_error_on_ambiguity().is_empty()
203 }
204
205 fn is_structural_in_adt_value<'tcx>(cx: &ConstCx<'_, 'tcx>, adt: AdtDef<'tcx>) -> bool {
206 // As soon as an ADT has a destructor, then the drop becomes non-structural
207 // in its value since:
208 // 1. The destructor may have `[const]` bounds which are not present on the type.
209 // Someone needs to check that those are satisfied.
210 // While this could be instead satisfied by checking that the `[const] Drop`
211 // impl holds (i.e. replicating part of the `in_any_value_of_ty` logic above),
212 // even in this case, we have another problem, which is,
213 // 2. The destructor may *modify* the operand being dropped, so even if we
214 // did recurse on the components of the operand, we may not be even dropping
215 // the same values that were present before the custom destructor was invoked.
216 !adt.has_dtor(cx.tcx)
217 }
218}
219
220// FIXME: Use `mir::visit::Visitor` for the `in_*` functions if/when it supports early return.
221
222/// Returns `true` if this `Rvalue` contains qualif `Q`.
223pub fn in_rvalue<'tcx, Q, F>(
224 cx: &ConstCx<'_, 'tcx>,
225 in_local: &mut F,
226 rvalue: &Rvalue<'tcx>,
227) -> bool
228where
229 Q: Qualif,
230 F: FnMut(Local) -> bool,
231{
232 match rvalue {
233 Rvalue::ThreadLocalRef(_) | Rvalue::NullaryOp(..) => {
234 Q::in_any_value_of_ty(cx, rvalue.ty(cx.body, cx.tcx))
235 }
236
237 Rvalue::Discriminant(place) => in_place::<Q, _>(cx, in_local, place.as_ref()),
238
239 Rvalue::CopyForDeref(place) => in_place::<Q, _>(cx, in_local, place.as_ref()),
240
241 Rvalue::Use(operand)
242 | Rvalue::Repeat(operand, _)
243 | Rvalue::UnaryOp(_, operand)
244 | Rvalue::Cast(_, operand, _)
245 | Rvalue::ShallowInitBox(operand, _) => in_operand::<Q, _>(cx, in_local, operand),
246
247 Rvalue::BinaryOp(_, box (lhs, rhs)) => {
248 in_operand::<Q, _>(cx, in_local, lhs) || in_operand::<Q, _>(cx, in_local, rhs)
249 }
250
251 Rvalue::Ref(_, _, place) | Rvalue::RawPtr(_, place) => {
252 // Special-case reborrows to be more like a copy of the reference.
253 if let Some((place_base, ProjectionElem::Deref)) = place.as_ref().last_projection() {
254 let base_ty = place_base.ty(cx.body, cx.tcx).ty;
255 if let ty::Ref(..) = base_ty.kind() {
256 return in_place::<Q, _>(cx, in_local, place_base);
257 }
258 }
259
260 in_place::<Q, _>(cx, in_local, place.as_ref())
261 }
262
263 Rvalue::WrapUnsafeBinder(op, _) => in_operand::<Q, _>(cx, in_local, op),
264
265 Rvalue::Aggregate(kind, operands) => {
266 // Return early if we know that the struct or enum being constructed is always
267 // qualified.
268 if let AggregateKind::Adt(adt_did, ..) = **kind {
269 let def = cx.tcx.adt_def(adt_did);
270 // Don't do any value-based reasoning for unions.
271 // Also, if the ADT is not structural in its fields,
272 // then we cannot recurse on its fields. Instead,
273 // we fall back to checking the qualif for *any* value
274 // of the ADT.
275 if def.is_union() || !Q::is_structural_in_adt_value(cx, def) {
276 return Q::in_any_value_of_ty(cx, rvalue.ty(cx.body, cx.tcx));
277 }
278 }
279
280 // Otherwise, proceed structurally...
281 operands.iter().any(|o| in_operand::<Q, _>(cx, in_local, o))
282 }
283 }
284}
285
286/// Returns `true` if this `Place` contains qualif `Q`.
287pub fn in_place<'tcx, Q, F>(cx: &ConstCx<'_, 'tcx>, in_local: &mut F, place: PlaceRef<'tcx>) -> bool
288where
289 Q: Qualif,
290 F: FnMut(Local) -> bool,
291{
292 let mut place = place;
293 while let Some((place_base, elem)) = place.last_projection() {
294 match elem {
295 ProjectionElem::Index(index) if in_local(index) => return true,
296
297 ProjectionElem::Deref
298 | ProjectionElem::Field(_, _)
299 | ProjectionElem::OpaqueCast(_)
300 | ProjectionElem::ConstantIndex { .. }
301 | ProjectionElem::Subslice { .. }
302 | ProjectionElem::Downcast(_, _)
303 | ProjectionElem::Index(_)
304 | ProjectionElem::UnwrapUnsafeBinder(_) => {}
305 }
306
307 let base_ty = place_base.ty(cx.body, cx.tcx);
308 let proj_ty = base_ty.projection_ty(cx.tcx, elem).ty;
309 if !Q::in_any_value_of_ty(cx, proj_ty) {
310 return false;
311 }
312
313 // `Deref` currently unconditionally "qualifies" if `in_any_value_of_ty` returns true,
314 // i.e., we treat all qualifs as non-structural for deref projections. Generally,
315 // we can say very little about `*ptr` even if we know that `ptr` satisfies all
316 // sorts of properties.
317 if matches!(elem, ProjectionElem::Deref) {
318 // We have to assume that this qualifies.
319 return true;
320 }
321
322 place = place_base;
323 }
324
325 assert!(place.projection.is_empty());
326 in_local(place.local)
327}
328
329/// Returns `true` if this `Operand` contains qualif `Q`.
330pub fn in_operand<'tcx, Q, F>(
331 cx: &ConstCx<'_, 'tcx>,
332 in_local: &mut F,
333 operand: &Operand<'tcx>,
334) -> bool
335where
336 Q: Qualif,
337 F: FnMut(Local) -> bool,
338{
339 let constant = match operand {
340 Operand::Copy(place) | Operand::Move(place) => {
341 return in_place::<Q, _>(cx, in_local, place.as_ref());
342 }
343
344 Operand::Constant(c) => c,
345 };
346
347 // Check the qualifs of the value of `const` items.
348 let uneval = match constant.const_ {
349 Const::Ty(_, ct)
350 if matches!(
351 ct.kind(),
352 ty::ConstKind::Param(_) | ty::ConstKind::Error(_) | ty::ConstKind::Value(_)
353 ) =>
354 {
355 None
356 }
357 Const::Ty(_, c) => {
358 bug!("expected ConstKind::Param or ConstKind::Value here, found {:?}", c)
359 }
360 Const::Unevaluated(uv, _) => Some(uv),
361 Const::Val(..) => None,
362 };
363
364 if let Some(mir::UnevaluatedConst { def, args: _, promoted }) = uneval {
365 // Use qualifs of the type for the promoted. Promoteds in MIR body should be possible
366 // only for `NeedsNonConstDrop` with precise drop checking. This is the only const
367 // check performed after the promotion. Verify that with an assertion.
368 assert!(promoted.is_none() || Q::ALLOW_PROMOTED);
369
370 // Avoid looking at attrs of anon consts as that will ICE
371 let is_type_const_item =
372 matches!(cx.tcx.def_kind(def), DefKind::Const | DefKind::AssocConst)
373 && find_attr!(cx.tcx.get_all_attrs(def), AttributeKind::TypeConst(_));
374
375 // Don't peak inside trait associated constants, also `#[type_const] const` items
376 // don't have bodies so there's nothing to look at
377 if promoted.is_none() && cx.tcx.trait_of_assoc(def).is_none() && !is_type_const_item {
378 let qualifs = cx.tcx.at(constant.span).mir_const_qualif(def);
379
380 if !Q::in_qualifs(&qualifs) {
381 return false;
382 }
383
384 // Just in case the type is more specific than
385 // the definition, e.g., impl associated const
386 // with type parameters, take it into account.
387 }
388 }
389
390 // Otherwise use the qualifs of the type.
391 Q::in_any_value_of_ty(cx, constant.const_.ty())
392}