rust-lang / rust-lang/rust

Redundant calls to Vec::reserve are not optimized out

Open
#128,613 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

C-optimization T-libs
Dominant language
Rust
Stars
119k
Forks
16.1k
PR merge metrics
PR metrics pending

Description

pub fn reservy(x: &mut Vec<u8>) {
    x.reserve(10);
    x.reserve(10);
}

Currently compiles to:

define void @example::reservy::hfd53462e17d1ffb0(ptr noalias nocapture noundef align 8 dereferenceable(24) %x) unnamed_addr #2 !dbg !239 {
start:
  %0 = getelementptr inbounds i8, ptr %x, i64 16, !dbg !241
  %len = load i64, ptr %0, align 8, !dbg !241
  %self = load i64, ptr %x, align 8, !dbg !248
  %_6 = sub i64 %self, %len, !dbg !258
  %_4 = icmp ult i64 %_6, 10, !dbg !262
  br i1 %_4, label %bb2, label %bb4, !dbg !263

bb2:
  tail call fastcc void @"alloc::raw_vec::RawVec<T,A>::reserve::do_reserve_and_handle::ha1fc33f26a8560a9"(ptr noalias noundef nonnull align 8 dereferenceable(16) %x, i64 noundef %len), !dbg !264
  %len1.pre = load i64, ptr %0, align 8, !dbg !265
  %self2.pre = load i64, ptr %x, align 8, !dbg !268
  %.pre = sub i64 %self2.pre, %len1.pre, !dbg !275
  %1 = icmp ult i64 %.pre, 10, !dbg !278
  br i1 %1, label %bb3, label %bb4, !dbg !279

bb4:
  ret void, !dbg !280

bb3:
  tail call fastcc void @"alloc::raw_vec::RawVec<T,A>::reserve::do_reserve_and_handle::ha1fc33f26a8560a9"(ptr noalias noundef nonnull align 8 dereferenceable(16) %x, i64 noundef %len1.pre), !dbg !282
  br label %bb4, !dbg !282
}

I found this while looking at the existing optimizer hints we have in RawVec. They are placed to optimize out redundant reserve calls, except that the hint is actually in the outlined part of reserve because of this wrapper that I wrote a while ago: https://github.com/rust-lang/rust/blob/edc4dc337b28a389dbd87b3825d7929381edeb8f/library/alloc/src/raw_vec.rs#L338-L343

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start in library/alloc/src/raw_vec.rs around the wrapper and optimizer hints at lines 338-343. Reproduce the shown reservy example and inspect its generated LLVM to understand why the second reserve remains. Done means redundant reserve calls are optimized out while the reserve behavior remains correct.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
compilers, performance
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.