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