Skip to main content

rustc_target/callconv/
mips64.rs

1use arrayvec::ArrayVec;
2use rustc_abi::{
3    BackendRepr, CanonAbi, FieldsShape, Float, HasDataLayout, Integer, Numeric, Primitive, Reg,
4    RegKind, Size, TyAbiInterface,
5};
6
7use crate::callconv::{
8    ArgAbi, ArgAttribute, ArgExtension, CastTarget, ComputeCallConv, PassMode, Uniform,
9};
10
11fn extend_integer_width_mips<Ty>(arg: &mut ArgAbi<'_, Ty>, bits: u64) {
12    // Always sign extend u32 values on 64-bit mips
13    if let BackendRepr::Scalar(scalar) = arg.layout.backend_repr
14        && let Primitive::Int(i, signed) = scalar.primitive()
15        && !signed
16        && i.size().bits() == 32
17        && let PassMode::Direct(ref mut attrs) = arg.mode
18    {
19        attrs.ext(ArgExtension::Sext);
20        return;
21    }
22
23    arg.extend_integer_width_to(bits);
24}
25
26fn float_reg<'a, Ty, C>(cx: &C, ret: &ArgAbi<'a, Ty>, i: usize) -> Option<Reg>
27where
28    Ty: TyAbiInterface<'a, C> + Copy,
29    C: HasDataLayout,
30{
31    match ret.layout.field(cx, i).backend_repr {
32        BackendRepr::Scalar(scalar) => match scalar.primitive() {
33            Primitive::Float(float) => {
34                match float {
35                    // C does not have the f16 type
36                    Float::F16 => None,
37                    Float::F32 => Some(Reg::f32()),
38                    Float::F64 => Some(Reg::f64()),
39                    Float::F128 => Some(Reg::f128()),
40                    Float::F16B => {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("`f16b` unsupported on mips64")));
}unreachable!("`f16b` unsupported on mips64"),
41                    Float::X87F80 => {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("`x87_f80` unsupported on mips64")));
}unreachable!("`x87_f80` unsupported on mips64"),
42                    Float::PpcF128 => {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("`ppcf128` unsupported on mips64")));
}unreachable!("`ppcf128` unsupported on mips64"),
43                }
44            }
45            _ => None,
46        },
47        _ => None,
48    }
49}
50
51fn classify_ret<'a, Ty, C>(cx: &C, ret: &mut ArgAbi<'a, Ty>, offset: &mut Size)
52where
53    Ty: TyAbiInterface<'a, C> + Copy,
54    C: HasDataLayout,
55{
56    if !ret.layout.is_aggregate() {
57        extend_integer_width_mips(ret, 64);
58        return;
59    }
60
61    let size = ret.layout.size;
62    let bits = size.bits();
63    if bits <= 128 {
64        // NOTE: Complex<f128> is returned indirectly.
65        if let Some(component) = ret.layout.complex_number(cx) {
66            match component {
67                Numeric::Int(Integer::I8 | Integer::I16 | Integer::I32, _) => {
68                    // Return a Complex<{integer}> packed into a single register when that fits.
69                    ret.cast_to(Reg { kind: RegKind::Integer, size });
70                }
71                _ => {
72                    // Otherwise pass in 2 registers.
73                    let reg = Reg { kind: component.reg_kind(), size: component.size() };
74                    ret.cast_to(CastTarget::pair(reg, reg));
75                }
76            }
77            return;
78        }
79
80        // Unlike other architectures which return aggregates in registers, MIPS n64 limits the
81        // use of float registers to structures (not unions) containing exactly one or two
82        // float fields.
83
84        if let FieldsShape::Arbitrary { .. } = ret.layout.fields {
85            if ret.layout.fields.count() == 1 {
86                if let Some(reg) = float_reg(cx, ret, 0) {
87                    // The inreg attribute forces LLVM to return a struct containing a f128 in
88                    // $f0 and $f1 rather than $f0 and $f2, see:
89                    // https://github.com/llvm/llvm-project/blob/a81db64570f94c2ca8ac0f598c0b5bba1a7ae59e/llvm/lib/Target/Mips/MipsCallingConv.td#L48-L51
90                    ret.cast_to_with_attrs(reg, ArgAttribute::InReg.into());
91                    return;
92                }
93            } else if ret.layout.fields.count() == 2
94                && let Some(reg0) = float_reg(cx, ret, 0)
95                && let Some(reg1) = float_reg(cx, ret, 1)
96            {
97                ret.cast_to_with_attrs(CastTarget::pair(reg0, reg1), ArgAttribute::InReg.into());
98                return;
99            }
100        }
101
102        // Cast to a uniform int structure
103        ret.cast_to(Uniform::new(Reg::i64(), size));
104    } else {
105        ret.make_indirect();
106        *offset += cx.data_layout().pointer_size();
107    }
108}
109
110fn classify_arg<'a, Ty, C>(cx: &C, arg: &mut ArgAbi<'a, Ty>, offset: &mut Size)
111where
112    Ty: TyAbiInterface<'a, C> + Copy,
113    C: HasDataLayout,
114{
115    let dl = cx.data_layout();
116    let size = arg.layout.size;
117    let mut prefix = ArrayVec::new();
118
119    // Detect need for padding
120    let align = Ord::clamp(arg.layout.align, dl.i64_align, dl.i128_align);
121    let pad_i32 = u8::from(!offset.is_aligned(align));
122
123    if !arg.layout.is_aggregate() {
124        extend_integer_width_mips(arg, 64);
125
126        // We always pad with an integer, even if the primitive is a float. This
127        // is because the N64 ABI puts the n-th argument in the n-th register
128        // starting from $4 if it belongs in a GPR and in the n-th register
129        // starting from $f12 if it belongs in a FPR.
130        // Therefore padding with an integer results in skipping a FPR for the
131        // next floating point parameter.
132        if let BackendRepr::Scalar(scalar) = arg.layout.backend_repr {
133            let kind = RegKind::from_primitive(scalar.primitive());
134            arg.cast_to_and_pad_i32(CastTarget::from(Reg { kind, size }), pad_i32);
135        }
136    } else if arg.layout.pass_indirectly_in_non_rustic_abis(cx) {
137        arg.make_indirect();
138    } else if let Some(component) = arg.layout.complex_number(cx)
139        && !#[allow(non_exhaustive_omitted_patterns)] match component {
    Numeric::Float(Float::F16) => true,
    _ => false,
}matches!(component, Numeric::Float(Float::F16))
140    {
141        let slot = dl.pointer_size();
142        let curr_offset = offset.align_to(align);
143
144        const NUM_ARG_SLOTS: u64 = 8;
145
146        match component {
147            Numeric::Float(Float::F16B) => {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("Complex<f16b> is not C-compatible")));
}unreachable!("Complex<f16b> is not C-compatible"),
148            Numeric::Float(Float::F16 | Float::X87F80 | Float::PpcF128) => {
149                {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("not supported on mips64")));
}unreachable!("not supported on mips64")
150            }
151            Numeric::Float(Float::F32 | Float::F64) => {
152                // Only pass a Complex<f32>/Complex<f64> in FPRs when two argument slots are free.
153                if curr_offset.bytes() / slot.bytes() + 2 <= NUM_ARG_SLOTS {
154                    // Both components claim a slot, even a Complex<f32> which could fit in one
155                    // slot.
156                    //
157                    // FIXME(complex_numbers): c-variadic arguments are passed in GPRs, so need a
158                    // special carve-out here and Complex<f32> is bitpacked into one 64-bit GPR.
159                    *offset = curr_offset + slot * 2;
160                    let unit = Reg { kind: RegKind::Float, size: component.size() };
161                    let cast_target = CastTarget::from(Uniform::new(unit, size));
162                    arg.cast_to(cast_target);
163                    return;
164                }
165
166                // Otherwise pack it into GPRs (or the stack) like an integer of the same size.
167                arg.cast_to_and_pad_i32(Uniform::new(Reg::i64(), size), pad_i32);
168            }
169            Numeric::Float(Float::F128) => {
170                // Complex<f128> is passed in 4 FPRs, but aligned to 16 so may need padding.
171                let reg = Reg { kind: RegKind::Float, size: arg.layout.field(cx, 0).size };
172                arg.cast_to_and_pad_i32(CastTarget::pair(reg, reg), pad_i32);
173            }
174            Numeric::Int(Integer::I8 | Integer::I16 | Integer::I32, _) => {
175                // Cast Complex<i8> into i16, Complex<i16> to i32, etc.
176                let cast_target = CastTarget::from(Reg { kind: RegKind::Integer, size });
177                // The inreg attribute makes the bits land in the right (upper) bits on BE targets.
178                arg.cast_to(cast_target.with_attrs(ArgAttribute::InReg.into()));
179            }
180            Numeric::Int(Integer::I64 | Integer::I128, _) => {
181                // Complex<i64> and Complex<i128> are passed as 2 separate arguments.
182                let cast_target = CastTarget::from(Reg { kind: RegKind::Integer, size });
183                arg.cast_to(cast_target);
184            }
185        }
186    } else {
187        match arg.layout.fields {
188            FieldsShape::Primitive => ::core::panicking::unreachable_default_msg()unreachable!(),
189            FieldsShape::Array { .. } => {
190                // Arrays are passed indirectly
191                arg.make_indirect();
192            }
193            FieldsShape::Union(_) => {
194                // Unions and are always treated as a series of 64-bit integer chunks
195            }
196            FieldsShape::Arbitrary { .. } => {
197                // Structures are split up into a series of 64-bit integer chunks, but any aligned
198                // doubles not part of another aggregate are passed as floats.
199                let mut last_offset = Size::ZERO;
200
201                'outer: for i in 0..arg.layout.fields.count() {
202                    let field = arg.layout.field(cx, i);
203                    let offset = arg.layout.fields.offset(i);
204
205                    // We only care about aligned doubles
206                    if let BackendRepr::Scalar(scalar) = field.backend_repr {
207                        if scalar.primitive() == Primitive::Float(Float::F64) {
208                            if offset.is_aligned(dl.f64_align) {
209                                // Insert enough integers to cover [last_offset, offset)
210                                if !last_offset.is_aligned(dl.f64_align) {
    ::core::panicking::panic("assertion failed: last_offset.is_aligned(dl.f64_align)")
};assert!(last_offset.is_aligned(dl.f64_align));
211                                for _ in 0..((offset - last_offset).bits() / 64) {
212                                    if prefix.try_push(Reg::i64()).is_err() {
213                                        break 'outer;
214                                    }
215                                }
216
217                                if prefix.try_push(Reg::f64()).is_err() {
218                                    break;
219                                }
220                                last_offset = offset + Reg::f64().size;
221                            }
222                        }
223                    }
224                }
225            }
226        };
227
228        // Extract first 8 chunks as the prefix
229        let rest_size = size - Size::from_bytes(8) * prefix.len() as u64;
230        arg.cast_to_and_pad_i32(
231            CastTarget::prefixed(prefix, Uniform::new(Reg::i64(), rest_size)),
232            pad_i32,
233        );
234    }
235    *offset = offset.align_to(align) + size.align_to(align);
236}
237
238pub(crate) struct Mips64CallConv {
239    offset: Size,
240}
241
242impl<'a, Ty, C> ComputeCallConv<'a, Ty, C> for Mips64CallConv
243where
244    Ty: TyAbiInterface<'a, C> + Copy,
245    C: HasDataLayout,
246{
247    fn new(_cx: &C, _conv: CanonAbi, _c_variadic: bool) -> Self {
248        // mips64 argument passing is also affected by the alignment of aggregates.
249        // see mips.rs for how the offset is used
250        Self { offset: Size::ZERO }
251    }
252
253    fn compute_ret_abi(&mut self, cx: &C, ret: &mut ArgAbi<'a, Ty>) {
254        classify_ret(cx, ret, &mut self.offset);
255    }
256
257    fn compute_arg_abi(&mut self, cx: &C, arg: &mut ArgAbi<'a, Ty>, _is_vararg: bool) {
258        if !arg.layout.is_sized() {
259            return;
260        }
261        classify_arg(cx, arg, &mut self.offset);
262    }
263}