]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/const_eval/eval_queries.rs
Update const_forget.rs
[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(),
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.validate_operand(mplace.into(), path, Some(&mut ref_tracking))?;
190             }
191         }
192         // Now that we validated, turn this into a proper constant.
193         // Statics/promoteds are always `ByRef`, for the rest `op_to_const` decides
194         // whether they become immediates.
195         if is_static || cid.promoted.is_some() {
196             let ptr = mplace.ptr.assert_ptr();
197             Ok(ConstValue::ByRef {
198                 alloc: ecx.tcx.alloc_map.lock().unwrap_memory(ptr.alloc_id),
199                 offset: ptr.offset,
200             })
201         } else {
202             Ok(op_to_const(&ecx, mplace.into()))
203         }
204     })();
205
206     val.map_err(|error| {
207         let err = error_to_const_error(&ecx, error);
208         match err.struct_error(ecx.tcx, "it is undefined behavior to use this value", |mut diag| {
209             diag.note(note_on_undefined_behavior_error());
210             diag.emit();
211         }) {
212             Ok(_) => ErrorHandled::Reported,
213             Err(err) => err,
214         }
215     })
216 }
217
218 pub fn const_eval_validated_provider<'tcx>(
219     tcx: TyCtxt<'tcx>,
220     key: ty::ParamEnvAnd<'tcx, GlobalId<'tcx>>,
221 ) -> ::rustc::mir::interpret::ConstEvalResult<'tcx> {
222     // see comment in const_eval_raw_provider for what we're doing here
223     if key.param_env.reveal == Reveal::All {
224         let mut key = key;
225         key.param_env.reveal = Reveal::UserFacing;
226         match tcx.const_eval_validated(key) {
227             // try again with reveal all as requested
228             Err(ErrorHandled::TooGeneric) => {}
229             // dedupliate calls
230             other => return other,
231         }
232     }
233
234     // We call `const_eval` for zero arg intrinsics, too, in order to cache their value.
235     // Catch such calls and evaluate them instead of trying to load a constant's MIR.
236     if let ty::InstanceDef::Intrinsic(def_id) = key.value.instance.def {
237         let ty = key.value.instance.ty_env(tcx, key.param_env);
238         let substs = match ty.kind {
239             ty::FnDef(_, substs) => substs,
240             _ => bug!("intrinsic with type {:?}", ty),
241         };
242         return eval_nullary_intrinsic(tcx, key.param_env, def_id, substs).map_err(|error| {
243             let span = tcx.def_span(def_id);
244             let error = ConstEvalErr { error: error.kind, stacktrace: vec![], span };
245             error.report_as_error(tcx.at(span), "could not evaluate nullary intrinsic")
246         });
247     }
248
249     tcx.const_eval_raw(key).and_then(|val| validate_and_turn_into_const(tcx, val, key))
250 }
251
252 pub fn const_eval_raw_provider<'tcx>(
253     tcx: TyCtxt<'tcx>,
254     key: ty::ParamEnvAnd<'tcx, GlobalId<'tcx>>,
255 ) -> ::rustc::mir::interpret::ConstEvalRawResult<'tcx> {
256     // Because the constant is computed twice (once per value of `Reveal`), we are at risk of
257     // reporting the same error twice here. To resolve this, we check whether we can evaluate the
258     // constant in the more restrictive `Reveal::UserFacing`, which most likely already was
259     // computed. For a large percentage of constants that will already have succeeded. Only
260     // associated constants of generic functions will fail due to not enough monomorphization
261     // information being available.
262
263     // In case we fail in the `UserFacing` variant, we just do the real computation.
264     if key.param_env.reveal == Reveal::All {
265         let mut key = key;
266         key.param_env.reveal = Reveal::UserFacing;
267         match tcx.const_eval_raw(key) {
268             // try again with reveal all as requested
269             Err(ErrorHandled::TooGeneric) => {}
270             // dedupliate calls
271             other => return other,
272         }
273     }
274     if cfg!(debug_assertions) {
275         // Make sure we format the instance even if we do not print it.
276         // This serves as a regression test against an ICE on printing.
277         // The next two lines concatenated contain some discussion:
278         // https://rust-lang.zulipchat.com/#narrow/stream/146212-t-compiler.2Fconst-eval/
279         // subject/anon_const_instance_printing/near/135980032
280         let instance = key.value.instance.to_string();
281         trace!("const eval: {:?} ({})", key, instance);
282     }
283
284     let cid = key.value;
285     let def_id = cid.instance.def.def_id();
286
287     if def_id.is_local()
288         && tcx.has_typeck_tables(def_id)
289         && tcx.typeck_tables_of(def_id).tainted_by_errors
290     {
291         return Err(ErrorHandled::Reported);
292     }
293
294     let is_static = tcx.is_static(def_id);
295
296     let span = tcx.def_span(cid.instance.def_id());
297     let mut ecx = InterpCx::new(
298         tcx.at(span),
299         key.param_env,
300         CompileTimeInterpreter::new(),
301         MemoryExtra { can_access_statics: is_static },
302     );
303
304     let res = ecx.load_mir(cid.instance.def, cid.promoted);
305     res.and_then(|body| eval_body_using_ecx(&mut ecx, cid, *body))
306         .and_then(|place| {
307             Ok(RawConst { alloc_id: place.ptr.assert_ptr().alloc_id, ty: place.layout.ty })
308         })
309         .map_err(|error| {
310             let err = error_to_const_error(&ecx, error);
311             // errors in statics are always emitted as fatal errors
312             if is_static {
313                 // Ensure that if the above error was either `TooGeneric` or `Reported`
314                 // an error must be reported.
315                 let v = err.report_as_error(ecx.tcx, "could not evaluate static initializer");
316
317                 // If this is `Reveal:All`, then we need to make sure an error is reported but if
318                 // this is `Reveal::UserFacing`, then it's expected that we could get a
319                 // `TooGeneric` error. When we fall back to `Reveal::All`, then it will either
320                 // succeed or we'll report this error then.
321                 if key.param_env.reveal == Reveal::All {
322                     tcx.sess.delay_span_bug(
323                         err.span,
324                         &format!("static eval failure did not emit an error: {:#?}", v),
325                     );
326                 }
327
328                 v
329             } else if def_id.is_local() {
330                 // constant defined in this crate, we can figure out a lint level!
331                 match tcx.def_kind(def_id) {
332                     // constants never produce a hard error at the definition site. Anything else is
333                     // a backwards compatibility hazard (and will break old versions of winapi for
334                     // sure)
335                     //
336                     // note that validation may still cause a hard error on this very same constant,
337                     // because any code that existed before validation could not have failed
338                     // validation thus preventing such a hard error from being a backwards
339                     // compatibility hazard
340                     Some(DefKind::Const) | Some(DefKind::AssocConst) => {
341                         let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
342                         err.report_as_lint(
343                             tcx.at(tcx.def_span(def_id)),
344                             "any use of this value will cause an error",
345                             hir_id,
346                             Some(err.span),
347                         )
348                     }
349                     // promoting runtime code is only allowed to error if it references broken
350                     // constants any other kind of error will be reported to the user as a
351                     // deny-by-default lint
352                     _ => {
353                         if let Some(p) = cid.promoted {
354                             let span = tcx.promoted_mir(def_id)[p].span;
355                             if let err_inval!(ReferencedConstant) = err.error {
356                                 err.report_as_error(
357                                     tcx.at(span),
358                                     "evaluation of constant expression failed",
359                                 )
360                             } else {
361                                 err.report_as_lint(
362                                     tcx.at(span),
363                                     "reaching this expression at runtime will panic or abort",
364                                     tcx.hir().as_local_hir_id(def_id).unwrap(),
365                                     Some(err.span),
366                                 )
367                             }
368                         // anything else (array lengths, enum initializers, constant patterns) are
369                         // reported as hard errors
370                         } else {
371                             err.report_as_error(ecx.tcx, "evaluation of constant value failed")
372                         }
373                     }
374                 }
375             } else {
376                 // use of broken constant from other crate
377                 err.report_as_error(ecx.tcx, "could not evaluate constant")
378             }
379         })
380 }