# Rustc Optimization: Whole Program Devirtualization

**URL:** <https://internals.rust-lang.org/t/rustc-optimization-whole-program-devirtualization/12942>\
**Category:** compiler\
**Created:** [August 22, 2020, 4:34pm UTC](https://internals.rust-lang.org/t/rustc-optimization-whole-program-devirtualization/12942 "2020-08-22T16:34:42Z")\
**Posts on this page:** 5\
**Page:** 1

<div class="post-metadata">

**Author:** ![jhwgh1968](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/jhwgh1968/32/7121_2.png) [@jhwgh1968](https://internals.rust-lang.org/u/jhwgh1968)\
**Post date:** [August 22, 2020, 4:34pm UTC](https://internals.rust-lang.org/t/rustc-optimization-whole-program-devirtualization/12942/1 "2020-08-22T16:34:43Z")

</div>

Hello everyone,

Back in 2019, Matt Godbolt did an entertaining talk about compiler optimization, and briefly mentioned something that really caught my attention: [speculative devirtualization in C++](https://www.youtube.com/watch?v=w0sz5WbS5AM#t=3090).

I found this exciting, because of Rust programs like this:

```rust
/ *********devirt-lib crate: src/lib.rs********* /
pub trait Printable {
    fn print_line(&self, handle: &mut dyn std::io::Write) -> std::io::Result<()>;
}

pub struct PrintableArray(Vec<Box<dyn Printable + 'static>>);

impl PrintableArray {
    pub fn new() -> PrintableArray {
        PrintableArray(Vec::new())
    }

    pub fn push(&mut self, item: impl Printable + 'static) {
        self.0.push(Box::new(item))
    }

    pub fn print_all(&self, handle: &mut dyn std::io::Write) -> std::io::Result<()> {
        self.0.iter().try_fold(handle, |handle, item| {
            item.print_line(handle)?;
            Ok(handle)
        }).map(|_| ())
    }
}

/ *********devirt-test crate: src/main.rs********** /
use std::io::Write;

use devirt_lib::PrintableArray;

struct Point {
    pub x: f32,
    pub y: f32,
}

impl devirt_lib::Printable for Point {
    fn print_line(&self, handle: &mut dyn Write) -> std::io::Result<()> {
        writeln!(handle, "Point: {{ {}, {} }}", self.x, self.y)
    }
}

fn main() -> std::io::Result<()> {
    let mut vec: PrintableArray = PrintableArray::new();
    vec.push(Point { x: 10.0, y: 20.0 });
    vec.push(Point { x: 20.0, y: 40.0 });
    vec.push(Point { x: 30.0, y: 60.0 });
    vec.push(Point { x: 40.0, y: 80.0 });
    vec.print_all(&mut std::io::stdout())
}

```

That type erasure across a crate boundary looks just like a C++ virtual function call. In fact, here is the assembly for loop inside `print_all`, which is inlined into the `main` function (produced on a recent nightly):

```nohighlight
    6f50: add r15,0xfffffffffffffff0
    6f54: add rbx,0x10
    6f58: add rbp,0x10
    6f5c: cmp rbp,r12
    6f5f: je 6f89 # loop exit
    6f61: mov rdi,QWORD PTR [rbx-0x10]
    6f65: mov rax,QWORD PTR [rbx-0x8]
    6f69: call QWORD PTR [rax] # virtual call
    6f6b: lea rbp,[rbx-0x10]
    6f6f: mov rax,QWORD PTR [rbp+0x8]
    6f73: mov rsi,QWORD PTR [rax+0x8]
    6f77: test rsi,rsi
    6f7a: je 6f50 # loop top
    6f7c: mov rdx,QWORD PTR [rax+0x10]
    6f80: mov rdi,QWORD PTR [rbx-0x10]
    6f84: call r13
    6f87: jmp 6f50 # loop top

```

It looks exactly the same, and could benefit from speculative devirtualization, which LLVM calls Whole Program Devirtualization (WPD).

At the time of the presentation in 2019, Matt said that LLVM was still working on it. A quick grep of the LLVM monorepo suggests it was [implemented in LLVM 10](https://github.com/llvm/llvm-project/commit/d2df54e6a55af509b08afa109fe522cd88ad1c33), with [additional improvements in LLVM 11](https://reviews.llvm.org/D71913).

At first, I hoped that LLVM would implement it, and Rust would get it for free. Unfortunately, reading the [LLVM RFC](http://lists.llvm.org/pipermail/llvm-dev/2019-December/137543.html) and several of the patches, some explicit support by the compiler is needed. It must handle LTO item visibility in certain ways in order for the pass to trigger.

Given the amount of work that Rust has done on LTO, I imagine it is not an easy change. If it was, I would have written this as a GitHub issue instead.

My post here is to just to ask if this is on anyone's radar, and see if people think it's worth it for Rust.

---

<div class="post-metadata">

**Author:** ![jethrogb](https://avatars.discourse-cdn.com/v4/letter/j/43a26b/32.png) [@jethrogb](https://internals.rust-lang.org/u/jethrogb)\
**Post date:** [August 24, 2020, 2:47pm UTC](https://internals.rust-lang.org/t/rustc-optimization-whole-program-devirtualization/12942/2 "2020-08-24T14:47:04Z")

</div>

Looks interesting, definitely sounds like something that could be beneficial to Rust!

---

<div class="post-metadata">

**Author:** ![nathanwhit](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/nathanwhit/32/5947_2.png) [@nathanwhit](https://internals.rust-lang.org/u/nathanwhit)\
**Post date:** [August 24, 2020, 4:14pm UTC](https://internals.rust-lang.org/t/rustc-optimization-whole-program-devirtualization/12942/3 "2020-08-24T16:14:22Z")

</div>

There’s an [open issue](https://github.com/rust-lang/rust/issues/68262) for this, and there are a few rough notes there on how it might be implemented.

---

<div class="post-metadata">

**Author:** ![jhwgh1968](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/jhwgh1968/32/7121_2.png) [@jhwgh1968](https://internals.rust-lang.org/u/jhwgh1968)\
**Post date:** [August 26, 2020, 3:50am UTC](https://internals.rust-lang.org/t/rustc-optimization-whole-program-devirtualization/12942/4 "2020-08-26T03:50:00Z")

</div>

Thanks for the pointer, @nathanwhit! I couldn't find that when I searched. I will give that a follow.

---

<div class="post-metadata">

**Author:** ![system](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/system/32/14092_2.png) [@system](https://internals.rust-lang.org/u/system)\
**Post date:** [November 24, 2020, 3:50am UTC](https://internals.rust-lang.org/t/rustc-optimization-whole-program-devirtualization/12942/5 "2020-11-24T03:50:05Z")

</div>

Closed on November 24, 2020, 3:50am UTC

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.
