Skip to content

opt -O2 deletes the panic path and produces silent wrong results #407

Closed

Description

@SomeB1oody

Description

When a kernel hits a diverging panic call (Option::unwrap on a runtime None, explicit panic!, unwrap_failed, etc.), mir-importer drops the call entirely and emits a bare mir.unreachable (crates/mir-importer/src/translator/terminator/mod.rs, line 1212–1219).

The comment there says: "we emit an unreachable terminator since panics can't actually execute". LLVM's unreachable tells the middle end that reaching the panic is UB, so the opt -O2 stage folds the None branch away, not preserving it.

This is the same problem as #396 (fixed by #405), but at a different lowering site. #405 fixed TerminatorKind::Assert in mir-lower's convert_assert. Diverging TerminatorKind::Call still produces the deletable pattern.

Minimal reproducer

use cuda_core::{CudaContext, DeviceBuffer, LaunchConfig};
use cuda_device::{DisjointSlice, kernel, thread};
use cuda_host::cuda_module;

#[cuda_module]
mod kernels {
    use super::*;

    #[kernel]
    pub fn unwrap_get(src: &[f32], j: usize, mut out: DisjointSlice<f32>) {
        if let Some(out_elem) = out.get_mut(thread::index_1d()) {
            *out_elem = src.get(j).copied().unwrap(); // None when j >= src.len() -> must panic
        }
    }
}

fn main() {
    let ctx = CudaContext::new(0).expect("context");
    let stream = ctx.default_stream();
    let module = kernels::load(&ctx).expect("load module");

    let src = DeviceBuffer::from_host(&stream, &[1.0f32, 2.0, 3.0, 4.0]).expect("src");
    let mut out = DeviceBuffer::from_host(&stream, &[-1.0f32]).expect("out");

    // SAFETY: one thread, one output element
    let result = unsafe {
        module.unwrap_get(
            &stream,
            LaunchConfig::for_num_elems(1),
            &src,
            1_000_000usize, // src.get(1_000_000) is None -> unwrap() must panic
            &mut out,
        )
    }
    .and_then(|()| out.to_host_vec(&stream));

    match result {
        Err(e) => println!("PASS (kernel trapped: {})", e),
        Ok(out) => {
            println!("FAIL (unwrap(None) did not panic, out[0] = {})", out[0]);
            std::process::exit(1);
        }
    }
}

Expected behavior

src.get(1_000_000) returns None and .unwrap() panics. According to rustc-codegen-cuda README ("If a panic condition is hit at runtime, the GPU traps"), the kernel must trap and the host must see the launch fail. At minimum, the None arm must never be compiled into code that produces a value.

Actual behavior

The launch succeeds and out[0] is overwritten with garbage (0.0 here, whatever an uninitialized register holds). No trap, no error code, and compute-sanitizer is completely silent:

FAIL (unwrap(None) did not panic, out[0] = 0)
========= COMPUTE-SANITIZER
FAIL (unwrap(None) did not panic, out[0] = 0)
========= Target application returned an error
========= ERROR SUMMARY: 0 errors

Environment

  • cuda-oxide: main@29396b7f
  • sm_120a
  • CUDA driver version: 595.71.05 (CUDA toolkit 13.3, nvcc V13.3.73)
  • rustc --version --verbose (repo-pinned nightly-2026-04-03):
    rustc 1.96.0-nightly (55e86c996 2026-04-02)
    binary: rustc
    commit-hash: 55e86c996809902e8bbad512cfb4d2c18be446d9
    commit-date: 2026-04-02
    host: x86_64-unknown-linux-gnu
    release: 1.96.0-nightly
    LLVM version: 22.1.2
    
  • llc-21 --version: Ubuntu LLVM version 21.1.8 (opt-21 from the same toolchain)

Activity

  1. added
    bug
    TBD
    on Jul 17, 2026
  2. SomeB1oody commented on Jul 17, 2026

    @SomeB1oody
    ContributorAuthor

    In pre-opt .ll, the unwrap_failed call was dropped by mir-importer, leaving a bare unreachable in the None arm (bb18):

    bb13:                                   ; match on Option<f32> discriminant
      %v45 = icmp eq i64 %v44, 0
      br i1 %v45, label %bb18, label %bb14
    ...
    bb18:                                   ; None -> unwrap_failed (call was dropped)
      unreachable

    In post-opt .ll, opt -O2 concludes the None arm cannot happen and folds the panic into a phi with undef:

    bb17:
      %v49 = load float, ptr %v33, align 4
      br label %bb19
    
    bb19:
      %v42 = phi float [ %v49, %bb17 ], [ undef, %bb2 ]   ; None arm -> undef
      store float %v42, ptr %v23, align 4

    In final PTX, the panic path is now "store whatever is in %r4":

    	setp.lt.u64 	%p2, %rd7, %rd6;    // j < src.len() ?
                                            // implicit-def: %r4
    	@%p2 bra 	$L__BB0_2;
    	bra.uni 	$L__BB0_3;
    $L__BB0_2:                              // in bounds
    	ld.global.b32 	%r4, [%rd5];
    $L__BB0_3:
    	st.global.b32 	[%rd4], %r4;        // None: %r4 is an uninitialized register
    

    When CUDA_OXIDE_NO_OPT=1, the bare unreachable can reach llc, and NVPTX will pass turns it into exit: the thread silently exits and out[0] keeps its -1.0 sentinel (in v0.2.0, the panic is still swallowed, but no wrong data is produced). So the bare unreachable was always semantically wrong for panic paths.

  3. midiareshadi commented on Jul 18, 2026

    @midiareshadi

    Nice find — and the silent variant here (#407) is the more dangerous of the two. With #396 at least compute-sanitizer caught the out-of-bounds read; here the launch just succeeds and you get undef in the output, with ERROR SUMMARY: 0 errors. Nothing complains.

    Good that the "unreachable on a runtime-reachable path" pattern is being swept out at every lowering site (Assert in #405, diverging Call here), not just the first one I happened to hit. Happy to test #408 on sm_89 (L4) as well if a second-architecture data point is useful.

  4. added a commit that references this issue on Jul 22, 2026
    1a23833
  5. added a commit that references this issue on Jul 22, 2026
    6300b8d
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    TBDbug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions