rust-lang / rust-lang/rust

Possibly missed return value optimization

Open
#144,009 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

C-discussion
Dominant language
Rust
Stars
119k
Forks
16.1k
PR merge metrics
PR metrics pending

Description

Given a function like:

let result = func();

fn func() -> T {
    let mut ret = T;  // size of T is known at compile-time
    // ...
    return ret;
}

I would expect result to be constructed in-place.

However, with code like

pub fn generate_moves(game: &BoardState) -> MoveList {
    let mut movelist = MoveList::new();
    match game.whites_turn() {
        true => MoveGen::<true>::new(game).generate_all_moves(&mut movelist),
        false => MoveGen::<false>::new(game).generate_all_moves(&mut movelist),
    }
    movelist
}

#[bitfield]
#[derive(Copy, Clone, Debug)]
#[repr(u16)]
pub struct Move {
    pub start: B6,  // 0-63
    pub variant: Variant, // normal, castle, promo, enpassant
    pub target: B6, // 0-63
    pub promo: Promo,  // knight, bishop, rook, queen
}

pub struct MoveList {
    size: u32,
    list: [Move; 224],
}

movelist is constructed on the stack, then copied/moved into the memory location reserved for the return spot. In MIR, movelist is not given the _0 binding and it's not apparent why rustc made that choice.

Hopefully, someone with more experience and chime in and give insight on whether this is a missed optimization or something purposefully overlooked.

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 by inspecting the MIR for generate_moves and the relationship between the local movelist and the _0 return place. Compare it with the simpler func example and determine whether the observed copy is intentional or an optimization gap. The issue is complete when the behavior is explained with supporting compiler evidence or a focused reproduction.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
compilers
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
30/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.