]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/const_eval/eval_queries.rs
Rollup merge of #75485 - RalfJung:pin, r=nagisa
[rust.git] / src / librustc_mir / 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, ConstValue, GlobalId, Immediate, InternKind,
5     InterpCx, InterpResult, MPlaceTy, MemoryKind, OpTy, RawConst, 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::traits::Reveal;
13 use rustc_middle::ty::{self, subst::Subst, TyCtxt};
14 use rustc_span::source_map::Span;
15 use rustc_target::abi::{Abi, LayoutOf};
16 use std::convert::TryInto;
17
18 pub fn note_on_undefined_behavior_error() -> &'static str {
19     "The rules on what exactly is undefined behavior aren't clear, \
20      so this check might be overzealous. Please open an issue on the rustc \
21      repository if you believe it should not be considered undefined behavior."
22 }
23
24 // Returns a pointer to where the result lives
25 fn eval_body_using_ecx<'mir, 'tcx>(
26     ecx: &mut CompileTimeEvalContext<'mir, 'tcx>,
27     cid: GlobalId<'tcx>,
28     body: &'mir mir::Body<'tcx>,
29 ) -> InterpResult<'tcx, MPlaceTy<'tcx>> {
30     debug!("eval_body_using_ecx: {:?}, {:?}", cid, ecx.param_env);
31     let tcx = *ecx.tcx;
32     let layout = ecx.layout_of(body.return_ty().subst(tcx, cid.instance.substs))?;
33     assert!(!layout.is_unsized());
34     let ret = ecx.allocate(layout, MemoryKind::Stack);
35
36     let name = ty::tls::with(|tcx| tcx.def_path_str(cid.instance.def_id()));
37     let prom = cid.promoted.map_or(String::new(), |p| format!("::promoted[{:?}]", p));
38     trace!("eval_body_using_ecx: pushing stack frame for global: {}{}", name, prom);
39
40     // Assert all args (if any) are zero-sized types; `eval_body_using_ecx` doesn't
41     // make sense if the body is expecting nontrivial arguments.
42     // (The alternative would be to use `eval_fn_call` with an args slice.)
43     for arg in body.args_iter() {
44         let decl = body.local_decls.get(arg).expect("arg missing from local_decls");
45         let layout = ecx.layout_of(decl.ty.subst(tcx, cid.instance.substs))?;
46         assert!(layout.is_zst())
47     }
48
49     ecx.push_stack_frame(
50         cid.instance,
51         body,
52         Some(ret.into()),
53         StackPopCleanup::None { cleanup: false },
54     )?;
55
56     // The main interpreter loop.
57     ecx.run()?;
58
59     // Intern the result
60     // FIXME: since the DefId of a promoted is the DefId of its owner, this
61     // means that promoteds in statics are actually interned like statics!
62     // However, this is also currently crucial because we promote mutable
63     // non-empty slices in statics to extend their lifetime, and this
64     // ensures that they are put into a mutable allocation.
65     // For other kinds of promoteds in statics (like array initializers), this is rather silly.
66     let intern_kind = match tcx.static_mutability(cid.instance.def_id()) {
67         Some(m) => InternKind::Static(m),
68         None if cid.promoted.is_some() => InternKind::Promoted,
69         _ => InternKind::Constant,
70     };
71     intern_const_alloc_recursive(
72         ecx,
73         intern_kind,
74         ret,
75         body.ignore_interior_mut_in_const_validation,
76     );
77
78     debug!("eval_body_using_ecx done: {:?}", *ret);
79     Ok(ret)
80 }
81
82 /// The `InterpCx` is only meant to be used to do field and index projections into constants for
83 /// `simd_shuffle` and const patterns in match arms.
84 ///
85 /// The function containing the `match` that is currently being analyzed may have generic bounds
86 /// that inform us about the generic bounds of the constant. E.g., using an associated constant
87 /// of a function's generic parameter will require knowledge about the bounds on the generic
88 /// parameter. These bounds are passed to `mk_eval_cx` via the `ParamEnv` argument.
89 pub(super) fn mk_eval_cx<'mir, 'tcx>(
90     tcx: TyCtxt<'tcx>,
91     root_span: Span,
92     param_env: ty::ParamEnv<'tcx>,
93     can_access_statics: bool,
94 ) -> CompileTimeEvalContext<'mir, 'tcx> {
95     debug!("mk_eval_cx: {:?}", param_env);
96     InterpCx::new(
97         tcx,
98         root_span,
99         param_env,
100         CompileTimeInterpreter::new(tcx.sess.const_eval_limit()),
101         MemoryExtra { can_access_statics },
102     )
103 }
104
105 pub(super) fn op_to_const<'tcx>(
106     ecx: &CompileTimeEvalContext<'_, 'tcx>,
107     op: OpTy<'tcx>,
108 ) -> ConstValue<'tcx> {
109     // We do not have value optimizations for everything.
110     // Only scalars and slices, since they are very common.
111     // Note that further down we turn scalars of uninitialized bits back to `ByRef`. These can result
112     // from scalar unions that are initialized with one of their zero sized variants. We could
113     // instead allow `ConstValue::Scalar` to store `ScalarMaybeUninit`, but that would affect all
114     // the usual cases of extracting e.g. a `usize`, without there being a real use case for the
115     // `Undef` situation.
116     let try_as_immediate = match op.layout.abi {
117         Abi::Scalar(..) => true,
118         Abi::ScalarPair(..) => match op.layout.ty.kind {
119             ty::Ref(_, inner, _) => match inner.kind {
120                 ty::Slice(elem) => elem == ecx.tcx.types.u8,
121                 ty::Str => true,
122                 _ => false,
123             },
124             _ => false,
125         },
126         _ => false,
127     };
128     let immediate = if try_as_immediate {
129         Err(ecx.read_immediate(op).expect("normalization works on validated constants"))
130     } else {
131         // It is guaranteed that any non-slice scalar pair is actually ByRef here.
132         // When we come back from raw const eval, we are always by-ref. The only way our op here is
133         // by-val is if we are in destructure_const, i.e., if this is (a field of) something that we
134         // "tried to make immediate" before. We wouldn't do that for non-slice scalar pairs or
135         // structs containing such.
136         op.try_as_mplace(ecx)
137     };
138
139     let to_const_value = |mplace: MPlaceTy<'_>| match mplace.ptr {
140         Scalar::Ptr(ptr) => {
141             let alloc = ecx.tcx.global_alloc(ptr.alloc_id).unwrap_memory();
142             ConstValue::ByRef { alloc, offset: ptr.offset }
143         }
144         Scalar::Raw { data, .. } => {
145             assert!(mplace.layout.is_zst());
146             assert_eq!(
147                 data,
148                 mplace.layout.align.abi.bytes().into(),
149                 "this MPlaceTy must come from `try_as_mplace` being used on a zst, so we know what
150                  value this integer address must have",
151             );
152             ConstValue::Scalar(Scalar::zst())
153         }
154     };
155     match immediate {
156         Ok(mplace) => to_const_value(mplace),
157         // see comment on `let try_as_immediate` above
158         Err(imm) => match *imm {
159             Immediate::Scalar(x) => match x {
160                 ScalarMaybeUninit::Scalar(s) => ConstValue::Scalar(s),
161                 ScalarMaybeUninit::Uninit => to_const_value(op.assert_mem_place(ecx)),
162             },
163             Immediate::ScalarPair(a, b) => {
164                 let (data, start) = match a.check_init().unwrap() {
165                     Scalar::Ptr(ptr) => {
166                         (ecx.tcx.global_alloc(ptr.alloc_id).unwrap_memory(), ptr.offset.bytes())
167                     }
168                     Scalar::Raw { .. } => (
169                         ecx.tcx
170                             .intern_const_alloc(Allocation::from_byte_aligned_bytes(b"" as &[u8])),
171                         0,
172                     ),
173                 };
174                 let len = b.to_machine_usize(ecx).unwrap();
175                 let start = start.try_into().unwrap();
176                 let len: usize = len.try_into().unwrap();
177                 ConstValue::Slice { data, start, end: start + len }
178             }
179         },
180     }
181 }
182
183 fn validate_and_turn_into_const<'tcx>(
184     tcx: TyCtxt<'tcx>,
185     constant: RawConst<'tcx>,
186     key: ty::ParamEnvAnd<'tcx, GlobalId<'tcx>>,
187 ) -> ::rustc_middle::mir::interpret::ConstEvalResult<'tcx> {
188     let cid = key.value;
189     let def_id = cid.instance.def.def_id();
190     let is_static = tcx.is_static(def_id);
191     let ecx = mk_eval_cx(tcx, tcx.def_span(key.value.instance.def_id()), key.param_env, is_static);
192     let val = (|| {
193         let mplace = ecx.raw_const_to_mplace(constant)?;
194
195         // FIXME do not validate promoteds until a decision on
196         // https://github.com/rust-lang/rust/issues/67465 is made
197         if cid.promoted.is_none() {
198             let mut ref_tracking = RefTracking::new(mplace);
199             while let Some((mplace, path)) = ref_tracking.todo.pop() {
200                 ecx.const_validate_operand(
201                     mplace.into(),
202                     path,
203                     &mut ref_tracking,
204                     /*may_ref_to_static*/ ecx.memory.extra.can_access_statics,
205                 )?;
206             }
207         }
208         // Now that we validated, turn this into a proper constant.
209         // Statics/promoteds are always `ByRef`, for the rest `op_to_const` decides
210         // whether they become immediates.
211         if is_static || cid.promoted.is_some() {
212             let ptr = mplace.ptr.assert_ptr();
213             Ok(ConstValue::ByRef {
214                 alloc: ecx.tcx.global_alloc(ptr.alloc_id).unwrap_memory(),
215                 offset: ptr.offset,
216             })
217         } else {
218             Ok(op_to_const(&ecx, mplace.into()))
219         }
220     })();
221
222     val.map_err(|error| {
223         let err = ConstEvalErr::new(&ecx, error, None);
224         err.struct_error(ecx.tcx, "it is undefined behavior to use this value", |mut diag| {
225             diag.note(note_on_undefined_behavior_error());
226             diag.emit();
227         })
228     })
229 }
230
231 pub fn const_eval_validated_provider<'tcx>(
232     tcx: TyCtxt<'tcx>,
233     key: ty::ParamEnvAnd<'tcx, GlobalId<'tcx>>,
234 ) -> ::rustc_middle::mir::interpret::ConstEvalResult<'tcx> {
235     // see comment in const_eval_raw_provider for what we're doing here
236     if key.param_env.reveal() == Reveal::All {
237         let mut key = key;
238         key.param_env = key.param_env.with_user_facing();
239         match tcx.const_eval_validated(key) {
240             // try again with reveal all as requested
241             Err(ErrorHandled::TooGeneric) => {}
242             // deduplicate calls
243             other => return other,
244         }
245     }
246
247     // We call `const_eval` for zero arg intrinsics, too, in order to cache their value.
248     // Catch such calls and evaluate them instead of trying to load a constant's MIR.
249     if let ty::InstanceDef::Intrinsic(def_id) = key.value.instance.def {
250         let ty = key.value.instance.ty(tcx, key.param_env);
251         let substs = match ty.kind {
252             ty::FnDef(_, substs) => substs,
253             _ => bug!("intrinsic with type {:?}", ty),
254         };
255         return eval_nullary_intrinsic(tcx, key.param_env, def_id, substs).map_err(|error| {
256             let span = tcx.def_span(def_id);
257             let error = ConstEvalErr { error: error.kind, stacktrace: vec![], span };
258             error.report_as_error(tcx.at(span), "could not evaluate nullary intrinsic")
259         });
260     }
261
262     tcx.const_eval_raw(key).and_then(|val| validate_and_turn_into_const(tcx, val, key))
263 }
264
265 pub fn const_eval_raw_provider<'tcx>(
266     tcx: TyCtxt<'tcx>,
267     key: ty::ParamEnvAnd<'tcx, GlobalId<'tcx>>,
268 ) -> ::rustc_middle::mir::interpret::ConstEvalRawResult<'tcx> {
269     // Because the constant is computed twice (once per value of `Reveal`), we are at risk of
270     // reporting the same error twice here. To resolve this, we check whether we can evaluate the
271     // constant in the more restrictive `Reveal::UserFacing`, which most likely already was
272     // computed. For a large percentage of constants that will already have succeeded. Only
273     // associated constants of generic functions will fail due to not enough monomorphization
274     // information being available.
275
276     // In case we fail in the `UserFacing` variant, we just do the real computation.
277     if key.param_env.reveal() == Reveal::All {
278         let mut key = key;
279         key.param_env = key.param_env.with_user_facing();
280         match tcx.const_eval_raw(key) {
281             // try again with reveal all as requested
282             Err(ErrorHandled::TooGeneric) => {}
283             // deduplicate calls
284             other => return other,
285         }
286     }
287     if cfg!(debug_assertions) {
288         // Make sure we format the instance even if we do not print it.
289         // This serves as a regression test against an ICE on printing.
290         // The next two lines concatenated contain some discussion:
291         // https://rust-lang.zulipchat.com/#narrow/stream/146212-t-compiler.2Fconst-eval/
292         // subject/anon_const_instance_printing/near/135980032
293         let instance = key.value.instance.to_string();
294         trace!("const eval: {:?} ({})", key, instance);
295     }
296
297     let cid = key.value;
298     let def = cid.instance.def.with_opt_param();
299
300     if let Some(def) = def.as_local() {
301         if tcx.has_typeck_results(def.did) {
302             if let Some(error_reported) = tcx.typeck_opt_const_arg(def).tainted_by_errors {
303                 return Err(ErrorHandled::Reported(error_reported));
304             }
305         }
306     }
307
308     let is_static = tcx.is_static(def.did);
309
310     let mut ecx = InterpCx::new(
311         tcx,
312         tcx.def_span(def.did),
313         key.param_env,
314         CompileTimeInterpreter::new(tcx.sess.const_eval_limit()),
315         MemoryExtra { can_access_statics: is_static },
316     );
317
318     let res = ecx.load_mir(cid.instance.def, cid.promoted);
319     res.and_then(|body| eval_body_using_ecx(&mut ecx, cid, &body))
320         .map(|place| RawConst { alloc_id: place.ptr.assert_ptr().alloc_id, ty: place.layout.ty })
321         .map_err(|error| {
322             let err = ConstEvalErr::new(&ecx, error, None);
323             // errors in statics are always emitted as fatal errors
324             if is_static {
325                 // Ensure that if the above error was either `TooGeneric` or `Reported`
326                 // an error must be reported.
327                 let v = err.report_as_error(
328                     ecx.tcx.at(ecx.cur_span()),
329                     "could not evaluate static initializer",
330                 );
331
332                 // If this is `Reveal:All`, then we need to make sure an error is reported but if
333                 // this is `Reveal::UserFacing`, then it's expected that we could get a
334                 // `TooGeneric` error. When we fall back to `Reveal::All`, then it will either
335                 // succeed or we'll report this error then.
336                 if key.param_env.reveal() == Reveal::All {
337                     tcx.sess.delay_span_bug(
338                         err.span,
339                         &format!("static eval failure did not emit an error: {:#?}", v),
340                     );
341                 }
342
343                 v
344             } else if let Some(def) = def.as_local() {
345                 // constant defined in this crate, we can figure out a lint level!
346                 match tcx.def_kind(def.did.to_def_id()) {
347                     // constants never produce a hard error at the definition site. Anything else is
348                     // a backwards compatibility hazard (and will break old versions of winapi for
349                     // sure)
350                     //
351                     // note that validation may still cause a hard error on this very same constant,
352                     // because any code that existed before validation could not have failed
353                     // validation thus preventing such a hard error from being a backwards
354                     // compatibility hazard
355                     DefKind::Const | DefKind::AssocConst => {
356                         let hir_id = tcx.hir().local_def_id_to_hir_id(def.did);
357                         err.report_as_lint(
358                             tcx.at(tcx.def_span(def.did)),
359                             "any use of this value will cause an error",
360                             hir_id,
361                             Some(err.span),
362                         )
363                     }
364                     // promoting runtime code is only allowed to error if it references broken
365                     // constants any other kind of error will be reported to the user as a
366                     // deny-by-default lint
367                     _ => {
368                         if let Some(p) = cid.promoted {
369                             let span = tcx.promoted_mir_of_opt_const_arg(def.to_global())[p].span;
370                             if let err_inval!(ReferencedConstant) = err.error {
371                                 err.report_as_error(
372                                     tcx.at(span),
373                                     "evaluation of constant expression failed",
374                                 )
375                             } else {
376                                 err.report_as_lint(
377                                     tcx.at(span),
378                                     "reaching this expression at runtime will panic or abort",
379                                     tcx.hir().local_def_id_to_hir_id(def.did),
380                                     Some(err.span),
381                                 )
382                             }
383                         // anything else (array lengths, enum initializers, constant patterns) are
384                         // reported as hard errors
385                         } else {
386                             err.report_as_error(
387                                 ecx.tcx.at(ecx.cur_span()),
388                                 "evaluation of constant value failed",
389                             )
390                         }
391                     }
392                 }
393             } else {
394                 // use of broken constant from other crate
395                 err.report_as_error(ecx.tcx.at(ecx.cur_span()), "could not evaluate constant")
396             }
397         })
398 }