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