Skip to content

Commit 8c15370

Browse files
Rollup merge of rust-lang#151346 - folkertdev:simd-splat, r=workingjubilee
add `simd_splat` intrinsic Add `simd_splat` which lowers to the LLVM canonical splat sequence. ```llvm insertelement <N x elem> poison, elem %x, i32 0 shufflevector <N x elem> v0, <N x elem> poison, <N x i32> zeroinitializer ``` Right now we try to fake it using one of ```rust fn splat(x: u32) -> u32x8 { u32x8::from_array([x; 8]) } ``` or (in `stdarch`) ```rust fn splat(value: $elem_type) -> $name { #[derive(Copy, Clone)] #[repr(simd)] struct JustOne([$elem_type; 1]); let one = JustOne([value]); // SAFETY: 0 is always in-bounds because we're shuffling // a simd type with exactly one element. unsafe { simd_shuffle!(one, one, [0; $len]) } } ``` Both of these can confuse the LLVM optimizer, producing sub-par code. Some examples: - rust-lang#60637 - rust-lang#137407 - rust-lang#122623 - rust-lang#97804 --- As far as I can tell there is no way to provide a fallback implementation for this intrinsic, because there is no `const` way of evaluating the number of elements (there might be issues beyond that, too). So, I added implementations for all 4 backends. Both GCC and const-eval appear to have some issues with simd vectors containing pointers. I have a workaround for GCC, but haven't yet been able to make const-eval work. See the comments below. Currently this just adds the intrinsic, it does not actually use it anywhere yet.
2 parents a18e6d9 + 71f3442 commit 8c15370

10 files changed

Lines changed: 192 additions & 1 deletion

File tree

compiler/rustc_codegen_cranelift/src/intrinsics/simd.rs

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -348,6 +348,31 @@ pub(super) fn codegen_simd_intrinsic_call<'tcx>(
348348
ret.write_cvalue(fx, ret_lane);
349349
}
350350

351+
sym::simd_splat => {
352+
intrinsic_args!(fx, args => (value); intrinsic);
353+
354+
if !ret.layout().ty.is_simd() {
355+
report_simd_type_validation_error(fx, intrinsic, span, ret.layout().ty);
356+
return;
357+
}
358+
let (lane_count, lane_ty) = ret.layout().ty.simd_size_and_type(fx.tcx);
359+
360+
if value.layout().ty != lane_ty {
361+
fx.tcx.dcx().span_fatal(
362+
span,
363+
format!(
364+
"[simd_splat] expected element type {lane_ty:?}, got {got:?}",
365+
got = value.layout().ty
366+
),
367+
);
368+
}
369+
370+
for i in 0..lane_count {
371+
let ret_lane = ret.place_lane(fx, i.into());
372+
ret_lane.write_cvalue(fx, value);
373+
}
374+
}
375+
351376
sym::simd_neg
352377
| sym::simd_bswap
353378
| sym::simd_bitreverse

compiler/rustc_codegen_gcc/src/intrinsic/simd.rs

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -121,6 +121,42 @@ pub fn generic_simd_intrinsic<'a, 'gcc, 'tcx>(
121121
return Ok(bx.vector_select(vector_mask, arg1, args[2].immediate()));
122122
}
123123

