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