Skip to content

[Experiment] Eliminate possible Vec::push branches #121300

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

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions library/alloc/src/vec/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -905,10 +905,14 @@ impl<T, A: Allocator> Vec<T, A> {
/// vec.reserve(10);
/// assert!(vec.capacity() >= 11);
/// ```
#[inline(always)]
#[cfg(not(no_global_oom_handling))]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn reserve(&mut self, additional: usize) {
self.buf.reserve(self.len, additional);
unsafe {
core::hint::assert_unchecked(self.len().unchecked_add(additional) <= self.capacity());
}
}

/// Reserves the minimum capacity for at least `additional` more elements to
Expand Down Expand Up @@ -1925,6 +1929,7 @@ impl<T, A: Allocator> Vec<T, A> {
let end = self.as_mut_ptr().add(self.len);
ptr::write(end, value);
self.len += 1;
Copy link
Contributor

Choose a reason for hiding this comment

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

@c410-f3r

Just as a note: LLVM's constraint elimination can work better when this is written as:

// rustc emits: `add nuw`, so the pass can assume that the instruction does not overflow
self.len = unsafe { self.len.unchecked_add(1) };

This reduces some calls to reserve_for_push but does not eliminate all of them. I haven't really had the time to dig in further to find out...

core::hint::assert_unchecked(self.len() < self.capacity());
}
}

Expand Down
16 changes: 16 additions & 0 deletions tests/codegen/reserve_local_push.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
// compile-flags: -O

#![crate_type = "lib"]

#[no_mangle]
pub fn push(v: &mut Vec<u8>) {
let _ = v.reserve(4);
// CHECK-NOT: call {{.*}}reserve_for_push
v.push(1);
// CHECK-NOT: call {{.*}}reserve_for_push
v.push(2);
// CHECK-NOT: call {{.*}}reserve_for_push
v.push(3);
// CHECK-NOT: call {{.*}}reserve_for_push
v.push(4);
}