rustc_const_eval/const_eval/
intrinsics.rs1use rustc_abi::{Align, Size};
2use rustc_middle::ty::layout::{HasTypingEnv, ValidityRequirement};
3use rustc_middle::ty::{self, FieldInfo};
4use rustc_middle::{mir, throw_machine_stop};
5use rustc_span::{Symbol, bug, span_bug, sym};
6
7use super::error::*;
8use crate::const_eval::{CompileTimeMachine, MemoryKind};
9use crate::interpret::{
10 self, AllocInit, CtfeProvenance, InterpCx, InterpResult, OpTy, PlaceTy, Scalar,
11 ensure_monomorphic_enough, err_inval, interp_ok, throw_ub_format,
12};
13
14impl<'tcx> InterpCx<'tcx, CompileTimeMachine<'tcx>> {
15 pub(crate) fn call_ctfe_intrinsic(
16 &mut self,
17 intrinsic_name: Symbol,
18 instance: ty::Instance<'tcx>,
19 args: &[OpTy<'tcx>],
20 dest: &PlaceTy<'tcx, CtfeProvenance>,
21 target: Option<mir::BasicBlock>,
22 ) -> InterpResult<'tcx, bool> {
23 match intrinsic_name {
24 sym::abort_immediate => {
25 do yeet ::rustc_middle::mir::interpret::InterpErrorKind::MachineStop(Box::new(ConstEvalErrKind::Abort));throw_machine_stop!(ConstEvalErrKind::Abort);
27 }
28 sym::ptr_guaranteed_cmp => {
29 let a = self.read_scalar(&args[0])?;
30 let b = self.read_scalar(&args[1])?;
31 let cmp = self.guaranteed_cmp(a, b)?;
32 self.write_scalar(Scalar::from_u8(cmp), dest)?;
33 }
34 sym::const_allocate => {
35 let size = self.read_scalar(&args[0])?.to_target_usize(self)?;
36 let align = self.read_scalar(&args[1])?.to_target_usize(self)?;
37
38 let align = match Align::from_bytes(align) {
39 Ok(a) => a,
40 Err(err) => {
41 do yeet ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::Ub(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("invalid align passed to `const_allocate`: {0}",
err))
})))throw_ub_format!("invalid align passed to `const_allocate`: {err}")
42 }
43 };
44
45 let ptr = self.allocate_ptr(
46 Size::from_bytes(size),
47 align,
48 interpret::MemoryKind::Machine(MemoryKind::Heap { was_made_global: false }),
49 AllocInit::Uninit,
50 )?;
51 self.write_pointer(ptr, dest)?;
52 }
53 sym::const_deallocate => {
54 let ptr = self.read_pointer(&args[0])?;
55 let size = self.read_scalar(&args[1])?.to_target_usize(self)?;
56 let align = self.read_scalar(&args[2])?.to_target_usize(self)?;
57
58 let size = Size::from_bytes(size);
59 let align = match Align::from_bytes(align) {
60 Ok(a) => a,
61 Err(err) => {
62 do yeet ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::Ub(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("invalid align passed to `const_deallocate`: {0}",
err))
})))throw_ub_format!("invalid align passed to `const_deallocate`: {err}")
63 }
64 };
65
66 let (alloc_id, _, _) = self.ptr_get_alloc_id(ptr, 0)?;
69 let is_allocated_in_another_const = #[allow(non_exhaustive_omitted_patterns)] match self.tcx.try_get_global_alloc(alloc_id)
{
Some(interpret::GlobalAlloc::Memory(_)) => true,
_ => false,
}matches!(
70 self.tcx.try_get_global_alloc(alloc_id),
71 Some(interpret::GlobalAlloc::Memory(_))
72 );
73
74 if !is_allocated_in_another_const {
75 self.deallocate_ptr(
76 ptr,
77 Some((size, align)),
78 interpret::MemoryKind::Machine(MemoryKind::Heap { was_made_global: false }),
79 )?;
80 }
81 }
82
83 sym::const_make_global => {
84 let ptr = self.read_pointer(&args[0])?;
85 self.make_const_heap_ptr_global(ptr)?;
86 self.write_pointer(ptr, dest)?;
87 }
88
89 sym::is_val_statically_known => self.write_scalar(Scalar::from_bool(false), dest)?,
94
95 sym::assert_inhabited
97 | sym::assert_zero_valid
98 | sym::assert_mem_uninitialized_valid => {
99 let ty = instance.args.type_at(0);
100 let requirement =
101 ValidityRequirement::from_rustc_intrinsic(intrinsic_name).unwrap();
102
103 let should_panic = !self
104 .tcx
105 .check_validity_requirement((requirement, self.typing_env().as_query_input(ty)))
106 .map_err(|_| ::rustc_middle::mir::interpret::InterpErrorKind::InvalidProgram(::rustc_middle::mir::interpret::InvalidProgramInfo::TooGeneric)err_inval!(TooGeneric))?;
107
108 if should_panic {
109 let layout = self.layout_of(ty)?;
110
111 let msg = Symbol::intern(&match requirement {
112 _ if layout.is_uninhabited() => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("aborted execution: attempted to instantiate uninhabited type `{0}`",
ty))
})format!(
115 "aborted execution: attempted to instantiate uninhabited type `{ty}`"
116 ),
117 ValidityRequirement::Inhabited => ::rustc_span::macros::bug_impl(None, format_args!("handled earlier"),
Location::caller())bug!("handled earlier"),
118 ValidityRequirement::Zero => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("aborted execution: attempted to zero-initialize type `{0}`, which is invalid",
ty))
})format!(
119 "aborted execution: attempted to zero-initialize type `{ty}`, which is invalid"
120 ),
121 ValidityRequirement::UninitMitigated0x01Fill => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("aborted execution: attempted to leave type `{0}` uninitialized, which is invalid",
ty))
})format!(
122 "aborted execution: attempted to leave type `{ty}` uninitialized, which is invalid"
123 ),
124 ValidityRequirement::Uninit => ::rustc_span::macros::bug_impl(None,
format_args!("assert_uninit_valid doesn\'t exist"), Location::caller())bug!("assert_uninit_valid doesn't exist"),
125 });
126
127 let span = self.caller_location();
128 let (file, line, col) = self.location_triple_for_span(span);
129
130 InterpResult::from(Err::<(), _>(ConstEvalErrKind::Panic {
131 msg,
132 file,
133 line,
134 col,
135 }))?;
136
137 return interp_ok(true);
139 }
140 }
141
142 sym::field_offset => {
143 let frt_ty = instance.args.type_at(0);
144 ensure_monomorphic_enough(frt_ty)?;
145
146 let (ty, variant, field) = if let ty::Adt(def, args) = frt_ty.kind()
147 && let Some(FieldInfo { base, variant_idx, field_idx, .. }) =
148 def.field_representing_type_info(self.tcx.tcx, *args)
149 {
150 (base, variant_idx, field_idx)
151 } else {
152 ::rustc_span::macros::bug_impl(Some(self.cur_span()),
format_args!("expected field representing type, got {0}", frt_ty),
Location::caller())span_bug!(self.cur_span(), "expected field representing type, got {frt_ty}")
153 };
154 let layout = self.layout_of(ty)?;
155 let cx = ty::layout::LayoutCx::new(self.tcx.tcx, self.typing_env());
156
157 let layout = layout.for_variant(&cx, variant);
158 let offset = layout.fields.offset(field.index()).bytes();
159
160 self.write_scalar(Scalar::from_target_usize(offset, self), dest)?;
161 }
162
163 _ => {
164 return interp_ok(false);
165 }
166 }
167
168 self.return_to_block(target)?;
170 interp_ok(true)
171 }
172}