]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_mir/src/transform/check_consts/qualifs.rs
Rollup merge of #81904 - jhpratt:const_int_fn-stabilization, r=jyn514
[rust.git] / compiler / rustc_mir / src / transform / check_consts / qualifs.rs
1 //! Structural const qualification.
2 //!
3 //! See the `Qualif` trait for more info.
4
5 use rustc_errors::ErrorReported;
6 use rustc_middle::mir::*;
7 use rustc_middle::ty::{self, subst::SubstsRef, AdtDef, Ty};
8 use rustc_span::DUMMY_SP;
9 use rustc_trait_selection::traits;
10
11 use super::ConstCx;
12
13 pub fn in_any_value_of_ty(
14     cx: &ConstCx<'_, 'tcx>,
15     ty: Ty<'tcx>,
16     error_occured: Option<ErrorReported>,
17 ) -> ConstQualifs {
18     ConstQualifs {
19         has_mut_interior: HasMutInterior::in_any_value_of_ty(cx, ty),
20         needs_drop: NeedsDrop::in_any_value_of_ty(cx, ty),
21         custom_eq: CustomEq::in_any_value_of_ty(cx, ty),
22         error_occured,
23     }
24 }
25
26 /// A "qualif"(-ication) is a way to look for something "bad" in the MIR that would disqualify some
27 /// code for promotion or prevent it from evaluating at compile time.
28 ///
29 /// Normally, we would determine what qualifications apply to each type and error when an illegal
30 /// operation is performed on such a type. However, this was found to be too imprecise, especially
31 /// in the presence of `enum`s. If only a single variant of an enum has a certain qualification, we
32 /// needn't reject code unless it actually constructs and operates on the qualifed variant.
33 ///
34 /// To accomplish this, const-checking and promotion use a value-based analysis (as opposed to a
35 /// type-based one). Qualifications propagate structurally across variables: If a local (or a
36 /// projection of a local) is assigned a qualifed value, that local itself becomes qualifed.
37 pub trait Qualif {
38     /// The name of the file used to debug the dataflow analysis that computes this qualif.
39     const ANALYSIS_NAME: &'static str;
40
41     /// Whether this `Qualif` is cleared when a local is moved from.
42     const IS_CLEARED_ON_MOVE: bool = false;
43
44     /// Extracts the field of `ConstQualifs` that corresponds to this `Qualif`.
45     fn in_qualifs(qualifs: &ConstQualifs) -> bool;
46
47     /// Returns `true` if *any* value of the given type could possibly have this `Qualif`.
48     ///
49     /// This function determines `Qualif`s when we cannot do a value-based analysis. Since qualif
50     /// propagation is context-insenstive, this includes function arguments and values returned
51     /// from a call to another function.
52     ///
53     /// It also determines the `Qualif`s for primitive types.
54     fn in_any_value_of_ty(cx: &ConstCx<'_, 'tcx>, ty: Ty<'tcx>) -> bool;
55
56     /// Returns `true` if this `Qualif` is inherent to the given struct or enum.
57     ///
58     /// By default, `Qualif`s propagate into ADTs in a structural way: An ADT only becomes
59     /// qualified if part of it is assigned a value with that `Qualif`. However, some ADTs *always*
60     /// have a certain `Qualif`, regardless of whether their fields have it. For example, a type
61     /// with a custom `Drop` impl is inherently `NeedsDrop`.
62     ///
63     /// Returning `true` for `in_adt_inherently` but `false` for `in_any_value_of_ty` is unsound.
64     fn in_adt_inherently(
65         cx: &ConstCx<'_, 'tcx>,
66         adt: &'tcx AdtDef,
67         substs: SubstsRef<'tcx>,
68     ) -> bool;
69 }
70
71 /// Constant containing interior mutability (`UnsafeCell<T>`).
72 /// This must be ruled out to make sure that evaluating the constant at compile-time
73 /// and at *any point* during the run-time would produce the same result. In particular,
74 /// promotion of temporaries must not change program behavior; if the promoted could be
75 /// written to, that would be a problem.
76 pub struct HasMutInterior;
77
78 impl Qualif for HasMutInterior {
79     const ANALYSIS_NAME: &'static str = "flow_has_mut_interior";
80
81     fn in_qualifs(qualifs: &ConstQualifs) -> bool {
82         qualifs.has_mut_interior
83     }
84
85     fn in_any_value_of_ty(cx: &ConstCx<'_, 'tcx>, ty: Ty<'tcx>) -> bool {
86         !ty.is_freeze(cx.tcx.at(DUMMY_SP), cx.param_env)
87     }
88
89     fn in_adt_inherently(cx: &ConstCx<'_, 'tcx>, adt: &'tcx AdtDef, _: SubstsRef<'tcx>) -> bool {
90         // Exactly one type, `UnsafeCell`, has the `HasMutInterior` qualif inherently.
91         // It arises structurally for all other types.
92         Some(adt.did) == cx.tcx.lang_items().unsafe_cell_type()
93     }
94 }
95
96 /// Constant containing an ADT that implements `Drop`.
97 /// This must be ruled out (a) because we cannot run `Drop` during compile-time
98 /// as that might not be a `const fn`, and (b) because implicit promotion would
99 /// remove side-effects that occur as part of dropping that value.
100 pub struct NeedsDrop;
101
102 impl Qualif for NeedsDrop {
103     const ANALYSIS_NAME: &'static str = "flow_needs_drop";
104     const IS_CLEARED_ON_MOVE: bool = true;
105
106     fn in_qualifs(qualifs: &ConstQualifs) -> bool {
107         qualifs.needs_drop
108     }
109
110     fn in_any_value_of_ty(cx: &ConstCx<'_, 'tcx>, ty: Ty<'tcx>) -> bool {
111         ty.needs_drop(cx.tcx, cx.param_env)
112     }
113
114     fn in_adt_inherently(cx: &ConstCx<'_, 'tcx>, adt: &'tcx AdtDef, _: SubstsRef<'tcx>) -> bool {
115         adt.has_dtor(cx.tcx)
116     }
117 }
118
119 /// A constant that cannot be used as part of a pattern in a `match` expression.
120 pub struct CustomEq;
121
122 impl Qualif for CustomEq {
123     const ANALYSIS_NAME: &'static str = "flow_custom_eq";
124
125     fn in_qualifs(qualifs: &ConstQualifs) -> bool {
126         qualifs.custom_eq
127     }
128
129     fn in_any_value_of_ty(cx: &ConstCx<'_, 'tcx>, ty: Ty<'tcx>) -> bool {
130         // If *any* component of a composite data type does not implement `Structural{Partial,}Eq`,
131         // we know that at least some values of that type are not structural-match. I say "some"
132         // because that component may be part of an enum variant (e.g.,
133         // `Option::<NonStructuralMatchTy>::Some`), in which case some values of this type may be
134         // structural-match (`Option::None`).
135         let id = cx.tcx.hir().local_def_id_to_hir_id(cx.def_id());
136         traits::search_for_structural_match_violation(id, cx.body.span, cx.tcx, ty).is_some()
137     }
138
139     fn in_adt_inherently(
140         cx: &ConstCx<'_, 'tcx>,
141         adt: &'tcx AdtDef,
142         substs: SubstsRef<'tcx>,
143     ) -> bool {
144         let ty = cx.tcx.mk_ty(ty::Adt(adt, substs));
145         !ty.is_structural_eq_shallow(cx.tcx)
146     }
147 }
148
149 // FIXME: Use `mir::visit::Visitor` for the `in_*` functions if/when it supports early return.
150
151 /// Returns `true` if this `Rvalue` contains qualif `Q`.
152 pub fn in_rvalue<Q, F>(cx: &ConstCx<'_, 'tcx>, in_local: &mut F, rvalue: &Rvalue<'tcx>) -> bool
153 where
154     Q: Qualif,
155     F: FnMut(Local) -> bool,
156 {
157     match rvalue {
158         Rvalue::ThreadLocalRef(_) | Rvalue::NullaryOp(..) => {
159             Q::in_any_value_of_ty(cx, rvalue.ty(cx.body, cx.tcx))
160         }
161
162         Rvalue::Discriminant(place) | Rvalue::Len(place) => {
163             in_place::<Q, _>(cx, in_local, place.as_ref())
164         }
165
166         Rvalue::Use(operand)
167         | Rvalue::Repeat(operand, _)
168         | Rvalue::UnaryOp(_, operand)
169         | Rvalue::Cast(_, operand, _) => in_operand::<Q, _>(cx, in_local, operand),
170
171         Rvalue::BinaryOp(_, lhs, rhs) | Rvalue::CheckedBinaryOp(_, lhs, rhs) => {
172             in_operand::<Q, _>(cx, in_local, lhs) || in_operand::<Q, _>(cx, in_local, rhs)
173         }
174
175         Rvalue::Ref(_, _, place) | Rvalue::AddressOf(_, place) => {
176             // Special-case reborrows to be more like a copy of the reference.
177             if let Some((place_base, ProjectionElem::Deref)) = place.as_ref().last_projection() {
178                 let base_ty = place_base.ty(cx.body, cx.tcx).ty;
179                 if let ty::Ref(..) = base_ty.kind() {
180                     return in_place::<Q, _>(cx, in_local, place_base);
181                 }
182             }
183
184             in_place::<Q, _>(cx, in_local, place.as_ref())
185         }
186
187         Rvalue::Aggregate(kind, operands) => {
188             // Return early if we know that the struct or enum being constructed is always
189             // qualified.
190             if let AggregateKind::Adt(def, _, substs, ..) = **kind {
191                 if Q::in_adt_inherently(cx, def, substs) {
192                     return true;
193                 }
194             }
195
196             // Otherwise, proceed structurally...
197             operands.iter().any(|o| in_operand::<Q, _>(cx, in_local, o))
198         }
199     }
200 }
201
202 /// Returns `true` if this `Place` contains qualif `Q`.
203 pub fn in_place<Q, F>(cx: &ConstCx<'_, 'tcx>, in_local: &mut F, place: PlaceRef<'tcx>) -> bool
204 where
205     Q: Qualif,
206     F: FnMut(Local) -> bool,
207 {
208     let mut place = place;
209     while let Some((place_base, elem)) = place.last_projection() {
210         match elem {
211             ProjectionElem::Index(index) if in_local(index) => return true,
212
213             ProjectionElem::Deref
214             | ProjectionElem::Field(_, _)
215             | ProjectionElem::ConstantIndex { .. }
216             | ProjectionElem::Subslice { .. }
217             | ProjectionElem::Downcast(_, _)
218             | ProjectionElem::Index(_) => {}
219         }
220
221         let base_ty = place_base.ty(cx.body, cx.tcx);
222         let proj_ty = base_ty.projection_ty(cx.tcx, elem).ty;
223         if !Q::in_any_value_of_ty(cx, proj_ty) {
224             return false;
225         }
226
227         place = place_base;
228     }
229
230     assert!(place.projection.is_empty());
231     in_local(place.local)
232 }
233
234 /// Returns `true` if this `Operand` contains qualif `Q`.
235 pub fn in_operand<Q, F>(cx: &ConstCx<'_, 'tcx>, in_local: &mut F, operand: &Operand<'tcx>) -> bool
236 where
237     Q: Qualif,
238     F: FnMut(Local) -> bool,
239 {
240     let constant = match operand {
241         Operand::Copy(place) | Operand::Move(place) => {
242             return in_place::<Q, _>(cx, in_local, place.as_ref());
243         }
244
245         Operand::Constant(c) => c,
246     };
247
248     // Check the qualifs of the value of `const` items.
249     if let ty::ConstKind::Unevaluated(def, _, promoted) = constant.literal.val {
250         assert!(promoted.is_none());
251         // Don't peek inside trait associated constants.
252         if cx.tcx.trait_of_item(def.did).is_none() {
253             let qualifs = if let Some((did, param_did)) = def.as_const_arg() {
254                 cx.tcx.at(constant.span).mir_const_qualif_const_arg((did, param_did))
255             } else {
256                 cx.tcx.at(constant.span).mir_const_qualif(def.did)
257             };
258
259             if !Q::in_qualifs(&qualifs) {
260                 return false;
261             }
262
263             // Just in case the type is more specific than
264             // the definition, e.g., impl associated const
265             // with type parameters, take it into account.
266         }
267     }
268     // Otherwise use the qualifs of the type.
269     Q::in_any_value_of_ty(cx, constant.literal.ty)
270 }