Skip to main content

rustc_target/callconv/
loongarch.rs

1use rustc_abi::{
2    BackendRepr, CanonAbi, FieldsShape, HasDataLayout, Primitive, Reg, RegKind, Size,
3    TyAbiInterface, TyAndLayout, Variants,
4};
5
6use crate::callconv::{
7    ArgAbi, ArgExtension, CastTarget, ComputeCallConv, FnAbi, PassMode, Uniform,
8};
9use crate::spec::{HasTargetSpec, LlvmAbi};
10
11#[derive(#[automatically_derived]impl ::core::marker::Copy for RegPassKind { }Copy, #[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for RegPassKind {
}
#[automatically_derived]impl ::core::clone::Clone for RegPassKind {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self {
        let _: ::core::clone::AssertParamIsClone<Size>;
        let _: ::core::clone::AssertParamIsClone<Reg>;
        *self
    }
}Clone)]
12enum RegPassKind {
13    Float { offset_from_start: Size, ty: Reg },
14    Integer { offset_from_start: Size, ty: Reg },
15    Unknown,
16}
17
18#[derive(#[automatically_derived]impl ::core::marker::Copy for FloatConv { }Copy, #[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for FloatConv {
}
#[automatically_derived]impl ::core::clone::Clone for FloatConv {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self {
        let _: ::core::clone::AssertParamIsClone<Reg>;
        let _: ::core::clone::AssertParamIsClone<Size>;
        *self
    }
}Clone)]
19enum FloatConv {
20    FloatPair { first_ty: Reg, second_ty_offset_from_start: Size, second_ty: Reg },
21    Float(Reg),
22    MixedPair { first_ty: Reg, second_ty_offset_from_start: Size, second_ty: Reg },
23}
24
25#[derive(#[automatically_derived]impl ::core::marker::Copy for CannotUseFpConv { }Copy, #[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for CannotUseFpConv {
}
#[automatically_derived]impl ::core::clone::Clone for CannotUseFpConv {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self { *self }
}Clone)]
26struct CannotUseFpConv;
27
28fn is_loongarch_aggregate<Ty>(arg: &ArgAbi<'_, Ty>) -> bool {
29    match arg.layout.backend_repr {
30        BackendRepr::SimdVector { .. } => true,
31        _ => arg.layout.is_aggregate(),
32    }
33}
34
35fn should_use_fp_conv_helper<'a, Ty, C>(
36    cx: &C,
37    arg_layout: &TyAndLayout<'a, Ty>,
38    xlen: u64,
39    flen: u64,
40    field1_kind: &mut RegPassKind,
41    field2_kind: &mut RegPassKind,
42    offset_from_start: Size,
43) -> Result<(), CannotUseFpConv>
44where
45    Ty: TyAbiInterface<'a, C> + Copy,
46{
47    match arg_layout.backend_repr {
48        BackendRepr::Scalar(scalar) => match scalar.primitive() {
49            Primitive::Bool | Primitive::Int(..) | Primitive::Pointer(_) => {
50                if arg_layout.size.bits() > xlen {
51                    return Err(CannotUseFpConv);
52                }
53                match (*field1_kind, *field2_kind) {
54                    (RegPassKind::Unknown, _) => {
55                        *field1_kind = RegPassKind::Integer {
56                            offset_from_start,
57                            ty: Reg { kind: RegKind::Integer, size: arg_layout.size },
58                        };
59                    }
60                    (RegPassKind::Float { .. }, RegPassKind::Unknown) => {
61                        *field2_kind = RegPassKind::Integer {
62                            offset_from_start,
63                            ty: Reg { kind: RegKind::Integer, size: arg_layout.size },
64                        };
65                    }
66                    _ => return Err(CannotUseFpConv),
67                }
68            }
69            Primitive::Float(_) => {
70                if arg_layout.size.bits() > flen {
71                    return Err(CannotUseFpConv);
72                }
73                match (*field1_kind, *field2_kind) {
74                    (RegPassKind::Unknown, _) => {
75                        *field1_kind = RegPassKind::Float {
76                            offset_from_start,
77                            ty: Reg { kind: RegKind::Float, size: arg_layout.size },
78                        };
79                    }
80                    (_, RegPassKind::Unknown) => {
81                        *field2_kind = RegPassKind::Float {
82                            offset_from_start,
83                            ty: Reg { kind: RegKind::Float, size: arg_layout.size },
84                        };
85                    }
86                    _ => return Err(CannotUseFpConv),
87                }
88            }
89        },
90        BackendRepr::SimdVector { .. } => {
91            return Err(CannotUseFpConv);
92        }
93        BackendRepr::SimdScalableVector { .. } => {
    ::core::panicking::panic_fmt(format_args!("scalable vectors are unsupported"));
}panic!("scalable vectors are unsupported"),
94        BackendRepr::ScalarPair { .. } | BackendRepr::Memory { .. } => match arg_layout.fields {
95            FieldsShape::Primitive => {
96                {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("aggregates can\'t have `FieldsShape::Primitive`")));
}unreachable!("aggregates can't have `FieldsShape::Primitive`")
97            }
98            FieldsShape::Union(_) => {
99                if !arg_layout.is_zst() {
100                    if arg_layout.is_transparent() {
101                        let non_1zst_elem = arg_layout.non_1zst_field(cx).expect("not exactly one non-1-ZST field in non-ZST repr(transparent) union").1;
102                        return should_use_fp_conv_helper(
103                            cx,
104                            &non_1zst_elem,
105                            xlen,
106                            flen,
107                            field1_kind,
108                            field2_kind,
109                            offset_from_start,
110                        );
111                    }
112                    return Err(CannotUseFpConv);
113                }
114            }
115            FieldsShape::Array { count, .. } => {
116                for i in 0..count {
117                    let elem_layout = arg_layout.field(cx, 0);
118                    should_use_fp_conv_helper(
119                        cx,
120                        &elem_layout,
121                        xlen,
122                        flen,
123                        field1_kind,
124                        field2_kind,
125                        offset_from_start + elem_layout.size * i,
126                    )?;
127                }
128            }
129            FieldsShape::Arbitrary { .. } => {
130                match arg_layout.variants {
131                    Variants::Multiple { .. } => return Err(CannotUseFpConv),
132                    Variants::Single { .. } | Variants::Empty => (),
133                }
134                for i in arg_layout.fields.index_by_increasing_offset() {
135                    let field = arg_layout.field(cx, i);
136                    should_use_fp_conv_helper(
137                        cx,
138                        &field,
139                        xlen,
140                        flen,
141                        field1_kind,
142                        field2_kind,
143                        offset_from_start + arg_layout.fields.offset(i),
144                    )?;
145                }
146            }
147        },
148    }
149    Ok(())
150}
151
152fn should_use_fp_conv<'a, Ty, C>(
153    cx: &C,
154    arg: &TyAndLayout<'a, Ty>,
155    xlen: u64,
156    flen: u64,
157) -> Option<FloatConv>
158where
159    Ty: TyAbiInterface<'a, C> + Copy,
160{
161    let mut field1_kind = RegPassKind::Unknown;
162    let mut field2_kind = RegPassKind::Unknown;
163    if should_use_fp_conv_helper(
164        cx,
165        arg,
166        xlen,
167        flen,
168        &mut field1_kind,
169        &mut field2_kind,
170        Size::ZERO,
171    )
172    .is_err()
173    {
174        return None;
175    }
176    match (field1_kind, field2_kind) {
177        (
178            RegPassKind::Integer { offset_from_start, .. }
179            | RegPassKind::Float { offset_from_start, .. },
180            _,
181        ) if offset_from_start != Size::ZERO => {
182            {
    ::core::panicking::panic_fmt(format_args!("type {0:?} has a first field with non-zero offset {1:?}",
            arg.ty, offset_from_start));
}panic!("type {:?} has a first field with non-zero offset {offset_from_start:?}", arg.ty)
183        }
184        (
185            RegPassKind::Integer { ty: first_ty, .. },
186            RegPassKind::Float { offset_from_start, ty: second_ty },
187        ) => Some(FloatConv::MixedPair {
188            first_ty,
189            second_ty_offset_from_start: offset_from_start,
190            second_ty,
191        }),
192        (
193            RegPassKind::Float { ty: first_ty, .. },
194            RegPassKind::Integer { offset_from_start, ty: second_ty },
195        ) => Some(FloatConv::MixedPair {
196            first_ty,
197            second_ty_offset_from_start: offset_from_start,
198            second_ty,
199        }),
200        (
201            RegPassKind::Float { ty: first_ty, .. },
202            RegPassKind::Float { offset_from_start, ty: second_ty },
203        ) => Some(FloatConv::FloatPair {
204            first_ty,
205            second_ty_offset_from_start: offset_from_start,
206            second_ty,
207        }),
208        (RegPassKind::Float { ty, .. }, RegPassKind::Unknown) => Some(FloatConv::Float(ty)),
209        _ => None,
210    }
211}
212
213fn classify_ret<'a, Ty, C>(cx: &C, arg: &mut ArgAbi<'a, Ty>, xlen: u64, flen: u64) -> bool
214where
215    Ty: TyAbiInterface<'a, C> + Copy,
216{
217    if !arg.layout.is_sized() {
218        // Not touching this...
219        return false; // I guess? return value of this function is not documented
220    }
221    if let Some(conv) = should_use_fp_conv(cx, &arg.layout, xlen, flen) {
222        match conv {
223            FloatConv::Float(f) => {
224                arg.cast_to(f);
225            }
226            FloatConv::FloatPair { first_ty, second_ty_offset_from_start, second_ty } => {
227                arg.cast_to(CastTarget::offset_pair(
228                    first_ty,
229                    second_ty_offset_from_start,
230                    second_ty,
231                ));
232            }
233            FloatConv::MixedPair { first_ty, second_ty_offset_from_start, second_ty } => {
234                arg.cast_to(CastTarget::offset_pair(
235                    first_ty,
236                    second_ty_offset_from_start,
237                    second_ty,
238                ));
239            }
240        }
241        return false;
242    }
243
244    let total = arg.layout.size;
245
246    // "Scalars wider than 2✕XLEN are passed by reference and are replaced in
247    // the argument list with the address."
248    // "Aggregates larger than 2✕XLEN bits are passed by reference and are
249    // replaced in the argument list with the address, as are C++ aggregates
250    // with nontrivial copy constructors, destructors, or vtables."
251    if total.bits() > 2 * xlen {
252        // We rely on the LLVM backend lowering code to lower passing a scalar larger than 2*XLEN.
253        if is_loongarch_aggregate(arg) {
254            arg.make_indirect();
255        }
256        return true;
257    }
258
259    let xlen_reg = match xlen {
260        32 => Reg::i32(),
261        64 => Reg::i64(),
262        _ => {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("Unsupported XLEN: {0}", xlen)));
}unreachable!("Unsupported XLEN: {}", xlen),
263    };
264    if is_loongarch_aggregate(arg) {
265        if total.bits() <= xlen {
266            arg.cast_to(xlen_reg);
267        } else {
268            arg.cast_to(Uniform::new(xlen_reg, Size::from_bits(xlen * 2)));
269        }
270        return false;
271    }
272
273    // "When passed in registers, scalars narrower than XLEN bits are widened
274    // according to the sign of their type up to 32 bits, then sign-extended to
275    // XLEN bits."
276    extend_integer_width(arg, xlen);
277    false
278}
279
280fn classify_arg<'a, Ty, C>(
281    cx: &C,
282    arg: &mut ArgAbi<'a, Ty>,
283    xlen: u64,
284    flen: u64,
285    is_vararg: bool,
286    avail_gprs: &mut u64,
287    avail_fprs: &mut u64,
288) where
289    Ty: TyAbiInterface<'a, C> + Copy,
290{
291    if !arg.layout.is_sized() {
292        // Not touching this...
293        return;
294    }
295    if arg.layout.pass_indirectly_in_non_rustic_abis(cx) {
296        arg.make_indirect();
297        *avail_gprs = (*avail_gprs).saturating_sub(1);
298        return;
299    }
300    if !is_vararg {
301        match should_use_fp_conv(cx, &arg.layout, xlen, flen) {
302            Some(FloatConv::Float(f)) if *avail_fprs >= 1 => {
303                *avail_fprs -= 1;
304                arg.cast_to(f);
305                return;
306            }
307            Some(FloatConv::FloatPair { first_ty, second_ty_offset_from_start, second_ty })
308                if *avail_fprs >= 2 =>
309            {
310                *avail_fprs -= 2;
311                arg.cast_to(CastTarget::offset_pair(
312                    first_ty,
313                    second_ty_offset_from_start,
314                    second_ty,
315                ));
316                return;
317            }
318            Some(FloatConv::MixedPair { first_ty, second_ty_offset_from_start, second_ty })
319                if *avail_fprs >= 1 && *avail_gprs >= 1 =>
320            {
321                *avail_gprs -= 1;
322                *avail_fprs -= 1;
323                arg.cast_to(CastTarget::offset_pair(
324                    first_ty,
325                    second_ty_offset_from_start,
326                    second_ty,
327                ));
328                return;
329            }
330            _ => (),
331        }
332    }
333
334    let total = arg.layout.size;
335    let align = arg.layout.align.bits();
336
337    // "Scalars wider than 2✕XLEN are passed by reference and are replaced in
338    // the argument list with the address."
339    // "Aggregates larger than 2✕XLEN bits are passed by reference and are
340    // replaced in the argument list with the address, as are C++ aggregates
341    // with nontrivial copy constructors, destructors, or vtables."
342    if total.bits() > 2 * xlen {
343        // We rely on the LLVM backend lowering code to lower passing a scalar larger than 2*XLEN.
344        if is_loongarch_aggregate(arg) {
345            arg.make_indirect();
346        }
347        if *avail_gprs >= 1 {
348            *avail_gprs -= 1;
349        }
350        return;
351    }
352
353    let double_xlen_reg = match xlen {
354        32 => Reg::i64(),
355        64 => Reg::i128(),
356        _ => {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("Unsupported XLEN: {0}", xlen)));
}unreachable!("Unsupported XLEN: {}", xlen),
357    };
358
359    let xlen_reg = match xlen {
360        32 => Reg::i32(),
361        64 => Reg::i64(),
362        _ => {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("Unsupported XLEN: {0}", xlen)));
}unreachable!("Unsupported XLEN: {}", xlen),
363    };
364
365    if total.bits() > xlen {
366        let align_regs = align > xlen;
367        if is_loongarch_aggregate(arg) {
368            arg.cast_to(Uniform::new(
369                if align_regs { double_xlen_reg } else { xlen_reg },
370                Size::from_bits(xlen * 2),
371            ));
372        }
373        if align_regs && is_vararg {
374            *avail_gprs -= *avail_gprs % 2;
375        }
376        if *avail_gprs >= 2 {
377            *avail_gprs -= 2;
378        } else {
379            *avail_gprs = 0;
380        }
381        return;
382    } else if is_loongarch_aggregate(arg) {
383        arg.cast_to(xlen_reg);
384        if *avail_gprs >= 1 {
385            *avail_gprs -= 1;
386        }
387        return;
388    }
389
390    // "When passed in registers, scalars narrower than XLEN bits are widened
391    // according to the sign of their type up to 32 bits, then sign-extended to
392    // XLEN bits."
393    if *avail_gprs >= 1 {
394        extend_integer_width(arg, xlen);
395        *avail_gprs -= 1;
396    }
397}
398
399fn extend_integer_width<Ty>(arg: &mut ArgAbi<'_, Ty>, xlen: u64) {
400    if let BackendRepr::Scalar(scalar) = arg.layout.backend_repr
401        && let Primitive::Int(i, _) = scalar.primitive()
402        && i.size().bits() == 32
403        && xlen > 32
404        && let PassMode::Direct(ref mut attrs) = arg.mode
405    {
406        // 32-bit integers are always sign-extended
407        attrs.ext(ArgExtension::Sext);
408        return;
409    }
410
411    arg.extend_integer_width_to(xlen);
412}
413
414pub(crate) struct LoongArchCallConv {
415    xlen: u64,
416    flen: u64,
417    avail_gprs: u64,
418    avail_fprs: u64,
419}
420
421impl<'a, Ty, C> ComputeCallConv<'a, Ty, C> for LoongArchCallConv
422where
423    Ty: TyAbiInterface<'a, C> + Copy,
424    C: HasDataLayout + HasTargetSpec,
425{
426    fn new(cx: &C, _conv: CanonAbi, _c_variadic: bool) -> Self {
427        let xlen = cx.data_layout().pointer_size().bits();
428        let flen = match &cx.target_spec().llvm_abiname {
429            LlvmAbi::Ilp32f | LlvmAbi::Lp64f => 32,
430            LlvmAbi::Ilp32d | LlvmAbi::Lp64d => 64,
431            _ => 0,
432        };
433
434        let avail_gprs = 8;
435        let avail_fprs = 8;
436
437        Self { xlen, flen, avail_gprs, avail_fprs }
438    }
439
440    fn compute_ret_abi(&mut self, cx: &C, ret: &mut ArgAbi<'a, Ty>) {
441        if classify_ret(cx, ret, self.xlen, self.flen) {
442            self.avail_gprs -= 1;
443        }
444    }
445
446    fn compute_arg_abi(&mut self, cx: &C, arg: &mut ArgAbi<'a, Ty>, is_vararg: bool) {
447        classify_arg(
448            cx,
449            arg,
450            self.xlen,
451            self.flen,
452            is_vararg,
453            &mut self.avail_gprs,
454            &mut self.avail_fprs,
455        );
456    }
457}
458
459pub(crate) fn compute_rust_abi_info<'a, Ty, C>(cx: &C, fn_abi: &mut FnAbi<'a, Ty>)
460where
461    Ty: TyAbiInterface<'a, C> + Copy,
462    C: HasDataLayout + HasTargetSpec,
463{
464    let grlen = cx.data_layout().pointer_size().bits();
465
466    for arg in fn_abi.args.iter_mut() {
467        if arg.is_ignore() {
468            continue;
469        }
470
471        // LLVM integers types do not differentiate between signed or unsigned integers.
472        // Some LoongArch instructions do not have a `.w` suffix version, they use all the
473        // GRLEN bits. By explicitly setting the `signext` or `zeroext` attribute
474        // according to signedness to avoid unnecessary integer extending instructions.
475        //
476        // This is similar to the RISC-V case, see
477        // https://github.com/rust-lang/rust/issues/114508 for details.
478        extend_integer_width(arg, grlen);
479    }
480}