Skip to content

Commit e07d163

Browse files
committed
Fix undefined behavior in hint::spin_loop for x86 targets without SSE2
The pause instruction requires SSE2 but was being unconditionally used on targets without it, resulting in undefined behavior. This PR fixes that by only using the pause intrinsic if SSE2 is available. It also removes the inline assembly which was not required since these instructions are available in core::arch, and extends support of the spin_loop hint to arm targets with the v6 feature which also support the yield instruction. Closes #59237 .
1 parent 52e8856 commit e07d163

File tree

1 file changed

+26
-7
lines changed

1 file changed

+26
-7
lines changed

src/libcore/hint.rs

+26-7
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
//! Hints to compiler that affects how code should be emitted or optimized.
44
5-
use intrinsics;
5+
use {arch, intrinsics};
66

77
/// Informs the compiler that this point in the code is not reachable, enabling
88
/// further optimizations.
@@ -62,13 +62,32 @@ pub unsafe fn unreachable_unchecked() -> ! {
6262
#[inline]
6363
#[unstable(feature = "renamed_spin_loop", issue = "55002")]
6464
pub fn spin_loop() {
65-
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
66-
unsafe {
67-
asm!("pause" ::: "memory" : "volatile");
65+
#[cfg(
66+
all(
67+
any(target_arch = "x86", target_arch = "x86_64"),
68+
target_feature = "sse2"
69+
)
70+
)] {
71+
#[cfg(target_arch = "x86")] {
72+
unsafe { arch::x86::_mm_pause() };
73+
}
74+
75+
#[cfg(target_arch = "x86_64")] {
76+
unsafe { arch::x86_64::_mm_pause() };
77+
}
6878
}
6979

70-
#[cfg(target_arch = "aarch64")]
71-
unsafe {
72-
asm!("yield" ::: "memory" : "volatile");
80+
#[cfg(
81+
any(
82+
target_arch = "aarch64",
83+
all(target_arch = "arm", target_feature = "v6")
84+
)
85+
)] {
86+
#[cfg(target_arch = "aarch64")] {
87+
unsafe { arch::aarch64::__yield() };
88+
}
89+
#[cfg(target_arch = "arm")] {
90+
unsafe { arch::arm::__yield() };
91+
}
7392
}
7493
}

0 commit comments

Comments
 (0)