Skip to content

Commit

Permalink
Auto merge of #62891 - vext01:improve-black-box-docs, r=RalfJung,Cent…
Browse files Browse the repository at this point in the history
…ril,gnzlbg

Improve the documentation for std::hint::black_box.

The other day a colleague was reviewing some of my code which was using `black_box` to block constant propogation. There was a little confusion because the documentation kind of implies that `black_box` is only useful for dead code elimination, and only in benchmarking scenarios.

The docs currently say:

> A function that is opaque to the optimizer, to allow benchmarks to pretend to use outputs to assist in avoiding dead-code elimination.

Here is our discussion, in which I show (using godbolt) that a black box can also block constant propagation:
ykjit/yk#21 (comment)

This change makes the docstring for `black_box` a little more general, and while we are here, I've added an example (the same one from our discussion).

![image](https://user-images.githubusercontent.com/604955/61701322-ddf1e400-ad35-11e9-878c-b5b44a20770c.png)

OK to go in?
  • Loading branch information
bors committed Aug 26, 2019
2 parents 4c58535 + a4b3dbe commit e2b4165
Showing 1 changed file with 12 additions and 4 deletions.
16 changes: 12 additions & 4 deletions src/libcore/hint.rs
Original file line number Diff line number Diff line change
Expand Up @@ -104,11 +104,19 @@ pub fn spin_loop() {
}
}

/// A function that is opaque to the optimizer, to allow benchmarks to
/// pretend to use outputs to assist in avoiding dead-code
/// elimination.
/// An identity function that *__hints__* to the compiler to be maximally pessimistic about what
/// `black_box` could do.
///
/// This function is a no-op, and does not even read from `dummy`.
/// [`std::convert::identity`]: https://doc.rust-lang.org/core/convert/fn.identity.html
///
/// Unlike [`std::convert::identity`], a Rust compiler is encouraged to assume that `black_box` can
/// use `x` in any possible valid way that Rust code is allowed to without introducing undefined
/// behavior in the calling code. This property makes `black_box` useful for writing code in which
/// certain optimizations are not desired, such as benchmarks.
///
/// Note however, that `black_box` is only (and can only be) provided on a "best-effort" basis. The
/// extent to which it can block optimisations may vary depending upon the platform and code-gen
/// backend used. Programs cannot rely on `black_box` for *correctness* in any way.
#[inline]
#[unstable(feature = "test", issue = "50297")]
#[allow(unreachable_code)] // this makes #[cfg] a bit easier below.
Expand Down

0 comments on commit e2b4165

Please sign in to comment.