Skip to main content

rustc_target/callconv/
powerpc64.rs

1// FIXME:
2// Alignment of 128 bit types is not currently handled, this will
3// need to be fixed when PowerPC vector support is added.
4
5use rustc_abi::{
6    CanonAbi, FieldsShape, HasDataLayout, Integer, Numeric, TyAbiInterface, TyAndLayout,
7};
8
9use crate::callconv::{Align, ArgAbi, CastTarget, ComputeCallConv, Reg, RegKind, Uniform};
10use crate::spec::{HasTargetSpec, LlvmAbi, Os};
11
12#[derive(#[automatically_derived]impl ::core::fmt::Debug for ABI {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                ABI::ELFv1 => "ELFv1",
                ABI::ELFv2 => "ELFv2",
                ABI::AIX => "AIX",
            })
    }
}Debug, #[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for ABI {
}
#[automatically_derived]impl ::core::clone::Clone for ABI {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]impl ::core::marker::Copy for ABI { }Copy, #[automatically_derived]impl ::core::marker::StructuralPartialEq for ABI { }
#[automatically_derived]impl ::core::cmp::PartialEq for ABI {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
            ::core::intrinsics::discriminant_value(other)
    }
}PartialEq)]
13enum ABI {
14    ELFv1, // original ABI used for powerpc64 (big-endian)
15    ELFv2, // newer ABI used for powerpc64le and musl (both endians)
16    AIX,   // used by AIX OS, big-endian only
17}
18use ABI::*;
19
20/// Whether `layout` is or contains a union.
21///
22/// `homogeneous_aggregate` merges the fields of a union, so it cannot tell a union from a
23/// structure. This walks the layout a second time; keep the array handling here in sync with
24/// `homogeneous_aggregate`. ZSTs are ignored entirely, as both GCC and Clang do.
25///
26/// This does not look at enums that are represented as unions at the ABI level (e.g. a
27/// `#[repr(C)]` enum with fields). That does not matter here: enums can only have integer
28/// discriminants, and `is_homogeneous_aggregate` rejects anything containing an integer, so an
29/// enum can never be a float or vector homogeneous aggregate.
30fn is_or_contains_union<'a, Ty, C>(cx: &C, layout: TyAndLayout<'a, Ty>) -> bool
31where
32    Ty: TyAbiInterface<'a, C> + Copy,
33    C: HasDataLayout,
34{
35    if layout.is_zst() {
36        return false;
37    }
38    match layout.fields {
39        FieldsShape::Primitive => false,
40        // A `repr(transparent)` union is guaranteed to be ABI-compatible with its single
41        // non-1-ZST field, so look through it instead of rejecting it.
42        FieldsShape::Union(_) => {
43            match layout.non_1zst_field(cx).filter(|_| layout.is_transparent()) {
44                Some((_, field)) => is_or_contains_union(cx, field),
45                None => true,
46            }
47        }
48        FieldsShape::Array { .. } => is_or_contains_union(cx, layout.field(cx, 0)),
49        FieldsShape::Arbitrary { .. } => {
50            (0..layout.fields.count()).any(|i| is_or_contains_union(cx, layout.field(cx, i)))
51        }
52    }
53}
54
55fn is_homogeneous_aggregate<'a, Ty, C>(
56    cx: &C,
57    arg: &mut ArgAbi<'a, Ty>,
58    abi: ABI,
59) -> Option<Uniform>
60where
61    Ty: TyAbiInterface<'a, C> + Copy,
62    C: HasDataLayout,
63{
64    arg.layout.homogeneous_aggregate(cx).ok().and_then(|ha| ha.unit()).and_then(|unit| {
65        match abi {
66            ELFv1 | AIX => {
67                // Pass only one-member aggregates transparently.
68                if arg.layout.size > unit.size || is_or_contains_union(cx, arg.layout) {
69                    return None;
70                }
71            }
72            ELFv2 => {
73                // A `ppcf128` occupies two floating-point registers, so only four of them fit.
74                let max_members = if unit.kind == RegKind::PpcF128 { 4 } else { 8 };
75
76                // Pass up to max_members uniquely addressable members.
77                if arg.layout.size > unit.size.checked_mul(max_members, cx).unwrap() {
78                    return None;
79                }
80            }
81        }
82
83        let valid_unit = match unit.kind {
84            RegKind::Integer => false,
85            RegKind::Float | RegKind::PpcF128 => true,
86            RegKind::Vector { .. } => unit.size.bits() == 128,
87        };
88
89        valid_unit.then_some(Uniform::new(unit, arg.layout.size))
90    })
91}
92
93fn classify<'a, Ty, C>(cx: &C, arg: &mut ArgAbi<'a, Ty>, abi: ABI, is_ret: bool)
94where
95    Ty: TyAbiInterface<'a, C> + Copy,
96    C: HasDataLayout,
97{
98    if !arg.layout.is_sized() {
99        // Not touching this...
100        return;
101    }
102    if !is_ret && arg.layout.pass_indirectly_in_non_rustic_abis(cx) {
103        arg.make_indirect();
104        return;
105    }
106    if !arg.layout.is_aggregate() {
107        arg.extend_integer_width_to(64);
108        return;
109    }
110    if let Some(component) = arg.layout.complex_number(cx) {
111        if let Numeric::Int(Integer::I16, _) = component {
112            // FIXME: use `PassMode::Cast` here. In LLVM 23 doing so would hit
113            // https://github.com/llvm/llvm-project/issues/218676.
114            return;
115        }
116
117        let reg = Reg { kind: component.reg_kind(), size: component.size() };
118        arg.cast_to(CastTarget::pair(reg, reg));
119        return;
120    }
121
122    // The AIX ABI expect byval for aggregates
123    // See https://github.com/llvm/llvm-project/blob/main/clang/lib/CodeGen/Targets/PPC.cpp.
124    // The incoming parameter is represented as a pointer in the IR,
125    // the alignment is associated with the size of the register. (align 8 for 64bit)
126    if !is_ret && abi == AIX {
127        arg.pass_by_stack_offset(Some(Align::from_bytes(8).unwrap()));
128        return;
129    }
130
131    // The ELFv1 ABI doesn't return aggregates in registers
132    if is_ret && (abi == ELFv1 || abi == AIX) {
133        arg.make_indirect();
134        return;
135    }
136
137    if let Some(uniform) = is_homogeneous_aggregate(cx, arg, abi) {
138        arg.cast_to(uniform);
139        return;
140    }
141
142    let size = arg.layout.size;
143    if is_ret && size.bits() > 128 {
144        // Non-homogeneous aggregates larger than two doublewords are returned indirectly.
145        arg.make_indirect();
146    } else if size.bits() <= 64 {
147        // Aggregates smaller than a doubleword should appear in
148        // the least-significant bits of the parameter doubleword.
149        arg.cast_to(Reg { kind: RegKind::Integer, size })
150    } else {
151        // Aggregates larger than i64 should be padded at the tail to fill out a whole number
152        // of i64s or i128s, depending on the aggregate alignment. Always use an array for
153        // this, even if there is only a single element.
154        let reg = if arg.layout.align.bytes() > 8 { Reg::i128() } else { Reg::i64() };
155        arg.cast_to(Uniform::consecutive(
156            reg,
157            size.align_to(Align::from_bytes(reg.size.bytes()).unwrap()),
158        ))
159    };
160}
161
162pub(crate) struct PowerPC64CallConv {
163    abi: ABI,
164}
165
166impl<'a, Ty, C> ComputeCallConv<'a, Ty, C> for PowerPC64CallConv
167where
168    Ty: TyAbiInterface<'a, C> + Copy,
169    C: HasDataLayout + HasTargetSpec,
170{
171    fn new(cx: &C, _conv: CanonAbi, _c_variadic: bool) -> Self {
172        let abi = match cx.target_spec().options.llvm_abiname {
173            LlvmAbi::ElfV1 => ELFv1,
174            LlvmAbi::ElfV2 => ELFv2,
175            LlvmAbi::Unspecified if cx.target_spec().os == Os::Aix => AIX,
176            // Target::check_consistency enforces that every target except AIX
177            // sets llvm_abiname to either ElfV1 or ElfV2
178            _ => ::core::panicking::unreachable_default_msg()unreachable!(),
179        };
180        Self { abi }
181    }
182
183    fn compute_ret_abi(&mut self, cx: &C, ret: &mut ArgAbi<'a, Ty>) {
184        classify(cx, ret, self.abi, true);
185    }
186
187    fn compute_arg_abi(&mut self, cx: &C, arg: &mut ArgAbi<'a, Ty>, _is_vararg: bool) {
188        classify(cx, arg, self.abi, false);
189    }
190}