Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-base

Source of release 0.46.0

0.46.0 / src / back / c / emit / standard.lucb

#==============================================================================================
#
#   emit/standard - Standard modules and memory
#
#   DESCRIPTION:
#       Standard module calls mapped onto the runtime (§16.6), and allocation, `free`, and
#       the `memory` module (§12).
#
#==============================================================================================
extend Emitter:
    # mark: Standard modules ===================================================================

    ## The standard calls no Base body can express: `atomic.fence` and the C streams.
    func std_call(e: ast.Node*, module: str, name: str, d: ast.Node*) -> !:
        if module == "atomic" and name == "fence":
            let first = e.body else return try self.put("((void)0)")
            let order = first.left else return try self.put("((void)0)")
            if order.text == "signal":
                try self.put("({ __asm__ volatile(\"\" ::: \"memory\"); (void)0; })")
                return
            try self.put("(atomic_thread_fence(")
            try self.memory_order(order)
            try self.put("))")
            return
        if module == "c" and (name == "stdin" or name == "stdout" or name == "stderr"):
            try self.put("((void*)")
            try self.put(name)
            try self.put(")")
            return
        try self.direct_call(e, d, none, try types.no_args())

    func receiver_address(receiver: ast.Node*, through_ptr: bool) -> !:
        if through_ptr:
            try self.expr(receiver)
        else:
            try self.address(receiver)

    ## An `atomic.Ordering` argument as a C memory order; an ordering not given is `seq_cst`.
    func memory_order(given: ast.Node*?) -> !:
        let spelled = ["memory_order_relaxed", "memory_order_consume", "memory_order_acquire", "memory_order_release", "memory_order_acq_rel", "memory_order_seq_cst"]
        try self.put(spelled[calls.ordering(given)])

    ## `co<n> = atomic_compare_exchange_<strength>_explicit(&x, &ce<n>, desired, orders)`, the
    ## exchange `cas` writes, weak or strong as its argument chooses.
    func compare_exchange(strength: str, receiver: ast.Node*, through_ptr: bool, n: u32, et: u32, desired: ast.Node*, success: ast.Node*?, failure: ast.Node*?) -> !:
        try self.put_tmp("co", n)
        try self.put(" = atomic_compare_exchange_")
        try self.put(strength)
        try self.put("_explicit(")
        try self.receiver_address(receiver, through_ptr)
        try self.put(", &")
        try self.put_tmp("ce", n)
        try self.put(", (")
        try self.put_type(et)
        try self.put(")(")
        try self.value(desired, et)
        try self.put("), ")
        try self.memory_order(success)
        try self.put(", ")
        try self.memory_order(failure)

    ## The operations of `@T` (§15.1).
    func atomic_call(e: ast.Node*, callee: ast.Node*, receiver: ast.Node*, rt: u32, through_ptr: bool) -> !:
        let name = callee.text
        let et = self.elem(rt)
        var args: MaybeNode[5]
        _ = calls.argument_values(e, args[0..])
        let n = self.tmp()
        if name == "load":
            try self.put("((")
            try self.put_type(et)
            try self.put(")atomic_load_explicit(")
            try self.receiver_address(receiver, through_ptr)
            try self.put(", ")
            try self.memory_order(args[0])
            try self.put("))")
            return
        if name == "store":
            let v = args[0] else return
            try self.put("(atomic_store_explicit(")
            try self.receiver_address(receiver, through_ptr)
            try self.put(", (")
            try self.put_type(et)
            try self.put(")(")
            try self.value(v, et)
            try self.put("), ")
            try self.memory_order(args[1])
            try self.put("), (void)0)")
            return
        if name == "wait":
            let v = args[0] else return
            try self.put("({ while (atomic_load_explicit(")
            try self.receiver_address(receiver, through_ptr)
            try self.put(", memory_order_seq_cst) == (")
            try self.put_type(et)
            try self.put(")(")
            try self.value(v, et)
            try self.put(")) { lb_pause(); } (void)0; })")
            return
        if name == "wake":
            let v = args[0] else return
            try self.put("((void)(")
            try self.expr(v)
            try self.put("))")
            return
        if name == "cas":
            let expected = args[0] else return
            let desired = args[1] else return
            try self.atomic_cas(e, receiver, through_ptr, et, n, expected, desired, args[2], args[3], args[4])
            return
        let v = args[0] else return
        if name == "max" or name == "min":
            try self.atomic_extreme(name == "max", receiver, through_ptr, et, n, v)
            return
        try self.atomic_update(name, receiver, through_ptr, et, v, args[1])

    ## `x.cas(expected, desired, success, failure, weak)`: a weak or a strong compare and
    ## exchange, by the flag at run time, into the result's pair of success and the value
    ## found.
    func atomic_cas(e: ast.Node*, receiver: ast.Node*, through_ptr: bool, et: u32, n: u32, expected: ast.Node*, desired: ast.Node*, success: ast.Node*?, failure: ast.Node*?, weak: ast.Node*?) -> !:
        let result = try self.ty(e)
        try self.put("({ ")
        try self.put_type(et)
        try self.put(" ")
        try self.put_tmp("ce", n)
        try self.put(" = (")
        try self.put_type(et)
        try self.put(")(")
        try self.value(expected, et)
        try self.put("); bool ")
        try self.put_tmp("co", n)
        try self.put("; if (")
        if let weak_flag = weak:
            try self.value(weak_flag, types.bool_id)
        else:
            try self.put("0")
        try self.put(") { ")
        try self.compare_exchange("weak", receiver, through_ptr, n, et, desired, success, failure)
        try self.put("); } else { ")
        try self.compare_exchange("strong", receiver, through_ptr, n, et, desired, success, failure)
        try self.put("); } (")
        try self.put_type(result)
        try self.put("){ ")
        try self.put_tmp("co", n)
        try self.put(", ")
        try self.put_tmp("ce", n)
        try self.put(" }; })")

    ## `x.max(v)` (`is_max`) or `x.min(v)`: a compare-exchange loop that keeps the larger
    ## or the smaller, giving the value it found.
    func atomic_extreme(is_max: bool, receiver: ast.Node*, through_ptr: bool, et: u32, n: u32, v: ast.Node*) -> !:
        try self.put("({ ")
        try self.put_type(et)
        try self.put(" ")
        try self.put_tmp("mo", n)
        try self.put(" = atomic_load_explicit(")
        try self.receiver_address(receiver, through_ptr)
        try self.put(", memory_order_seq_cst); ")
        try self.put_type(et)
        try self.put(" ")
        try self.put_tmp("mn", n)
        try self.put(" = (")
        try self.put_type(et)
        try self.put(")(")
        try self.value(v, et)
        try self.put("); for (;;) { ")
        try self.put_type(et)
        try self.put(" _w = (")
        try self.put_tmp("mo", n)
        try self.put(" >= " if is_max else " <= ")
        try self.put_tmp("mn", n)
        try self.put(") ? ")
        try self.put_tmp("mo", n)
        try self.put(" : ")
        try self.put_tmp("mn", n)
        try self.put("; if (atomic_compare_exchange_weak_explicit(")
        try self.receiver_address(receiver, through_ptr)
        try self.put(", &")
        try self.put_tmp("mo", n)
        try self.put(", _w, memory_order_seq_cst, memory_order_seq_cst)) break; } ")
        try self.put_tmp("mo", n)
        try self.put("; })")

    ## `x.add(v)`, `sub`, `set`, `clear`, `flip`, and `swap`: one C11 read-modify-write
    ## at the given order, giving the value before it.
    func atomic_update(name: str, receiver: ast.Node*, through_ptr: bool, et: u32, v: ast.Node*, order: ast.Node*?) -> !:
        try self.put("((")
        try self.put_type(et)
        try self.put(")")
        if name == "sub":
            try self.put("atomic_fetch_sub_explicit(")
        elif name == "set":
            try self.put("atomic_fetch_or_explicit(")
        elif name == "clear":
            try self.put("atomic_fetch_and_explicit(")
        elif name == "flip":
            try self.put("atomic_fetch_xor_explicit(")
        elif name == "swap":
            try self.put("atomic_exchange_explicit(")
        else:
            try self.put("atomic_fetch_add_explicit(")
        try self.receiver_address(receiver, through_ptr)
        try self.put(", (")
        try self.put_type(et)
        try self.put(")(")
        if name == "clear":
            try self.put("~(")
            try self.value(v, et)
            try self.put(")")
        else:
            try self.value(v, et)
        try self.put("), ")
        try self.memory_order(order)
        try self.put("))")

    # mark: Memory =============================================================================

    ## The allocator view for `in x` and `with x`, or the current allocator.
    func allocator_of(e: ast.Node*?) -> !:
        let a = e else return try self.put("lb_memory_allocator")
        try self.allocator_view(a)

    func allocator_view(e: ast.Node*) -> !:
        let t = try self.ty(e)
        if self.is_iface(t):
            try self.expr(e)
            return
        let target = self.elem(t) if self.is_ptr(t) else t
        if self.is_ptr(t):
            try self.iface_view(e, target, self.c.allocator_type())
            return
        # a `var` record: take its address
        let i = self.decl_of(self.c.allocator_type()) else return try self.expr(e)
        try self.put("((lb_iface){ (void*)(&(")
        try self.place(e)
        try self.put(")), &lb_vt_")
        try self.put_mangled(target)
        try self.put("_")
        try self.put(i.text)
        try self.put(" })")
        try self.note_vtable(target, self.c.allocator_type())

    ## The failing result for exhaustion.
    func exhausted(result: u32) -> !:
        try self.put("((")
        try self.put_type(result)
        try self.put("){ .error = { .code = ")
        try self.put_u64(check.exhausted_code())
        try self.put(", .message = (lb_str){\"memory.exhausted\", 16}, .at = lb_here() }, .failed = true })")

    ## `new T`, `new T(args)`, `new T.case(...)`, and `new T[count]`: an allocation through
    ## the allocator in effect, initialised in place, as a statement expression giving the
    ## fallible pointer.
    func new_expr(e: ast.Node*) -> !:
        let t = e.ty else return
        let (n, result, payload) = try self.open_allocation(e)
        if self.is_span(payload):
            let count = t.right else return
            try self.counted_allocation(n, payload, count, result, true)
            return
        let et = self.elem(payload)
        try self.put_block_type()
        try self.put(" ")
        try self.put_tmp("ao", n)
        try self.put(" = lb_alloc_call(")
        try self.put_tmp("a", n)
        try self.put(", sizeof(")
        try self.put_type(et)
        try self.put("), _Alignof(")
        try self.put_type(et)
        try self.put(")); ")
        try self.put_type(result)
        try self.put(" ")
        try self.put_tmp("r", n)
        try self.put("; if (!")
        try self.put_tmp("ao", n)
        try self.put(".present) { ")
        try self.put_tmp("r", n)
        try self.put(" = ")
        try self.exhausted(result)
        try self.put("; } else { ")
        try self.put_type(et)
        try self.put("* ")
        try self.put_tmp("p", n)
        try self.put(" = (")
        try self.put_type(et)
        try self.put("*)")
        try self.put_tmp("ao", n)
        try self.put(".value.data; ")
        var failed_init = false
        if let init = e.initializer():
            failed_init = try self.new_init(e, init, et, n)
        elif let body = e.body:
            try self.put("*")
            try self.put_tmp("p", n)
            try self.put(" = ")
            if body.kind == ast.Kind.case_value:
                try self.enum_value(body)
            else:
                try self.constructor(e, et)
            try self.put("; ")
        elif e.text == "()":
            try self.put("*")
            try self.put_tmp("p", n)
            try self.put(" = ")
            try self.constructor(e, et)
            try self.put("; ")
        else:
            try self.put("memset(")
            try self.put_tmp("p", n)
            try self.put(", 0, sizeof(")
            try self.put_type(et)
            try self.put(")); ")
        try self.put_tmp("r", n)
        try self.put(".value = ")
        try self.put_tmp("p", n)
        try self.put("; ")
        try self.put_tmp("r", n)
        try self.put(".failed = false; ")
        if failed_init:
            try self.put("} ")
        try self.put("} ")
        try self.put_tmp("r", n)
        try self.put("; })")

    ## The zeroed allocation `p<n>` of a `new T(args)` given to `T`'s `init`; true when the
    ## init can fail, when what follows runs in the `else` of its success and a failure
    ## releases the allocation into the result `r<n>`.
    func new_init(e: ast.Node*, init: ast.Node*, et: u32, n: u32) -> bool!:
        let native_type = self.c.table.get(et)
        var fn = try self.map(init.type_id)
        if let declaration = native_type.decl:
            fn = try self.c.substitute(fn, declaration, native_type.args)
        _ = try self.add_func(init, try types.no_args(), native_type.decl, native_type.args)
        try self.put("memset(")
        try self.put_tmp("p", n)
        try self.put(", 0, sizeof(")
        try self.put_type(et)
        try self.put(")); ")
        let failed_init = init.has(ast.flag_fallible)
        if failed_init:
            try self.put("lb_r_unit ")
            try self.put_tmp("init", n)
            try self.put(" = ")
        let hoisted = try self.begin_sequence(e.body, fn, init)
        try self.put_func_name(init, try types.no_args(), native_type.decl, native_type.args)
        try self.put("(")
        try self.put_tmp("p", n)
        if init.right != none:
            try self.put(", ")
            try self.arguments(e.body, fn, init, try types.no_args())
        try self.put(")")
        try self.end_sequence(hoisted)
        try self.put("; ")
        if failed_init:
            try self.put("if (")
            try self.put_tmp("init", n)
            try self.put(".failed) { ")
            try self.put_tmp("r", n)
            try self.put(".failed = true; ")
            try self.put_tmp("r", n)
            try self.put(".error = ")
            try self.put_tmp("init", n)
            try self.put(".error; lb_release_call(")
            try self.put_tmp("a", n)
            try self.put(", ")
            try self.put_tmp("ao", n)
            try self.put(".value); } else { ")
        return failed_init

    ## `count` elements of a span payload, zeroed when `zero`, else left unwritten, which the
    ## diagnostic profile fills with its pattern (§19.4); closes the statement expression.
    func counted_allocation(n: u32, payload: u32, count: ast.Node*, result: u32, zero: bool) -> !:
        let et = self.elem(payload)
        try self.put("size_t ")
        try self.put_tmp("n", n)
        try self.put(" = (size_t)(")
        try self.value(count, types.usize_id)
        try self.put("); ")
        try self.put_type(result)
        try self.put(" ")
        try self.put_tmp("r", n)
        try self.put("; if (")
        try self.put_tmp("n", n)
        try self.put(" > UINT64_C(")
        let stride = self.c.table.size_of(et)
        try self.put_u64(18446744073709551615 if stride == 0 else 4611686018427387904 // stride)
        try self.put(")")
        try self.put(") { ")
        try self.put_tmp("r", n)
        try self.put(" = ")
        try self.exhausted(result)
        try self.put("; } else { size_t ")
        try self.put_tmp("bytes", n)
        try self.put(" = sizeof(")
        try self.put_type(et)
        try self.put(") * ")
        try self.put_tmp("n", n)
        try self.put("; ")
        try self.put_block_type()
        try self.put(" ")
        try self.put_tmp("ao", n)
        try self.put(" = lb_alloc_call(")
        try self.put_tmp("a", n)
        try self.put(", ")
        try self.put_tmp("bytes", n)
        try self.put(", _Alignof(")
        try self.put_type(et)
        try self.put(")); if (")
        try self.put_tmp("bytes", n)
        try self.put(" != 0 && !")
        try self.put_tmp("ao", n)
        try self.put(".present) { ")
        try self.put_tmp("r", n)
        try self.put(" = ")
        try self.exhausted(result)
        try self.put("; } else { ")
        if zero or self.diagnostic:
            try self.put("if (")
            try self.put_tmp("ao", n)
            try self.put(".value.data != NULL) memset(")
            try self.put_tmp("ao", n)
            try self.put(".value.data, 0, " if zero else ".value.data, 0xAA, ")
            try self.put_tmp("bytes", n)
            try self.put("); ")
        try self.note_allocation(n, "bytes")
        try self.put_tmp("r", n)
        try self.put(".value.data = ")
        try self.put_tmp("ao", n)
        try self.put(".value.data; ")
        try self.put_tmp("r", n)
        try self.put(".value.length = ")
        try self.put_tmp("n", n)
        try self.put("; ")
        try self.put_tmp("r", n)
        try self.put(".failed = false; } } ")
        try self.put_tmp("r", n)
        try self.put("; })")

    ## The start of an allocation's statement expression, `({ lb_iface a<n> = allocator; `:
    ## its temporary's number, the result type and the type it points at.
    func open_allocation(e: ast.Node*) -> (u32, u32, u32)!:
        self.site_line = e.line
        let result = try self.ty(e)
        let payload = self.elem(result)
        try self.note(result)
        let n = self.tmp()
        try self.put("({ lb_iface ")
        try self.put_tmp("a", n)
        try self.put(" = ")
        try self.allocator_of(e.right)
        try self.put("; ")
        return (n, result, payload)

    ## `new T[count] ---`: `count` elements through the allocator, left unwritten (§12.2).
    func unwritten_expr(e: ast.Node*) -> !:
        let (n, result, payload) = try self.open_allocation(e)
        let t = e.ty else return
        let count = t.right else return
        try self.counted_allocation(n, payload, count, result, false)