Skip to content

CCodegen: a global whose initializer is not a literal is emitted zero-initialized (1 << 3, [7u16, 9u16], Some(3) all become 0) #1484

Closed

Description

@ehartford

Found while fixing #1429 (the same file's global_decl_tid fallback). Stage1 of main (base of #1429's branch), --emit-c:

let SHIFTED = 1 << 3
let TABLE = [7u16, 9u16]
let MAYBE = Some(3)
fn main:
    print(f"{SHIFTED} {TABLE[1]} {MAYBE.unwrap()}")

The LLVM backend prints 8 9 3. The emitted C initializes all three globals to zero and nothing assigns them later (no init function; main reads them directly):

static int32_t __with_global_SHIFTED__13322 = 0;
static uint16_t __with_global_TABLE__13323[2] = {0};
static Option_i32_ __with_global_MAYBE__13324 = (Option_i32_){0};

CCodegen.global_init_text (src/CCodegen.w) renders int/bool/float/string/c-string/null literals and falls through to zero_value_text(tid) — or {0} for an array — for every other initializer: a binary expression, an array literal, a variant constructor, a call. That is a silent fallback (AGENTS.md No Silent Fallbacks): the program compiles and reads different values.

Expected: every initializer the C backend cannot express as a C constant initializer is either lowered (e.g. through the MIR const-init body the LLVM backend runs) or refused with self.fail(...) naming the global and the initializer.

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