Memcpy optimizations


#1

Say I have the following struct

struct InnerVec(Vec<u8>);

(note that it is private) and I don’t push to the vec anywhere. Can rust spot that the vec is unused and remove it. If not, can rust spot that the struct is elegable for memcpy because the pointer is always null?

EDIT: this is a toy example.


#2

It certainly can in trivial cases. Take this for example:

pub struct InnerVec(Vec<u8>);

pub fn foo() -> usize {
    let v = InnerVec(Vec::new());
    bar(v)
}

fn bar(v: InnerVec) -> usize {
    v.0.len()
}

This produces the following assembly (Rust 1.24, -C opt-level=2):

example::foo:
        pushq   %rbp
        movq    %rsp, %rbp
        xorl    %eax, %eax
        popq    %rbp
        retq

All it does is frame setup and zero’ing of the return register (eax).

Whether the compiler can see that it’s “unused” in more involved code will depend on optimization horizon.