Skip to content

C2Rust emits unused asm operand for inline assembly input that is not referenced by the template #1706

@lynae99

Description

@lynae99

C2Rust incorrectly preserves an unused input operand when translating GCC-style inline assembly to Rust asm!, producing non-compilable Rust code.
Reproducer

#include <stdio.h>

int main() {
    int a = 4;
    int b = 6;
    int result;

    __asm__ volatile (
        "movl %[b], %[r]\n\t"            // result = b
        : [r] "=&r"(result)
        : [a] "r"(a), [b] "r"(b)         // NOTE: a is intentionally unused
        : "cc"
    );

    // result should be 6; a is unused and does not affect semantics
    printf("UnusedInput: a=%d, b=%d, result=%d\n", a, b, result);
    return 0;
}

Generated Rust

#![allow(
    dead_code,
    non_camel_case_types,
    non_snake_case,
    non_upper_case_globals,
    unused_assignments,
    unused_mut
)]
use ::core::arch::asm;
extern "C" {
    fn printf(__format: *const ::core::ffi::c_char, ...) -> ::core::ffi::c_int;
}
unsafe fn main_0() -> ::core::ffi::c_int {
    let mut a: ::core::ffi::c_int = 4 as ::core::ffi::c_int;
    let mut b: ::core::ffi::c_int = 6 as ::core::ffi::c_int;
    let mut result: ::core::ffi::c_int = 0;
    asm!(
        "movl {2}, {0}\n", "\t\n", out(reg) result, inlateout(reg) a => _, inlateout(reg)
        b => _, options(att_syntax)
    );
    printf(
        b"UnusedInput: a=%d, b=%d, result=%d\n\0" as *const u8
            as *const ::core::ffi::c_char,
        a,
        b,
        result,
    );
    return 0 as ::core::ffi::c_int;
}
pub fn main() {
    unsafe { ::std::process::exit(main_0() as i32) }
}

Rust Compilation Error

error: argument never used

The original C inline assembly is valid: GCC-style inline asm permits inputs that are declared but not referenced in the template.
However, Rust asm! requires every declared operand to be used in the assembly template. The translated code still emits the unused operand a, causing a compilation error.
Environment

  • c2rust version: v0.21.0
  • platform: Ubuntu 24.04
  • Rust: nightly-2022-08-08
  • Clang version: 17.0.6

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions