]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_const_eval/src/const_eval/eval_queries.rs
Auto merge of #96010 - eduardosm:Unique-on-top-of-NonNull, r=m-ou-se,tmiasko
[rust.git] / compiler / rustc_const_eval / src / const_eval / eval_queries.rs
1 use super::{CompileTimeEvalContext, CompileTimeInterpreter, ConstEvalErr};
2 use crate::interpret::eval_nullary_intrinsic;
3 use crate::interpret::{
4     intern_const_alloc_recursive, Allocation, ConstAlloc, ConstValue, CtfeValidationMode, GlobalId,
5     Immediate, InternKind, InterpCx, InterpResult, MPlaceTy, MemoryKind, OpTy, RefTracking, Scalar,
6     ScalarMaybeUninit, StackPopCleanup,
7 };
8
9 use rustc_hir::def::DefKind;
10 use rustc_middle::mir;
11 use rustc_middle::mir::interpret::ErrorHandled;
12 use rustc_middle::mir::pretty::display_allocation;
13 use rustc_middle::traits::Reveal;
14 use rustc_middle::ty::layout::LayoutOf;
15 use rustc_middle::ty::print::with_no_trimmed_paths;
16 use rustc_middle::ty::{self, subst::Subst, TyCtxt};
17 use rustc_span::source_map::Span;
18 use rustc_target::abi::{self, Abi};
19 use std::borrow::Cow;
20 use std::convert::TryInto;
21
22 pub fn note_on_undefined_behavior_error() -> &'static str {
23     "The rules on what exactly is undefined behavior aren't clear, \
24      so this check might be overzealous. Please open an issue on the rustc \
25      repository if you believe it should not be considered undefined behavior."
26 }
27
28 // Returns a pointer to where the result lives
29 fn eval_body_using_ecx<'mir, 'tcx>(
30     ecx: &mut CompileTimeEvalContext<'mir, 'tcx>,
31     cid: GlobalId<'tcx>,
32     body: &'mir mir::Body<'tcx>,
33 ) -> InterpResult<'tcx, MPlaceTy<'tcx>> {
34     debug!("eval_body_using_ecx: {:?}, {:?}", cid, ecx.param_env);
35     let tcx = *ecx.tcx;
36     assert!(
37         cid.promoted.is_some()
38             || matches!(
39                 ecx.tcx.def_kind(cid.instance.def_id()),
40                 DefKind::Const
41                     | DefKind::Static(_)
42                     | DefKind::ConstParam
43                     | DefKind::AnonConst
44                     | DefKind::InlineConst
45                     | DefKind::AssocConst
46             ),
47         "Unexpected DefKind: {:?}",
48         ecx.tcx.def_kind(cid.instance.def_id())
49     );
50     let layout = ecx.layout_of(body.return_ty().subst(tcx, cid.instance.substs))?;
51     assert!(!layout.is_unsized());
52     let ret = ecx.allocate(layout, MemoryKind::Stack)?;
53
54     trace!(
55         "eval_body_using_ecx: pushing stack frame for global: {}{}",
56         with_no_trimmed_paths!(ty::tls::with(|tcx| tcx.def_path_str(cid.instance.def_id()))),
57         cid.promoted.map_or_else(String::new, |p| format!("::promoted[{:?}]", p))
58     );
59
60     ecx.push_stack_frame(
61         cid.instance,
62         body,
63         Some(&ret.into()),
64         StackPopCleanup::Root { cleanup: false },
65     )?;
66
67     // The main interpreter loop.
68     ecx.run()?;
69
70     // Intern the result
71     let intern_kind = if cid.promoted.is_some() {
72         InternKind::Promoted
73     } else {
74         match tcx.static_mutability(cid.instance.def_id()) {
75             Some(m) => InternKind::Static(m),
76             None => InternKind::Constant,
77         }
78     };
79     intern_const_alloc_recursive(ecx, intern_kind, &ret)?;
80
81     debug!("eval_body_using_ecx done: {:?}", *ret);
82     Ok(ret)
83 }
84
85 /// The `InterpCx` is only meant to be used to do field and index projections into constants for
86 /// `simd_shuffle` and const patterns in match arms.
87 ///
88 /// The function containing the `match` that is currently being analyzed may have generic bounds
89 /// that inform us about the generic bounds of the constant. E.g., using an associated constant
90 /// of a function's generic parameter will require knowledge about the bounds on the generic
91 /// parameter. These bounds are passed to `mk_eval_cx` via the `ParamEnv` argument.
92 pub(super) fn mk_eval_cx<'mir, 'tcx>(
93     tcx: TyCtxt<'tcx>,
94     root_span: Span,
95     param_env: ty::ParamEnv<'tcx>,
96     can_access_statics: bool,
97 ) -> CompileTimeEvalContext<'mir, 'tcx> {
98     debug!("mk_eval_cx: {:?}", param_env);
99     InterpCx::new(
100         tcx,
101         root_span,
102         param_env,
103         CompileTimeInterpreter::new(tcx.const_eval_limit(), can_access_statics),
104     )
105 }
106
107 /// This function converts an interpreter value into a constant that is meant for use in the
108 /// type system.
109 pub(super) fn op_to_const<'tcx>(
110     ecx: &CompileTimeEvalContext<'_, 'tcx>,
111     op: &OpTy<'tcx>,
112 ) -> ConstValue<'tcx> {
113     // We do not have value optimizations for everything.
114     // Only scalars and slices, since they are very common.
115     // Note that further down we turn scalars of uninitialized bits back to `ByRef`. These can result
116     // from scalar unions that are initialized with one of their zero sized variants. We could
117     // instead allow `ConstValue::Scalar` to store `ScalarMaybeUninit`, but that would affect all
118     // the usual cases of extracting e.g. a `usize`, without there being a real use case for the
119     // `Undef` situation.
120     let try_as_immediate = match op.layout.abi {
121         Abi::Scalar(abi::Scalar::Initialized { .. }) => true,
122         Abi::ScalarPair(..) => match op.layout.ty.kind() {
123             ty::Ref(_, inner, _) => match *inner.kind() {
124                 ty::Slice(elem) => elem == ecx.tcx.types.u8,
125                 ty::Str => true,
126                 _ => false,
127             },
128             _ => false,
129         },
130         _ => false,
131     };
132     let immediate = if try_as_immediate {
133         Err(ecx.read_immediate(op).expect("normalization works on validated constants"))
134     } else {
135         // It is guaranteed that any non-slice scalar pair is actually ByRef here.
136         // When we come back from raw const eval, we are always by-ref. The only way our op here is
137         // by-val is if we are in destructure_const, i.e., if this is (a field of) something that we
138         // "tried to make immediate" before. We wouldn't do that for non-slice scalar pairs or
139         // structs containing such.
140         op.try_as_mplace()
141     };
142
143     // We know `offset` is relative to the allocation, so we can use `into_parts`.
144     let to_const_value = |mplace: &MPlaceTy<'_>| match mplace.ptr.into_parts() {
145         (Some(alloc_id), offset) => {
146             let alloc = ecx.tcx.global_alloc(alloc_id).unwrap_memory();
147             ConstValue::ByRef { alloc, offset }
148         }
149         (None, offset) => {
150             assert!(mplace.layout.is_zst());
151             assert_eq!(
152                 offset.bytes() % mplace.layout.align.abi.bytes(),
153                 0,
154                 "this MPlaceTy must come from a validated constant, thus we can assume the \
155                 alignment is correct",
156             );
157             ConstValue::Scalar(Scalar::ZST)
158         }
159     };
160     match immediate {
161         Ok(ref mplace) => to_const_value(mplace),
162         // see comment on `let try_as_immediate` above
163         Err(imm) => match *imm {
164             Immediate::Scalar(x) => match x {
165                 ScalarMaybeUninit::Scalar(s) => ConstValue::Scalar(s),
166                 ScalarMaybeUninit::Uninit => to_const_value(&op.assert_mem_place()),
167             },
168             Immediate::ScalarPair(a, b) => {
169                 // We know `offset` is relative to the allocation, so we can use `into_parts`.
170                 let (data, start) =
171                     match ecx.scalar_to_ptr(a.check_init().unwrap()).unwrap().into_parts() {
172                         (Some(alloc_id), offset) => {
173                             (ecx.tcx.global_alloc(alloc_id).unwrap_memory(), offset.bytes())
174                         }
175                         (None, _offset) => (
176                             ecx.tcx.intern_const_alloc(
177                                 Allocation::from_bytes_byte_aligned_immutable(b"" as &[u8]),
178                             ),
179                             0,
180                         ),
181                     };
182                 let len = b.to_machine_usize(ecx).unwrap();
183                 let start = start.try_into().unwrap();
184                 let len: usize = len.try_into().unwrap();
185                 ConstValue::Slice { data, start, end: start + len }
186             }
187         },
188     }
189 }
190
191 #[instrument(skip(tcx), level = "debug")]
192 fn turn_into_const_value<'tcx>(
193     tcx: TyCtxt<'tcx>,
194     constant: ConstAlloc<'tcx>,
195     key: ty::ParamEnvAnd<'tcx, GlobalId<'tcx>>,
196 ) -> ConstValue<'tcx> {
197     let cid = key.value;
198     let def_id = cid.instance.def.def_id();
199     let is_static = tcx.is_static(def_id);
200     let ecx = mk_eval_cx(tcx, tcx.def_span(key.value.instance.def_id()), key.param_env, is_static);
201
202     let mplace = ecx.raw_const_to_mplace(constant).expect(
203         "can only fail if layout computation failed, \
204         which should have given a good error before ever invoking this function",
205     );
206     assert!(
207         !is_static || cid.promoted.is_some(),
208         "the `eval_to_const_value_raw` query should not be used for statics, use `eval_to_allocation` instead"
209     );
210
211     // Turn this into a proper constant.
212     op_to_const(&ecx, &mplace.into())
213 }
214
215 pub fn eval_to_const_value_raw_provider<'tcx>(
216     tcx: TyCtxt<'tcx>,
217     key: ty::ParamEnvAnd<'tcx, GlobalId<'tcx>>,
218 ) -> ::rustc_middle::mir::interpret::EvalToConstValueResult<'tcx> {
219     assert!(key.param_env.is_const());
220     // see comment in eval_to_allocation_raw_provider for what we're doing here
221     if key.param_env.reveal() == Reveal::All {
222         let mut key = key;
223         key.param_env = key.param_env.with_user_facing();
224         match tcx.eval_to_const_value_raw(key) {
225             // try again with reveal all as requested
226             Err(ErrorHandled::TooGeneric) => {}
227             // deduplicate calls
228             other => return other,
229         }
230     }
231
232     // We call `const_eval` for zero arg intrinsics, too, in order to cache their value.
233     // Catch such calls and evaluate them instead of trying to load a constant's MIR.
234     if let ty::InstanceDef::Intrinsic(def_id) = key.value.instance.def {
235         let ty = key.value.instance.ty(tcx, key.param_env);
236         let ty::FnDef(_, substs) = ty.kind() else {
237             bug!("intrinsic with type {:?}", ty);
238         };
239         return eval_nullary_intrinsic(tcx, key.param_env, def_id, substs).map_err(|error| {
240             let span = tcx.def_span(def_id);
241             let error = ConstEvalErr { error: error.into_kind(), stacktrace: vec![], span };
242             error.report_as_error(tcx.at(span), "could not evaluate nullary intrinsic")
243         });
244     }
245
246     tcx.eval_to_allocation_raw(key).map(|val| turn_into_const_value(tcx, val, key))
247 }
248
249 pub fn eval_to_allocation_raw_provider<'tcx>(
250     tcx: TyCtxt<'tcx>,
251     key: ty::ParamEnvAnd<'tcx, GlobalId<'tcx>>,
252 ) -> ::rustc_middle::mir::interpret::EvalToAllocationRawResult<'tcx> {
253     assert!(key.param_env.is_const());
254     // Because the constant is computed twice (once per value of `Reveal`), we are at risk of
255     // reporting the same error twice here. To resolve this, we check whether we can evaluate the
256     // constant in the more restrictive `Reveal::UserFacing`, which most likely already was
257     // computed. For a large percentage of constants that will already have succeeded. Only
258     // associated constants of generic functions will fail due to not enough monomorphization
259     // information being available.
260
261     // In case we fail in the `UserFacing` variant, we just do the real computation.
262     if key.param_env.reveal() == Reveal::All {
263         let mut key = key;
264         key.param_env = key.param_env.with_user_facing();
265         match tcx.eval_to_allocation_raw(key) {
266             // try again with reveal all as requested
267             Err(ErrorHandled::TooGeneric) => {}
268             // deduplicate calls
269             other => return other,
270         }
271     }
272     if cfg!(debug_assertions) {
273         // Make sure we format the instance even if we do not print it.
274         // This serves as a regression test against an ICE on printing.
275         // The next two lines concatenated contain some discussion:
276         // https://rust-lang.zulipchat.com/#narrow/stream/146212-t-compiler.2Fconst-eval/
277         // subject/anon_const_instance_printing/near/135980032
278         let instance = with_no_trimmed_paths!(key.value.instance.to_string());
279         trace!("const eval: {:?} ({})", key, instance);
280     }
281
282     let cid = key.value;
283     let def = cid.instance.def.with_opt_param();
284     let is_static = tcx.is_static(def.did);
285
286     let mut ecx = InterpCx::new(
287         tcx,
288         tcx.def_span(def.did),
289         key.param_env,
290         // Statics (and promoteds inside statics) may access other statics, because unlike consts
291         // they do not have to behave "as if" they were evaluated at runtime.
292         CompileTimeInterpreter::new(tcx.const_eval_limit(), /*can_access_statics:*/ is_static),
293     );
294
295     let res = ecx.load_mir(cid.instance.def, cid.promoted);
296     match res.and_then(|body| eval_body_using_ecx(&mut ecx, cid, &body)) {
297         Err(error) => {
298             let err = ConstEvalErr::new(&ecx, error, None);
299             // Some CTFE errors raise just a lint, not a hard error; see
300             // <https://github.com/rust-lang/rust/issues/71800>.
301             let is_hard_err = if let Some(def) = def.as_local() {
302                 // (Associated) consts only emit a lint, since they might be unused.
303                 !matches!(tcx.def_kind(def.did.to_def_id()), DefKind::Const | DefKind::AssocConst)
304                     // check if the inner InterpError is hard
305                     || err.error.is_hard_err()
306             } else {
307                 // use of broken constant from other crate: always an error
308                 true
309             };
310
311             if is_hard_err {
312                 let msg = if is_static {
313                     Cow::from("could not evaluate static initializer")
314                 } else {
315                     // If the current item has generics, we'd like to enrich the message with the
316                     // instance and its substs: to show the actual compile-time values, in addition to
317                     // the expression, leading to the const eval error.
318                     let instance = &key.value.instance;
319                     if !instance.substs.is_empty() {
320                         let instance = with_no_trimmed_paths!(instance.to_string());
321                         let msg = format!("evaluation of `{}` failed", instance);
322                         Cow::from(msg)
323                     } else {
324                         Cow::from("evaluation of constant value failed")
325                     }
326                 };
327
328                 Err(err.report_as_error(ecx.tcx.at(ecx.cur_span()), &msg))
329             } else {
330                 let hir_id = tcx.hir().local_def_id_to_hir_id(def.as_local().unwrap().did);
331                 Err(err.report_as_lint(
332                     tcx.at(tcx.def_span(def.did)),
333                     "any use of this value will cause an error",
334                     hir_id,
335                     Some(err.span),
336                 ))
337             }
338         }
339         Ok(mplace) => {
340             // Since evaluation had no errors, validate the resulting constant.
341             // This is a separate `try` block to provide more targeted error reporting.
342             let validation = try {
343                 let mut ref_tracking = RefTracking::new(mplace);
344                 let mut inner = false;
345                 while let Some((mplace, path)) = ref_tracking.todo.pop() {
346                     let mode = match tcx.static_mutability(cid.instance.def_id()) {
347                         Some(_) if cid.promoted.is_some() => {
348                             // Promoteds in statics are allowed to point to statics.
349                             CtfeValidationMode::Const { inner, allow_static_ptrs: true }
350                         }
351                         Some(_) => CtfeValidationMode::Regular, // a `static`
352                         None => CtfeValidationMode::Const { inner, allow_static_ptrs: false },
353                     };
354                     ecx.const_validate_operand(&mplace.into(), path, &mut ref_tracking, mode)?;
355                     inner = true;
356                 }
357             };
358             let alloc_id = mplace.ptr.provenance.unwrap();
359             if let Err(error) = validation {
360                 // Validation failed, report an error. This is always a hard error.
361                 let err = ConstEvalErr::new(&ecx, error, None);
362                 Err(err.struct_error(
363                     ecx.tcx,
364                     "it is undefined behavior to use this value",
365                     |diag| {
366                         diag.note(note_on_undefined_behavior_error());
367                         diag.note(&format!(
368                             "the raw bytes of the constant ({}",
369                             display_allocation(
370                                 *ecx.tcx,
371                                 ecx.tcx.global_alloc(alloc_id).unwrap_memory().inner()
372                             )
373                         ));
374                     },
375                 ))
376             } else {
377                 // Convert to raw constant
378                 Ok(ConstAlloc { alloc_id, ty: mplace.layout.ty })
379             }
380         }
381     }
382 }