Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Redo the swap code for better tail & padding handling #134954

Draft
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

scottmcm
Copy link
Member

A couple of parts here

Fixes #134713

Actually using the type passed to ptr::swap_nonoverlapping for anything other than its size + align turns out to not work, so this redo goes back to always swapping via not-!noundef integers.

(Except in const, which keeps doing the same thing as before to preserve @RalfJung's fix from #134689)

Fixes #134946

I'd previously moved the swapping to use auto-vectorization, but someone pointed out on Discord that the tail loop handling from that left a whole bunch of byte-by-byte swapping around. This PR goes back to a manual chunk, with at most logarithmic more instructions for the tail.

(There are other ways that could potentially handle the tail even better, but this seems to be pretty good, since it's how LLVM ends up lowering operations on types like i56.)

Polymorphization

Since it's silly to have separate copies of swapping -- especially untyped swapping! -- for u32, i32, f32, [u16; 2], etc, this sends everything to byte versions, but still mono'd by alignment. That should make it more ok that the code is somewhat more complex, since we only get 7 monomorphizations of the complicated bit.

(One day we'll be able to remove some of the hacks by being able to just call foo::<{align_of::<T>()}>, but since alignments are only powers of two, the manual dispatch out isn't a big deal.)

@rustbot
Copy link
Collaborator

rustbot commented Dec 31, 2024

r? @thomcc

rustbot has assigned @thomcc.
They will have a look at your PR within the next two weeks and either review your PR or reassign to another reviewer.

Use r? to explicitly pick a reviewer

@rustbot rustbot added S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. T-compiler Relevant to the compiler team, which will review and decide on the PR/issue. T-libs Relevant to the library team, which will review and decide on the PR/issue. labels Dec 31, 2024
@rust-log-analyzer

This comment has been minimized.

@scottmcm
Copy link
Member Author

@bors try @rust-timer queue

@rust-timer

This comment has been minimized.

@rustbot rustbot added the S-waiting-on-perf Status: Waiting on a perf run to be completed. label Dec 31, 2024
bors added a commit to rust-lang-ci/rust that referenced this pull request Dec 31, 2024
Redo the swap code for better tail & padding handling

A couple of parts here

## Fixes rust-lang#134713

Actually using the type passed to `ptr::swap_nonoverlapping` for anything other than its size + align turns out to not work, so this redo goes back to *always* swapping via not-`!noundef` integers.

(Except in `const`, which keeps doing the same thing as before to preserve `@RalfJung's` fix from rust-lang#134689)

## Fixes rust-lang#134946

I'd previously moved the swapping to use auto-vectorization, but someone pointed out on Discord that the tail loop handling from that left a whole bunch of byte-by-byte swapping around.  This PR goes back to a manual chunk, with at most logarithmic more instructions for the tail.

(There are other ways that could potentially handle the tail even better, but this seems to be pretty good, since it's how LLVM ends up lowering operations on types like `i56`.)

## Polymorphization

Since it's silly to have separate copies of swapping -- especially *untyped* swapping! -- for `u32`, `i32`, `f32`, `[u16; 2]`, etc, this sends everything to byte versions, but still mono'd by alignment.  That should make it more ok that the code is somewhat more complex, since we only get 7 monomorphizations of the complicated bit.

(One day we'll be able to remove some of the hacks by being able to just call `foo::<{align_of::<T>()}>`, but since alignments are only powers of two, the manual dispatch out isn't a big deal.)
@bors
Copy link
Contributor

bors commented Dec 31, 2024

⌛ Trying commit 932f981 with merge 407c8de...

@rust-log-analyzer
Copy link
Collaborator

The job x86_64-gnu-llvm-18 failed! Check out the build log: (web) (plain)

Click to see the possible cause of the failure (guessed by this bot)
#22 exporting to docker image format
#22 sending tarball 27.3s done
#22 DONE 32.5s
##[endgroup]
Setting extra environment values for docker:  --env ENABLE_GCC_CODEGEN=1 --env GCC_EXEC_PREFIX=/usr/lib/gcc/
[CI_JOB_NAME=x86_64-gnu-llvm-18]
debug: `DISABLE_CI_RUSTC_IF_INCOMPATIBLE` configured.
---
sccache: Starting the server...
##[group]Configure the build
configure: processing command line
configure: 
configure: build.configure-args := ['--build=x86_64-unknown-linux-gnu', '--llvm-root=/usr/lib/llvm-18', '--enable-llvm-link-shared', '--set', 'rust.randomize-layout=true', '--set', 'rust.thin-lto-import-instr-limit=10', '--enable-verbose-configure', '--enable-sccache', '--disable-manage-submodules', '--enable-locked-deps', '--enable-cargo-native-static', '--set', 'rust.codegen-units-std=1', '--set', 'dist.compression-profile=balanced', '--dist-compression-formats=xz', '--set', 'rust.lld=false', '--disable-dist-src', '--release-channel=nightly', '--enable-debug-assertions', '--enable-overflow-checks', '--enable-llvm-assertions', '--set', 'rust.verify-llvm-ir', '--set', 'rust.codegen-backends=llvm,cranelift,gcc', '--set', 'llvm.static-libstdcpp', '--enable-new-symbol-mangling']
configure: target.x86_64-unknown-linux-gnu.llvm-config := /usr/lib/llvm-18/bin/llvm-config
configure: llvm.link-shared     := True
configure: rust.randomize-layout := True
configure: rust.thin-lto-import-instr-limit := 10
---
3    |
4    = note: unable to copy parts of a pointer from memory at ALLOC0
5    |

- note: inside `std::ptr::read::<MaybeUninit<MaybeUninit<u8>>>`
-   --> $SRC_DIR/core/src/ptr/mod.rs:LL:COL
- note: inside `std::ptr::swap_nonoverlapping_simple_untyped::<MaybeUninit<u8>>`
-   --> $SRC_DIR/core/src/ptr/mod.rs:LL:COL
- note: inside `swap_nonoverlapping::compiletime::<MaybeUninit<u8>>`
-   --> $SRC_DIR/core/src/ptr/mod.rs:LL:COL
+ note: inside `copy_nonoverlapping::<MaybeUninit<MaybeUninit<u8>>>`
+   --> $SRC_DIR/core/src/intrinsics/mod.rs:LL:COL
+ note: inside `std::ptr::mut_ptr::<impl *mut MaybeUninit<MaybeUninit<u8>>>::copy_from_nonoverlapping`
+   --> $SRC_DIR/core/src/ptr/mut_ptr.rs:LL:COL
+ note: inside `untyped_swap_nonoverlapping::<MaybeUninit<u8>>`
+   --> $SRC_DIR/core/src/intrinsics/mod.rs:LL:COL
+ note: inside `core::swapping::swap_nonoverlapping_const::<MaybeUninit<u8>>`
+   --> $SRC_DIR/core/src/swapping.rs:LL:COL
+ note: inside `core::swapping::swap_nonoverlapping::compiletime::<MaybeUninit<u8>>`
+   --> $SRC_DIR/core/src/swapping.rs:LL:COL
+ note: inside `core::swapping::swap_nonoverlapping::<MaybeUninit<u8>>`
+   --> $SRC_DIR/core/src/swapping.rs:LL:COL
12 note: inside `swap_nonoverlapping::<MaybeUninit<u8>>`
13   --> $SRC_DIR/core/src/ptr/mod.rs:LL:COL
14 note: inside `X`
22    | |_________^
23    = help: this code performed an operation that depends on the underlying bytes representing a pointer
24    = help: the absolute address of a pointer is not known at compile-time, so such operations are not supported
-    = note: this error originates in the macro `$crate::intrinsics::const_eval_select` which comes from the expansion of the macro `const_eval_select` (in Nightly builds, run with -Z macro-backtrace for more info)
---
-   --> /rustc/FAKE_PREFIX/library/core/src/intrinsics/mod.rs:4033:9
-   --> /rustc/FAKE_PREFIX/library/core/src/swapping.rs:38:13
-   --> /rustc/FAKE_PREFIX/library/core/src/swapping.rs:15:22
-   --> /rustc/FAKE_PREFIX/library/core/src/swapping.rs:8:5
+   --> $SRC_DIR/core/src/intrinsics/mod.rs:LL:COL
+ note: inside `copy_nonoverlapping::<MaybeUninit<MaybeUninit<u8>>>`
+   --> $SRC_DIR/core/src/intrinsics/mod.rs:LL:COL
+ note: inside `std::ptr::mut_ptr::<impl *mut MaybeUninit<MaybeUninit<u8>>>::copy_from_nonoverlapping`
+   --> $SRC_DIR/core/src/ptr/mut_ptr.rs:LL:COL
+ note: inside `untyped_swap_nonoverlapping::<MaybeUninit<u8>>`
+   --> $SRC_DIR/core/src/intrinsics/mod.rs:LL:COL
+ note: inside `core::swapping::swap_nonoverlapping_const::<MaybeUninit<u8>>`
+   --> $SRC_DIR/core/src/swapping.rs:LL:COL
+ note: inside `core::swapping::swap_nonoverlapping::compiletime::<MaybeUninit<u8>>`
+   --> $SRC_DIR/core/src/swapping.rs:LL:COL
+ note: inside `core::swapping::swap_nonoverlapping::<MaybeUninit<u8>>`
+   --> $SRC_DIR/core/src/swapping.rs:LL:COL
+    = note: this error originates in the macro `$crate::intrinsics::const_eval_select` which comes from the expansion of the macro `intrinsics::const_eval_select` (in Nightly builds, run with -Z macro-backtrace for more info)

The actual stderr differed from the expected stderr.
To update references, rerun the tests and pass the `--bless` flag
To only update this specific test, also pass `--test-args consts/missing_span_in_backtrace.rs`
To only update this specific test, also pass `--test-args consts/missing_span_in_backtrace.rs`

error: 1 errors occurred comparing output.
status: exit status: 1
command: env -u RUSTC_LOG_COLOR RUSTC_ICE="0" RUST_BACKTRACE="short" "/checkout/obj/build/x86_64-unknown-linux-gnu/stage2/bin/rustc" "/checkout/tests/ui/consts/missing_span_in_backtrace.rs" "-Zthreads=1" "-Zsimulate-remapped-rust-src-base=/rustc/FAKE_PREFIX" "-Ztranslate-remapped-path-to-local-path=no" "-Z" "ignore-directory-in-diagnostics-source-blocks=/cargo" "-Z" "ignore-directory-in-diagnostics-source-blocks=/checkout/vendor" "--sysroot" "/checkout/obj/build/x86_64-unknown-linux-gnu/stage2" "--target=x86_64-unknown-linux-gnu" "--check-cfg" "cfg(FALSE)" "--error-format" "json" "--json" "future-incompat" "-Ccodegen-units=1" "-Zui-testing" "-Zdeduplicate-diagnostics=no" "-Zwrite-long-types-to-disk=no" "-Cstrip=debuginfo" "--emit" "metadata" "-C" "prefer-dynamic" "--out-dir" "/checkout/obj/build/x86_64-unknown-linux-gnu/test/ui/consts/missing_span_in_backtrace" "-A" "unused" "-A" "internal_features" "-Crpath" "-Cdebuginfo=0" "-Lnative=/checkout/obj/build/x86_64-unknown-linux-gnu/native/rust-test-helpers" "-Z" "ui-testing=no"
--- stderr -------------------------------
error[E0080]: evaluation of constant value failed
##[error]  --> /rustc/FAKE_PREFIX/library/core/src/intrinsics/mod.rs:4420:14
   |
   |
   = note: unable to copy parts of a pointer from memory at alloc25
   |
note: inside `copy_nonoverlapping::<MaybeUninit<MaybeUninit<u8>>>`
  --> /rustc/FAKE_PREFIX/library/core/src/intrinsics/mod.rs:4420:14
note: inside `std::ptr::mut_ptr::<impl *mut MaybeUninit<MaybeUninit<u8>>>::copy_from_nonoverlapping`
  --> /rustc/FAKE_PREFIX/library/core/src/ptr/mut_ptr.rs:1480:18
note: inside `untyped_swap_nonoverlapping::<MaybeUninit<u8>>`
note: inside `core::swapping::swap_nonoverlapping_const::<MaybeUninit<u8>>`
  --> /rustc/FAKE_PREFIX/library/core/src/swapping.rs:38:13
note: inside `core::swapping::swap_nonoverlapping::compiletime::<MaybeUninit<u8>>`
  --> /rustc/FAKE_PREFIX/library/core/src/swapping.rs:15:22
  --> /rustc/FAKE_PREFIX/library/core/src/swapping.rs:15:22
note: inside `core::swapping::swap_nonoverlapping::<MaybeUninit<u8>>`
  --> /rustc/FAKE_PREFIX/library/core/src/swapping.rs:8:5
note: inside `swap_nonoverlapping::<MaybeUninit<u8>>`
note: inside `X`
  --> /checkout/tests/ui/consts/missing_span_in_backtrace.rs:16:9
   |
16 | /         ptr::swap_nonoverlapping(
16 | /         ptr::swap_nonoverlapping(
17 | |             &mut ptr1 as *mut _ as *mut MaybeUninit<u8>,
18 | |             &mut ptr2 as *mut _ as *mut MaybeUninit<u8>,
19 | |             mem::size_of::<&i32>(),
   | |_________^
   = help: this code performed an operation that depends on the underlying bytes representing a pointer
   = help: the absolute address of a pointer is not known at compile-time, so such operations are not supported
   = note: this error originates in the macro `$crate::intrinsics::const_eval_select` which comes from the expansion of the macro `intrinsics::const_eval_select` (in Nightly builds, run with -Z macro-backtrace for more info)

@bors
Copy link
Contributor

bors commented Dec 31, 2024

☀️ Try build successful - checks-actions
Build commit: 407c8de (407c8de91172b575f44f63b7e9cc1b8139d9c0a6)

@rust-timer

This comment has been minimized.

@rust-timer
Copy link
Collaborator

Finished benchmarking commit (407c8de): comparison URL.

Overall result: ❌✅ regressions and improvements - please read the text below

Benchmarking this pull request likely means that it is perf-sensitive, so we're automatically marking it as not fit for rolling up. While you can manually mark this PR as fit for rollup, we strongly recommend not doing so since this PR may lead to changes in compiler perf.

Next Steps: If you can justify the regressions found in this try perf run, please indicate this with @rustbot label: +perf-regression-triaged along with sufficient written justification. If you cannot justify the regressions please fix the regressions and do another perf run. If the next run shows neutral or positive results, the label will be automatically removed.

@bors rollup=never
@rustbot label: -S-waiting-on-perf +perf-regression

Instruction count

This is the most reliable metric that we have; it was used to determine the overall result at the top of this comment. However, even this metric can sometimes exhibit noise.

mean range count
Regressions ❌
(primary)
1.1% [0.2%, 5.9%] 18
Regressions ❌
(secondary)
0.1% [0.1%, 0.2%] 4
Improvements ✅
(primary)
-0.7% [-2.0%, -0.2%] 5
Improvements ✅
(secondary)
- - 0
All ❌✅ (primary) 0.7% [-2.0%, 5.9%] 23

Max RSS (memory usage)

Results (primary 0.1%, secondary 2.3%)

This is a less reliable metric that may be of interest but was not used to determine the overall result at the top of this comment.

mean range count
Regressions ❌
(primary)
4.5% [2.2%, 7.8%] 5
Regressions ❌
(secondary)
4.6% [2.8%, 6.4%] 2
Improvements ✅
(primary)
-4.3% [-9.2%, -1.1%] 5
Improvements ✅
(secondary)
-2.1% [-2.1%, -2.1%] 1
All ❌✅ (primary) 0.1% [-9.2%, 7.8%] 10

Cycles

Results (primary 1.8%, secondary 1.5%)

This is a less reliable metric that may be of interest but was not used to determine the overall result at the top of this comment.

mean range count
Regressions ❌
(primary)
2.4% [0.9%, 6.2%] 6
Regressions ❌
(secondary)
3.1% [2.5%, 4.0%] 3
Improvements ✅
(primary)
-1.8% [-1.8%, -1.8%] 1
Improvements ✅
(secondary)
-3.4% [-3.4%, -3.4%] 1
All ❌✅ (primary) 1.8% [-1.8%, 6.2%] 7

Binary size

Results (primary 0.7%, secondary 0.1%)

This is a less reliable metric that may be of interest but was not used to determine the overall result at the top of this comment.

mean range count
Regressions ❌
(primary)
2.1% [0.0%, 15.8%] 24
Regressions ❌
(secondary)
0.1% [0.1%, 0.1%] 35
Improvements ✅
(primary)
-0.3% [-0.6%, -0.0%] 39
Improvements ✅
(secondary)
- - 0
All ❌✅ (primary) 0.7% [-0.6%, 15.8%] 63

Bootstrap: 761.022s -> 763.29s (0.30%)
Artifact size: 325.49 MiB -> 325.39 MiB (-0.03%)

@rustbot rustbot added perf-regression Performance regression. and removed S-waiting-on-perf Status: Waiting on a perf run to be completed. labels Dec 31, 2024
Copy link
Member

@RalfJung RalfJung left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Our swap code is slowly turning into a huge pile of spaghetti, which is concerning... do we really need two intrinsics?

// and our fresh local is always disjoint from anything otherwise readable.
unsafe {
(&raw mut temp).copy_from_nonoverlapping(x, 1);
x.copy_from_nonoverlapping(y, 1);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
x.copy_from_nonoverlapping(y, 1);
// Important for miri::intrinsic_fallback_is_spec: here we get language UB
// if x and y overlap.
x.copy_from_nonoverlapping(y, 1);

//#[rustc_allow_const_fn_unstable(const_eval_select)]
#[rustc_const_unstable(feature = "const_swap_nonoverlapping", issue = "133668")]
#[inline]
pub(crate) const unsafe fn swap_nonoverlapping<T>(x: *mut T, y: *mut T, count: usize) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please add a comment clarifying whether this is typed or untyped.

Comment on lines +77 to +79
MAX_ALIGN.. => MAX_ALIGN,
64.. => 64,
32.. => 32,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

On 32bit machines, the 64.. and 32.. arms are dead code. Is that deliberate? If so, that should be explained in comments.

x: &mut mem::MaybeUninit<C>,
y: &mut mem::MaybeUninit<C>,
) {
assert!(size_of::<C>() % ALIGN == 0);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's a bit odd to see a runtime assertion in code like this. Does this work in a const { ... } block?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That's how I first had it, but no, it doesn't because calls to this are guarded with "runtime" checks on the specific ALIGN used -- aka it would need a const-eval-impacting const if for the caller.

I could change it to debug_assert or just remove it.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah, right. Just adding a comment about this could already help.

Comment on lines +173 to +174
hint::assert_unchecked(x.is_aligned_to(ALIGN));
hint::assert_unchecked(y.is_aligned_to(ALIGN));
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do these actually help? Seems worth commenting on that since experience shows that assert_unchecked can often hurt codegen.

@@ -498,6 +498,23 @@ impl<'ll, 'tcx> IntrinsicCallBuilderMethods<'tcx> for Builder<'_, 'll, 'tcx> {
}
}

sym::untyped_swap_nonoverlapping => {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is there a good reason for why this is handled in a different way than typed_swap_nonoverlapping, and in a completely different place as well?

@scottmcm
Copy link
Member Author

do we really need two intrinsics?

I certainly didn't want to add another one :P

From a myopic perspective, they're for two different things:

  1. typed_swap is about taking advantage of the compiler being able to know layout and thus do something smarter than either load-storing the whole items (which is bad for large things) or just swapping the bytes (which is bad for certain pair things)
  2. untyped_swap is about avoiding the LLVM problem where memcpy lowering leaves behind copies through the stack even for simple things like asking it to swap two [u8; 32]s.

I'd be happy to change either if you have good ideas. For example, I might be able to make a copy_nonoverlapping_small or something instead of having it be swap-specific for the latter one, if you think that'd be cleaner. Or maybe I could require backends to override the former, despite the fallback MIR, for some types so that the fallback code can call back into the same intrinsic just with simpler types (like integer primitives or maybeuninits thereof).

@RalfJung
Copy link
Member

RalfJung commented Jan 1, 2025

I'm afraid I don't have the overview to suggest a different architecture here... I haven't quite gotten to the bottom of the spaghetti yet. ;)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
perf-regression Performance regression. S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. T-compiler Relevant to the compiler team, which will review and decide on the PR/issue. T-libs Relevant to the library team, which will review and decide on the PR/issue.
Projects
None yet
7 participants