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