Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-base

Source of release 0.43.0

0.43.0 / src / back / ir / lower / function.lucb

#==============================================================================================
#
#   lower/function - The current function
#
#   DESCRIPTION:
#       The function being lowered: its temporaries, slots, labels, and debug
#       scopes, and the deferred blocks each scope's exits run.
#
#==============================================================================================
import strings

extend Lowerer:
    # mark: The current function ===============================================================

    func temp(cls: ir.Class) -> ir.Ref!:
        return ir.temp_ref(try self.f.temp(cls))

    func new_slot(id: u32) -> u32!:
        return try self.f.slot(self.size(id), self.align(id))

    ## Open a loop `for i in 0..<count` in the function being built: the index is in a slot
    ## of its own, and the body follows this; `count_on` closes it.
    func count_up(count: i64) -> Counting!:
        return try self.count_up_to(ir.const_ref(count))

    ## `count_up` to a bound computed at run time, `bound` a `usize` value.
    func count_up_to(bound: ir.Ref) -> Counting!:
        let counter = try self.f.slot(8, 8)
        try self.f.store(ir.Op.storel, ir.const_ref(0), try self.slot_address(counter))
        let head = self.f.label()
        let body = self.f.label()
        let done = self.f.label()
        try self.f.jump(head)
        try self.f.place_label(head)
        let i = try self.f.load(ir.Op.loadl, ir.Class.l, try self.slot_address(counter))
        let more = try self.f.binary(ir.Op.cult, ir.Class.l, i, bound)
        try self.f.branch(more, body, done)
        try self.f.place_label(body)
        return Counting(counter = counter, head = head, done = done, index = i)

    ## Close a loop `count_up` opened: the next index, back to the test, and out after it.
    func count_on(counting: Counting) -> !:
        let next = try self.f.binary(ir.Op.add, ir.Class.l, try self.f.load(ir.Op.loadl, ir.Class.l, try self.slot_address(counting.counter)), ir.const_ref(1))
        try self.f.store(ir.Op.storel, next, try self.slot_address(counting.counter))
        try self.f.jump(counting.head)
        try self.f.place_label(counting.done)

    ## The slot of a parameter of type `pt`: at least a register wide and aligned, since it
    ## arrives as one.
    func param_slot(pt: u32) -> u32!:
        let size = self.size(pt)
        let align = self.align(pt)
        return try self.f.slot(size if size >= 16 else 16, align if align >= 8 else 8)

    func slot_address(slot: u32) -> ir.Ref!:
        return try self.f.address_of(ir.slot_ref(slot))

    ## The address `base + offset`.
    func offset_address(base: ir.Ref, offset: u64) -> ir.Ref!:
        if offset == 0:
            return base
        return try self.f.binary(ir.Op.add, ir.Class.l, base, ir.const_ref((i64)offset))

    ## Store a value at an address, by class or by blit.
    func store_to(address: ir.Ref, v: LowerValue) -> !:
        if v.in_memory:
            try self.f.copy_bytes(address, v.ref, self.size(v.type_id))
            return
        if v.type_id == types.unit_id or v.type_id == types.never_id:
            return
        try self.f.store(ir.store_op(self.scalar_size(v.type_id), self.is_float(v.type_id)), v.ref, address)

    ## A value read from an address.
    func load_from(address: ir.Ref, id: u32) -> LowerValue!:
        if self.kind(id) == types.Kind.atomic and self.is_scalar(self.elem(id)):
            # a plain read of `@T` is a sequentially consistent load (§15.1)
            let et = self.elem(id)
            let cls = self.class_of(et)
            let t = try self.f.temp(cls)
            try self.f.instrs.push(ir.Instr(op = ir.Op.atomic_load, cls = cls, dst = t, a = address, b = ir.none_ref(), extra = u32(self.scalar_size(et)), extra2 = 5, line = 0, file = 0, scope = 0, site = 0))
            return LowerValue(ref = ir.temp_ref(t), type_id = id, in_memory = false)
        if not self.is_scalar(id):
            return LowerValue(ref = address, type_id = id, in_memory = true)
        if id == types.unit_id or id == types.never_id:
            return LowerValue(ref = ir.const_ref(0), type_id = id, in_memory = false)
        let op = ir.load_op(self.scalar_size(id), self.signed_of(id), self.is_float(id))
        return LowerValue(ref = try self.f.load(op, self.class_of(id), address), type_id = id, in_memory = false)

    ## A value copied into a fresh slot; its address.
    func materialise(v: LowerValue) -> ir.Ref!:
        let s = try self.new_slot(v.type_id)
        let a = try self.slot_address(s)
        try self.store_to(a, v)
        return a

    ## A value as its address, materialising scalars.
    func address_of_value(v: LowerValue) -> ir.Ref!:
        if v.in_memory:
            return v.ref
        return try self.materialise(v)

    func find_local(decl: ast.Node*) -> u32?:
        var i = self.locals.count
        while i > 0:
            i -= 1
            let l = self.locals.get(i)
            if l.decl == decl:
                return l.slot
        return none

    func bind_local(decl: ast.Node*, id: u32) -> u32!:
        let s = try self.new_slot(id)
        try self.locals.push(LowerLocal(decl = decl, slot = s))
        try self.describe_local(decl, s, id)
        return s

    ## The path of the file the function being lowered came from.
    func source_of_current() -> str:
        let f = self.current_fn else return self.src_file
        return self.source_of(f)

    ## The statement being lowered: what a trap in it names (§11.5), through the source's
    ## position directives (§3.3).
    func set_position(n: ast.Node*):
        self.at_text = 0
        self.at_file = self.src_file
        self.at_line = n.line
        self.at_column = 1
        if let f = self.current_fn:
            if self.position_fn != f or self.position_file != self.src_file:
                self.position_fn = f
                self.position_file = self.src_file
                self.position_source = instances.source_unit_of(self.c, f, self.src_file)
            if let s = self.position_source:
                let (file, line, column) = s.mapped(n.line, s.statement_column(n.line))
                # a directive's file is the source's own text, named as it says
                self.at_file = file if s.directed(n.line) else self.under_root(file)
                self.at_line = line
                self.at_column = column

        ## The unit's text of the current statement's position, `file:line:column`.
        # the instructions emitted from here carry the position (`--release --debug`)
        if self.f.symbols:
            self.f.at_line = self.at_line
            self.f.at_file = self.program_unit.file_index(self.at_file) catch failure:
                _ = failure
                recover 0

    ## `path` relative to `position_root` when under it.
    func under_root(path: str) -> str:
        let root = self.position_root
        if root.length > 0 and path.length > root.length and (str)path.bytes[..<root.length] == root:
            return (str)path.bytes[root.length..]
        return path

    func position_ref() -> ir.Ref!:
        if self.at_text == 0:
            let room = try new u8[self.at_file.length + 24] ---
            let text = try strings.format(room, f"{self.at_file}:{self.at_line}:{self.at_column}")
            self.at_text = (try self.program_unit.text(text)) + 1
        return ir.text_ref(self.at_text - 1)

    ## The current statement's position, the text a trap there names, as its distance from
    ## `core.origin_base`: how an error keeps `at` and `called_at` (§11.3).
    func origin_distance() -> ir.Ref!:
        let text = try self.f.address_of(try self.position_ref())
        let base = try self.f.address_of(ir.global_ref("lb_core_11origin_base"))
        return try self.f.binary(ir.Op.sub, ir.Class.l, text, base)

    ## The `at` of the error at `err`, where it was raised (§11.3), in the word after the
    ## code; `core.origin` reads it back.
    func store_origin(err: ir.Ref) -> !:
        try self.f.store(ir.Op.storew, try self.origin_distance(), try self.offset_address(err, 4))

    ## The `called_at` of the error at `err`: the current statement, a call into another
    ## package that the error came out of (§11.3). The outermost such call is kept, so each
    ## one replaces the last. It is the word above the message's 32-bit length, which writing
    ## a new message clears.
    func store_called(err: ir.Ref) -> !:
        try self.f.store(ir.Op.storew, try self.origin_distance(), try self.offset_address(err, 20))

    ## The message of the error at `err` as a `str`, in a slot of its own: the length is the
    ## error's 32 bits, without `called_at` above them (§11.3).
    func message_of(err: ir.Ref) -> LowerValue!:
        let slot = try self.slot_address(try self.new_slot(types.str_id))
        try self.f.copy_bytes(slot, try self.offset_address(err, 8), 16)
        try self.f.store(ir.Op.storew, ir.const_ref(0), try self.offset_address(slot, 12))
        return LowerValue(ref = slot, type_id = types.str_id, in_memory = true)

    ## The last instruction emitted, a `bounds` or a checked operation, names the current
    ## statement's position in `extra2` (index + 1) for the trap it may raise.
    func mark_position() -> !:
        let p = try self.position_ref()
        var last = self.f.instrs.get(self.f.instrs.count - 1)
        last.extra2 = p.index + 1
        self.f.instrs.set(self.f.instrs.count - 1, last)

    ## The path of the file a declaration came from; a standard module's is its name.
    func source_of(decl: ast.Node*) -> str:
        let m = decl.resolved else return self.src_file
        var i: usize = 0
        while i < self.c.modules.count:
            let module = self.c.modules.get(i)
            if module.tree == m:
                return module.src.path
            i += 1
        return self.src_file

    ## `--debug`: a named local joins the frame's descriptor.
    func describe_local(decl: ast.Node*, slot: u32, id: u32) -> !:
        if not (self.f.debug or self.f.symbols) or decl.text.length == 0 or decl.text == "_":
            return
        try self.f.locals.push(ir.LocalInfo(name = decl.text, slot = slot, kind = try self.c.spell(id), size = self.size(id), type_id = id, line = decl.line, parameter = decl.kind == ast.Kind.param, scope = self.scopes.get(self.scopes.count - 1).debug_scope if self.scopes.count > 0 else 0, site = 0))

    ## `--debug`: the address of this function's descriptor, `lbd_<name>`.
    func descriptor_ref() -> ir.Ref!:
        self.scratch.clear()
        try self.scratch.put("lbd_")
        try self.scratch.put(self.f.name)
        let name = try names.keep(&self.scratch)
        return try self.f.address_of(ir.global_ref(name))

    func debug_call(name: str, start: u32, count: u32) -> !:
        _ = try self.call_named(name, start, count, ir.Class.w, false, types.unit_id)

    # mark: Scopes and cleanup =================================================================

    func push_scope(loop: bool, label: str, break_label: u32, continue_label: u32) -> !:
        var scope: usize = 0
        if self.f.debug or self.f.symbols:
            scope = self.f.debug_scopes.count
            let parent = self.scopes.get(self.scopes.count - 1).debug_scope if self.scopes.count > 0 else 0
            try self.f.debug_scopes.push(ir.DebugScope(parent = parent, start = self.f.instrs.count, end = 0, site = 0))
            self.f.at_scope = u32(scope)
        try self.scopes.push(exits.Scope(defer_base = self.defers.count, loop = loop, label = label, restore_alloc = false, alloc_saved = 0, exit = break_label, continue_label = continue_label, debug_scope = scope))

    func pop_scope():
        let sc = self.scopes.get(self.scopes.count - 1)
        if self.f.debug or self.f.symbols:
            self.f.debug_scopes.items[sc.debug_scope].end = self.f.instrs.count
            self.f.at_scope = u32(self.f.debug_scopes.get(sc.debug_scope).parent)
        self.defers.count = sc.defer_base
        self.scopes.count -= 1

    func unwind(index: usize, failing: bool) -> !:
        let sc = self.scopes.get(index)
        var at = exits.deferred_end(&self.scopes, self.defers.count, index)
        while let deferred = exits.next_deferred(&self.defers, sc.defer_base, &at, failing):
            try self.block(deferred)
        if sc.restore_alloc:
            let saved = try self.slot_address(sc.alloc_saved)
            let target = try self.allocator_global()
            try self.f.copy_bytes(target, saved, 16)
        # a handler finished: its error's message is given back to the thread's room; a
        # failure leaving it has already taken its place
        if sc.handler and not failing:
            try self.message_handled(LowerValue(ref = try self.offset_address(try self.slot_address(sc.handled), 8), type_id = types.str_id, in_memory = true))

    func unwind_from(start: usize, failing: bool) -> !:
        var i = self.scopes.count
        while i > start:
            i -= 1
            try self.unwind(i, failing)

    ## The address of `memory.allocator`, the thread-local current allocator.
    func allocator_global() -> ir.Ref!:
        let t = try self.temp(ir.Class.l)
        try self.f.emit(ir.Op.addr_tls, ir.Class.l, t.index, ir.global_ref("lb_memory_allocator"), ir.none_ref(), 0)
        return t