Iterating an array by value keeps a second copy of it on the stack even though the original is dead

Abierto
#166,627 1 comentario 0 reacciones 0 asignados Ver en GitHub

Los mantenedores suelen responder en 1 día

Nadie ha tomado este issue todavía.

Evaluación

Dificultad
4/5
Tiempo estimado
3-5 días
Aptitud para principiantes
38/100
Tipo de issue
Error
Claridad
Bastante claro
Estado de actividad
Activo
Stack tecnológico
compilers, rust

Línea de trabajo

Start by reproducing the reported stack frames and memcpy calls with the linked Godbolt example, then trace how array by-value iteration is lowered through core::array::IntoIter and optimized by rustc and LLVM. Compare by_value with by_reference and drain_gen_block; done when the cause is identified and a compiler change eliminates the redundant array copy without changing iteration behavior.

Escrito por el modelo de indexación a partir del texto del issue.

Descripción

A-array A-codegen A-iterators A-LLVM C-optimization S-has-mcve T-compiler

Iterating a local array by value (for value in array) copies the whole array into core::array::IntoIter with a memcpy, and both copies stay in the stack frame, even though the original array is never used again.

Iterating by reference doesn't have the copy.

Example (reduced by LLM from a real project for demo purposes):

#![feature(gen_blocks)]

use std::hint::black_box;

const N: usize = 128;

unsafe extern "Rust" {
    safe fn consume(value: u64);
}

/// Fully visible to the optimizer, the address of `batch` doesn't escape
#[inline(always)]
fn fill(batch: &mut [u64; N]) {
    let seed = black_box(1u64);
    for (offset, value) in (0u64..).zip(batch.iter_mut()) {
        *value = seed.wrapping_mul(offset);
    }
}

/// Iterating the array by value: the array is copied into `array::IntoIter`, the original is dead
/// afterwards, yet both copies stay on the stack
#[unsafe(no_mangle)]
pub fn by_value() {
    let mut batch = [0u64; N];
    fill(&mut batch);
    for value in batch {
        consume(value);
    }
}

/// The same with iteration by reference, only one array on the stack
#[unsafe(no_mangle)]
pub fn by_reference() {
    let mut batch = [0u64; N];
    fill(&mut batch);
    for &value in &batch {
        consume(value);
    }
}

/// In a `gen` block the iterator must live in the coroutine state, and the array is still built on
/// the stack of the resume function first
#[unsafe(no_mangle)]
pub fn gen_block() -> impl Iterator<Item = u64> {
    gen {
        let mut batch = [0u64; N];
        fill(&mut batch);
        for value in batch {
            yield value;
        }
    }
}

#[unsafe(no_mangle)]
pub fn drain_gen_block() {
    for value in gen_block() {
        consume(black_box(value));
    }
}

https://rust.godbolt.org/z/3rY7qcY79

On x86-64:

function frame (sub rsp) memcpy calls
by_value 2072 B 1 (1024 bytes, right after fill)
by_reference 1032 B 0
drain_gen_block 2080 B 1

I expected by_value to only need one array since batch is dead after it is moved (copied) into the iterator, so the iterator can use its storage, and the frame should be about the size of by_reference.

LLVM apparently has stack-move optimization in MemCpyOpt (https://reviews.llvm.org/D153453), but it doesn't kick in here.

While workarounds for this are possible, neither of them look as pretty as gen {} block.

Possibly related issues found by LLM
  • #87949 (array::IntoIter doesn't get optimized as well as vec::IntoIter, closed)
  • #86912 (array::map stack usage)
  • #84513 (the "copying large arrays" footgun listed as an open item of edition-dependent IntoIterator for arrays)
  • #64301 (too many memcpys)
  • #42763 (self moved with a memmove into an inlined into_iter())
  • #52274 (large by-value Copy arguments copied)
  • #99504 (callee futures built in a stack temporary and then copied into the caller's state)
  • #161506, #161568 (separate stack slots for call results due to MIR passes or MemCpyOpt)
Meta
rustc 1.102.0-nightly (65ce8611f 2026-11-18)
binary: rustc
commit-hash: 65ce8611fed3142053320be6996ef00e9992671f
commit-date: 2026-11-18
host: x86_64-unknown-linux-gnu
release: 1.102.0-nightly
LLVM version: 23.1.6
Lenguaje dominante
Rust
Estrellas
123k
Forks
16.6k
Merge medio
2 d 17 h
PR fusionados (30 d)
532

Preparar el entorno

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Más de rust-lang/rust

Todos los issues de rust-lang/rust

Issues similares

Más issues de Rust

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.