Skip to main content

rustc_codegen_ssa/mir/
intrinsic.rs

1use rustc_abi::{Align, FieldIdx, WrappingRange};
2use rustc_middle::mir::SourceInfo;
3use rustc_middle::ty::{self, Intrinsic, Ty, TyCtxt};
4use rustc_session::config::OptLevel;
5use rustc_span::{ErrorGuaranteed, bug, span_bug, sym};
6use rustc_target::spec::Arch;
7
8use super::operand::{OperandRef, OperandValue};
9use super::place::PlaceValue;
10use super::{FunctionCx, IntrinsicResult};
11use crate::common::{AtomicRmwBinOp, SynchronizationScope};
12use crate::diagnostics::InvalidMonomorphization;
13use crate::mir::operand::OperandRefBuilder;
14use crate::traits::*;
15use crate::{MemFlags, meth, size_of_val};
16
17fn copy_intrinsic<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
18    bx: &mut Bx,
19    allow_overlap: bool,
20    volatile: bool,
21    ty: Ty<'tcx>,
22    dst: Bx::Value,
23    src: Bx::Value,
24    count: Bx::Value,
25) {
26    let layout = bx.layout_of(ty);
27    let size = layout.size;
28    let align = layout.align;
29    let size = bx.unchecked_sumul(bx.const_usize(size.bytes()), count);
30    let flags = if volatile { MemFlags::VOLATILE } else { MemFlags::empty() };
31    if allow_overlap {
32        bx.memmove(dst, align, src, align, size, flags);
33    } else {
34        bx.memcpy(dst, align, src, align, size, flags, None);
35    }
36}
37
38fn memset_intrinsic<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
39    bx: &mut Bx,
40    volatile: bool,
41    ty: Ty<'tcx>,
42    dst: Bx::Value,
43    val: Bx::Value,
44    count: Bx::Value,
45) {
46    let layout = bx.layout_of(ty);
47    let size = layout.size;
48    let align = layout.align;
49    let size = bx.mul(bx.const_usize(size.bytes()), count);
50    let flags = if volatile { MemFlags::VOLATILE } else { MemFlags::empty() };
51    bx.memset(dst, val, size, align, flags);
52}
53
54impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
55    /// In the `Fallback` case, returns the instance that should be called instead.
56    pub fn codegen_intrinsic_call(
57        &mut self,
58        bx: &mut Bx,
59        instance: ty::Instance<'tcx>,
60        args: &[OperandRef<'tcx, Bx::Value>],
61        result_layout: ty::layout::TyAndLayout<'tcx>,
62        result_place: Option<PlaceValue<Bx::Value>>,
63        source_info: SourceInfo,
64    ) -> IntrinsicResult<'tcx, Bx::Value> {
65        // When `-Zforce-intrinsic-fallback` is enabled, always use the fallback body if it exists,
66        if bx.tcx().sess.opts.unstable_opts.force_intrinsic_fallback
67            && let Some(def) = bx.tcx().intrinsic(instance.def_id())
68            && !def.must_be_overridden
69        {
70            return IntrinsicResult::Fallback(ty::Instance::new_raw(
71                instance.def_id(),
72                instance.args,
73            ));
74        }
75
76        let span = source_info.span;
77
78        let name = bx.tcx().intrinsic(instance.def_id()).unwrap().name;
79        let fn_args = instance.args;
80
81        let check_value = |op: OperandValue<<Bx as BackendTypes>::Value>| {
82            if true {
    if !op.is_expected_variant_for_type(result_layout) {
        {
            ::core::panicking::panic_fmt(format_args!("[{0:?}] Value {1:?} is wrong for type {2:?}",
                    name, op, result_layout));
        }
    };
};debug_assert!(
83                op.is_expected_variant_for_type(result_layout),
84                "[{name:?}] Value {op:?} is wrong for type {result_layout:?}",
85            );
86        };
87
88        let Intrinsic::Rustc(name) = name else {
89            // Backend intrinsics go directly to the backend.
90            let result =
91                bx.codegen_intrinsic_call(instance, args, result_layout, result_place, span);
92
93            if let IntrinsicResult::Operand(op) = result {
94                check_value(op);
95            }
96            return result;
97        };
98
99        // If we're swapping something that's *not* an `OperandValue::Ref`,
100        // then we can do it directly and avoid the alloca.
101        // Otherwise, we'll let the fallback MIR body take care of it.
102        if let sym::typed_swap_nonoverlapping = name {
103            let pointee_ty = fn_args.type_at(0);
104            let pointee_layout = bx.layout_of(pointee_ty);
105            if pointee_layout.is_ssa_standalone()
106                // But if we're not going to optimize, trying to use the fallback
107                // body just makes things worse, so don't bother.
108                || bx.sess().opts.optimize == OptLevel::No
109                // NOTE(eddyb) SPIR-V's Logical addressing model doesn't allow for arbitrary
110                // reinterpretation of values as (chunkable) byte arrays, and the loop in the
111                // block optimization in `ptr::swap_nonoverlapping` is hard to rewrite back
112                // into the (unoptimized) direct swapping implementation, so we disable it.
113                || bx.sess().target.arch == Arch::SpirV
114            {
115                let align = pointee_layout.align;
116                let x_place = args[0].val.deref(align);
117                let y_place = args[1].val.deref(align);
118                bx.typed_place_swap(x_place, y_place, pointee_layout);
119                return IntrinsicResult::Operand(OperandValue::ZeroSized);
120            }
121        }
122
123        let invalid_monomorphization_int_type = |ty| -> ErrorGuaranteed {
124            bx.tcx().dcx().emit_err(InvalidMonomorphization::BasicIntegerType {
125                span,
126                name: Intrinsic::Rustc(name),
127                ty,
128            })
129        };
130        let invalid_monomorphization_int_or_ptr_type = |ty| -> ErrorGuaranteed {
131            bx.tcx().dcx().emit_err(InvalidMonomorphization::BasicIntegerOrPtrType {
132                span,
133                name: Intrinsic::Rustc(name),
134                ty,
135            })
136        };
137
138        let parse_atomic_ordering = |ord: ty::Value<'tcx>| {
139            let discr = ord.to_branch()[0].to_leaf();
140            discr.to_atomic_ordering()
141        };
142
143        if args.is_empty() {
144            match name {
145                sym::abort_immediate
146                | sym::unreachable
147                | sym::cold_path
148                | sym::gpu_launch_sized_workgroup_mem
149                | sym::breakpoint
150                | sym::codeview_annotation
151                | sym::amdgpu_dispatch_ptr
152                | sym::assert_zero_valid
153                | sym::assert_mem_uninitialized_valid
154                | sym::assert_inhabited
155                | sym::ub_checks
156                | sym::contract_checks
157                | sym::atomic_fence
158                | sym::atomic_singlethreadfence
159                | sym::caller_location
160                | sym::offload_get_num_devices
161                | sym::return_address => {}
162                _ => {
163                    ::rustc_span::macros::bug_impl(Some(span),
    format_args!("Nullary intrinsic {0} must be called in a const block. If you are seeing this message from code outside the standard library, the unstable implementation details of the relevant intrinsic may have changed. Consider using stable APIs instead. If you are adding a new nullary intrinsic that is inherently a runtime intrinsic, update this check.",
        name), Location::caller());span_bug!(
164                        span,
165                        "Nullary intrinsic {name} must be called in a const block. \
166                        If you are seeing this message from code outside the standard library, the \
167                        unstable implementation details of the relevant intrinsic may have changed. \
168                        Consider using stable APIs instead. \
169                        If you are adding a new nullary intrinsic that is inherently a runtime \
170                        intrinsic, update this check."
171                    );
172                }
173            }
174        }
175
176        let op_val: OperandValue<_> = match name {
177            sym::abort_immediate => {
178                bx.abort_immediate();
179                OperandValue::ZeroSized
180            }
181
182            sym::caller_location => {
183                let location = self.get_caller_location(bx, source_info);
184                location.val
185            }
186
187            sym::size_of_val => {
188                let tp_ty = fn_args.type_at(0);
189                let (_, meta) = args[0].val.pointer_parts();
190                let (llsize, _) = size_of_val::size_and_align_of_dst(bx, tp_ty, meta, span);
191                OperandValue::Immediate(llsize)
192            }
193            sym::align_of_val => {
194                let tp_ty = fn_args.type_at(0);
195                let (_, meta) = args[0].val.pointer_parts();
196                let (_, llalign) = size_of_val::size_and_align_of_dst(bx, tp_ty, meta, span);
197                OperandValue::Immediate(llalign)
198            }
199            sym::vtable_size | sym::vtable_align => {
200                let vtable = args[0].immediate();
201                let idx = match name {
202                    sym::vtable_size => ty::COMMON_VTABLE_ENTRIES_SIZE,
203                    sym::vtable_align => ty::COMMON_VTABLE_ENTRIES_ALIGN,
204                    _ => ::rustc_span::macros::bug_impl(None, format_args!("impossible case reached"),
    Location::caller())bug!(),
205                };
206                let value = meth::VirtualIndex::from_index(idx).get_usize(bx, vtable);
207                match name {
208                    // Size is always <= isize::MAX.
209                    sym::vtable_size => {
210                        let size_bound = bx.data_layout().ptr_sized_integer().signed_max() as u128;
211                        bx.range_metadata(value, WrappingRange { start: 0, end: size_bound });
212                    }
213                    // Alignment is always a power of two, thus 1..=0x800…000,
214                    // but also bounded by the maximum we support in type layout.
215                    sym::vtable_align => {
216                        let align_bound = Align::max_for_target(bx.data_layout()).bytes().into();
217                        bx.range_metadata(value, WrappingRange { start: 1, end: align_bound })
218                    }
219                    _ => {}
220                }
221                OperandValue::Immediate(value)
222            }
223            sym::arith_offset => {
224                let ty = fn_args.type_at(0);
225                let layout = bx.layout_of(ty);
226                let ptr = args[0].immediate();
227                let offset = args[1].immediate();
228                OperandValue::Immediate(bx.gep(layout.size, ptr, offset))
229            }
230            sym::copy => {
231                copy_intrinsic(
232                    bx,
233                    true,
234                    false,
235                    fn_args.type_at(0),
236                    args[1].immediate(),
237                    args[0].immediate(),
238                    args[2].immediate(),
239                );
240                OperandValue::ZeroSized
241            }
242            sym::write_bytes => {
243                memset_intrinsic(
244                    bx,
245                    false,
246                    fn_args.type_at(0),
247                    args[0].immediate(),
248                    args[1].immediate(),
249                    args[2].immediate(),
250                );
251                OperandValue::ZeroSized
252            }
253
254            sym::volatile_copy_nonoverlapping_memory => {
255                copy_intrinsic(
256                    bx,
257                    false,
258                    true,
259                    fn_args.type_at(0),
260                    args[0].immediate(),
261                    args[1].immediate(),
262                    args[2].immediate(),
263                );
264                OperandValue::ZeroSized
265            }
266            sym::volatile_copy_memory => {
267                copy_intrinsic(
268                    bx,
269                    true,
270                    true,
271                    fn_args.type_at(0),
272                    args[0].immediate(),
273                    args[1].immediate(),
274                    args[2].immediate(),
275                );
276                OperandValue::ZeroSized
277            }
278            sym::volatile_set_memory => {
279                memset_intrinsic(
280                    bx,
281                    true,
282                    fn_args.type_at(0),
283                    args[0].immediate(),
284                    args[1].immediate(),
285                    args[2].immediate(),
286                );
287                OperandValue::ZeroSized
288            }
289            sym::volatile_store | sym::unaligned_volatile_store => {
290                let dst = args[0].deref(bx.cx());
291                let dst = if name == sym::volatile_store { dst } else { dst.unaligned() };
292                args[1].val.volatile_store(bx, dst);
293                OperandValue::ZeroSized
294            }
295            sym::disjoint_bitor => {
296                let a = args[0].immediate();
297                let b = args[1].immediate();
298                OperandValue::Immediate(bx.or_disjoint(a, b))
299            }
300            sym::exact_div => {
301                let ty = args[0].layout.ty;
302                match int_type_width_signed(ty, bx.tcx()) {
303                    Some((_width, signed)) => OperandValue::Immediate(if signed {
304                        bx.exactsdiv(args[0].immediate(), args[1].immediate())
305                    } else {
306                        bx.exactudiv(args[0].immediate(), args[1].immediate())
307                    }),
308                    None => {
309                        let err =
310                            bx.tcx().dcx().emit_err(InvalidMonomorphization::BasicIntegerType {
311                                span,
312                                name: Intrinsic::Rustc(name),
313                                ty,
314                            });
315                        return IntrinsicResult::Err(err);
316                    }
317                }
318            }
319            sym::fadd_fast | sym::fsub_fast | sym::fmul_fast | sym::fdiv_fast | sym::frem_fast => {
320                match float_type_width(args[0].layout.ty) {
321                    Some(_width) => OperandValue::Immediate(match name {
322                        sym::fadd_fast => bx.fadd_fast(args[0].immediate(), args[1].immediate()),
323                        sym::fsub_fast => bx.fsub_fast(args[0].immediate(), args[1].immediate()),
324                        sym::fmul_fast => bx.fmul_fast(args[0].immediate(), args[1].immediate()),
325                        sym::fdiv_fast => bx.fdiv_fast(args[0].immediate(), args[1].immediate()),
326                        sym::frem_fast => bx.frem_fast(args[0].immediate(), args[1].immediate()),
327                        _ => ::rustc_span::macros::bug_impl(None, format_args!("impossible case reached"),
    Location::caller())bug!(),
328                    }),
329                    None => {
330                        let err =
331                            bx.tcx().dcx().emit_err(InvalidMonomorphization::BasicFloatType {
332                                span,
333                                name: Intrinsic::Rustc(name),
334                                ty: args[0].layout.ty,
335                            });
336                        return IntrinsicResult::Err(err);
337                    }
338                }
339            }
340            sym::fadd_algebraic
341            | sym::fsub_algebraic
342            | sym::fmul_algebraic
343            | sym::fdiv_algebraic
344            | sym::frem_algebraic => match float_type_width(args[0].layout.ty) {
345                Some(_width) => OperandValue::Immediate(match name {
346                    sym::fadd_algebraic => {
347                        bx.fadd_algebraic(args[0].immediate(), args[1].immediate())
348                    }
349                    sym::fsub_algebraic => {
350                        bx.fsub_algebraic(args[0].immediate(), args[1].immediate())
351                    }
352                    sym::fmul_algebraic => {
353                        bx.fmul_algebraic(args[0].immediate(), args[1].immediate())
354                    }
355                    sym::fdiv_algebraic => {
356                        bx.fdiv_algebraic(args[0].immediate(), args[1].immediate())
357                    }
358                    sym::frem_algebraic => {
359                        bx.frem_algebraic(args[0].immediate(), args[1].immediate())
360                    }
361                    _ => ::rustc_span::macros::bug_impl(None, format_args!("impossible case reached"),
    Location::caller())bug!(),
362                }),
363                None => {
364                    let err = bx.tcx().dcx().emit_err(InvalidMonomorphization::BasicFloatType {
365                        span,
366                        name: Intrinsic::Rustc(name),
367                        ty: args[0].layout.ty,
368                    });
369                    return IntrinsicResult::Err(err);
370                }
371            },
372
373            sym::float_to_int_unchecked => {
374                if float_type_width(args[0].layout.ty).is_none() {
375                    let err =
376                        bx.tcx().dcx().emit_err(InvalidMonomorphization::FloatToIntUnchecked {
377                            span,
378                            ty: args[0].layout.ty,
379                        });
380                    return IntrinsicResult::Err(err);
381                }
382                let Some((_width, signed)) = int_type_width_signed(result_layout.ty, bx.tcx())
383                else {
384                    let err =
385                        bx.tcx().dcx().emit_err(InvalidMonomorphization::FloatToIntUnchecked {
386                            span,
387                            ty: result_layout.ty,
388                        });
389                    return IntrinsicResult::Err(err);
390                };
391                OperandValue::Immediate(if signed {
392                    bx.fptosi(args[0].immediate(), bx.backend_type(result_layout))
393                } else {
394                    bx.fptoui(args[0].immediate(), bx.backend_type(result_layout))
395                })
396            }
397
398            sym::atomic_load => {
399                let ty = fn_args.type_at(0);
400                if !(int_type_width_signed(ty, bx.tcx()).is_some() || ty.is_raw_ptr()) {
401                    let err = invalid_monomorphization_int_or_ptr_type(ty);
402                    return IntrinsicResult::Err(err);
403                }
404                let ordering = fn_args.const_at(1).to_value();
405                let volatile = fn_args.const_at(2).to_value();
406                let layout = bx.layout_of(ty);
407                let source = args[0].immediate();
408                OperandValue::Immediate(bx.atomic_load(
409                    bx.backend_type(layout),
410                    source,
411                    parse_atomic_ordering(ordering),
412                    volatile.to_leaf().try_to_bool().unwrap(),
413                    layout.size,
414                ))
415            }
416            sym::atomic_store => {
417                let ty = fn_args.type_at(0);
418                if !(int_type_width_signed(ty, bx.tcx()).is_some() || ty.is_raw_ptr()) {
419                    let err = invalid_monomorphization_int_or_ptr_type(ty);
420                    return IntrinsicResult::Err(err);
421                }
422                let ordering = fn_args.const_at(1).to_value();
423                let volatile = fn_args.const_at(2).to_value();
424                let size = bx.layout_of(ty).size;
425                let val = args[1].immediate();
426                let ptr = args[0].immediate();
427                bx.atomic_store(
428                    val,
429                    ptr,
430                    parse_atomic_ordering(ordering),
431                    volatile.to_leaf().try_to_bool().unwrap(),
432                    size,
433                );
434                OperandValue::ZeroSized
435            }
436            // These are all AtomicRMW ops
437            sym::atomic_cxchg | sym::atomic_cxchgweak => {
438                let ty = fn_args.type_at(0);
439                if !(int_type_width_signed(ty, bx.tcx()).is_some() || ty.is_raw_ptr()) {
440                    let err = invalid_monomorphization_int_or_ptr_type(ty);
441                    return IntrinsicResult::Err(err);
442                }
443                let succ_ordering = fn_args.const_at(1).to_value();
444                let fail_ordering = fn_args.const_at(2).to_value();
445                let weak = name == sym::atomic_cxchgweak;
446                let dst = args[0].immediate();
447                let cmp = args[1].immediate();
448                let src = args[2].immediate();
449                let (val, success) = bx.atomic_cmpxchg(
450                    dst,
451                    cmp,
452                    src,
453                    parse_atomic_ordering(succ_ordering),
454                    parse_atomic_ordering(fail_ordering),
455                    weak,
456                );
457
458                let mut builder = OperandRefBuilder::new(result_layout);
459                builder.insert_imm(FieldIdx::from_u32(0), val);
460                builder.insert_imm(FieldIdx::from_u32(1), success);
461                builder.build(bx.cx()).val
462            }
463            sym::atomic_max | sym::atomic_min => {
464                let atom_op = if name == sym::atomic_max {
465                    AtomicRmwBinOp::AtomicMax
466                } else {
467                    AtomicRmwBinOp::AtomicMin
468                };
469
470                let ty = fn_args.type_at(0);
471                if #[allow(non_exhaustive_omitted_patterns)] match ty.kind() {
    ty::Int(_) => true,
    _ => false,
}matches!(ty.kind(), ty::Int(_)) {
472                    let ordering = fn_args.const_at(1).to_value();
473                    let ptr = args[0].immediate();
474                    let val = args[1].immediate();
475                    OperandValue::Immediate(bx.atomic_rmw(
476                        atom_op,
477                        ptr,
478                        val,
479                        parse_atomic_ordering(ordering),
480                        /* ret_ptr */ false,
481                    ))
482                } else {
483                    let err = invalid_monomorphization_int_type(ty);
484                    return IntrinsicResult::Err(err);
485                }
486            }
487            sym::atomic_umax | sym::atomic_umin => {
488                let atom_op = if name == sym::atomic_umax {
489                    AtomicRmwBinOp::AtomicUMax
490                } else {
491                    AtomicRmwBinOp::AtomicUMin
492                };
493
494                let ty = fn_args.type_at(0);
495                if #[allow(non_exhaustive_omitted_patterns)] match ty.kind() {
    ty::Uint(_) => true,
    _ => false,
}matches!(ty.kind(), ty::Uint(_)) {
496                    let ordering = fn_args.const_at(1).to_value();
497                    let ptr = args[0].immediate();
498                    let val = args[1].immediate();
499                    OperandValue::Immediate(bx.atomic_rmw(
500                        atom_op,
501                        ptr,
502                        val,
503                        parse_atomic_ordering(ordering),
504                        /* ret_ptr */ false,
505                    ))
506                } else {
507                    let err = invalid_monomorphization_int_type(ty);
508                    return IntrinsicResult::Err(err);
509                }
510            }
511            sym::atomic_xchg => {
512                let ty = fn_args.type_at(0);
513                let ordering = fn_args.const_at(1).to_value();
514                if int_type_width_signed(ty, bx.tcx()).is_some() || ty.is_raw_ptr() {
515                    let ptr = args[0].immediate();
516                    let val = args[1].immediate();
517                    let atomic_op = AtomicRmwBinOp::AtomicXchg;
518                    OperandValue::Immediate(bx.atomic_rmw(
519                        atomic_op,
520                        ptr,
521                        val,
522                        parse_atomic_ordering(ordering),
523                        /* ret_ptr */ ty.is_raw_ptr(),
524                    ))
525                } else {
526                    let err = invalid_monomorphization_int_or_ptr_type(ty);
527                    return IntrinsicResult::Err(err);
528                }
529            }
530            sym::atomic_xadd
531            | sym::atomic_xsub
532            | sym::atomic_and
533            | sym::atomic_nand
534            | sym::atomic_or
535            | sym::atomic_xor => {
536                let atom_op = match name {
537                    sym::atomic_xadd => AtomicRmwBinOp::AtomicAdd,
538                    sym::atomic_xsub => AtomicRmwBinOp::AtomicSub,
539                    sym::atomic_and => AtomicRmwBinOp::AtomicAnd,
540                    sym::atomic_nand => AtomicRmwBinOp::AtomicNand,
541                    sym::atomic_or => AtomicRmwBinOp::AtomicOr,
542                    sym::atomic_xor => AtomicRmwBinOp::AtomicXor,
543                    _ => ::core::panicking::unreachable_default_msg()unreachable!(),
544                };
545
546                // The type of the in-memory data.
547                let ty_mem = fn_args.type_at(0);
548                // The type of the 2nd operand, given by-value.
549                let ty_op = fn_args.type_at(1);
550
551                let ordering = fn_args.const_at(2).to_value();
552                // We require either both arguments to have the same integer type, or the first to
553                // be a pointer and the second to be `usize`.
554                if (int_type_width_signed(ty_mem, bx.tcx()).is_some() && ty_op == ty_mem)
555                    || (ty_mem.is_raw_ptr() && ty_op == bx.tcx().types.usize)
556                {
557                    let ptr = args[0].immediate(); // of type "pointer to `ty_mem`"
558                    let val = args[1].immediate(); // of type `ty_op`
559                    OperandValue::Immediate(bx.atomic_rmw(
560                        atom_op,
561                        ptr,
562                        val,
563                        parse_atomic_ordering(ordering),
564                        /* ret_ptr */ ty_mem.is_raw_ptr(),
565                    ))
566                } else {
567                    let err = invalid_monomorphization_int_or_ptr_type(ty_mem);
568                    return IntrinsicResult::Err(err);
569                }
570            }
571            sym::atomic_fence => {
572                let ordering = fn_args.const_at(0).to_value();
573                bx.atomic_fence(parse_atomic_ordering(ordering), SynchronizationScope::CrossThread);
574                OperandValue::ZeroSized
575            }
576
577            sym::atomic_singlethreadfence => {
578                let ordering = fn_args.const_at(0).to_value();
579                bx.atomic_fence(
580                    parse_atomic_ordering(ordering),
581                    SynchronizationScope::SingleThread,
582                );
583                OperandValue::ZeroSized
584            }
585
586            sym::nontemporal_store => {
587                let dst = args[0].deref(bx.cx());
588                args[1].val.nontemporal_store(bx, dst);
589                OperandValue::ZeroSized
590            }
591
592            sym::ptr_offset_from | sym::ptr_offset_from_unsigned => {
593                let ty = fn_args.type_at(0);
594                let pointee_size = bx.layout_of(ty).size;
595
596                let a = args[0].immediate();
597                let b = args[1].immediate();
598                let a = bx.ptrtoint(a, bx.type_isize());
599                let b = bx.ptrtoint(b, bx.type_isize());
600                let pointee_size = bx.const_usize(pointee_size.bytes());
601                OperandValue::Immediate(if name == sym::ptr_offset_from {
602                    // This is the same sequence that Clang emits for pointer subtraction.
603                    // It can be neither `nsw` nor `nuw` because the input is treated as
604                    // unsigned but then the output is treated as signed, so neither works.
605                    let d = bx.sub(a, b);
606                    // this is where the signed magic happens (notice the `s` in `exactsdiv`)
607                    bx.exactsdiv(d, pointee_size)
608                } else {
609                    // The `_unsigned` version knows the relative ordering of the pointers,
610                    // so can use `sub nuw` and `udiv exact` instead of dealing in signed.
611                    let d = bx.unchecked_usub(a, b);
612                    bx.exactudiv(d, pointee_size)
613                })
614            }
615
616            sym::cold_path => {
617                // This is a no-op. The intrinsic is just a hint to the optimizer.
618                OperandValue::ZeroSized
619            }
620
621            _ => {
622                // Need to use backend-specific things in the implementation.
623                let result =
624                    bx.codegen_intrinsic_call(instance, args, result_layout, result_place, span);
625                if let IntrinsicResult::Operand(op) = result {
626                    op
627                } else {
628                    return result;
629                }
630            }
631        };
632
633        check_value(op_val);
634
635        IntrinsicResult::Operand(op_val)
636    }
637}
638
639// Returns the width of an int Ty, and if it's signed or not
640// Returns None if the type is not an integer
641// FIXME: there’s multiple of this functions, investigate using some of the already existing
642// stuffs.
643fn int_type_width_signed(ty: Ty<'_>, tcx: TyCtxt<'_>) -> Option<(u64, bool)> {
644    match ty.kind() {
645        ty::Int(t) => {
646            Some((t.bit_width().unwrap_or(u64::from(tcx.sess.target.pointer_width)), true))
647        }
648        ty::Uint(t) => {
649            Some((t.bit_width().unwrap_or(u64::from(tcx.sess.target.pointer_width)), false))
650        }
651        _ => None,
652    }
653}
654
655// Returns the width of a float Ty
656// Returns None if the type is not a float
657fn float_type_width(ty: Ty<'_>) -> Option<u64> {
658    match ty.kind() {
659        ty::Float(t) => Some(t.bit_width()),
660        _ => None,
661    }
662}