Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-base

Source of release 0.44.0

0.44.0 / src / back / ir / lower / program.lucb

#==============================================================================================
#
#   lower/program - Program
#
#   DESCRIPTION:
#       The unit: the instance worklist, globals, witness tables, and the entry point or
#       test runner.
#
#==============================================================================================
extend Lowerer:
    # mark: Program ============================================================================

    ## Lower the program: every function of every module registered, the globals'
    ## initialiser, then the functions the program reaches, its tests, the entry, and the
    ## tables.
    pub func program(mode: u32) -> !:
        self.mode = mode
        self.program_unit.trap_function = "lb_core_trap"
        self.program_unit.trap_at_function = "lb_core_7trap_at"
        self.program_unit.trap_two_at_function = "lb_core_11trap_two_at"
        var i: usize = 0
        while i < self.c.modules.count:
            try self.modules.push(self.c.modules.get(i).tree)
            i += 1
        i = 0
        while i < self.modules.count:
            var cursor = self.modules.get(i).body
            while let d = cursor:
                if d.kind == ast.Kind.func_ and check.generic_params_of(d) == none:
                    _ = try self.add_func(d, try types.no_args(), none, try types.no_args())
                elif d.kind == ast.Kind.asm_ and d.text == self.arch_name():
                    try self.module_asm(d)
                elif (d.kind == ast.Kind.struct_ or d.kind == ast.Kind.enum_ or d.kind == ast.Kind.union_) and check.generic_params_of(d) == none:
                    var member = d.body
                    while let m = member:
                        if m.kind == ast.Kind.func_ and check.generic_params_of(m) == none:
                            _ = try self.add_func(m, try types.no_args(), d, try types.no_args())
                        member = m.next
                    var listed = d.ty if d.kind != ast.Kind.enum_ else d.right
                    while let l = listed:
                        try self.note_vtable(d.type_id, l.type_id)
                        listed = l.next
                elif d.kind == ast.Kind.test_ and mode == 1 and self.c.modules.get(i).tested:
                    # the tests of the package under test, never a dependency's (§16.5)
                    try self.tests.push(d)
                elif d.kind == ast.Kind.global or d.kind == ast.Kind.constant:
                    try self.declare_global(d)
                cursor = d.next
            i += 1
        try self.globals_initialiser()
        try self.note_initialisers()
        for text in self.program_unit.module_asm.span():
            try self.reach_asm.push(text.bytes)
        # only what the program reaches is lowered (`lower_reached`)
        try self.lower_reached()
        for t in 0..<self.tests.count:
            try self.test_body(self.tests.get(t), u32(t))
            try self.lower_reached()
        if mode == 3:
            try self.library_init_function()
        elif mode != 4:
            try self.entry_function(mode)
        try self.lower_reached()
        try self.witness_tables()

    func declare_global(d: ast.Node*) -> !:
        let name = try self.global_name(d)
        let used = ast.has_attribute(d, "used")
        let standard = check.is_library_module(names.module_of(d))
        var global = ir.Global(name = name, standard = standard, size = self.size(d.type_id), align = self.align(d.type_id), is_thread_local = d.has(ast.flag_thread_local), exported = false, weak = ast.has_attribute(d, "weak"), used = used, section = section_of(d), external = ast.is_linked(d))
        if let data = try self.static_data(d):
            _ = try self.laid_out.add(name, self.program_unit.globals.count)
            # storage that starts zero needs no bytes: it stays zero-filled
            if not all_zero(data):
                global.data = data
                global.read_only = d.kind == ast.Kind.constant
        try self.program_unit.globals.push(global)

    ## Whether `d`'s initialiser runs as code: it has one, and it was not laid out as the
    ## global's bytes (`static_data`).
    func runs_initialiser(d: ast.Node*) -> bool!:
        if not initialised(d):
            return false
        return not self.laid_out.has(try self.global_name(d))

    ## `lb_init_globals`, every top-level initialiser in module order: the standard modules
    ## first, in `ORDER`, then the program's, so a module's globals are set before those of
    ## any module that imports it. A standard global's initialiser is a function of its own
    ## (`<global>_0init`) that `lb_init_globals` calls, so the pruner drops it, its texts
    ## and the global together when nothing reaches the global.
    func globals_initialiser() -> !:
        var i: usize = 0
        while i < self.modules.count:
            var cursor = self.modules.get(i).body
            while let d = cursor:
                if (try self.runs_initialiser(d)) and check.is_library_module(names.module_of(d)):
                    try self.global_initialiser(d)
                cursor = d.next
            i += 1
        let locals = try self.thread_locals_initialiser()
        let inst = instances.Instance(decl = self.entry, args = try types.no_args(), owner = none, owner_args = try types.no_args(), done = true)
        try self.begin_function("lb_init_globals", none, inst)
        self.generic.fn_decl = none
        self.current_fn = none
        # kept whole: the pruner drops the calls to dead initialisers here, not in `main`
        self.f.noinline = true
        try self.push_scope(false, "", 0, 0)
        if locals:
            # the initial thread's `local var`s
            _ = try self.call_named(thread_locals_function, u32(self.f.args.count), 0, ir.Class.w, false, types.unit_id)
        i = 0
        while i < self.modules.count:
            var cursor = self.modules.get(i).body
            while let d = cursor:
                if (try self.runs_initialiser(d)) and not d.has(ast.flag_thread_local):
                    if check.is_library_module(names.module_of(d)):
                        _ = try self.call_named(try self.init_function_name(d), u32(self.f.args.count), 0, ir.Class.w, false, types.unit_id)
                    else:
                        try self.store_initialiser(d)
                cursor = d.next
            i += 1
        if locals:
            # and every thread `thread.spawn` starts; last, so no initialiser overwrites it
            if let hook = self.thread_start_hook():
                try self.f.store(ir.Op.storel, try self.f.address_of(ir.function_ref(thread_locals_function)), try self.global_address(hook))
        self.pop_scope()
        try self.f.emit(ir.Op.ret, ir.Class.l, 0, ir.none_ref(), ir.none_ref(), 0)
        try self.end_function()

    ## `lb_init_thread_locals`, the initialisers of every `local var` (§6.3). Thread-local
    ## storage starts zeroed here, so a thread runs these before anything else: the
    ## initial thread from `lb_init_globals`, a spawned one through `thread.locals_start`.
    ## Answers whether there is any; none, no function.
    func thread_locals_initialiser() -> bool!:
        var any = false
        var i: usize = 0
        while i < self.modules.count:
            var cursor = self.modules.get(i).body
            while let d = cursor:
                if initialised(d) and d.has(ast.flag_thread_local):
                    any = true
                cursor = d.next
            i += 1
        if not any:
            return false
        let inst = instances.Instance(decl = self.entry, args = try types.no_args(), owner = none, owner_args = try types.no_args(), done = true)
        try self.begin_function(thread_locals_function, none, inst)
        self.generic.fn_decl = none
        self.current_fn = none
        # kept whole, as `lb_init_globals` is: the pruner drops its calls to dead initialisers
        self.f.noinline = true
        try self.push_scope(false, "", 0, 0)
        i = 0
        while i < self.modules.count:
            var cursor = self.modules.get(i).body
            while let d = cursor:
                if initialised(d) and d.has(ast.flag_thread_local):
                    if check.is_library_module(names.module_of(d)):
                        _ = try self.call_named(try self.init_function_name(d), u32(self.f.args.count), 0, ir.Class.w, false, types.unit_id)
                    else:
                        try self.store_initialiser(d)
                cursor = d.next
            i += 1
        self.pop_scope()
        try self.f.emit(ir.Op.ret, ir.Class.l, 0, ir.none_ref(), ir.none_ref(), 0)
        try self.end_function()
        return true

    ## `thread.locals_start`, which `thread.spawn`'s new thread calls first, when the program
    ## has the `thread` module.
    func thread_start_hook() -> ast.Node*?:
        var i: usize = 0
        while i < self.modules.count:
            var cursor = self.modules.get(i).body
            while let d = cursor:
                if d.kind == ast.Kind.global and d.text == "locals_start" and names.module_of(d) == "thread":
                    return d
                cursor = d.next
            i += 1
        return none

    ## `<global>_0init`: the initialiser function of one standard global.
    func init_function_name(d: ast.Node*) -> str!:
        let name = try self.global_name(d)
        let room = try new u8[name.length + 8] ---
        return try strings.format(room, f"{name}_0init")

    ## One standard global's initialiser as its own function, named on the global.
    func global_initialiser(d: ast.Node*) -> !:
        let inst = instances.Instance(decl = self.entry, args = try types.no_args(), owner = none, owner_args = try types.no_args(), done = true)
        let name = try self.init_function_name(d)
        let global = try self.global_name(d)
        var g: usize = 0
        while g < self.program_unit.globals.count:
            if self.program_unit.globals.items[g].name == global:
                self.program_unit.globals.items[g].init_function = name
            g += 1
        try self.begin_function(name, none, inst)
        self.generic.fn_decl = none
        self.current_fn = none
        self.f.standard = true
        # never expanded into `lb_init_globals`: the pruner must still see it apart
        self.f.noinline = true
        try self.push_scope(false, "", 0, 0)
        try self.store_initialiser(d)
        self.pop_scope()
        try self.f.emit(ir.Op.ret, ir.Class.l, 0, ir.none_ref(), ir.none_ref(), 0)
        try self.end_function()

    ## Global `d` given its initialiser's value, in the function being built. An array
    ## literal it makes a span of gets storage of its own (`static_literal`), since this
    ## function's frame is gone when the span is read.
    func store_initialiser(d: ast.Node*) -> !:
        let init = d.left else return
        self.literal_owner = d
        self.literal_count = 0
        let v = try self.value(init, d.type_id)
        try self.store_to(try self.global_address(d), v)
        self.literal_owner = none

    func test_body(t: ast.Node*, index: u32) -> !:
        let inst = instances.Instance(decl = t, args = try types.no_args(), owner = none, owner_args = try types.no_args(), done = true)
        try self.begin_function(try self.test_name(index), t, inst)
        # never expanded into the runner's `main`: a module of many small tests would make
        # one huge function, whose passes are then slower than all the tests apart
        self.f.noinline = true
        try self.push_scope(false, "", 0, 0)
        if let body = t.body:
            var cursor = body.body
            while let s = cursor:
                try self.stmt(s)
                cursor = s.next
        try self.unwind(self.scopes.count - 1, false)
        self.pop_scope()
        try self.fall_off_end()
        try self.end_function()

    ## A library has no `main`: `lb_library_init`, run when the library is loaded through the
    ## target's initialiser section, starts the globals and the allocator (§17.6).
    func library_init_function() -> !:
        let inst = instances.Instance(decl = self.entry, args = try types.no_args(), owner = none, owner_args = try types.no_args(), done = true)
        try self.begin_function("lb_library_init", none, inst)
        self.generic.fn_decl = none
        self.current_fn = none
        self.f.used = true
        try self.push_scope(false, "", 0, 0)
        _ = try self.call_named("lb_init_globals", u32(self.f.args.count), 0, ir.Class.w, false, types.unit_id)
        _ = try self.call_named("lb_memory_startup", u32(self.f.args.count), 0, ir.Class.w, false, types.unit_id)
        self.pop_scope()
        try self.f.emit(ir.Op.ret, ir.Class.l, 0, ir.none_ref(), ir.none_ref(), 0)
        try self.end_function()
        self.program_unit.init_function = "lb_library_init"

    ## `main`: startup, the arguments, the program's entry, the exit code; or the test runner.
    func entry_function(mode: u32) -> !:
        let inst = instances.Instance(decl = self.entry, args = try types.no_args(), owner = none, owner_args = try types.no_args(), done = true)
        try self.begin_function("main", none, inst)
        self.generic.fn_decl = none
        self.current_fn = none
        self.f.exported = true
        try self.set_result(types.i32_id)
        # int main(int argc, char** argv)
        let argc_slot = try self.f.slot(4, 4)
        let argv_slot = try self.f.slot(8, 8)
        try self.f.params.push(ir.Param(cls = ir.Class.w, size = 0, align = 4, type_id = types.i32_id, slot = argc_slot, shape = 0))
        try self.f.params.push(ir.Param(cls = ir.Class.l, size = 0, align = 8, type_id = types.usize_id, slot = argv_slot, shape = 0))
        try self.push_scope(false, "", 0, 0)
        _ = try self.call_named("lb_init_globals", u32(self.f.args.count), 0, ir.Class.w, false, types.unit_id)
        if self.diagnostic:
            # the allocator quarantines what is released (§19.4)
            try self.f.store(ir.Op.storeb, ir.const_ref(1), try self.f.address_of(ir.global_ref("lb_memory_diagnostic")))
        _ = try self.call_named("lb_core_13process_start", u32(self.f.args.count), 0, ir.Class.w, false, types.unit_id)
        _ = try self.call_named("lb_memory_startup", u32(self.f.args.count), 0, ir.Class.w, false, types.unit_id)
        let exit_code = try self.f.slot(4, 4)
        try self.f.store(ir.Op.storew, ir.const_ref(0), try self.slot_address(exit_code))
        if mode == 1:
            try self.run_tests(exit_code)
        elif mode == 2:
            let answer = check.find_decl(self.entry, "answer") else return
            try self.answer_call(answer, exit_code)
        else:
            let main_fn = check.find_decl(self.entry, "main") else return
            try self.main_call(main_fn, argc_slot, argv_slot, exit_code)
        self.pop_scope()
        let code = try self.f.load(ir.Op.loadsw, ir.Class.w, try self.slot_address(exit_code))
        try self.f.store(ir.Op.storew, code, try self.slot_address(self.result_slot))
        let out = try self.f.load(ir.Op.loadsw, ir.Class.w, try self.slot_address(self.result_slot))
        try self.f.emit(ir.Op.ret, ir.Class.w, 0, out, ir.none_ref(), 0)
        try self.end_function()

    ## The test runner's body: each test between `testing_begin` and `testing_end`, its
    ## outcome reported, and the summary's code in `exit_code`.
    func run_tests(exit_code: u32) -> !:
        var i: usize = 0
        while i < self.tests.count:
            try self.run_test(i)
            i += 1
        let code = try self.call_named("lb_core_12test_summary", u32(self.f.args.count), 0, ir.Class.w, true, types.i32_id)
        try self.f.store(ir.Op.storew, code, try self.slot_address(exit_code))

    ## Test `i`: started by its title, run, and reported (`core.test_report` keeps the tally).
    func run_test(i: usize) -> !:
        let t = self.tests.get(i)
        let title = literals.decode_text(t.text)
        let index = try self.program_unit.text(title)
        let name = try self.span_of(try self.f.address_of(ir.text_ref(index)), ir.const_ref((i64)title.length), types.str_id)
        let s0 = u32(self.f.args.count)
        try self.f.args.push(try self.arg_of(name))
        _ = try self.call_named("lb_core_10test_start", s0, 1, ir.Class.w, false, types.unit_id)
        let s1 = u32(self.f.args.count)
        try self.f.args.push(ir.Arg(value = ir.const_ref((i64)i), cls = ir.Class.l, size = 0, align = 8, type_id = types.u64_id, shape = 0))
        _ = try self.call_named("lb_testing_begin", s1, 1, ir.Class.w, false, types.unit_id)
        let r = try self.call_aggregate(try self.test_name(u32(i)), u32(self.f.args.count), 0, try self.c.table.fallible(types.unit_id))
        _ = try self.call_named("lb_testing_end", u32(self.f.args.count), 0, ir.Class.w, false, types.unit_id)
        let failed = try self.f.load(ir.Op.loadub, ir.Class.w, try self.offset_address(r.ref, self.failed_offset(r.type_id)))
        let message = try self.message_of(try self.failure_address())
        let place = try self.test_place(t)
        let s2 = u32(self.f.args.count)
        try self.f.args.push(ir.Arg(value = failed, cls = ir.Class.w, size = 0, align = 4, type_id = types.bool_id, shape = 0))
        try self.f.args.push(ir.Arg(value = try self.f.address_of(place), cls = ir.Class.l, size = 0, align = 8, type_id = types.cstr_id, shape = 0))
        try self.f.args.push(try self.arg_of(message))
        _ = try self.call_named("lb_core_11test_report", s2, 3, ir.Class.w, false, types.unit_id)
        # the runner handled the test's failure: its message is given back (§11.3)
        try self.message_handled(try self.failure_message())

    ## `file:line:column` of test `t`, where it is reported when it fails by an error (§16.5).
    func test_place(t: ast.Node*) -> ir.Ref!:
        let (saved_fn, saved_file, saved_line, saved_column, saved_text) = (self.current_fn, self.at_file, self.at_line, self.at_column, self.at_text)
        self.current_fn = t
        self.set_position(t)
        let place = try self.position_ref()
        self.current_fn = saved_fn
        self.at_file = saved_file
        self.at_line = saved_line
        self.at_column = saved_column
        self.at_text = saved_text
        return place

    ## `answer()` of a program run for its answer: the value printed, or a failure's report
    ## and code in `exit_code`.
    func answer_call(answer: ast.Node*, exit_code: u32) -> !:
        let name = try self.function_name(answer, try types.no_args(), none, try types.no_args())
        if not answer.has(ast.flag_fallible):
            let value = try self.call_named(name, u32(self.f.args.count), 0, ir.Class.l, true, types.i64_id)
            try self.print_answer(value)
            return
        let r = try self.call_aggregate(name, u32(self.f.args.count), 0, try self.c.table.fallible(types.i64_id))
        let failed = try self.f.load(ir.Op.loadub, ir.Class.w, try self.offset_address(r.ref, self.failed_offset(r.type_id)))
        let ok = self.f.label()
        let bad = self.f.label()
        try self.f.branch(failed, bad, ok)
        try self.f.place_label(bad)
        let s4 = u32(self.f.args.count)
        try self.push_error_pieces(try self.failure_address())
        let code = try self.call_named("lb_core_11main_failed", s4, 4, ir.Class.w, true, types.i32_id)
        try self.f.store(ir.Op.storew, code, try self.slot_address(exit_code))
        # the label after the answer is printed, the next one made
        try self.f.jump(self.f.labels + 1)
        try self.f.place_label(ok)
        let value = try self.f.load(ir.Op.loadl, ir.Class.l, r.ref)
        try self.print_answer(value)
        try self.f.place_label(self.f.label())

    ## The program's `main`, given its arguments as text or as C strings from `argc` and
    ## `argv`; its code, or a failure's, in `exit_code`.
    func main_call(main_fn: ast.Node*, argc_slot: u32, argv_slot: u32, exit_code: u32) -> !:
        let ft = self.c.table.get(main_fn.type_id)
        var as_text = true
        if ft.args.length > 0:
            as_text = self.elem(ft.args[0]) != types.cstr_id
        let argc = try self.f.load(ir.Op.loadsw, ir.Class.w, try self.slot_address(argc_slot))
        let argv = try self.f.load(ir.Op.loadl, ir.Class.l, try self.slot_address(argv_slot))
        let s5 = u32(self.f.args.count)
        try self.f.args.push(ir.Arg(value = argc, cls = ir.Class.w, size = 0, align = 4, type_id = types.i32_id, shape = 0))
        try self.f.args.push(ir.Arg(value = argv, cls = ir.Class.l, size = 0, align = 8, type_id = types.usize_id, shape = 0))
        let span_type = try self.c.table.span(types.str_id if as_text else types.cstr_id, false)
        let args = try self.call_aggregate("lb_core_arguments" if as_text else "lb_core_13raw_arguments", s5, 2, span_type)
        let s6 = u32(self.f.args.count)
        var main_args: u32 = 0
        if ft.args.length > 0:
            try self.f.args.push(try self.arg_of(args))
            main_args = 1
        if main_fn.has(ast.flag_fallible):
            let r = try self.call_aggregate("lb_main", s6, main_args, try self.c.table.fallible(types.i32_id))
            let failed = try self.f.load(ir.Op.loadub, ir.Class.w, try self.offset_address(r.ref, self.failed_offset(r.type_id)))
            let ok = self.f.label()
            let bad = self.f.label()
            let done = self.f.label()
            try self.f.branch(failed, bad, ok)
            try self.f.place_label(bad)
            let s7 = u32(self.f.args.count)
            try self.push_error_pieces(try self.failure_address())
            let code = try self.call_named("lb_core_11main_failed", s7, 4, ir.Class.w, true, types.i32_id)
            try self.f.store(ir.Op.storew, code, try self.slot_address(exit_code))
            try self.f.jump(done)
            try self.f.place_label(ok)
            let value = try self.f.load(ir.Op.loadsw, ir.Class.w, r.ref)
            try self.f.store(ir.Op.storew, value, try self.slot_address(exit_code))
            try self.f.jump(done)
            try self.f.place_label(done)
        else:
            let code = try self.call_named("lb_main", s6, main_args, ir.Class.w, true, types.i32_id)
            try self.f.store(ir.Op.storew, code, try self.slot_address(exit_code))
        if as_text:
            # Text argument descriptors are owned by this shim. Release
            # them after reporting errors, which can borrow argument text.
            let data = try self.f.load(ir.Op.loadl, ir.Class.l, args.ref)
            let release_start = u32(self.f.args.count)
            try self.f.args.push(ir.Arg(value = data, cls = ir.Class.l, size = 0, align = 8, type_id = types.usize_id, shape = 0))
            _ = try self.call_named("free", release_start, 1, ir.Class.w, false, types.unit_id)

    ## An error value's code, message, `at` and `called_at` as four arguments.
    func push_error_pieces(err: ir.Ref) -> !:
        let code = try self.f.load(ir.Op.loadsw, ir.Class.w, err)
        let message = try self.message_of(err)
        let at = try self.f.load(ir.Op.loadsw, ir.Class.w, try self.offset_address(err, 4))
        let called = try self.f.load(ir.Op.loadsw, ir.Class.w, try self.offset_address(err, 20))
        try self.f.args.push(ir.Arg(value = code, cls = ir.Class.w, size = 0, align = 4, type_id = types.i32_id, shape = 0))
        try self.f.args.push(try self.arg_of(message))
        try self.f.args.push(ir.Arg(value = at, cls = ir.Class.w, size = 0, align = 4, type_id = types.i32_id, shape = 0))
        try self.f.args.push(ir.Arg(value = called, cls = ir.Class.w, size = 0, align = 4, type_id = types.i32_id, shape = 0))

    ## `answer()` programs print their result as the seed's `start.c` did.
    func print_answer(value: ir.Ref) -> !:
        let s = u32(self.f.args.count)
        try self.f.args.push(ir.Arg(value = value, cls = ir.Class.l, size = 0, align = 8, type_id = types.i64_id, shape = 0))
        _ = try self.call_named("lb_core_9print_i64", s, 1, ir.Class.w, false, types.unit_id)

    ## Every witness table as data: one pointer per interface requirement.
    func witness_tables() -> !:
        var i: usize = 0
        while i < self.vtables.count:
            let w = self.vtables.get(i)
            let d = self.decl_of(w.record) else return
            let iface = self.decl_of(w.iface) else return
            let t = self.c.table.get(w.record)
            let name = try self.vtable_name(w.record, iface)
            var table = ir.WitnessTable(name = name, entries = try list.List[str].create(8))
            var req = iface.body
            while let r = req:
                if r.kind == ast.Kind.func_:
                    if let m = check.witness_member(d, r.text):
                        try table.entries.push(try self.function_name(m, try types.no_args(), d, t.args))
                    else:
                        try table.entries.push("")
                req = r.next
            try self.program_unit.tables.push(table)
            i += 1

    # mark: Static data =======================================================================

    ## A global's starting bytes, when its initialiser is literals the object file can hold
    ## as they are: an array, of arrays, of integers, `bool`s and floats, each a constant the
    ## checker folds exactly (§6.4). Embedded SPIR-V words, glyphs or tables then cost their
    ## size in data, not a store instruction per element run before `main`. None for
    ## anything else, a thread-local, a weak global or one in a named section, which keep
    ## their initialiser.
    func static_data(d: ast.Node*) -> u8[]?!:
        let init = d.left else return none
        if not initialised(d) or d.has(ast.flag_thread_local) or ast.has_attribute(d, "weak") or section_of(d).length > 0:
            return none
        if not self.is_array(d.type_id):
            return none
        return try self.literal_bytes(init, d.type_id)

    ## The bytes of array `e` of type `t` laid out (`lay_out`), or none when they are not
    ## all constants it lays out.
    func literal_bytes(e: ast.Node*, t: u32) -> u8[]?!:
        if self.size(t) == 0:
            return none
        let data = try new u8[(usize)self.size(t)]
        var laid = false
        defer:
            if not laid:
                free(data)
        if not self.lay_out(e, t, data, 0):
            return none
        laid = true
        return data

    ## Write constant `e` of type `t` into `data` at `offset`, as the target holds it in
    ## memory (little-endian on every native target); false when `e` is not one this lays out.
    func lay_out(e: ast.Node*, t: u32, data: u8[], offset: u64) -> bool:
        if self.is_array(t):
            if e.kind != ast.Kind.array_lit:
                return false
            let et = self.elem(t)
            let stride = self.c.table.size_of(et)
            var at = offset
            var cursor = e.body
            while let m = cursor:
                if not self.lay_out(m, et, data, at):
                    return false
                at += stride
                cursor = m.next
            return true
        let size = self.c.table.size_of(t)
        var bits: u64 = 0
        if t == types.bool_id:
            let truth = self.c.constant_bool(e) else return false
            bits = 1 if truth else 0
        elif self.is_int(t):
            let v = self.c.exact_integer(e, size * 8, self.is_signed(t)) else return false
            bits = (u64)v
        elif t == types.f16_id or t == types.f32_id or t == types.f64_id:
            bits = float_constant(e, u32(size * 8)) else return false
        else:
            return false
        for k in 0..<size:
            data[offset + k] = (u8)((bits >> (8 * k)) & 255)
        return true

## The IEEE bits at `width` of a float literal, negated or in parentheses; none for any
## other expression, which its initialiser computes.
func float_constant(e: ast.Node*, width: u32) -> u64?:
    match e.kind:
        .literal:
            if not literals.is_float_literal(e.text):
                return none
            return decimal.bits(literals.literal_body(e.text), width)
        .group:
            let inner = e.left else return none
            return float_constant(inner, width)
        .unary:
            let inner = e.left else return none
            if e.text != "-":
                return none
            let v = float_constant(inner, width) else return none
            return v ^ ((u64)1 << (u64)(width - 1))
        _:
            return none

## Whether every byte of `data` is zero.
func all_zero(data: const u8[]) -> bool:
    for b in data:
        if b != 0:
            return false
    return true

## Whether a top-level declaration has an initialiser this unit runs.
func initialised(d: ast.Node*) -> bool:
    return (d.kind == ast.Kind.global or d.kind == ast.Kind.constant) and not d.has(ast.flag_uninit) and not ast.is_linked(d) and d.left != none