Skip to main content

miri/intrinsics/
mod.rs

1#![warn(clippy::arithmetic_side_effects)]
2
3mod aarch64;
4mod loongarch;
5mod math;
6mod simd;
7mod x86;
8
9#[rustfmt::skip] // prevent `use` reordering
10use rand::RngExt;
11use rustc_abi::{Endian, Size};
12use rustc_middle::ty::Intrinsic;
13use rustc_middle::{mir, ty};
14use rustc_span::sym;
15use rustc_target::spec::Arch;
16
17use self::math::EvalContextExt as _;
18use self::simd::EvalContextExt as _;
19use crate::*;
20
21/// Check that the number of args is what we expect.
22fn check_intrinsic_arg_count<'a, 'tcx, const N: usize>(
23    args: &'a [OpTy<'tcx>],
24) -> InterpResult<'tcx, &'a [OpTy<'tcx>; N]>
25where
26    &'a [OpTy<'tcx>; N]: TryFrom<&'a [OpTy<'tcx>]>,
27{
28    if let Ok(ops) = args.try_into() {
29        return interp_ok(ops);
30    }
31    throw_ub_format!(
32        "incorrect number of arguments for intrinsic: got {}, expected {}",
33        args.len(),
34        N
35    )
36}
37
38impl<'tcx> EvalContextExt<'tcx> for crate::MiriInterpCx<'tcx> {}
39pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> {
40    fn call_intrinsic(
41        &mut self,
42        instance: ty::Instance<'tcx>,
43        args: &[OpTy<'tcx>],
44        dest: &PlaceTy<'tcx>,
45        ret: Option<mir::BasicBlock>,
46        unwind: mir::UnwindAction,
47    ) -> InterpResult<'tcx, Option<ty::Instance<'tcx>>> {
48        let ecx = self.eval_context_mut();
49
50        // See if the core engine can handle this intrinsic.
51        if ecx.eval_intrinsic(instance, args, dest, ret)? {
52            return interp_ok(None);
53        }
54
55        let intrinsic = ecx.tcx.intrinsic(instance.def_id()).unwrap();
56        let res = match intrinsic.name {
57            Intrinsic::Rustc(name) =>
58                ecx.emulate_intrinsic_by_name(name.as_str(), instance.args, args, dest, ret)?,
59            Intrinsic::Backend { .. } => EmulateItemResult::NotSupported,
60        };
61        res.jump_to_next_block(ecx, dest, ret, Some(unwind), |ecx| {
62            // We haven't handled the intrinsic, let's see if we can use a fallback body.
63            if intrinsic.must_be_overridden {
64                throw_unsup_format!("unimplemented intrinsic: `{}`", intrinsic.name)
65            }
66            let intrinsic_fallback_is_spec = ecx
67                .tcx
68                .tool_attrs(
69                    instance.def_id(),
70                    &[sym::miri, sym::intrinsic_fallback_is_spec],
71                )
72                .next()
73                .is_some();
74            if !intrinsic_fallback_is_spec {
75                throw_unsup_format!(
76                    "Miri can only use intrinsic fallback bodies that exactly reflect the specification: \
77                    they fully check for UB and are as non-deterministic as possible. \
78                    After verifying that `{}` does so, add the `#[miri::intrinsic_fallback_is_spec]` attribute to it; \
79                    also ping @rust-lang/miri when you do that",
80                    intrinsic.name
81                );
82            }
83            interp_ok(Some(ty::Instance {
84                def: ty::InstanceKind::Item(instance.def_id()),
85                args: instance.args,
86            }))
87        })
88    }
89
90    /// Emulates a Miri-supported intrinsic (not supported by the core engine).
91    /// Returns `Ok(true)` if the intrinsic was handled.
92    fn emulate_intrinsic_by_name(
93        &mut self,
94        intrinsic_name: &str,
95        generic_args: ty::GenericArgs<'tcx>,
96        args: &[OpTy<'tcx>],
97        dest: &PlaceTy<'tcx>,
98        ret: Option<mir::BasicBlock>,
99    ) -> InterpResult<'tcx, EmulateItemResult> {
100        let ecx = self.eval_context_mut();
101
102        if let Some(name) = intrinsic_name.strip_prefix("simd_") {
103            return ecx.emulate_simd_intrinsic(name, args, dest);
104        }
105
106        match intrinsic_name {
107            // Basic control flow
108            "abort_immediate" => {
109                // Note that `abort_immediate` is also hooked separately in CTFE.
110                throw_machine_stop!(TerminationInfo::Abort(
111                    "the program aborted execution".to_owned()
112                ));
113            }
114            "catch_unwind" => {
115                let [try_fn, data, catch_fn] = check_intrinsic_arg_count(args)?;
116                ecx.handle_catch_unwind(try_fn, data, catch_fn, dest, ret)?;
117                // This pushed a stack frame, don't jump to `ret`.
118                return interp_ok(EmulateItemResult::AlreadyJumped);
119            }
120
121            // Memory model / provenance manipulation
122            "ptr_mask" => {
123                let [ptr, mask] = check_intrinsic_arg_count(args)?;
124
125                let ptr = ecx.read_pointer(ptr)?;
126                let mask = ecx.read_target_usize(mask)?;
127
128                let masked_addr = Size::from_bytes(ptr.addr().bytes() & mask);
129
130                ecx.write_pointer(Pointer::new(ptr.provenance, masked_addr), dest)?;
131            }
132
133            // We want to return either `true` or `false` at random, or else something like
134            // ```
135            // if !is_val_statically_known(0) { unreachable_unchecked(); }
136            // ```
137            // Would not be considered UB, or the other way around (`is_val_statically_known(0)`).
138            "is_val_statically_known" => {
139                let [_arg] = check_intrinsic_arg_count(args)?;
140                // FIXME: should we check for validity here? It's tricky because we do not have a
141                // place. Codegen does not seem to set any attributes like `noundef` for intrinsic
142                // calls, so we don't *have* to do anything.
143                let branch: bool = ecx.machine.rng.get_mut().random();
144                ecx.write_scalar(Scalar::from_bool(branch), dest)?;
145            }
146
147            // Other
148            "breakpoint" => {
149                let [] = check_intrinsic_arg_count(args)?;
150                // normally this would raise a SIGTRAP, which aborts if no debugger is connected
151                throw_machine_stop!(TerminationInfo::Abort(format!("trace/breakpoint trap")))
152            }
153
154            "assert_inhabited" | "assert_zero_valid" | "assert_mem_uninitialized_valid" => {
155                // Make these a NOP, so we get the better Miri-native error messages.
156            }
157
158            _ => return ecx.emulate_math_intrinsic(intrinsic_name, generic_args, args, dest),
159        }
160
161        interp_ok(EmulateItemResult::NeedsReturn)
162    }
163
164    fn call_llvm_intrinsic(
165        &mut self,
166        instance: ty::Instance<'tcx>,
167        args: &[OpTy<'tcx>],
168        dest: &PlaceTy<'tcx>,
169        ret: Option<mir::BasicBlock>,
170    ) -> InterpResult<'tcx> {
171        let ecx = self.eval_context_mut();
172
173        let link_name = ecx.tcx.codegen_fn_attrs(instance.def_id()).symbol_name.unwrap();
174
175        // These are anyway mostly vector intrinsics and vectors live in memory.
176        let dest = ecx.force_allocation(dest)?;
177
178        let res = 'handled: {
179            match link_name.as_str() {
180                // LLVM intrinsics
181                "llvm.prefetch.p0" => {
182                    let [p, rw, loc, ty] = ecx.check_shim_sig_llvm_intrinsic(link_name, args)?;
183
184                    let _ = ecx.read_pointer(p)?;
185                    let rw = ecx.read_scalar(rw)?.to_i32()?;
186                    let loc = ecx.read_scalar(loc)?.to_i32()?;
187                    let ty = ecx.read_scalar(ty)?.to_i32()?;
188
189                    if ty == 1 {
190                        // Data cache prefetch.
191                        // Notably, we do not have to check the pointer, this operation is never UB!
192
193                        if !matches!(rw, 0 | 1) {
194                            throw_unsup_format!(
195                                "invalid `rw` value passed to `llvm.prefetch`: {rw}"
196                            );
197                        }
198                        if !matches!(loc, 0..=3) {
199                            throw_unsup_format!(
200                                "invalid `loc` value passed to `llvm.prefetch`: {loc}"
201                            );
202                        }
203                    } else {
204                        throw_unsup_format!("unsupported `llvm.prefetch` type argument: {ty}");
205                    }
206                }
207                // Used to implement the x86 `_mm{,256,512}_popcnt_epi{8,16,32,64}` and wasm
208                // `{i,u}8x16_popcnt` functions.
209                name if name.starts_with("llvm.ctpop.v")
210                    && ecx.tcx.sess.target.endian == Endian::Little =>
211                {
212                    let [op] = ecx.check_shim_sig_llvm_intrinsic(link_name, args)?;
213
214                    let (op, op_len) = ecx.project_to_simd(op)?;
215                    let (dest, dest_len) = ecx.project_to_simd(&dest)?;
216
217                    assert_eq!(dest_len, op_len);
218
219                    for i in 0..dest_len {
220                        // Use `read_int` to get a zero-extended `u128`. Those
221                        // extra zeros will not affect `count_ones`.
222                        let op = ecx.read_int::<u128>(&ecx.project_index(&op, i)?)?;
223                        let res = op.count_ones();
224
225                        ecx.write_int(res, &ecx.project_index(&dest, i)?)?;
226                    }
227                }
228
229                // Target-specific shims
230                name if name.starts_with("llvm.x86.")
231                    && matches!(ecx.tcx.sess.target.arch, Arch::X86 | Arch::X86_64)
232                    && ecx.tcx.sess.target.endian == Endian::Little =>
233                    break 'handled x86::EvalContextExt::emulate_x86_intrinsic(
234                        ecx, link_name, args, &dest,
235                    )?,
236                name if name.starts_with("llvm.aarch64.")
237                    && ecx.tcx.sess.target.arch == Arch::AArch64
238                    && ecx.tcx.sess.target.endian == Endian::Little =>
239                    break 'handled aarch64::EvalContextExt::emulate_aarch64_intrinsic(
240                        ecx, link_name, args, &dest,
241                    )?,
242                name if name.starts_with("llvm.loongarch.")
243                    && matches!(
244                        ecx.tcx.sess.target.arch,
245                        Arch::LoongArch32 | Arch::LoongArch64
246                    )
247                    && ecx.tcx.sess.target.endian == Endian::Little =>
248                    break 'handled loongarch::EvalContextExt::emulate_loongarch_intrinsic(
249                        ecx, link_name, args, &dest,
250                    )?,
251                _ => break 'handled EmulateItemResult::NotSupported,
252            }
253            EmulateItemResult::NeedsReturn
254        };
255
256        // The rest either implements the logic, or falls back to `lookup_exported_symbol`.
257        res.jump_to_next_block(ecx, &dest.clone().into(), ret, None, |ecx| {
258            throw_machine_stop!(TerminationInfo::UnsupportedForeignItem(format!(
259                "can't call LLVM intrinsic `{link_name}` on architecture `{arch}`",
260                arch = ecx.tcx.sess.target.arch,
261            )));
262        })
263    }
264}