]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_const_eval/src/const_eval/machine.rs
Auto merge of #91403 - cjgillot:inherit-async, r=oli-obk
[rust.git] / compiler / rustc_const_eval / src / const_eval / machine.rs
1 use rustc_errors::ErrorReported;
2 use rustc_hir::def::DefKind;
3 use rustc_middle::mir;
4 use rustc_middle::ty::{self, Ty};
5 use std::borrow::Borrow;
6 use std::collections::hash_map::Entry;
7 use std::hash::Hash;
8
9 use rustc_data_structures::fx::FxHashMap;
10 use std::fmt;
11
12 use rustc_ast::Mutability;
13 use rustc_hir::def_id::DefId;
14 use rustc_middle::mir::AssertMessage;
15 use rustc_session::Limit;
16 use rustc_span::symbol::{sym, Symbol};
17 use rustc_target::abi::{Align, Size};
18 use rustc_target::spec::abi::Abi;
19
20 use crate::interpret::{
21     self, compile_time_machine, AllocId, Allocation, Frame, ImmTy, InterpCx, InterpResult, OpTy,
22     PlaceTy, Scalar, StackPopUnwind,
23 };
24
25 use super::error::*;
26
27 impl<'mir, 'tcx> InterpCx<'mir, 'tcx, CompileTimeInterpreter<'mir, 'tcx>> {
28     /// "Intercept" a function call to a panic-related function
29     /// because we have something special to do for it.
30     /// If this returns successfully (`Ok`), the function should just be evaluated normally.
31     fn hook_special_const_fn(
32         &mut self,
33         instance: ty::Instance<'tcx>,
34         args: &[OpTy<'tcx>],
35     ) -> InterpResult<'tcx, Option<ty::Instance<'tcx>>> {
36         // All `#[rustc_do_not_const_check]` functions should be hooked here.
37         let def_id = instance.def_id();
38
39         if Some(def_id) == self.tcx.lang_items().const_eval_select() {
40             // redirect to const_eval_select_ct
41             if let Some(const_eval_select) = self.tcx.lang_items().const_eval_select_ct() {
42                 return Ok(Some(
43                     ty::Instance::resolve(
44                         *self.tcx,
45                         ty::ParamEnv::reveal_all(),
46                         const_eval_select,
47                         instance.substs,
48                     )
49                     .unwrap()
50                     .unwrap(),
51                 ));
52             }
53         } else if Some(def_id) == self.tcx.lang_items().panic_display()
54             || Some(def_id) == self.tcx.lang_items().begin_panic_fn()
55         {
56             // &str or &&str
57             assert!(args.len() == 1);
58
59             let mut msg_place = self.deref_operand(&args[0])?;
60             while msg_place.layout.ty.is_ref() {
61                 msg_place = self.deref_operand(&msg_place.into())?;
62             }
63
64             let msg = Symbol::intern(self.read_str(&msg_place)?);
65             let span = self.find_closest_untracked_caller_location();
66             let (file, line, col) = self.location_triple_for_span(span);
67             return Err(ConstEvalErrKind::Panic { msg, file, line, col }.into());
68         } else if Some(def_id) == self.tcx.lang_items().panic_fmt() {
69             // For panic_fmt, call const_panic_fmt instead.
70             if let Some(const_panic_fmt) = self.tcx.lang_items().const_panic_fmt() {
71                 return Ok(Some(
72                     ty::Instance::resolve(
73                         *self.tcx,
74                         ty::ParamEnv::reveal_all(),
75                         const_panic_fmt,
76                         self.tcx.intern_substs(&[]),
77                     )
78                     .unwrap()
79                     .unwrap(),
80                 ));
81             }
82         }
83         Ok(None)
84     }
85 }
86
87 /// Extra machine state for CTFE, and the Machine instance
88 pub struct CompileTimeInterpreter<'mir, 'tcx> {
89     /// For now, the number of terminators that can be evaluated before we throw a resource
90     /// exhaustion error.
91     ///
92     /// Setting this to `0` disables the limit and allows the interpreter to run forever.
93     pub steps_remaining: usize,
94
95     /// The virtual call stack.
96     pub(crate) stack: Vec<Frame<'mir, 'tcx, AllocId, ()>>,
97 }
98
99 #[derive(Copy, Clone, Debug)]
100 pub struct MemoryExtra {
101     /// We need to make sure consts never point to anything mutable, even recursively. That is
102     /// relied on for pattern matching on consts with references.
103     /// To achieve this, two pieces have to work together:
104     /// * Interning makes everything outside of statics immutable.
105     /// * Pointers to allocations inside of statics can never leak outside, to a non-static global.
106     /// This boolean here controls the second part.
107     pub(super) can_access_statics: bool,
108 }
109
110 impl<'mir, 'tcx> CompileTimeInterpreter<'mir, 'tcx> {
111     pub(super) fn new(const_eval_limit: Limit) -> Self {
112         CompileTimeInterpreter { steps_remaining: const_eval_limit.0, stack: Vec::new() }
113     }
114 }
115
116 impl<K: Hash + Eq, V> interpret::AllocMap<K, V> for FxHashMap<K, V> {
117     #[inline(always)]
118     fn contains_key<Q: ?Sized + Hash + Eq>(&mut self, k: &Q) -> bool
119     where
120         K: Borrow<Q>,
121     {
122         FxHashMap::contains_key(self, k)
123     }
124
125     #[inline(always)]
126     fn insert(&mut self, k: K, v: V) -> Option<V> {
127         FxHashMap::insert(self, k, v)
128     }
129
130     #[inline(always)]
131     fn remove<Q: ?Sized + Hash + Eq>(&mut self, k: &Q) -> Option<V>
132     where
133         K: Borrow<Q>,
134     {
135         FxHashMap::remove(self, k)
136     }
137
138     #[inline(always)]
139     fn filter_map_collect<T>(&self, mut f: impl FnMut(&K, &V) -> Option<T>) -> Vec<T> {
140         self.iter().filter_map(move |(k, v)| f(k, &*v)).collect()
141     }
142
143     #[inline(always)]
144     fn get_or<E>(&self, k: K, vacant: impl FnOnce() -> Result<V, E>) -> Result<&V, E> {
145         match self.get(&k) {
146             Some(v) => Ok(v),
147             None => {
148                 vacant()?;
149                 bug!("The CTFE machine shouldn't ever need to extend the alloc_map when reading")
150             }
151         }
152     }
153
154     #[inline(always)]
155     fn get_mut_or<E>(&mut self, k: K, vacant: impl FnOnce() -> Result<V, E>) -> Result<&mut V, E> {
156         match self.entry(k) {
157             Entry::Occupied(e) => Ok(e.into_mut()),
158             Entry::Vacant(e) => {
159                 let v = vacant()?;
160                 Ok(e.insert(v))
161             }
162         }
163     }
164 }
165
166 crate type CompileTimeEvalContext<'mir, 'tcx> =
167     InterpCx<'mir, 'tcx, CompileTimeInterpreter<'mir, 'tcx>>;
168
169 #[derive(Debug, PartialEq, Eq, Copy, Clone)]
170 pub enum MemoryKind {
171     Heap,
172 }
173
174 impl fmt::Display for MemoryKind {
175     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
176         match self {
177             MemoryKind::Heap => write!(f, "heap allocation"),
178         }
179     }
180 }
181
182 impl interpret::MayLeak for MemoryKind {
183     #[inline(always)]
184     fn may_leak(self) -> bool {
185         match self {
186             MemoryKind::Heap => false,
187         }
188     }
189 }
190
191 impl interpret::MayLeak for ! {
192     #[inline(always)]
193     fn may_leak(self) -> bool {
194         // `self` is uninhabited
195         self
196     }
197 }
198
199 impl<'mir, 'tcx: 'mir> CompileTimeEvalContext<'mir, 'tcx> {
200     fn guaranteed_eq(&mut self, a: Scalar, b: Scalar) -> bool {
201         match (a, b) {
202             // Comparisons between integers are always known.
203             (Scalar::Int { .. }, Scalar::Int { .. }) => a == b,
204             // Equality with integers can never be known for sure.
205             (Scalar::Int { .. }, Scalar::Ptr(..)) | (Scalar::Ptr(..), Scalar::Int { .. }) => false,
206             // FIXME: return `true` for when both sides are the same pointer, *except* that
207             // some things (like functions and vtables) do not have stable addresses
208             // so we need to be careful around them (see e.g. #73722).
209             (Scalar::Ptr(..), Scalar::Ptr(..)) => false,
210         }
211     }
212
213     fn guaranteed_ne(&mut self, a: Scalar, b: Scalar) -> bool {
214         match (a, b) {
215             // Comparisons between integers are always known.
216             (Scalar::Int(_), Scalar::Int(_)) => a != b,
217             // Comparisons of abstract pointers with null pointers are known if the pointer
218             // is in bounds, because if they are in bounds, the pointer can't be null.
219             // Inequality with integers other than null can never be known for sure.
220             (Scalar::Int(int), Scalar::Ptr(ptr, _)) | (Scalar::Ptr(ptr, _), Scalar::Int(int)) => {
221                 int.is_null() && !self.memory.ptr_may_be_null(ptr.into())
222             }
223             // FIXME: return `true` for at least some comparisons where we can reliably
224             // determine the result of runtime inequality tests at compile-time.
225             // Examples include comparison of addresses in different static items.
226             (Scalar::Ptr(..), Scalar::Ptr(..)) => false,
227         }
228     }
229 }
230
231 impl<'mir, 'tcx> interpret::Machine<'mir, 'tcx> for CompileTimeInterpreter<'mir, 'tcx> {
232     compile_time_machine!(<'mir, 'tcx>);
233
234     type MemoryKind = MemoryKind;
235
236     type MemoryExtra = MemoryExtra;
237
238     const PANIC_ON_ALLOC_FAIL: bool = false; // will be raised as a proper error
239
240     fn load_mir(
241         ecx: &InterpCx<'mir, 'tcx, Self>,
242         instance: ty::InstanceDef<'tcx>,
243     ) -> InterpResult<'tcx, &'tcx mir::Body<'tcx>> {
244         match instance {
245             ty::InstanceDef::Item(def) => {
246                 if ecx.tcx.is_ctfe_mir_available(def.did) {
247                     Ok(ecx.tcx.mir_for_ctfe_opt_const_arg(def))
248                 } else if ecx.tcx.def_kind(def.did) == DefKind::AssocConst {
249                     ecx.tcx.sess.delay_span_bug(
250                         rustc_span::DUMMY_SP,
251                         "This is likely a const item that is missing from its impl",
252                     );
253                     throw_inval!(AlreadyReported(ErrorReported {}));
254                 } else {
255                     let path = ecx.tcx.def_path_str(def.did);
256                     Err(ConstEvalErrKind::NeedsRfc(format!("calling extern function `{}`", path))
257                         .into())
258                 }
259             }
260             _ => Ok(ecx.tcx.instance_mir(instance)),
261         }
262     }
263
264     fn find_mir_or_eval_fn(
265         ecx: &mut InterpCx<'mir, 'tcx, Self>,
266         instance: ty::Instance<'tcx>,
267         _abi: Abi,
268         args: &[OpTy<'tcx>],
269         _ret: Option<(&PlaceTy<'tcx>, mir::BasicBlock)>,
270         _unwind: StackPopUnwind, // unwinding is not supported in consts
271     ) -> InterpResult<'tcx, Option<(&'mir mir::Body<'tcx>, ty::Instance<'tcx>)>> {
272         debug!("find_mir_or_eval_fn: {:?}", instance);
273
274         // Only check non-glue functions
275         if let ty::InstanceDef::Item(def) = instance.def {
276             // Execution might have wandered off into other crates, so we cannot do a stability-
277             // sensitive check here.  But we can at least rule out functions that are not const
278             // at all.
279             if !ecx.tcx.is_const_fn_raw(def.did) {
280                 // allow calling functions marked with #[default_method_body_is_const].
281                 if !ecx.tcx.has_attr(def.did, sym::default_method_body_is_const) {
282                     // We certainly do *not* want to actually call the fn
283                     // though, so be sure we return here.
284                     throw_unsup_format!("calling non-const function `{}`", instance)
285                 }
286             }
287
288             if let Some(new_instance) = ecx.hook_special_const_fn(instance, args)? {
289                 // We call another const fn instead.
290                 // However, we return the *original* instance to make backtraces work out
291                 // (and we hope this does not confuse the FnAbi checks too much).
292                 return Ok(Self::find_mir_or_eval_fn(
293                     ecx,
294                     new_instance,
295                     _abi,
296                     args,
297                     _ret,
298                     _unwind,
299                 )?
300                 .map(|(body, _instance)| (body, instance)));
301             }
302         }
303         // This is a const fn. Call it.
304         Ok(Some((ecx.load_mir(instance.def, None)?, instance)))
305     }
306
307     fn call_intrinsic(
308         ecx: &mut InterpCx<'mir, 'tcx, Self>,
309         instance: ty::Instance<'tcx>,
310         args: &[OpTy<'tcx>],
311         ret: Option<(&PlaceTy<'tcx>, mir::BasicBlock)>,
312         _unwind: StackPopUnwind,
313     ) -> InterpResult<'tcx> {
314         // Shared intrinsics.
315         if ecx.emulate_intrinsic(instance, args, ret)? {
316             return Ok(());
317         }
318         let intrinsic_name = ecx.tcx.item_name(instance.def_id());
319
320         // CTFE-specific intrinsics.
321         let (dest, ret) = match ret {
322             None => {
323                 return Err(ConstEvalErrKind::NeedsRfc(format!(
324                     "calling intrinsic `{}`",
325                     intrinsic_name
326                 ))
327                 .into());
328             }
329             Some(p) => p,
330         };
331         match intrinsic_name {
332             sym::ptr_guaranteed_eq | sym::ptr_guaranteed_ne => {
333                 let a = ecx.read_immediate(&args[0])?.to_scalar()?;
334                 let b = ecx.read_immediate(&args[1])?.to_scalar()?;
335                 let cmp = if intrinsic_name == sym::ptr_guaranteed_eq {
336                     ecx.guaranteed_eq(a, b)
337                 } else {
338                     ecx.guaranteed_ne(a, b)
339                 };
340                 ecx.write_scalar(Scalar::from_bool(cmp), dest)?;
341             }
342             sym::const_allocate => {
343                 let size = ecx.read_scalar(&args[0])?.to_machine_usize(ecx)?;
344                 let align = ecx.read_scalar(&args[1])?.to_machine_usize(ecx)?;
345
346                 let align = match Align::from_bytes(align) {
347                     Ok(a) => a,
348                     Err(err) => throw_ub_format!("align has to be a power of 2, {}", err),
349                 };
350
351                 let ptr = ecx.memory.allocate(
352                     Size::from_bytes(size as u64),
353                     align,
354                     interpret::MemoryKind::Machine(MemoryKind::Heap),
355                 )?;
356                 ecx.write_pointer(ptr, dest)?;
357             }
358             sym::const_deallocate => {
359                 let ptr = ecx.read_pointer(&args[0])?;
360                 let size = ecx.read_scalar(&args[1])?.to_machine_usize(ecx)?;
361                 let align = ecx.read_scalar(&args[2])?.to_machine_usize(ecx)?;
362
363                 let size = Size::from_bytes(size);
364                 let align = match Align::from_bytes(align) {
365                     Ok(a) => a,
366                     Err(err) => throw_ub_format!("align has to be a power of 2, {}", err),
367                 };
368
369                 // If an allocation is created in an another const,
370                 // we don't deallocate it.
371                 let (alloc_id, _, _) = ecx.memory.ptr_get_alloc(ptr)?;
372                 let is_allocated_in_another_const = matches!(
373                     ecx.tcx.get_global_alloc(alloc_id),
374                     Some(interpret::GlobalAlloc::Memory(_))
375                 );
376
377                 if !is_allocated_in_another_const {
378                     ecx.memory.deallocate(
379                         ptr,
380                         Some((size, align)),
381                         interpret::MemoryKind::Machine(MemoryKind::Heap),
382                     )?;
383                 }
384             }
385             _ => {
386                 return Err(ConstEvalErrKind::NeedsRfc(format!(
387                     "calling intrinsic `{}`",
388                     intrinsic_name
389                 ))
390                 .into());
391             }
392         }
393
394         ecx.go_to_block(ret);
395         Ok(())
396     }
397
398     fn assert_panic(
399         ecx: &mut InterpCx<'mir, 'tcx, Self>,
400         msg: &AssertMessage<'tcx>,
401         _unwind: Option<mir::BasicBlock>,
402     ) -> InterpResult<'tcx> {
403         use rustc_middle::mir::AssertKind::*;
404         // Convert `AssertKind<Operand>` to `AssertKind<Scalar>`.
405         let eval_to_int =
406             |op| ecx.read_immediate(&ecx.eval_operand(op, None)?).map(|x| x.to_const_int());
407         let err = match msg {
408             BoundsCheck { ref len, ref index } => {
409                 let len = eval_to_int(len)?;
410                 let index = eval_to_int(index)?;
411                 BoundsCheck { len, index }
412             }
413             Overflow(op, l, r) => Overflow(*op, eval_to_int(l)?, eval_to_int(r)?),
414             OverflowNeg(op) => OverflowNeg(eval_to_int(op)?),
415             DivisionByZero(op) => DivisionByZero(eval_to_int(op)?),
416             RemainderByZero(op) => RemainderByZero(eval_to_int(op)?),
417             ResumedAfterReturn(generator_kind) => ResumedAfterReturn(*generator_kind),
418             ResumedAfterPanic(generator_kind) => ResumedAfterPanic(*generator_kind),
419         };
420         Err(ConstEvalErrKind::AssertFailure(err).into())
421     }
422
423     fn abort(_ecx: &mut InterpCx<'mir, 'tcx, Self>, msg: String) -> InterpResult<'tcx, !> {
424         Err(ConstEvalErrKind::Abort(msg).into())
425     }
426
427     fn binary_ptr_op(
428         _ecx: &InterpCx<'mir, 'tcx, Self>,
429         _bin_op: mir::BinOp,
430         _left: &ImmTy<'tcx>,
431         _right: &ImmTy<'tcx>,
432     ) -> InterpResult<'tcx, (Scalar, bool, Ty<'tcx>)> {
433         Err(ConstEvalErrKind::NeedsRfc("pointer arithmetic or comparison".to_string()).into())
434     }
435
436     fn before_terminator(ecx: &mut InterpCx<'mir, 'tcx, Self>) -> InterpResult<'tcx> {
437         // The step limit has already been hit in a previous call to `before_terminator`.
438         if ecx.machine.steps_remaining == 0 {
439             return Ok(());
440         }
441
442         ecx.machine.steps_remaining -= 1;
443         if ecx.machine.steps_remaining == 0 {
444             throw_exhaust!(StepLimitReached)
445         }
446
447         Ok(())
448     }
449
450     #[inline(always)]
451     fn init_frame_extra(
452         ecx: &mut InterpCx<'mir, 'tcx, Self>,
453         frame: Frame<'mir, 'tcx>,
454     ) -> InterpResult<'tcx, Frame<'mir, 'tcx>> {
455         // Enforce stack size limit. Add 1 because this is run before the new frame is pushed.
456         if !ecx.recursion_limit.value_within_limit(ecx.stack().len() + 1) {
457             throw_exhaust!(StackFrameLimitReached)
458         } else {
459             Ok(frame)
460         }
461     }
462
463     #[inline(always)]
464     fn stack<'a>(
465         ecx: &'a InterpCx<'mir, 'tcx, Self>,
466     ) -> &'a [Frame<'mir, 'tcx, Self::PointerTag, Self::FrameExtra>] {
467         &ecx.machine.stack
468     }
469
470     #[inline(always)]
471     fn stack_mut<'a>(
472         ecx: &'a mut InterpCx<'mir, 'tcx, Self>,
473     ) -> &'a mut Vec<Frame<'mir, 'tcx, Self::PointerTag, Self::FrameExtra>> {
474         &mut ecx.machine.stack
475     }
476
477     fn before_access_global(
478         memory_extra: &MemoryExtra,
479         alloc_id: AllocId,
480         allocation: &Allocation,
481         static_def_id: Option<DefId>,
482         is_write: bool,
483     ) -> InterpResult<'tcx> {
484         if is_write {
485             // Write access. These are never allowed, but we give a targeted error message.
486             if allocation.mutability == Mutability::Not {
487                 Err(err_ub!(WriteToReadOnly(alloc_id)).into())
488             } else {
489                 Err(ConstEvalErrKind::ModifiedGlobal.into())
490             }
491         } else {
492             // Read access. These are usually allowed, with some exceptions.
493             if memory_extra.can_access_statics {
494                 // Machine configuration allows us read from anything (e.g., `static` initializer).
495                 Ok(())
496             } else if static_def_id.is_some() {
497                 // Machine configuration does not allow us to read statics
498                 // (e.g., `const` initializer).
499                 // See const_eval::machine::MemoryExtra::can_access_statics for why
500                 // this check is so important: if we could read statics, we could read pointers
501                 // to mutable allocations *inside* statics. These allocations are not themselves
502                 // statics, so pointers to them can get around the check in `validity.rs`.
503                 Err(ConstEvalErrKind::ConstAccessesStatic.into())
504             } else {
505                 // Immutable global, this read is fine.
506                 // But make sure we never accept a read from something mutable, that would be
507                 // unsound. The reason is that as the content of this allocation may be different
508                 // now and at run-time, so if we permit reading now we might return the wrong value.
509                 assert_eq!(allocation.mutability, Mutability::Not);
510                 Ok(())
511             }
512         }
513     }
514 }
515
516 // Please do not add any code below the above `Machine` trait impl. I (oli-obk) plan more cleanups
517 // so we can end up having a file with just that impl, but for now, let's keep the impl discoverable
518 // at the bottom of this file.