Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Black box function #145

Open
kazimuth opened this issue Sep 11, 2019 · 2 comments
Open

Black box function #145

kazimuth opened this issue Sep 11, 2019 · 2 comments

Comments

@kazimuth
Copy link

It would be nice to have a function to disable dead-code elimination / constant propagation. Rust has this; it's implemented as the identity function, but with magic inside:

assert_eq!(100, std::hints::black_box(100));

Rust implementation:

/// A function that is opaque to the optimizer, to allow benchmarks to
/// pretend to use outputs to assist in avoiding dead-code
/// elimination.
///
/// This function is a no-op, and does not even read from `dummy`.
#[inline]
#[unstable(feature = "test", issue = "27812")]
#[allow(unreachable_code)] // this makes #[cfg] a bit easier below.
pub fn black_box<T>(dummy: T) -> T {
    // We need to "use" the argument in some way LLVM can't introspect, and on
    // targets that support it we can typically leverage inline assembly to do
    // this. LLVM's intepretation of inline assembly is that it's, well, a black
    // box. This isn't the greatest implementation since it probably deoptimizes
    // more than we want, but it's so far good enough.
    #[cfg(not(any(
        target_arch = "asmjs",
        all(
            target_arch = "wasm32",
            target_os = "emscripten"
        )
    )))]
    unsafe {
        asm!("" : : "r"(&dummy));
        return dummy;
    }

    // Not all platforms support inline assembly so try to do something without
    // inline assembly which in theory still hinders at least some optimizations
    // on those targets. This is the "best effort" scenario.
    unsafe {
        let ret = crate::ptr::read_volatile(&dummy);
        crate::mem::forget(dummy);
        ret
    }
}

I don't know how hard this would be to translate to Julia.

@gdalle
Copy link
Collaborator

gdalle commented Jun 13, 2023

See #92

@Zentrik
Copy link
Contributor

Zentrik commented Jan 3, 2024

I think Base.donotdelete should be similar to Rust's version. It doesn't affect constant folding but I don't think Rust's does either.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants