]> git.proxmox.com Git - rustc.git/blame - compiler/rustc_const_eval/src/transform/check_consts/qualifs.rs
New upstream version 1.60.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
fc512014 5use rustc_errors::ErrorReported;
c295e0f8 6use rustc_infer::infer::TyCtxtInferExt;
5099ac24 7use rustc_infer::traits::TraitEngine;
ba9703b0 8use rustc_middle::mir::*;
f9f354fc 9use rustc_middle::ty::{self, subst::SubstsRef, AdtDef, Ty};
dfeec247 10use rustc_span::DUMMY_SP;
c295e0f8 11use rustc_trait_selection::traits::{
5099ac24 12 self, FulfillmentContext, 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>,
5099ac24 20 tainted_by_errors: Option<ErrorReported>,
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
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.
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
XL
73 cx: &ConstCx<'_, 'tcx>,
74 adt: &'tcx AdtDef,
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 {
f035d41b 94 !ty.is_freeze(cx.tcx.at(DUMMY_SP), cx.param_env)
e74abb32
XL
95 }
96
a2a8927a
XL
97 fn in_adt_inherently<'tcx>(
98 cx: &ConstCx<'_, 'tcx>,
99 adt: &'tcx AdtDef,
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.
104 Some(adt.did) == cx.tcx.lang_items().unsafe_cell_type()
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>,
129 adt: &'tcx AdtDef,
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
5099ac24
FG
149 fn in_any_value_of_ty<'tcx>(cx: &ConstCx<'_, 'tcx>, ty: Ty<'tcx>) -> bool {
150 // Avoid selecting for simple cases, such as builtin types.
151 if ty::util::is_trivially_const_drop(ty) {
152 return false;
c295e0f8
XL
153 }
154
3c0e092e 155 let Some(drop_trait) = cx.tcx.lang_items().drop_trait() else {
c295e0f8
XL
156 // there is no way to define a type that needs non-const drop
157 // without having the lang item present.
158 return false;
159 };
5099ac24 160
c295e0f8
XL
161 let obligation = Obligation::new(
162 ObligationCause::dummy(),
163 cx.param_env,
164 ty::Binder::dummy(ty::TraitPredicate {
5099ac24
FG
165 trait_ref: ty::TraitRef {
166 def_id: drop_trait,
167 substs: cx.tcx.mk_substs_trait(ty, &[]),
168 },
c295e0f8 169 constness: ty::BoundConstness::ConstIfConst,
3c0e092e 170 polarity: ty::ImplPolarity::Positive,
c295e0f8
XL
171 }),
172 );
173
5099ac24 174 cx.tcx.infer_ctxt().enter(|infcx| {
a2a8927a 175 let mut selcx = SelectionContext::new(&infcx);
5099ac24
FG
176 let Some(impl_src) = selcx.select(&obligation).ok().flatten() else {
177 // If we couldn't select a const drop candidate, then it's bad
178 return true;
179 };
180
181 if !matches!(
182 impl_src,
3c0e092e 183 ImplSource::ConstDrop(_) | ImplSource::Param(_, ty::BoundConstness::ConstIfConst)
5099ac24
FG
184 ) {
185 // If our const drop candidate is not ConstDrop or implied by the param env,
186 // then it's bad
187 return true;
188 }
189
190 if impl_src.borrow_nested_obligations().is_empty() {
191 return false;
192 }
193
194 // If we successfully found one, then select all of the predicates
195 // implied by our const drop impl.
196 let mut fcx = FulfillmentContext::new();
197 for nested in impl_src.nested_obligations() {
198 fcx.register_predicate_obligation(&infcx, nested);
199 }
200
201 // If we had any errors, then it's bad
202 !fcx.select_all_or_error(&infcx).is_empty()
203 })
e74abb32
XL
204 }
205
a2a8927a
XL
206 fn in_adt_inherently<'tcx>(
207 cx: &ConstCx<'_, 'tcx>,
208 adt: &'tcx AdtDef,
209 _: SubstsRef<'tcx>,
210 ) -> bool {
c295e0f8 211 adt.has_non_const_dtor(cx.tcx)
ba9703b0
XL
212 }
213}
214
f9f354fc
XL
215/// A constant that cannot be used as part of a pattern in a `match` expression.
216pub struct CustomEq;
217
218impl Qualif for CustomEq {
219 const ANALYSIS_NAME: &'static str = "flow_custom_eq";
220
221 fn in_qualifs(qualifs: &ConstQualifs) -> bool {
222 qualifs.custom_eq
223 }
224
a2a8927a 225 fn in_any_value_of_ty<'tcx>(cx: &ConstCx<'_, 'tcx>, ty: Ty<'tcx>) -> bool {
f9f354fc
XL
226 // If *any* component of a composite data type does not implement `Structural{Partial,}Eq`,
227 // we know that at least some values of that type are not structural-match. I say "some"
228 // because that component may be part of an enum variant (e.g.,
229 // `Option::<NonStructuralMatchTy>::Some`), in which case some values of this type may be
230 // structural-match (`Option::None`).
5099ac24 231 traits::search_for_structural_match_violation(cx.body.span, cx.tcx, ty).is_some()
f9f354fc
XL
232 }
233
a2a8927a 234 fn in_adt_inherently<'tcx>(
f9f354fc
XL
235 cx: &ConstCx<'_, 'tcx>,
236 adt: &'tcx AdtDef,
237 substs: SubstsRef<'tcx>,
238 ) -> bool {
239 let ty = cx.tcx.mk_ty(ty::Adt(adt, substs));
f035d41b 240 !ty.is_structural_eq_shallow(cx.tcx)
f9f354fc
XL
241 }
242}
243
ba9703b0
XL
244// FIXME: Use `mir::visit::Visitor` for the `in_*` functions if/when it supports early return.
245
246/// Returns `true` if this `Rvalue` contains qualif `Q`.
a2a8927a
XL
247pub fn in_rvalue<'tcx, Q, F>(
248 cx: &ConstCx<'_, 'tcx>,
249 in_local: &mut F,
250 rvalue: &Rvalue<'tcx>,
251) -> bool
ba9703b0
XL
252where
253 Q: Qualif,
254 F: FnMut(Local) -> bool,
255{
256 match rvalue {
f9f354fc
XL
257 Rvalue::ThreadLocalRef(_) | Rvalue::NullaryOp(..) => {
258 Q::in_any_value_of_ty(cx, rvalue.ty(cx.body, cx.tcx))
259 }
ba9703b0
XL
260
261 Rvalue::Discriminant(place) | Rvalue::Len(place) => {
262 in_place::<Q, _>(cx, in_local, place.as_ref())
263 }
264
265 Rvalue::Use(operand)
266 | Rvalue::Repeat(operand, _)
267 | Rvalue::UnaryOp(_, operand)
c295e0f8
XL
268 | Rvalue::Cast(_, operand, _)
269 | Rvalue::ShallowInitBox(operand, _) => in_operand::<Q, _>(cx, in_local, operand),
ba9703b0 270
6a06907d 271 Rvalue::BinaryOp(_, box (lhs, rhs)) | Rvalue::CheckedBinaryOp(_, box (lhs, rhs)) => {
ba9703b0
XL
272 in_operand::<Q, _>(cx, in_local, lhs) || in_operand::<Q, _>(cx, in_local, rhs)
273 }
274
275 Rvalue::Ref(_, _, place) | Rvalue::AddressOf(_, place) => {
276 // Special-case reborrows to be more like a copy of the reference.
5869c6ff
XL
277 if let Some((place_base, ProjectionElem::Deref)) = place.as_ref().last_projection() {
278 let base_ty = place_base.ty(cx.body, cx.tcx).ty;
1b1a35ee 279 if let ty::Ref(..) = base_ty.kind() {
5869c6ff 280 return in_place::<Q, _>(cx, in_local, place_base);
ba9703b0
XL
281 }
282 }
283
284 in_place::<Q, _>(cx, in_local, place.as_ref())
285 }
286
287 Rvalue::Aggregate(kind, operands) => {
288 // Return early if we know that the struct or enum being constructed is always
289 // qualified.
a2a8927a
XL
290 if let AggregateKind::Adt(adt_did, _, substs, ..) = **kind {
291 let def = cx.tcx.adt_def(adt_did);
f9f354fc 292 if Q::in_adt_inherently(cx, def, substs) {
e74abb32
XL
293 return true;
294 }
3c0e092e
XL
295 if def.is_union() && Q::in_any_value_of_ty(cx, rvalue.ty(cx.body, cx.tcx)) {
296 return true;
297 }
e74abb32 298 }
ba9703b0
XL
299
300 // Otherwise, proceed structurally...
301 operands.iter().any(|o| in_operand::<Q, _>(cx, in_local, o))
e74abb32 302 }
ba9703b0
XL
303 }
304}
e74abb32 305
ba9703b0 306/// Returns `true` if this `Place` contains qualif `Q`.
a2a8927a 307pub fn in_place<'tcx, Q, F>(cx: &ConstCx<'_, 'tcx>, in_local: &mut F, place: PlaceRef<'tcx>) -> bool
ba9703b0
XL
308where
309 Q: Qualif,
310 F: FnMut(Local) -> bool,
311{
5869c6ff
XL
312 let mut place = place;
313 while let Some((place_base, elem)) = place.last_projection() {
314 match elem {
ba9703b0
XL
315 ProjectionElem::Index(index) if in_local(index) => return true,
316
317 ProjectionElem::Deref
318 | ProjectionElem::Field(_, _)
319 | ProjectionElem::ConstantIndex { .. }
320 | ProjectionElem::Subslice { .. }
321 | ProjectionElem::Downcast(_, _)
322 | ProjectionElem::Index(_) => {}
323 }
324
5869c6ff
XL
325 let base_ty = place_base.ty(cx.body, cx.tcx);
326 let proj_ty = base_ty.projection_ty(cx.tcx, elem).ty;
ba9703b0
XL
327 if !Q::in_any_value_of_ty(cx, proj_ty) {
328 return false;
329 }
330
5869c6ff 331 place = place_base;
ba9703b0
XL
332 }
333
5869c6ff 334 assert!(place.projection.is_empty());
ba9703b0
XL
335 in_local(place.local)
336}
337
338/// Returns `true` if this `Operand` contains qualif `Q`.
a2a8927a
XL
339pub fn in_operand<'tcx, Q, F>(
340 cx: &ConstCx<'_, 'tcx>,
341 in_local: &mut F,
342 operand: &Operand<'tcx>,
343) -> bool
ba9703b0
XL
344where
345 Q: Qualif,
346 F: FnMut(Local) -> bool,
347{
348 let constant = match operand {
349 Operand::Copy(place) | Operand::Move(place) => {
350 return in_place::<Q, _>(cx, in_local, place.as_ref());
351 }
352
353 Operand::Constant(c) => c,
354 };
355
356 // Check the qualifs of the value of `const` items.
6a06907d 357 if let Some(ct) = constant.literal.const_for_ty() {
5099ac24 358 if let ty::ConstKind::Unevaluated(ty::Unevaluated { def, substs: _, promoted }) = ct.val() {
3c0e092e
XL
359 // Use qualifs of the type for the promoted. Promoteds in MIR body should be possible
360 // only for `NeedsNonConstDrop` with precise drop checking. This is the only const
361 // check performed after the promotion. Verify that with an assertion.
362 assert!(promoted.is_none() || Q::ALLOW_PROMOTED);
6a06907d 363 // Don't peek inside trait associated constants.
3c0e092e 364 if promoted.is_none() && cx.tcx.trait_of_item(def.did).is_none() {
6a06907d
XL
365 let qualifs = if let Some((did, param_did)) = def.as_const_arg() {
366 cx.tcx.at(constant.span).mir_const_qualif_const_arg((did, param_did))
367 } else {
368 cx.tcx.at(constant.span).mir_const_qualif(def.did)
369 };
370
371 if !Q::in_qualifs(&qualifs) {
372 return false;
373 }
ba9703b0 374
6a06907d
XL
375 // Just in case the type is more specific than
376 // the definition, e.g., impl associated const
377 // with type parameters, take it into account.
378 }
ba9703b0 379 }
e74abb32 380 }
ba9703b0 381 // Otherwise use the qualifs of the type.
6a06907d 382 Q::in_any_value_of_ty(cx, constant.literal.ty())
e74abb32 383}