Skip to content

Variadic calls: an argument narrower than int is not promoted (i8 -3 arrives as 253) #1849

Closed

Description

@ehartford

Found while fixing #1831. A variadic argument narrower than int is passed without C's default argument promotion (C11 6.5.2.2p7: the arguments matched by ... get the default argument promotions — an integer narrower than int becomes int, keeping its sign). Codegen passes the i8/i16 value as is into the LLVM vararg call, where its upper bits are undefined; LLVM gives them no extension.

// vsum.c
#include <stdarg.h>
#include <stdio.h>
int vsum(int n, ...) { va_list ap; va_start(ap, n); double f = va_arg(ap, double); int b = va_arg(ap, int); int u = va_arg(ap, int); va_end(ap); printf("f=%g b=%d u=%d\n", f, b, u); return n; }
use c_import("int vsum(int n, ...);")
fn pick(x: i8) -> i8: x
fn pickf(x: f32) -> f32: x
fn main:
    let f = pickf(1.5)
    let b = pick(-3)
    let u: u8 = 200
    print(unsafe { vsum(3, f, b, u) })

clang -c vsum.c && with build main.w --link-object vsum.o prints f=1.5 b=253 u=200 (expected b=-3), v0.15.3.0 on darwin arm64: the i8 constant is materialized as mov w9, #0xfd into the 8-byte stack slot. With runtime-computed values the register often happens to hold the extended value, so the bug hides.

Fix: Sema states the promoted type of each ... argument (the same c_default_promoted_type #1831 adds for unprototyped calls) and codegen coerces each variadic argument to it, sign- or zero-extending by the argument's own type, as clang does (sext i8 ... to i32, fpext float ... to double).

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