Enum ctor fn + branch = missed optimization/inlining

未关闭
#166,153 0 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

维护者通常 1 天内回复

还没有人认领这个 Issue。

评估

难度
3/5
预计耗时
1-2 天
新手友好度
49/100
Issue 类型
缺陷
描述清晰度
基本清楚
活跃度
活跃
技术栈
rust

调研方向

The report includes blockmaker and blockmaker2 examples and assembly output, but names no rustc source file or test. Start by reproducing the difference on the linked Godbolt setup with nightly and -C opt-level=3, then trace how enum variant constructors used as function values are optimized. Done when the constructor function branch produces equivalent optimized output to the direct conditional construction, with a regression test covering the case.

由索引模型根据 Issue 内容生成。

描述

A-LLVM C-optimization T-compiler

I tried this code:

pub enum Block {
    Outlined(i32),
    Hollow(i32),
}

#[unsafe(no_mangle)]
pub fn blockmaker(condition: bool, mass: i32) -> Block {
    (if condition { Block::Hollow } else { Block::Outlined }) (mass)
}

#[unsafe(no_mangle)]
pub fn blockmaker2(condition: bool, mass: i32) -> Block {
    if condition { Block::Hollow(mass) } else { Block::Outlined(mass) }
}

I expected to see this happen: blockmaker should result in the same assembly as blockmaker2

Instead, this happened: They compile to different assembly:

example[9d75cd1f3a21f3ed]::Block::Hollow:
  mov eax, 1
  mov edx, edi
  ret

example[9d75cd1f3a21f3ed]::Block::Outlined:
  xor eax, eax
  mov edx, edi
  ret

blockmaker:
  lea rax, [rip + example[9d75cd1f3a21f3ed]::Block::Hollow]
  lea rcx, [rip + example[9d75cd1f3a21f3ed]::Block::Outlined]
  test edi, edi
  cmovne rcx, rax
  mov edi, esi
  jmp rcx

blockmaker2:
  mov edx, esi
  mov eax, edi
  ret

blockmaker uses a weird way to do conditional jumps (instead of using the traditional jnz/jz + jmp). Meanwhile, blockmaker2 seems to be properly inlined and optimized.

Godbolt link

This missed optimization happens on all three channels (stable 1.99.0/beta/nightly) on godbolt, for amd64, with -C opt-level=3

主要语言
Rust
星标
122k
派生
16.7k
平均合并
2 天 16 小时
30 天内合并 PR
515

环境准备

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

rust-lang/rust 的其他 Issue

查看 rust-lang/rust 的全部 Issue

相似的 Issue

更多 Rust Issue

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。