124+
#[cfg(feature = "master")]
125+
if name == sym::simd_splat {
126+
let (out_len, out_ty) = require_simd2!(ret_ty, SimdReturn);
127+
128+
require!(
129+
args[0].layout.ty == out_ty,
130+
InvalidMonomorphization::ExpectedVectorElementType {
131+
span,
132+
name,
133+
expected_element: out_ty,
134+
vector_type: ret_ty,
135+
}
136+
);
137+
138+
let vec_ty = llret_ty.unqualified().dyncast_vector().expect("vector return type");
139+
let elem_ty = vec_ty.get_element_type();
140+
141+
// Cast pointer type to usize (GCC does not support pointer SIMD vectors).
142+
let value = args[0];
143+
let scalar = if value.layout.ty.is_numeric() {
144+
value.immediate()
145+
} else if value.layout.ty.is_raw_ptr() {
146+
bx.ptrtoint(value.immediate(), elem_ty)
147+
} else {
148+
return_error!(InvalidMonomorphization::UnsupportedOperation {
149+
span,
150+
name,
151+
in_ty: ret_ty,
152+
in_elem: value.layout.ty
153+
});
154+
};
155+
156+
let elements = vec![scalar; out_len as usize];
157+
return Ok(bx.context.new_rvalue_from_vector(bx.location, llret_ty, &elements));
158+
}
159+
124160
// every intrinsic below takes a SIMD vector as its first argument
125161
require_simd!(
126162
args[0].layout.ty,

compiler/rustc_codegen_llvm/src/intrinsic.rs

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1581,6 +1581,31 @@ fn generic_simd_intrinsic<'ll, 'tcx>(
15811581
return Ok(bx.select(m_i1s, args[1].immediate(), args[2].immediate()));
15821582
}
15831583

1584+
if name == sym::simd_splat {
1585+
let (_out_len, out_ty) = require_simd!(ret_ty, SimdReturn);
1586+
1587+
require!(
1588+
args[0].layout.ty == out_ty,
1589+
InvalidMonomorphization::ExpectedVectorElementType {
1590+
span,
1591+
name,
1592+
expected_element: out_ty,
1593+
vector_type: ret_ty,
1594+
}
1595+
);
1596+
1597+
// `insertelement <N x elem> poison, elem %x, i32 0`
1598+
let poison_vec = bx.const_poison(llret_ty);
1599+
let idx0 = bx.const_i32(0);
1600+
let v0 = bx.insert_element(poison_vec, args[0].immediate(), idx0);
1601+
1602+
// `shufflevector <N x elem> v0, <N x elem> poison, <N x i32> zeroinitializer`
1603+
// The masks is all zeros, so this splats lane 0 (which has our element in it).
1604+
let splat = bx.shuffle_vector(v0, poison_vec, bx.const_null(llret_ty));
1605+
1606+
return Ok(splat);
1607+
}
1608+
15841609
// every intrinsic below takes a SIMD vector as its first argument
15851610
let (in_len, in_elem) = require_simd!(args[0].layout.ty, SimdInput);
15861611
let in_ty = args[0].layout.ty;

compiler/rustc_codegen_ssa/src/mir/operand.rs

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1074,8 +1074,14 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
10741074
if constant_ty.is_simd() {
10751075
// However, some SIMD types do not actually use the vector ABI
10761076
// (in particular, packed SIMD types do not). Ensure we exclude those.
1077+
//
1078+
// We also have to exclude vectors of pointers because `immediate_const_vector`
1079+
// does not work for those.
10771080
let layout = bx.layout_of(constant_ty);
1078-
if let BackendRepr::SimdVector { .. } = layout.backend_repr {
1081+
let (_, element_ty) = constant_ty.simd_size_and_type(bx.tcx());
1082+
if let BackendRepr::SimdVector { .. } = layout.backend_repr
1083+
&& element_ty.is_numeric()
1084+
{
10791085
let (llval, ty) = self.immediate_const_vector(bx, constant);
10801086
return OperandRef {
10811087
val: OperandValue::Immediate(llval),

compiler/rustc_const_eval/src/interpret/intrinsics/simd.rs

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,15 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
6161
}
6262
self.copy_op(&self.project_index(&input, index)?, &dest)?;
6363
}
64+
sym::simd_splat => {
65+
let elem = &args[0];
66+
let (dest, dest_len) = self.project_to_simd(&dest)?;
67+
68+
for i in 0..dest_len {
69+
let place = self.project_index(&dest, i)?;
70+
self.copy_op(elem, &place)?;
71+
}
72+
}
6473
sym::simd_neg
6574
| sym::simd_fabs
6675
| sym::simd_ceil

compiler/rustc_hir_analysis/src/check/intrinsic.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -746,6 +746,7 @@ pub(crate) fn check_intrinsic_type(
746746
sym::simd_extract | sym::simd_extract_dyn => {
747747
(2, 0, vec![param(0), tcx.types.u32], param(1))
748748
}
749+
sym::simd_splat => (2, 0, vec![param(1)], param(0)),
749750
sym::simd_cast
750751
| sym::simd_as
751752
| sym::simd_cast_ptr

compiler/rustc_span/src/symbol.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2140,6 +2140,7 @@ symbols! {
21402140
simd_shr,
21412141
simd_shuffle,
21422142
simd_shuffle_const_generic,
2143+
simd_splat,
21432144
simd_sub,
21442145
simd_trunc,
21452146
simd_with_exposed_provenance,

library/core/src/intrinsics/simd.rs

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,13 @@ pub const unsafe fn simd_insert_dyn<T, U>(x: T, idx: u32, val: U) -> T;
5252
#[rustc_intrinsic]
5353
pub const unsafe fn simd_extract_dyn<T, U>(x: T, idx: u32) -> U;
5454

55+
/// Creates a vector where every lane has the provided value.
56+
///
57+
/// `T` must be a vector with element type `U`.
58+
#[rustc_nounwind]
59+
#[rustc_intrinsic]
60+
pub const unsafe fn simd_splat<T, U>(value: U) -> T;
61+
5562
/// Adds two simd vectors elementwise.
5663
///
5764
/// `T` must be a vector of integers or floats.

tests/codegen-llvm/simd/splat.rs

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
//@ compile-flags: -Copt-level=3
2+
#![crate_type = "lib"]
3+
#![no_std]
4+
#![feature(repr_simd, core_intrinsics)]
5+
use core::intrinsics::simd::simd_splat;
6+
7+
#[path = "../../auxiliary/minisimd.rs"]
8+
mod minisimd;
9+
use minisimd::*;
10+
11+
// Test that `simd_splat` produces the canonical LLVM splat sequence.
12+
13+
#[no_mangle]
14+
unsafe fn int(x: u16) -> u16x2 {
15+
// CHECK-LABEL: int
16+
// CHECK: start:
17+
// CHECK-NEXT: %0 = insertelement <2 x i16> poison, i16 %x, i64 0
18+
// CHECK-NEXT: %1 = shufflevector <2 x i16> %0, <2 x i16> poison, <2 x i32> zeroinitializer
19+
// CHECK-NEXT: store
20+
// CHECK-NEXT: ret
21+
simd_splat(x)
22+
}
23+
24+
#[no_mangle]
25+
unsafe fn float(x: f32) -> f32x4 {
26+
// CHECK-LABEL: float
27+
// CHECK: start:
28+
// CHECK-NEXT: %0 = insertelement <4 x float> poison, float %x, i64 0
29+
// CHECK-NEXT: %1 = shufflevector <4 x float> %0, <4 x float> poison, <4 x i32> zeroinitializer
30+
// CHECK-NEXT: store
31+
// CHECK-NEXT: ret
32+
simd_splat(x)
33+
}

tests/ui/simd/intrinsic/splat.rs

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
//@ run-pass
2+
#![feature(repr_simd, core_intrinsics)]
3+
4+
#[path = "../../../auxiliary/minisimd.rs"]
5+
mod minisimd;
6+
use minisimd::*;
7+
8+
use std::intrinsics::simd::simd_splat;
9+
10+
fn main() {
11+
unsafe {
12+
let x: Simd<u32, 1> = simd_splat(123u32);
13+
let y: Simd<u32, 1> = const { simd_splat(123u32) };
14+
assert_eq!(x.into_array(), [123; 1]);
15+
assert_eq!(x.into_array(), y.into_array());
16+
17+
let x: u16x2 = simd_splat(42u16);
18+
let y: u16x2 = const { simd_splat(42u16) };
19+
assert_eq!(x.into_array(), [42; 2]);
20+
assert_eq!(x.into_array(), y.into_array());
21+
22+
let x: u128x4 = simd_splat(42u128);
23+
let y: u128x4 = const { simd_splat(42u128) };
24+
assert_eq!(x.into_array(), [42; 4]);
25+
assert_eq!(x.into_array(), y.into_array());
26+
27+
let x: i32x4 = simd_splat(-7i32);
28+
let y: i32x4 = const { simd_splat(-7i32) };
29+
assert_eq!(x.into_array(), [-7; 4]);
30+
assert_eq!(x.into_array(), y.into_array());
31+
32+
let x: f32x4 = simd_splat(42.0f32);
33+
let y: f32x4 = const { simd_splat(42.0f32) };
34+
assert_eq!(x.into_array(), [42.0; 4]);
35+
assert_eq!(x.into_array(), y.into_array());
36+
37+
let x: f64x2 = simd_splat(42.0f64);
38+
let y: f64x2 = const { simd_splat(42.0f64) };
39+
assert_eq!(x.into_array(), [42.0; 2]);
40+
assert_eq!(x.into_array(), y.into_array());
41+
42+
static ZERO: u8 = 0u8;
43+
let x: Simd<*const u8, 2> = simd_splat(&raw const ZERO);
44+
let y: Simd<*const u8, 2> = const { simd_splat(&raw const ZERO) };
45+
assert_eq!(x.into_array(), [&raw const ZERO; 2]);
46+
assert_eq!(x.into_array(), y.into_array());
47+
}
48+
}

0 commit comments

Comments
 (0)