rust-lang / rust-lang/rust

Lint on `black_box`ing ZSTs

Open
#137,658 6 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

A-lints A-ZST C-enhancement E-medium T-compiler
Dominant language
Rust
Stars
119k
Forks
16.1k
PR merge metrics
PR metrics pending

Description

If a function pointer is black boxed, the call is treated as opaque:

use core::hint::black_box;
use core::ops::Shl;

#[no_mangle]
pub fn coerce_to_fn() {
    let f: fn(u32, u32) -> u32 = u32::shl;
    let fbb = black_box(f);
    fbb(1, 2);
}
coerce_to_fn:
        push    rax
        lea     rax, [rip + <u32 as core::ops::bit::Shl>::shl::hf57c419aa60bbfeb]
        mov     qword ptr [rsp], rax
        mov     rax, rsp
        mov     edi, 1
        mov     esi, 2
        call    qword ptr [rsp]
        pop     rax
        ret

However, black boxing a ZST that implements Fn does nothing:

#[no_mangle]
pub fn with_zst() {
    let fbb = black_box(u32::shl);
    fbb(1, 2);
}
with_zst:
        ret

This difference is subtle and we should lint on it. Suggested by @beetrees.

For reference: https://rust.godbolt.org/z/nvoEcnxKh

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 reproducing the two examples with black_box, comparing the function-pointer call with the ZST Fn call and inspecting the generated assembly. The issue does not name implementation files or tests; done means adding a lint that identifies this ineffective ZST black boxing and covering the behavior with an appropriate compiler test.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
compilers
Issue type
Feature
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
38/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.