rustc_codegen_ssa/mir/
rvalue.rs

1use itertools::Itertools as _;
2use rustc_abi::{self as abi, BackendRepr, FIRST_VARIANT};
3use rustc_middle::ty::adjustment::PointerCoercion;
4use rustc_middle::ty::layout::{HasTyCtxt, HasTypingEnv, LayoutOf, TyAndLayout};
5use rustc_middle::ty::{self, Instance, Ty, TyCtxt};
6use rustc_middle::{bug, mir, span_bug};
7use rustc_session::config::OptLevel;
8use tracing::{debug, instrument};
9
10use super::FunctionCx;
11use super::operand::{OperandRef, OperandRefBuilder, OperandValue};
12use super::place::{PlaceRef, PlaceValue, codegen_tag_value};
13use crate::common::{IntPredicate, TypeKind};
14use crate::traits::*;
15use crate::{MemFlags, base};
16
17impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
18    #[instrument(level = "trace", skip(self, bx))]
19    pub(crate) fn codegen_rvalue(
20        &mut self,
21        bx: &mut Bx,
22        dest: PlaceRef<'tcx, Bx::Value>,
23        rvalue: &mir::Rvalue<'tcx>,
24    ) {
25        match *rvalue {
26            mir::Rvalue::Use(ref operand) => {
27                let cg_operand = self.codegen_operand(bx, operand);
28                // Crucially, we do *not* use `OperandValue::Ref` for types with
29                // `BackendRepr::Scalar | BackendRepr::ScalarPair`. This ensures we match the MIR
30                // semantics regarding when assignment operators allow overlap of LHS and RHS.
31                if matches!(
32                    cg_operand.layout.backend_repr,
33                    BackendRepr::Scalar(..) | BackendRepr::ScalarPair(..),
34                ) {
35                    debug_assert!(!matches!(cg_operand.val, OperandValue::Ref(..)));
36                }
37                // FIXME: consider not copying constants through stack. (Fixable by codegen'ing
38                // constants into `OperandValue::Ref`; why don’t we do that yet if we don’t?)
39                cg_operand.store_with_annotation(bx, dest);
40            }
41
42            mir::Rvalue::Cast(
43                mir::CastKind::PointerCoercion(PointerCoercion::Unsize, _),
44                ref source,
45                _,
46            ) => {
47                // The destination necessarily contains a wide pointer, so if
48                // it's a scalar pair, it's a wide pointer or newtype thereof.
49                if bx.cx().is_backend_scalar_pair(dest.layout) {
50                    // Into-coerce of a thin pointer to a wide pointer -- just
51                    // use the operand path.
52                    let temp = self.codegen_rvalue_operand(bx, rvalue);
53                    temp.store_with_annotation(bx, dest);
54                    return;
55                }
56
57                // Unsize of a nontrivial struct. I would prefer for
58                // this to be eliminated by MIR building, but
59                // `CoerceUnsized` can be passed by a where-clause,
60                // so the (generic) MIR may not be able to expand it.
61                let operand = self.codegen_operand(bx, source);
62                match operand.val {
63                    OperandValue::Pair(..) | OperandValue::Immediate(_) => {
64                        // Unsize from an immediate structure. We don't
65                        // really need a temporary alloca here, but
66                        // avoiding it would require us to have
67                        // `coerce_unsized_into` use `extractvalue` to
68                        // index into the struct, and this case isn't
69                        // important enough for it.
70                        debug!("codegen_rvalue: creating ugly alloca");
71                        let scratch = PlaceRef::alloca(bx, operand.layout);
72                        scratch.storage_live(bx);
73                        operand.store_with_annotation(bx, scratch);
74                        base::coerce_unsized_into(bx, scratch, dest);
75                        scratch.storage_dead(bx);
76                    }
77                    OperandValue::Ref(val) => {
78                        if val.llextra.is_some() {
79                            bug!("unsized coercion on an unsized rvalue");
80                        }
81                        base::coerce_unsized_into(bx, val.with_type(operand.layout), dest);
82                    }
83                    OperandValue::ZeroSized => {
84                        bug!("unsized coercion on a ZST rvalue");
85                    }
86                }
87            }
88
89            mir::Rvalue::Cast(
90                mir::CastKind::Transmute | mir::CastKind::Subtype,
91                ref operand,
92                _ty,
93            ) => {
94                let src = self.codegen_operand(bx, operand);
95                self.codegen_transmute(bx, src, dest);
96            }
97
98            mir::Rvalue::Repeat(ref elem, count) => {
99                // Do not generate the loop for zero-sized elements or empty arrays.
100                if dest.layout.is_zst() {
101                    return;
102                }
103
104                // When the element is a const with all bytes uninit, emit a single memset that
105                // writes undef to the entire destination.
106                if let mir::Operand::Constant(const_op) = elem {
107                    let val = self.eval_mir_constant(const_op);
108                    if val.all_bytes_uninit(self.cx.tcx()) {
109                        let size = bx.const_usize(dest.layout.size.bytes());
110                        bx.memset(
111                            dest.val.llval,
112                            bx.const_undef(bx.type_i8()),
113                            size,
114                            dest.val.align,
115                            MemFlags::empty(),
116                        );
117                        return;
118                    }
119                }
120
121                let cg_elem = self.codegen_operand(bx, elem);
122
123                let try_init_all_same = |bx: &mut Bx, v| {
124                    let start = dest.val.llval;
125                    let size = bx.const_usize(dest.layout.size.bytes());
126
127                    // Use llvm.memset.p0i8.* to initialize all same byte arrays
128                    if let Some(int) = bx.cx().const_to_opt_u128(v, false)
129                        && let bytes = &int.to_le_bytes()[..cg_elem.layout.size.bytes_usize()]
130                        && let Ok(&byte) = bytes.iter().all_equal_value()
131                    {
132                        let fill = bx.cx().const_u8(byte);
133                        bx.memset(start, fill, size, dest.val.align, MemFlags::empty());
134                        return true;
135                    }
136
137                    // Use llvm.memset.p0i8.* to initialize byte arrays
138                    let v = bx.from_immediate(v);
139                    if bx.cx().val_ty(v) == bx.cx().type_i8() {
140                        bx.memset(start, v, size, dest.val.align, MemFlags::empty());
141                        return true;
142                    }
143                    false
144                };
145
146                if let OperandValue::Immediate(v) = cg_elem.val
147                    && try_init_all_same(bx, v)
148                {
149                    return;
150                }
151
152                let count = self
153                    .monomorphize(count)
154                    .try_to_target_usize(bx.tcx())
155                    .expect("expected monomorphic const in codegen");
156
157                bx.write_operand_repeatedly(cg_elem, count, dest);
158            }
159
160            // This implementation does field projection, so never use it for `RawPtr`,
161            // which will always be fine with the `codegen_rvalue_operand` path below.
162            mir::Rvalue::Aggregate(ref kind, ref operands)
163                if !matches!(**kind, mir::AggregateKind::RawPtr(..)) =>
164            {
165                let (variant_index, variant_dest, active_field_index) = match **kind {
166                    mir::AggregateKind::Adt(_, variant_index, _, _, active_field_index) => {
167                        let variant_dest = dest.project_downcast(bx, variant_index);
168                        (variant_index, variant_dest, active_field_index)
169                    }
170                    _ => (FIRST_VARIANT, dest, None),
171                };
172                if active_field_index.is_some() {
173                    assert_eq!(operands.len(), 1);
174                }
175                for (i, operand) in operands.iter_enumerated() {
176                    let op = self.codegen_operand(bx, operand);
177                    // Do not generate stores and GEPis for zero-sized fields.
178                    if !op.layout.is_zst() {
179                        let field_index = active_field_index.unwrap_or(i);
180                        let field = if let mir::AggregateKind::Array(_) = **kind {
181                            let llindex = bx.cx().const_usize(field_index.as_u32().into());
182                            variant_dest.project_index(bx, llindex)
183                        } else {
184                            variant_dest.project_field(bx, field_index.as_usize())
185                        };
186                        op.store_with_annotation(bx, field);
187                    }
188                }
189                dest.codegen_set_discr(bx, variant_index);
190            }
191
192            _ => {
193                let temp = self.codegen_rvalue_operand(bx, rvalue);
194                temp.store_with_annotation(bx, dest);
195            }
196        }
197    }
198
199    /// Transmutes the `src` value to the destination type by writing it to `dst`.
200    ///
201    /// See also [`Self::codegen_transmute_operand`] for cases that can be done
202    /// without needing a pre-allocated place for the destination.
203    fn codegen_transmute(
204        &mut self,
205        bx: &mut Bx,
206        src: OperandRef<'tcx, Bx::Value>,
207        dst: PlaceRef<'tcx, Bx::Value>,
208    ) {
209        // The MIR validator enforces no unsized transmutes.
210        assert!(src.layout.is_sized());
211        assert!(dst.layout.is_sized());
212
213        if src.layout.size != dst.layout.size
214            || src.layout.is_uninhabited()
215            || dst.layout.is_uninhabited()
216        {
217            // These cases are all UB to actually hit, so don't emit code for them.
218            // (The size mismatches are reachable via `transmute_unchecked`.)
219            bx.unreachable_nonterminator();
220        } else {
221            // Since in this path we have a place anyway, we can store or copy to it,
222            // making sure we use the destination place's alignment even if the
223            // source would normally have a higher one.
224            src.store_with_annotation(bx, dst.val.with_type(src.layout));
225        }
226    }
227
228    /// Transmutes an `OperandValue` to another `OperandValue`.
229    ///
230    /// This is supported for all cases where the `cast` type is SSA,
231    /// but for non-ZSTs with [`abi::BackendRepr::Memory`] it ICEs.
232    pub(crate) fn codegen_transmute_operand(
233        &mut self,
234        bx: &mut Bx,
235        operand: OperandRef<'tcx, Bx::Value>,
236        cast: TyAndLayout<'tcx>,
237    ) -> OperandValue<Bx::Value> {
238        if let abi::BackendRepr::Memory { .. } = cast.backend_repr
239            && !cast.is_zst()
240        {
241            span_bug!(self.mir.span, "Use `codegen_transmute` to transmute to {cast:?}");
242        }
243
244        // `Layout` is interned, so we can do a cheap check for things that are
245        // exactly the same and thus don't need any handling.
246        if abi::Layout::eq(&operand.layout.layout, &cast.layout) {
247            return operand.val;
248        }
249
250        // Check for transmutes that are always UB.
251        if operand.layout.size != cast.size
252            || operand.layout.is_uninhabited()
253            || cast.is_uninhabited()
254        {
255            bx.unreachable_nonterminator();
256
257            // We still need to return a value of the appropriate type, but
258            // it's already UB so do the easiest thing available.
259            return OperandValue::poison(bx, cast);
260        }
261
262        // To or from pointers takes different methods, so we use this to restrict
263        // the SimdVector case to types which can be `bitcast` between each other.
264        #[inline]
265        fn vector_can_bitcast(x: abi::Scalar) -> bool {
266            matches!(
267                x,
268                abi::Scalar::Initialized {
269                    value: abi::Primitive::Int(..) | abi::Primitive::Float(..),
270                    ..
271                }
272            )
273        }
274
275        let cx = bx.cx();
276        match (operand.val, operand.layout.backend_repr, cast.backend_repr) {
277            _ if cast.is_zst() => OperandValue::ZeroSized,
278            (OperandValue::Ref(source_place_val), abi::BackendRepr::Memory { .. }, _) => {
279                assert_eq!(source_place_val.llextra, None);
280                // The existing alignment is part of `source_place_val`,
281                // so that alignment will be used, not `cast`'s.
282                bx.load_operand(source_place_val.with_type(cast)).val
283            }
284            (
285                OperandValue::Immediate(imm),
286                abi::BackendRepr::Scalar(from_scalar),
287                abi::BackendRepr::Scalar(to_scalar),
288            ) if from_scalar.size(cx) == to_scalar.size(cx) => {
289                OperandValue::Immediate(transmute_scalar(bx, imm, from_scalar, to_scalar))
290            }
291            (
292                OperandValue::Immediate(imm),
293                abi::BackendRepr::SimdVector { element: from_scalar, .. },
294                abi::BackendRepr::SimdVector { element: to_scalar, .. },
295            ) if vector_can_bitcast(from_scalar) && vector_can_bitcast(to_scalar) => {
296                let to_backend_ty = bx.cx().immediate_backend_type(cast);
297                OperandValue::Immediate(bx.bitcast(imm, to_backend_ty))
298            }
299            (
300                OperandValue::Pair(imm_a, imm_b),
301                abi::BackendRepr::ScalarPair(in_a, in_b),
302                abi::BackendRepr::ScalarPair(out_a, out_b),
303            ) if in_a.size(cx) == out_a.size(cx) && in_b.size(cx) == out_b.size(cx) => {
304                OperandValue::Pair(
305                    transmute_scalar(bx, imm_a, in_a, out_a),
306                    transmute_scalar(bx, imm_b, in_b, out_b),
307                )
308            }
309            _ => {
310                // For any other potentially-tricky cases, make a temporary instead.
311                // If anything else wants the target local to be in memory this won't
312                // be hit, as `codegen_transmute` will get called directly. Thus this
313                // is only for places where everything else wants the operand form,
314                // and thus it's not worth making those places get it from memory.
315                //
316                // Notably, Scalar ⇌ ScalarPair cases go here to avoid padding
317                // and endianness issues, as do SimdVector ones to avoid worrying
318                // about things like f32x8 ⇌ ptrx4 that would need multiple steps.
319                let align = Ord::max(operand.layout.align.abi, cast.align.abi);
320                let size = Ord::max(operand.layout.size, cast.size);
321                let temp = PlaceValue::alloca(bx, size, align);
322                bx.lifetime_start(temp.llval, size);
323                operand.store_with_annotation(bx, temp.with_type(operand.layout));
324                let val = bx.load_operand(temp.with_type(cast)).val;
325                bx.lifetime_end(temp.llval, size);
326                val
327            }
328        }
329    }
330
331    /// Cast one of the immediates from an [`OperandValue::Immediate`]
332    /// or an [`OperandValue::Pair`] to an immediate of the target type.
333    ///
334    /// Returns `None` if the cast is not possible.
335    fn cast_immediate(
336        &self,
337        bx: &mut Bx,
338        mut imm: Bx::Value,
339        from_scalar: abi::Scalar,
340        from_backend_ty: Bx::Type,
341        to_scalar: abi::Scalar,
342        to_backend_ty: Bx::Type,
343    ) -> Option<Bx::Value> {
344        use abi::Primitive::*;
345
346        // When scalars are passed by value, there's no metadata recording their
347        // valid ranges. For example, `char`s are passed as just `i32`, with no
348        // way for LLVM to know that they're 0x10FFFF at most. Thus we assume
349        // the range of the input value too, not just the output range.
350        assume_scalar_range(bx, imm, from_scalar, from_backend_ty, None);
351
352        imm = match (from_scalar.primitive(), to_scalar.primitive()) {
353            (Int(_, is_signed), Int(..)) => bx.intcast(imm, to_backend_ty, is_signed),
354            (Float(_), Float(_)) => {
355                let srcsz = bx.cx().float_width(from_backend_ty);
356                let dstsz = bx.cx().float_width(to_backend_ty);
357                if dstsz > srcsz {
358                    bx.fpext(imm, to_backend_ty)
359                } else if srcsz > dstsz {
360                    bx.fptrunc(imm, to_backend_ty)
361                } else {
362                    imm
363                }
364            }
365            (Int(_, is_signed), Float(_)) => {
366                if is_signed {
367                    bx.sitofp(imm, to_backend_ty)
368                } else {
369                    bx.uitofp(imm, to_backend_ty)
370                }
371            }
372            (Pointer(..), Pointer(..)) => bx.pointercast(imm, to_backend_ty),
373            (Int(_, is_signed), Pointer(..)) => {
374                let usize_imm = bx.intcast(imm, bx.cx().type_isize(), is_signed);
375                bx.inttoptr(usize_imm, to_backend_ty)
376            }
377            (Float(_), Int(_, is_signed)) => bx.cast_float_to_int(is_signed, imm, to_backend_ty),
378            _ => return None,
379        };
380        Some(imm)
381    }
382
383    pub(crate) fn codegen_rvalue_operand(
384        &mut self,
385        bx: &mut Bx,
386        rvalue: &mir::Rvalue<'tcx>,
387    ) -> OperandRef<'tcx, Bx::Value> {
388        match *rvalue {
389            mir::Rvalue::Cast(ref kind, ref source, mir_cast_ty) => {
390                let operand = self.codegen_operand(bx, source);
391                debug!("cast operand is {:?}", operand);
392                let cast = bx.cx().layout_of(self.monomorphize(mir_cast_ty));
393
394                let val = match *kind {
395                    mir::CastKind::PointerExposeProvenance => {
396                        assert!(bx.cx().is_backend_immediate(cast));
397                        let llptr = operand.immediate();
398                        let llcast_ty = bx.cx().immediate_backend_type(cast);
399                        let lladdr = bx.ptrtoint(llptr, llcast_ty);
400                        OperandValue::Immediate(lladdr)
401                    }
402                    mir::CastKind::PointerCoercion(PointerCoercion::ReifyFnPointer, _) => {
403                        match *operand.layout.ty.kind() {
404                            ty::FnDef(def_id, args) => {
405                                let instance = ty::Instance::resolve_for_fn_ptr(
406                                    bx.tcx(),
407                                    bx.typing_env(),
408                                    def_id,
409                                    args,
410                                )
411                                .unwrap();
412                                OperandValue::Immediate(bx.get_fn_addr(instance))
413                            }
414                            _ => bug!("{} cannot be reified to a fn ptr", operand.layout.ty),
415                        }
416                    }
417                    mir::CastKind::PointerCoercion(PointerCoercion::ClosureFnPointer(_), _) => {
418                        match *operand.layout.ty.kind() {
419                            ty::Closure(def_id, args) => {
420                                let instance = Instance::resolve_closure(
421                                    bx.cx().tcx(),
422                                    def_id,
423                                    args,
424                                    ty::ClosureKind::FnOnce,
425                                );
426                                OperandValue::Immediate(bx.cx().get_fn_addr(instance))
427                            }
428                            _ => bug!("{} cannot be cast to a fn ptr", operand.layout.ty),
429                        }
430                    }
431                    mir::CastKind::PointerCoercion(PointerCoercion::UnsafeFnPointer, _) => {
432                        // This is a no-op at the LLVM level.
433                        operand.val
434                    }
435                    mir::CastKind::PointerCoercion(PointerCoercion::Unsize, _) => {
436                        assert!(bx.cx().is_backend_scalar_pair(cast));
437                        let (lldata, llextra) = operand.val.pointer_parts();
438                        let (lldata, llextra) =
439                            base::unsize_ptr(bx, lldata, operand.layout.ty, cast.ty, llextra);
440                        OperandValue::Pair(lldata, llextra)
441                    }
442                    mir::CastKind::PointerCoercion(
443                        PointerCoercion::MutToConstPointer | PointerCoercion::ArrayToPointer, _
444                    ) => {
445                        bug!("{kind:?} is for borrowck, and should never appear in codegen");
446                    }
447                    mir::CastKind::PtrToPtr
448                        if bx.cx().is_backend_scalar_pair(operand.layout) =>
449                    {
450                        if let OperandValue::Pair(data_ptr, meta) = operand.val {
451                            if bx.cx().is_backend_scalar_pair(cast) {
452                                OperandValue::Pair(data_ptr, meta)
453                            } else {
454                                // Cast of wide-ptr to thin-ptr is an extraction of data-ptr.
455                                OperandValue::Immediate(data_ptr)
456                            }
457                        } else {
458                            bug!("unexpected non-pair operand");
459                        }
460                    }
461                    | mir::CastKind::IntToInt
462                    | mir::CastKind::FloatToInt
463                    | mir::CastKind::FloatToFloat
464                    | mir::CastKind::IntToFloat
465                    | mir::CastKind::PtrToPtr
466                    | mir::CastKind::FnPtrToPtr
467                    // Since int2ptr can have arbitrary integer types as input (so we have to do
468                    // sign extension and all that), it is currently best handled in the same code
469                    // path as the other integer-to-X casts.
470                    | mir::CastKind::PointerWithExposedProvenance => {
471                        let imm = operand.immediate();
472                        let abi::BackendRepr::Scalar(from_scalar) = operand.layout.backend_repr else {
473                            bug!("Found non-scalar for operand {operand:?}");
474                        };
475                        let from_backend_ty = bx.cx().immediate_backend_type(operand.layout);
476
477                        assert!(bx.cx().is_backend_immediate(cast));
478                        let to_backend_ty = bx.cx().immediate_backend_type(cast);
479                        if operand.layout.is_uninhabited() {
480                            let val = OperandValue::Immediate(bx.cx().const_poison(to_backend_ty));
481                            return OperandRef { val, layout: cast, move_annotation: None };
482                        }
483                        let abi::BackendRepr::Scalar(to_scalar) = cast.layout.backend_repr else {
484                            bug!("Found non-scalar for cast {cast:?}");
485                        };
486
487                        self.cast_immediate(bx, imm, from_scalar, from_backend_ty, to_scalar, to_backend_ty)
488                            .map(OperandValue::Immediate)
489                            .unwrap_or_else(|| {
490                                bug!("Unsupported cast of {operand:?} to {cast:?}");
491                            })
492                    }
493                    mir::CastKind::Transmute | mir::CastKind::Subtype => {
494                        self.codegen_transmute_operand(bx, operand, cast)
495                    }
496                };
497                OperandRef { val, layout: cast, move_annotation: None }
498            }
499
500            mir::Rvalue::Ref(_, bk, place) => {
501                let mk_ref = move |tcx: TyCtxt<'tcx>, ty: Ty<'tcx>| {
502                    Ty::new_ref(tcx, tcx.lifetimes.re_erased, ty, bk.to_mutbl_lossy())
503                };
504                self.codegen_place_to_pointer(bx, place, mk_ref)
505            }
506
507            mir::Rvalue::RawPtr(kind, place) => {
508                let mk_ptr = move |tcx: TyCtxt<'tcx>, ty: Ty<'tcx>| {
509                    Ty::new_ptr(tcx, ty, kind.to_mutbl_lossy())
510                };
511                self.codegen_place_to_pointer(bx, place, mk_ptr)
512            }
513
514            mir::Rvalue::BinaryOp(op_with_overflow, box (ref lhs, ref rhs))
515                if let Some(op) = op_with_overflow.overflowing_to_wrapping() =>
516            {
517                let lhs = self.codegen_operand(bx, lhs);
518                let rhs = self.codegen_operand(bx, rhs);
519                let result = self.codegen_scalar_checked_binop(
520                    bx,
521                    op,
522                    lhs.immediate(),
523                    rhs.immediate(),
524                    lhs.layout.ty,
525                );
526                let val_ty = op.ty(bx.tcx(), lhs.layout.ty, rhs.layout.ty);
527                let operand_ty = Ty::new_tup(bx.tcx(), &[val_ty, bx.tcx().types.bool]);
528                OperandRef {
529                    val: result,
530                    layout: bx.cx().layout_of(operand_ty),
531                    move_annotation: None,
532                }
533            }
534            mir::Rvalue::BinaryOp(op, box (ref lhs, ref rhs)) => {
535                let lhs = self.codegen_operand(bx, lhs);
536                let rhs = self.codegen_operand(bx, rhs);
537                let llresult = match (lhs.val, rhs.val) {
538                    (
539                        OperandValue::Pair(lhs_addr, lhs_extra),
540                        OperandValue::Pair(rhs_addr, rhs_extra),
541                    ) => self.codegen_wide_ptr_binop(
542                        bx,
543                        op,
544                        lhs_addr,
545                        lhs_extra,
546                        rhs_addr,
547                        rhs_extra,
548                        lhs.layout.ty,
549                    ),
550
551                    (OperandValue::Immediate(lhs_val), OperandValue::Immediate(rhs_val)) => self
552                        .codegen_scalar_binop(
553                            bx,
554                            op,
555                            lhs_val,
556                            rhs_val,
557                            lhs.layout.ty,
558                            rhs.layout.ty,
559                        ),
560
561                    _ => bug!(),
562                };
563                OperandRef {
564                    val: OperandValue::Immediate(llresult),
565                    layout: bx.cx().layout_of(op.ty(bx.tcx(), lhs.layout.ty, rhs.layout.ty)),
566                    move_annotation: None,
567                }
568            }
569
570            mir::Rvalue::UnaryOp(op, ref operand) => {
571                let operand = self.codegen_operand(bx, operand);
572                let is_float = operand.layout.ty.is_floating_point();
573                let (val, layout) = match op {
574                    mir::UnOp::Not => {
575                        let llval = bx.not(operand.immediate());
576                        (OperandValue::Immediate(llval), operand.layout)
577                    }
578                    mir::UnOp::Neg => {
579                        let llval = if is_float {
580                            bx.fneg(operand.immediate())
581                        } else {
582                            bx.neg(operand.immediate())
583                        };
584                        (OperandValue::Immediate(llval), operand.layout)
585                    }
586                    mir::UnOp::PtrMetadata => {
587                        assert!(operand.layout.ty.is_raw_ptr() || operand.layout.ty.is_ref(),);
588                        let (_, meta) = operand.val.pointer_parts();
589                        assert_eq!(operand.layout.fields.count() > 1, meta.is_some());
590                        if let Some(meta) = meta {
591                            (OperandValue::Immediate(meta), operand.layout.field(self.cx, 1))
592                        } else {
593                            (OperandValue::ZeroSized, bx.cx().layout_of(bx.tcx().types.unit))
594                        }
595                    }
596                };
597                assert!(
598                    val.is_expected_variant_for_type(self.cx, layout),
599                    "Made wrong variant {val:?} for type {layout:?}",
600                );
601                OperandRef { val, layout, move_annotation: None }
602            }
603
604            mir::Rvalue::Discriminant(ref place) => {
605                let discr_ty = rvalue.ty(self.mir, bx.tcx());
606                let discr_ty = self.monomorphize(discr_ty);
607                let operand = self.codegen_consume(bx, place.as_ref());
608                let discr = operand.codegen_get_discr(self, bx, discr_ty);
609                OperandRef {
610                    val: OperandValue::Immediate(discr),
611                    layout: self.cx.layout_of(discr_ty),
612                    move_annotation: None,
613                }
614            }
615
616            mir::Rvalue::NullaryOp(ref null_op) => {
617                let val = match null_op {
618                    mir::NullOp::RuntimeChecks(kind) => {
619                        let val = kind.value(bx.tcx().sess);
620                        bx.cx().const_bool(val)
621                    }
622                };
623                let tcx = self.cx.tcx();
624                OperandRef {
625                    val: OperandValue::Immediate(val),
626                    layout: self.cx.layout_of(null_op.ty(tcx)),
627                    move_annotation: None,
628                }
629            }
630
631            mir::Rvalue::ThreadLocalRef(def_id) => {
632                assert!(bx.cx().tcx().is_static(def_id));
633                let layout = bx.layout_of(bx.cx().tcx().static_ptr_ty(def_id, bx.typing_env()));
634                let static_ = if !def_id.is_local() && bx.cx().tcx().needs_thread_local_shim(def_id)
635                {
636                    let instance = ty::Instance {
637                        def: ty::InstanceKind::ThreadLocalShim(def_id),
638                        args: ty::GenericArgs::empty(),
639                    };
640                    let fn_ptr = bx.get_fn_addr(instance);
641                    let fn_abi = bx.fn_abi_of_instance(instance, ty::List::empty());
642                    let fn_ty = bx.fn_decl_backend_type(fn_abi);
643                    let fn_attrs = if bx.tcx().def_kind(instance.def_id()).has_codegen_attrs() {
644                        Some(bx.tcx().codegen_instance_attrs(instance.def))
645                    } else {
646                        None
647                    };
648                    bx.call(
649                        fn_ty,
650                        fn_attrs.as_deref(),
651                        Some(fn_abi),
652                        fn_ptr,
653                        &[],
654                        None,
655                        Some(instance),
656                    )
657                } else {
658                    bx.get_static(def_id)
659                };
660                OperandRef { val: OperandValue::Immediate(static_), layout, move_annotation: None }
661            }
662            mir::Rvalue::Use(ref operand) => self.codegen_operand(bx, operand),
663            mir::Rvalue::Repeat(ref elem, len_const) => {
664                // All arrays have `BackendRepr::Memory`, so only the ZST cases
665                // end up here. Anything else forces the destination local to be
666                // `Memory`, and thus ends up handled in `codegen_rvalue` instead.
667                let operand = self.codegen_operand(bx, elem);
668                let array_ty = Ty::new_array_with_const_len(bx.tcx(), operand.layout.ty, len_const);
669                let array_ty = self.monomorphize(array_ty);
670                let array_layout = bx.layout_of(array_ty);
671                assert!(array_layout.is_zst());
672                OperandRef {
673                    val: OperandValue::ZeroSized,
674                    layout: array_layout,
675                    move_annotation: None,
676                }
677            }
678            mir::Rvalue::Aggregate(ref kind, ref fields) => {
679                let (variant_index, active_field_index) = match **kind {
680                    mir::AggregateKind::Adt(_, variant_index, _, _, active_field_index) => {
681                        (variant_index, active_field_index)
682                    }
683                    _ => (FIRST_VARIANT, None),
684                };
685
686                let ty = rvalue.ty(self.mir, self.cx.tcx());
687                let ty = self.monomorphize(ty);
688                let layout = self.cx.layout_of(ty);
689
690                let mut builder = OperandRefBuilder::new(layout);
691                for (field_idx, field) in fields.iter_enumerated() {
692                    let op = self.codegen_operand(bx, field);
693                    let fi = active_field_index.unwrap_or(field_idx);
694                    builder.insert_field(bx, variant_index, fi, op);
695                }
696
697                let tag_result = codegen_tag_value(self.cx, variant_index, layout);
698                match tag_result {
699                    Err(super::place::UninhabitedVariantError) => {
700                        // Like codegen_set_discr we use a sound abort, but could
701                        // potentially `unreachable` or just return the poison for
702                        // more optimizability, if that turns out to be helpful.
703                        bx.abort();
704                        let val = OperandValue::poison(bx, layout);
705                        OperandRef { val, layout, move_annotation: None }
706                    }
707                    Ok(maybe_tag_value) => {
708                        if let Some((tag_field, tag_imm)) = maybe_tag_value {
709                            builder.insert_imm(tag_field, tag_imm);
710                        }
711                        builder.build(bx.cx())
712                    }
713                }
714            }
715            mir::Rvalue::WrapUnsafeBinder(ref operand, binder_ty) => {
716                let operand = self.codegen_operand(bx, operand);
717                let binder_ty = self.monomorphize(binder_ty);
718                let layout = bx.cx().layout_of(binder_ty);
719                OperandRef { val: operand.val, layout, move_annotation: None }
720            }
721            mir::Rvalue::CopyForDeref(_) => bug!("`CopyForDeref` in codegen"),
722            mir::Rvalue::ShallowInitBox(..) => bug!("`ShallowInitBox` in codegen"),
723        }
724    }
725
726    /// Codegen an `Rvalue::RawPtr` or `Rvalue::Ref`
727    fn codegen_place_to_pointer(
728        &mut self,
729        bx: &mut Bx,
730        place: mir::Place<'tcx>,
731        mk_ptr_ty: impl FnOnce(TyCtxt<'tcx>, Ty<'tcx>) -> Ty<'tcx>,
732    ) -> OperandRef<'tcx, Bx::Value> {
733        let cg_place = self.codegen_place(bx, place.as_ref());
734        let val = cg_place.val.address();
735
736        let ty = cg_place.layout.ty;
737        assert!(
738            if bx.cx().tcx().type_has_metadata(ty, bx.cx().typing_env()) {
739                matches!(val, OperandValue::Pair(..))
740            } else {
741                matches!(val, OperandValue::Immediate(..))
742            },
743            "Address of place was unexpectedly {val:?} for pointee type {ty:?}",
744        );
745
746        OperandRef {
747            val,
748            layout: self.cx.layout_of(mk_ptr_ty(self.cx.tcx(), ty)),
749            move_annotation: None,
750        }
751    }
752
753    fn codegen_scalar_binop(
754        &mut self,
755        bx: &mut Bx,
756        op: mir::BinOp,
757        lhs: Bx::Value,
758        rhs: Bx::Value,
759        lhs_ty: Ty<'tcx>,
760        rhs_ty: Ty<'tcx>,
761    ) -> Bx::Value {
762        let is_float = lhs_ty.is_floating_point();
763        let is_signed = lhs_ty.is_signed();
764        match op {
765            mir::BinOp::Add => {
766                if is_float {
767                    bx.fadd(lhs, rhs)
768                } else {
769                    bx.add(lhs, rhs)
770                }
771            }
772            mir::BinOp::AddUnchecked => {
773                if is_signed {
774                    bx.unchecked_sadd(lhs, rhs)
775                } else {
776                    bx.unchecked_uadd(lhs, rhs)
777                }
778            }
779            mir::BinOp::Sub => {
780                if is_float {
781                    bx.fsub(lhs, rhs)
782                } else {
783                    bx.sub(lhs, rhs)
784                }
785            }
786            mir::BinOp::SubUnchecked => {
787                if is_signed {
788                    bx.unchecked_ssub(lhs, rhs)
789                } else {
790                    bx.unchecked_usub(lhs, rhs)
791                }
792            }
793            mir::BinOp::Mul => {
794                if is_float {
795                    bx.fmul(lhs, rhs)
796                } else {
797                    bx.mul(lhs, rhs)
798                }
799            }
800            mir::BinOp::MulUnchecked => {
801                if is_signed {
802                    bx.unchecked_smul(lhs, rhs)
803                } else {
804                    bx.unchecked_umul(lhs, rhs)
805                }
806            }
807            mir::BinOp::Div => {
808                if is_float {
809                    bx.fdiv(lhs, rhs)
810                } else if is_signed {
811                    bx.sdiv(lhs, rhs)
812                } else {
813                    bx.udiv(lhs, rhs)
814                }
815            }
816            mir::BinOp::Rem => {
817                if is_float {
818                    bx.frem(lhs, rhs)
819                } else if is_signed {
820                    bx.srem(lhs, rhs)
821                } else {
822                    bx.urem(lhs, rhs)
823                }
824            }
825            mir::BinOp::BitOr => bx.or(lhs, rhs),
826            mir::BinOp::BitAnd => bx.and(lhs, rhs),
827            mir::BinOp::BitXor => bx.xor(lhs, rhs),
828            mir::BinOp::Offset => {
829                let pointee_type = lhs_ty
830                    .builtin_deref(true)
831                    .unwrap_or_else(|| bug!("deref of non-pointer {:?}", lhs_ty));
832                let pointee_layout = bx.cx().layout_of(pointee_type);
833                if pointee_layout.is_zst() {
834                    // `Offset` works in terms of the size of pointee,
835                    // so offsetting a pointer to ZST is a noop.
836                    lhs
837                } else {
838                    let llty = bx.cx().backend_type(pointee_layout);
839                    if !rhs_ty.is_signed() {
840                        bx.inbounds_nuw_gep(llty, lhs, &[rhs])
841                    } else {
842                        bx.inbounds_gep(llty, lhs, &[rhs])
843                    }
844                }
845            }
846            mir::BinOp::Shl | mir::BinOp::ShlUnchecked => {
847                let rhs = base::build_shift_expr_rhs(bx, lhs, rhs, op == mir::BinOp::ShlUnchecked);
848                bx.shl(lhs, rhs)
849            }
850            mir::BinOp::Shr | mir::BinOp::ShrUnchecked => {
851                let rhs = base::build_shift_expr_rhs(bx, lhs, rhs, op == mir::BinOp::ShrUnchecked);
852                if is_signed { bx.ashr(lhs, rhs) } else { bx.lshr(lhs, rhs) }
853            }
854            mir::BinOp::Ne
855            | mir::BinOp::Lt
856            | mir::BinOp::Gt
857            | mir::BinOp::Eq
858            | mir::BinOp::Le
859            | mir::BinOp::Ge => {
860                if is_float {
861                    bx.fcmp(base::bin_op_to_fcmp_predicate(op), lhs, rhs)
862                } else {
863                    bx.icmp(base::bin_op_to_icmp_predicate(op, is_signed), lhs, rhs)
864                }
865            }
866            mir::BinOp::Cmp => {
867                assert!(!is_float);
868                bx.three_way_compare(lhs_ty, lhs, rhs)
869            }
870            mir::BinOp::AddWithOverflow
871            | mir::BinOp::SubWithOverflow
872            | mir::BinOp::MulWithOverflow => {
873                bug!("{op:?} needs to return a pair, so call codegen_scalar_checked_binop instead")
874            }
875        }
876    }
877
878    fn codegen_wide_ptr_binop(
879        &mut self,
880        bx: &mut Bx,
881        op: mir::BinOp,
882        lhs_addr: Bx::Value,
883        lhs_extra: Bx::Value,
884        rhs_addr: Bx::Value,
885        rhs_extra: Bx::Value,
886        _input_ty: Ty<'tcx>,
887    ) -> Bx::Value {
888        match op {
889            mir::BinOp::Eq => {
890                let lhs = bx.icmp(IntPredicate::IntEQ, lhs_addr, rhs_addr);
891                let rhs = bx.icmp(IntPredicate::IntEQ, lhs_extra, rhs_extra);
892                bx.and(lhs, rhs)
893            }
894            mir::BinOp::Ne => {
895                let lhs = bx.icmp(IntPredicate::IntNE, lhs_addr, rhs_addr);
896                let rhs = bx.icmp(IntPredicate::IntNE, lhs_extra, rhs_extra);
897                bx.or(lhs, rhs)
898            }
899            mir::BinOp::Le | mir::BinOp::Lt | mir::BinOp::Ge | mir::BinOp::Gt => {
900                // a OP b ~ a.0 STRICT(OP) b.0 | (a.0 == b.0 && a.1 OP a.1)
901                let (op, strict_op) = match op {
902                    mir::BinOp::Lt => (IntPredicate::IntULT, IntPredicate::IntULT),
903                    mir::BinOp::Le => (IntPredicate::IntULE, IntPredicate::IntULT),
904                    mir::BinOp::Gt => (IntPredicate::IntUGT, IntPredicate::IntUGT),
905                    mir::BinOp::Ge => (IntPredicate::IntUGE, IntPredicate::IntUGT),
906                    _ => bug!(),
907                };
908                let lhs = bx.icmp(strict_op, lhs_addr, rhs_addr);
909                let and_lhs = bx.icmp(IntPredicate::IntEQ, lhs_addr, rhs_addr);
910                let and_rhs = bx.icmp(op, lhs_extra, rhs_extra);
911                let rhs = bx.and(and_lhs, and_rhs);
912                bx.or(lhs, rhs)
913            }
914            _ => {
915                bug!("unexpected wide ptr binop");
916            }
917        }
918    }
919
920    fn codegen_scalar_checked_binop(
921        &mut self,
922        bx: &mut Bx,
923        op: mir::BinOp,
924        lhs: Bx::Value,
925        rhs: Bx::Value,
926        input_ty: Ty<'tcx>,
927    ) -> OperandValue<Bx::Value> {
928        let (val, of) = match op {
929            // These are checked using intrinsics
930            mir::BinOp::Add | mir::BinOp::Sub | mir::BinOp::Mul => {
931                let oop = match op {
932                    mir::BinOp::Add => OverflowOp::Add,
933                    mir::BinOp::Sub => OverflowOp::Sub,
934                    mir::BinOp::Mul => OverflowOp::Mul,
935                    _ => unreachable!(),
936                };
937                bx.checked_binop(oop, input_ty, lhs, rhs)
938            }
939            _ => bug!("Operator `{:?}` is not a checkable operator", op),
940        };
941
942        OperandValue::Pair(val, of)
943    }
944}
945
946/// Transmutes a single scalar value `imm` from `from_scalar` to `to_scalar`.
947///
948/// This is expected to be in *immediate* form, as seen in [`OperandValue::Immediate`]
949/// or [`OperandValue::Pair`] (so `i1` for bools, not `i8`, for example).
950///
951/// ICEs if the passed-in `imm` is not a value of the expected type for
952/// `from_scalar`, such as if it's a vector or a pair.
953pub(super) fn transmute_scalar<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
954    bx: &mut Bx,
955    mut imm: Bx::Value,
956    from_scalar: abi::Scalar,
957    to_scalar: abi::Scalar,
958) -> Bx::Value {
959    assert_eq!(from_scalar.size(bx.cx()), to_scalar.size(bx.cx()));
960    let imm_ty = bx.cx().val_ty(imm);
961    assert_ne!(
962        bx.cx().type_kind(imm_ty),
963        TypeKind::Vector,
964        "Vector type {imm_ty:?} not allowed in transmute_scalar {from_scalar:?} -> {to_scalar:?}"
965    );
966
967    // While optimizations will remove no-op transmutes, they might still be
968    // there in debug or things that aren't no-op in MIR because they change
969    // the Rust type but not the underlying layout/niche.
970    if from_scalar == to_scalar {
971        return imm;
972    }
973
974    use abi::Primitive::*;
975    imm = bx.from_immediate(imm);
976
977    let from_backend_ty = bx.cx().type_from_scalar(from_scalar);
978    debug_assert_eq!(bx.cx().val_ty(imm), from_backend_ty);
979    let to_backend_ty = bx.cx().type_from_scalar(to_scalar);
980
981    // If we have a scalar, we must already know its range. Either
982    //
983    // 1) It's a parameter with `range` parameter metadata,
984    // 2) It's something we `load`ed with `!range` metadata, or
985    // 3) After a transmute we `assume`d the range (see below).
986    //
987    // That said, last time we tried removing this, it didn't actually help
988    // the rustc-perf results, so might as well keep doing it
989    // <https://github.com/rust-lang/rust/pull/135610#issuecomment-2599275182>
990    assume_scalar_range(bx, imm, from_scalar, from_backend_ty, Some(&to_scalar));
991
992    imm = match (from_scalar.primitive(), to_scalar.primitive()) {
993        (Int(..) | Float(_), Int(..) | Float(_)) => bx.bitcast(imm, to_backend_ty),
994        (Pointer(..), Pointer(..)) => bx.pointercast(imm, to_backend_ty),
995        (Int(..), Pointer(..)) => bx.inttoptr(imm, to_backend_ty),
996        (Pointer(..), Int(..)) => {
997            // FIXME: this exposes the provenance, which shouldn't be necessary.
998            bx.ptrtoint(imm, to_backend_ty)
999        }
1000        (Float(_), Pointer(..)) => {
1001            let int_imm = bx.bitcast(imm, bx.cx().type_isize());
1002            bx.inttoptr(int_imm, to_backend_ty)
1003        }
1004        (Pointer(..), Float(_)) => {
1005            // FIXME: this exposes the provenance, which shouldn't be necessary.
1006            let int_imm = bx.ptrtoint(imm, bx.cx().type_isize());
1007            bx.bitcast(int_imm, to_backend_ty)
1008        }
1009    };
1010
1011    debug_assert_eq!(bx.cx().val_ty(imm), to_backend_ty);
1012
1013    // This `assume` remains important for cases like (a conceptual)
1014    //    transmute::<u32, NonZeroU32>(x) == 0
1015    // since it's never passed to something with parameter metadata (especially
1016    // after MIR inlining) so the only way to tell the backend about the
1017    // constraint that the `transmute` introduced is to `assume` it.
1018    assume_scalar_range(bx, imm, to_scalar, to_backend_ty, Some(&from_scalar));
1019
1020    imm = bx.to_immediate_scalar(imm, to_scalar);
1021    imm
1022}
1023
1024/// Emits an `assume` call that `imm`'s value is within the known range of `scalar`.
1025///
1026/// If `known` is `Some`, only emits the assume if it's more specific than
1027/// whatever is already known from the range of *that* scalar.
1028fn assume_scalar_range<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
1029    bx: &mut Bx,
1030    imm: Bx::Value,
1031    scalar: abi::Scalar,
1032    backend_ty: Bx::Type,
1033    known: Option<&abi::Scalar>,
1034) {
1035    if matches!(bx.cx().sess().opts.optimize, OptLevel::No) {
1036        return;
1037    }
1038
1039    match (scalar, known) {
1040        (abi::Scalar::Union { .. }, _) => return,
1041        (_, None) => {
1042            if scalar.is_always_valid(bx.cx()) {
1043                return;
1044            }
1045        }
1046        (abi::Scalar::Initialized { valid_range, .. }, Some(known)) => {
1047            let known_range = known.valid_range(bx.cx());
1048            if valid_range.contains_range(known_range, scalar.size(bx.cx())) {
1049                return;
1050            }
1051        }
1052    }
1053
1054    match scalar.primitive() {
1055        abi::Primitive::Int(..) => {
1056            let range = scalar.valid_range(bx.cx());
1057            bx.assume_integer_range(imm, backend_ty, range);
1058        }
1059        abi::Primitive::Pointer(abi::AddressSpace::ZERO)
1060            if !scalar.valid_range(bx.cx()).contains(0) =>
1061        {
1062            bx.assume_nonnull(imm);
1063        }
1064        abi::Primitive::Pointer(..) | abi::Primitive::Float(..) => {}
1065    }
1066}