]> git.proxmox.com Git - rustc.git/blame - compiler/rustc_const_eval/src/transform/check_consts/qualifs.rs
New upstream version 1.69.0+dfsg1
[rustc.git] / compiler / rustc_const_eval / src / transform / check_consts / qualifs.rs
CommitLineData
ba9703b0
XL
1//! Structural const qualification.
2//!
3//! See the `Qualif` trait for more info.
e74abb32 4
5e7ed085
FG
5use rustc_errors::ErrorGuaranteed;
6use rustc_hir::LangItem;
c295e0f8 7use rustc_infer::infer::TyCtxtInferExt;
2b03887a 8use rustc_middle::mir;
ba9703b0 9use rustc_middle::mir::*;
f9f354fc 10use rustc_middle::ty::{self, subst::SubstsRef, AdtDef, Ty};
c295e0f8 11use rustc_trait_selection::traits::{
f2b60f7d 12 self, ImplSource, Obligation, ObligationCause, SelectionContext,
c295e0f8 13};
e74abb32 14
f9f354fc 15use super::ConstCx;
e74abb32 16
a2a8927a 17pub fn in_any_value_of_ty<'tcx>(
fc512014
XL
18 cx: &ConstCx<'_, 'tcx>,
19 ty: Ty<'tcx>,
5e7ed085 20 tainted_by_errors: Option<ErrorGuaranteed>,
fc512014 21) -> ConstQualifs {
60c5eb7d
XL
22 ConstQualifs {
23 has_mut_interior: HasMutInterior::in_any_value_of_ty(cx, ty),
3c0e092e
XL
24 needs_drop: NeedsDrop::in_any_value_of_ty(cx, ty),
25 needs_non_const_drop: NeedsNonConstDrop::in_any_value_of_ty(cx, ty),
f9f354fc 26 custom_eq: CustomEq::in_any_value_of_ty(cx, ty),
5099ac24 27 tainted_by_errors,
e74abb32
XL
28 }
29}
30
31/// A "qualif"(-ication) is a way to look for something "bad" in the MIR that would disqualify some
ba9703b0 32/// code for promotion or prevent it from evaluating at compile time.
e74abb32 33///
ba9703b0
XL
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
cdc7bbd5 37/// needn't reject code unless it actually constructs and operates on the qualified variant.
ba9703b0
XL
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
cdc7bbd5 41/// projection of a local) is assigned a qualified value, that local itself becomes qualified.
e74abb32 42pub trait Qualif {
e74abb32
XL
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
3c0e092e
XL
49 /// Whether this `Qualif` might be evaluated after the promotion and can encounter a promoted.
50 const ALLOW_PROMOTED: bool = false;
51
ba9703b0 52 /// Extracts the field of `ConstQualifs` that corresponds to this `Qualif`.
60c5eb7d
XL
53 fn in_qualifs(qualifs: &ConstQualifs) -> bool;
54
ba9703b0
XL
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
5e7ed085 58 /// propagation is context-insensitive, this includes function arguments and values returned
ba9703b0
XL
59 /// from a call to another function.
60 ///
61 /// It also determines the `Qualif`s for primitive types.
a2a8927a 62 fn in_any_value_of_ty<'tcx>(cx: &ConstCx<'_, 'tcx>, ty: Ty<'tcx>) -> bool;
ba9703b0
XL
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.
a2a8927a 72 fn in_adt_inherently<'tcx>(
f9f354fc 73 cx: &ConstCx<'_, 'tcx>,
5e7ed085 74 adt: AdtDef<'tcx>,
f9f354fc
XL
75 substs: SubstsRef<'tcx>,
76 ) -> bool;
e74abb32
XL
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.
84pub struct HasMutInterior;
85
86impl Qualif for HasMutInterior {
e74abb32
XL
87 const ANALYSIS_NAME: &'static str = "flow_has_mut_interior";
88
60c5eb7d
XL
89 fn in_qualifs(qualifs: &ConstQualifs) -> bool {
90 qualifs.has_mut_interior
91 }
92
a2a8927a 93 fn in_any_value_of_ty<'tcx>(cx: &ConstCx<'_, 'tcx>, ty: Ty<'tcx>) -> bool {
2b03887a 94 !ty.is_freeze(cx.tcx, cx.param_env)
e74abb32
XL
95 }
96
a2a8927a 97 fn in_adt_inherently<'tcx>(
064997fb 98 _cx: &ConstCx<'_, 'tcx>,
5e7ed085 99 adt: AdtDef<'tcx>,
a2a8927a
XL
100 _: SubstsRef<'tcx>,
101 ) -> bool {
ba9703b0
XL
102 // Exactly one type, `UnsafeCell`, has the `HasMutInterior` qualif inherently.
103 // It arises structurally for all other types.
064997fb 104 adt.is_unsafe_cell()
e74abb32
XL
105 }
106}
107
108/// Constant containing an ADT that implements `Drop`.
3c0e092e
XL
109/// This must be ruled out because implicit promotion would remove side-effects
110/// that occur as part of dropping that value. N.B., the implicit promotion has
111/// to reject const Drop implementations because even if side-effects are ruled
112/// out through other means, the execution of the drop could diverge.
113pub struct NeedsDrop;
114
115impl Qualif for NeedsDrop {
116 const ANALYSIS_NAME: &'static str = "flow_needs_drop";
117 const IS_CLEARED_ON_MOVE: bool = true;
118
119 fn in_qualifs(qualifs: &ConstQualifs) -> bool {
120 qualifs.needs_drop
121 }
122
a2a8927a 123 fn in_any_value_of_ty<'tcx>(cx: &ConstCx<'_, 'tcx>, ty: Ty<'tcx>) -> bool {
3c0e092e
XL
124 ty.needs_drop(cx.tcx, cx.param_env)
125 }
126
a2a8927a
XL
127 fn in_adt_inherently<'tcx>(
128 cx: &ConstCx<'_, 'tcx>,
5e7ed085 129 adt: AdtDef<'tcx>,
a2a8927a
XL
130 _: SubstsRef<'tcx>,
131 ) -> bool {
3c0e092e
XL
132 adt.has_dtor(cx.tcx)
133 }
134}
135
136/// Constant containing an ADT that implements non-const `Drop`.
137/// This must be ruled out because we cannot run `Drop` during compile-time.
c295e0f8 138pub struct NeedsNonConstDrop;
e74abb32 139
c295e0f8
XL
140impl Qualif for NeedsNonConstDrop {
141 const ANALYSIS_NAME: &'static str = "flow_needs_nonconst_drop";
e74abb32 142 const IS_CLEARED_ON_MOVE: bool = true;
3c0e092e 143 const ALLOW_PROMOTED: bool = true;
e74abb32 144
60c5eb7d 145 fn in_qualifs(qualifs: &ConstQualifs) -> bool {
3c0e092e 146 qualifs.needs_non_const_drop
60c5eb7d
XL
147 }
148
487cf647 149 #[instrument(level = "trace", skip(cx), ret)]
5099ac24
FG
150 fn in_any_value_of_ty<'tcx>(cx: &ConstCx<'_, 'tcx>, ty: Ty<'tcx>) -> bool {
151 // Avoid selecting for simple cases, such as builtin types.
152 if ty::util::is_trivially_const_drop(ty) {
153 return false;
c295e0f8
XL
154 }
155
c295e0f8 156 let obligation = Obligation::new(
487cf647
FG
157 cx.tcx,
158 ObligationCause::dummy_with_span(cx.body.span),
c295e0f8 159 cx.param_env,
487cf647
FG
160 ty::Binder::dummy(cx.tcx.at(cx.body.span).mk_trait_ref(LangItem::Destruct, [ty]))
161 .with_constness(ty::BoundConstness::ConstIfConst),
c295e0f8
XL
162 );
163
2b03887a
FG
164 let infcx = cx.tcx.infer_ctxt().build();
165 let mut selcx = SelectionContext::new(&infcx);
166 let Some(impl_src) = selcx.select(&obligation).ok().flatten() else {
167 // If we couldn't select a const destruct candidate, then it's bad
168 return true;
169 };
170
487cf647
FG
171 trace!(?impl_src);
172
2b03887a
FG
173 if !matches!(
174 impl_src,
175 ImplSource::ConstDestruct(_) | ImplSource::Param(_, ty::BoundConstness::ConstIfConst)
176 ) {
177 // If our const destruct candidate is not ConstDestruct or implied by the param env,
178 // then it's bad
179 return true;
180 }
5099ac24 181
2b03887a
FG
182 if impl_src.borrow_nested_obligations().is_empty() {
183 return false;
184 }
5099ac24 185
2b03887a
FG
186 // If we had any errors, then it's bad
187 !traits::fully_solve_obligations(&infcx, impl_src.nested_obligations()).is_empty()
e74abb32
XL
188 }
189
a2a8927a
XL
190 fn in_adt_inherently<'tcx>(
191 cx: &ConstCx<'_, 'tcx>,
5e7ed085 192 adt: AdtDef<'tcx>,
a2a8927a
XL
193 _: SubstsRef<'tcx>,
194 ) -> bool {
c295e0f8 195 adt.has_non_const_dtor(cx.tcx)
ba9703b0
XL
196 }
197}
198
f9f354fc
XL
199/// A constant that cannot be used as part of a pattern in a `match` expression.
200pub struct CustomEq;
201
202impl Qualif for CustomEq {
203 const ANALYSIS_NAME: &'static str = "flow_custom_eq";
204
205 fn in_qualifs(qualifs: &ConstQualifs) -> bool {
206 qualifs.custom_eq
207 }
208
a2a8927a 209 fn in_any_value_of_ty<'tcx>(cx: &ConstCx<'_, 'tcx>, ty: Ty<'tcx>) -> bool {
f9f354fc
XL
210 // If *any* component of a composite data type does not implement `Structural{Partial,}Eq`,
211 // we know that at least some values of that type are not structural-match. I say "some"
212 // because that component may be part of an enum variant (e.g.,
213 // `Option::<NonStructuralMatchTy>::Some`), in which case some values of this type may be
214 // structural-match (`Option::None`).
5099ac24 215 traits::search_for_structural_match_violation(cx.body.span, cx.tcx, ty).is_some()
f9f354fc
XL
216 }
217
a2a8927a 218 fn in_adt_inherently<'tcx>(
f9f354fc 219 cx: &ConstCx<'_, 'tcx>,
9ffffee4 220 def: AdtDef<'tcx>,
f9f354fc
XL
221 substs: SubstsRef<'tcx>,
222 ) -> bool {
9ffffee4 223 let ty = cx.tcx.mk_adt(def, substs);
f035d41b 224 !ty.is_structural_eq_shallow(cx.tcx)
f9f354fc
XL
225 }
226}
227
ba9703b0
XL
228// FIXME: Use `mir::visit::Visitor` for the `in_*` functions if/when it supports early return.
229
230/// Returns `true` if this `Rvalue` contains qualif `Q`.
a2a8927a
XL
231pub fn in_rvalue<'tcx, Q, F>(
232 cx: &ConstCx<'_, 'tcx>,
233 in_local: &mut F,
234 rvalue: &Rvalue<'tcx>,
235) -> bool
ba9703b0
XL
236where
237 Q: Qualif,
238 F: FnMut(Local) -> bool,
239{
240 match rvalue {
f9f354fc
XL
241 Rvalue::ThreadLocalRef(_) | Rvalue::NullaryOp(..) => {
242 Q::in_any_value_of_ty(cx, rvalue.ty(cx.body, cx.tcx))
243 }
ba9703b0
XL
244
245 Rvalue::Discriminant(place) | Rvalue::Len(place) => {
246 in_place::<Q, _>(cx, in_local, place.as_ref())
247 }
248
064997fb
FG
249 Rvalue::CopyForDeref(place) => in_place::<Q, _>(cx, in_local, place.as_ref()),
250
ba9703b0
XL
251 Rvalue::Use(operand)
252 | Rvalue::Repeat(operand, _)
253 | Rvalue::UnaryOp(_, operand)
c295e0f8
XL
254 | Rvalue::Cast(_, operand, _)
255 | Rvalue::ShallowInitBox(operand, _) => in_operand::<Q, _>(cx, in_local, operand),
ba9703b0 256
6a06907d 257 Rvalue::BinaryOp(_, box (lhs, rhs)) | Rvalue::CheckedBinaryOp(_, box (lhs, rhs)) => {
ba9703b0
XL
258 in_operand::<Q, _>(cx, in_local, lhs) || in_operand::<Q, _>(cx, in_local, rhs)
259 }
260
261 Rvalue::Ref(_, _, place) | Rvalue::AddressOf(_, place) => {
262 // Special-case reborrows to be more like a copy of the reference.
5869c6ff
XL
263 if let Some((place_base, ProjectionElem::Deref)) = place.as_ref().last_projection() {
264 let base_ty = place_base.ty(cx.body, cx.tcx).ty;
1b1a35ee 265 if let ty::Ref(..) = base_ty.kind() {
5869c6ff 266 return in_place::<Q, _>(cx, in_local, place_base);
ba9703b0
XL
267 }
268 }
269
270 in_place::<Q, _>(cx, in_local, place.as_ref())
271 }
272
273 Rvalue::Aggregate(kind, operands) => {
274 // Return early if we know that the struct or enum being constructed is always
275 // qualified.
a2a8927a
XL
276 if let AggregateKind::Adt(adt_did, _, substs, ..) = **kind {
277 let def = cx.tcx.adt_def(adt_did);
f9f354fc 278 if Q::in_adt_inherently(cx, def, substs) {
e74abb32
XL
279 return true;
280 }
3c0e092e
XL
281 if def.is_union() && Q::in_any_value_of_ty(cx, rvalue.ty(cx.body, cx.tcx)) {
282 return true;
283 }
e74abb32 284 }
ba9703b0
XL
285
286 // Otherwise, proceed structurally...
287 operands.iter().any(|o| in_operand::<Q, _>(cx, in_local, o))
e74abb32 288 }
ba9703b0
XL
289 }
290}
e74abb32 291
ba9703b0 292/// Returns `true` if this `Place` contains qualif `Q`.
a2a8927a 293pub fn in_place<'tcx, Q, F>(cx: &ConstCx<'_, 'tcx>, in_local: &mut F, place: PlaceRef<'tcx>) -> bool
ba9703b0
XL
294where
295 Q: Qualif,
296 F: FnMut(Local) -> bool,
297{
5869c6ff
XL
298 let mut place = place;
299 while let Some((place_base, elem)) = place.last_projection() {
300 match elem {
ba9703b0
XL
301 ProjectionElem::Index(index) if in_local(index) => return true,
302
303 ProjectionElem::Deref
304 | ProjectionElem::Field(_, _)
2b03887a 305 | ProjectionElem::OpaqueCast(_)
ba9703b0
XL
306 | ProjectionElem::ConstantIndex { .. }
307 | ProjectionElem::Subslice { .. }
308 | ProjectionElem::Downcast(_, _)
309 | ProjectionElem::Index(_) => {}
310 }
311
5869c6ff
XL
312 let base_ty = place_base.ty(cx.body, cx.tcx);
313 let proj_ty = base_ty.projection_ty(cx.tcx, elem).ty;
ba9703b0
XL
314 if !Q::in_any_value_of_ty(cx, proj_ty) {
315 return false;
316 }
317
5869c6ff 318 place = place_base;
ba9703b0
XL
319 }
320
5869c6ff 321 assert!(place.projection.is_empty());
ba9703b0
XL
322 in_local(place.local)
323}
324
325/// Returns `true` if this `Operand` contains qualif `Q`.
a2a8927a
XL
326pub fn in_operand<'tcx, Q, F>(
327 cx: &ConstCx<'_, 'tcx>,
328 in_local: &mut F,
329 operand: &Operand<'tcx>,
330) -> bool
ba9703b0
XL
331where
332 Q: Qualif,
333 F: FnMut(Local) -> bool,
334{
335 let constant = match operand {
336 Operand::Copy(place) | Operand::Move(place) => {
337 return in_place::<Q, _>(cx, in_local, place.as_ref());
338 }
339
340 Operand::Constant(c) => c,
341 };
342
343 // Check the qualifs of the value of `const` items.
f2b60f7d
FG
344 // FIXME(valtrees): check whether const qualifs should behave the same
345 // way for type and mir constants.
346 let uneval = match constant.literal {
487cf647
FG
347 ConstantKind::Ty(ct)
348 if matches!(ct.kind(), ty::ConstKind::Param(_) | ty::ConstKind::Error(_)) =>
349 {
350 None
351 }
2b03887a 352 ConstantKind::Ty(c) => bug!("expected ConstKind::Param here, found {:?}", c),
f2b60f7d
FG
353 ConstantKind::Unevaluated(uv, _) => Some(uv),
354 ConstantKind::Val(..) => None,
355 };
ba9703b0 356
2b03887a 357 if let Some(mir::UnevaluatedConst { def, substs: _, promoted }) = uneval {
f2b60f7d
FG
358 // Use qualifs of the type for the promoted. Promoteds in MIR body should be possible
359 // only for `NeedsNonConstDrop` with precise drop checking. This is the only const
360 // check performed after the promotion. Verify that with an assertion.
361 assert!(promoted.is_none() || Q::ALLOW_PROMOTED);
362
363 // Don't peek inside trait associated constants.
364 if promoted.is_none() && cx.tcx.trait_of_item(def.did).is_none() {
2b03887a
FG
365 assert_eq!(def.const_param_did, None, "expected associated const: {def:?}");
366 let qualifs = cx.tcx.at(constant.span).mir_const_qualif(def.did);
f2b60f7d
FG
367
368 if !Q::in_qualifs(&qualifs) {
369 return false;
6a06907d 370 }
f2b60f7d
FG
371
372 // Just in case the type is more specific than
373 // the definition, e.g., impl associated const
374 // with type parameters, take it into account.
ba9703b0 375 }
e74abb32 376 }
f2b60f7d 377
ba9703b0 378 // Otherwise use the qualifs of the type.
6a06907d 379 Q::in_any_value_of_ty(cx, constant.literal.ty())
e74abb32 380}