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