diff --git a/.gitignore b/.gitignore index 592ec7267..2d039a182 100644 --- a/.gitignore +++ b/.gitignore @@ -96,4 +96,8 @@ signing/credentials signing/fido-signer/target # vscode extension support -tools-bao/.venv/ \ No newline at end of file +tools-bao/.venv/ + +# Zig artifacts +.zig-cache/ +zig-out/ diff --git a/libs/bio-lib/src/c/build.zig b/libs/bio-lib/src/c/build.zig new file mode 100644 index 000000000..ddda3a769 --- /dev/null +++ b/libs/bio-lib/src/c/build.zig @@ -0,0 +1,173 @@ +// build.zig +const std = @import("std"); + +pub fn build(b: *std.Build) void { + const optimize = b.standardOptimizeOption(.{}); + + const linker_script = b.option( + []const u8, + "linker", + "Path to linker script (optional)", + ); + + // Module name for the "dis" step: e.g. -Dmodule=math_test + // Defaults to "test" to match the legacy layout. + const module_name = b.option( + []const u8, + "module", + "Subdirectory module to compile (e.g. math_test). " ++ + "Expects /main.c to exist.", + ) orelse "test"; + + // -- RV32IMC target with x16-x31 reserved ------------------------- + // + // The reserve_x* features tell LLVM's register allocator to never + // use these registers. This is the reliable way to reserve registers + // -- the -ffixed-xN C flags depend on the clang driver translating + // them into +reserve_xN target features, which zig cc may not do + // correctly when invoked as a system command. + const target = b.resolveTargetQuery(.{ + .cpu_arch = .riscv32, + .os_tag = .freestanding, + .abi = .none, + .cpu_model = .{ .explicit = &std.Target.riscv.cpu.generic_rv32 }, + .cpu_features_add = blk: { + var features = std.Target.Cpu.Feature.Set.empty; + features.addFeature(@intFromEnum(std.Target.riscv.Feature.m)); + features.addFeature(@intFromEnum(std.Target.riscv.Feature.c)); + // Reserve x16-x31 for coprocessor use (FIFOs, special regs). + // This prevents the compiler from using these registers for + // general-purpose allocation, which would conflict with the + // inline asm in bio.h that reads/writes them directly. + features.addFeature(@intFromEnum(std.Target.riscv.Feature.reserve_x16)); + features.addFeature(@intFromEnum(std.Target.riscv.Feature.reserve_x17)); + features.addFeature(@intFromEnum(std.Target.riscv.Feature.reserve_x18)); + features.addFeature(@intFromEnum(std.Target.riscv.Feature.reserve_x19)); + features.addFeature(@intFromEnum(std.Target.riscv.Feature.reserve_x20)); + features.addFeature(@intFromEnum(std.Target.riscv.Feature.reserve_x21)); + features.addFeature(@intFromEnum(std.Target.riscv.Feature.reserve_x22)); + features.addFeature(@intFromEnum(std.Target.riscv.Feature.reserve_x23)); + features.addFeature(@intFromEnum(std.Target.riscv.Feature.reserve_x24)); + features.addFeature(@intFromEnum(std.Target.riscv.Feature.reserve_x25)); + features.addFeature(@intFromEnum(std.Target.riscv.Feature.reserve_x26)); + features.addFeature(@intFromEnum(std.Target.riscv.Feature.reserve_x27)); + features.addFeature(@intFromEnum(std.Target.riscv.Feature.reserve_x28)); + features.addFeature(@intFromEnum(std.Target.riscv.Feature.reserve_x29)); + features.addFeature(@intFromEnum(std.Target.riscv.Feature.reserve_x30)); + features.addFeature(@intFromEnum(std.Target.riscv.Feature.reserve_x31)); + break :blk features; + }, + }); + + // -- Build the firmware ELF (uses the selected module) ------------ + const exe = b.addExecutable(.{ + .name = "firmware", + .root_module = b.createModule(.{ + .target = target, + .optimize = optimize, + }), + }); + + // main.c lives inside the module subdirectory + const main_c_path = b.pathJoin(&.{ module_name, "main.c" }); + exe.root_module.addCSourceFile(.{ + .file = b.path(main_c_path), + .flags = c_flags, + }); + + // Headers: module dir first (bio.h, fp.h, etc.), then top-level include/ + exe.root_module.addIncludePath(b.path(module_name)); + exe.root_module.addIncludePath(b.path("include")); + + // -- Linker script ------------------------------------------------ + if (linker_script) |ld| { + exe.setLinkerScript(b.path(ld)); + } + + b.installArtifact(exe); + + // -- "zig build dis -Dmodule=" - emit assembly ----------------- + // Output: zig-out/.s + // + // This invokes "zig cc -S" as a separate system command, so it does + // NOT inherit the target features from the resolveTargetQuery above. + // We must pass the reserve features explicitly via -mcpu. + const dis_step = b.step("dis", "Generate assembly from C source"); + + const dis_cmd = b.addSystemCommand(&.{ + b.graph.zig_exe, + "cc", + "-S", // stop after compilation, emit assembly + "-fverbose-asm", + "-o", + }); + dis_cmd.has_side_effects = true; + + // The output filename is the module name with a .s extension. + const out_s_name = b.fmt("{s}.s", .{module_name}); + const dis_output = dis_cmd.addOutputFileArg(out_s_name); + + dis_cmd.addFileArg(b.path(main_c_path)); + dis_cmd.addArgs(&.{ + "-target", + "riscv32-freestanding", + // Pack the reserve features directly into the -mcpu string. + // This bypasses any issues with -ffixed-xN not being translated + // into LLVM target features by the zig cc driver. + "-mcpu=generic_rv32+m+c" ++ + "+reserve_x16+reserve_x17+reserve_x18+reserve_x19" ++ + "+reserve_x20+reserve_x21+reserve_x22+reserve_x23" ++ + "+reserve_x24+reserve_x25+reserve_x26+reserve_x27" ++ + "+reserve_x28+reserve_x29+reserve_x30+reserve_x31", + }); + // Include paths for the compiler invocation + dis_cmd.addArg(b.fmt("-I{s}", .{module_name})); + dis_cmd.addArg("-Iinclude"); + dis_cmd.addArgs(c_flags); + + // Install the .s file into zig-out/ at the top level. + const install_dis = b.addInstallFile(dis_output, out_s_name); + dis_step.dependOn(&install_dis.step); +} + +// --------------------------------------------------------------------- +// C compiler flags shared by both the ELF build and the dis step. +// +// Note: register reservation is NOT done here via -ffixed-xN because +// zig cc does not reliably translate those into LLVM +reserve_xN +// features. Instead, reservation is handled via: +// - cpu_features_add in the target query (ELF build) +// - the -mcpu string (dis step) +// The -ffixed-xN flags are kept as a belt-and-suspenders measure in +// case a future zig version starts honoring them, but they are not +// the primary mechanism. +// --------------------------------------------------------------------- +const c_flags = &[_][]const u8{ + "-std=c11", + "-Wall", + "-Wextra", + "-ffreestanding", + "-fno-common", + "-ffunction-sections", + "-fdata-sections", + "-Os", + + // Belt-and-suspenders: these may or may not be honored by zig cc, + // but the real reservation is done via target features (see above). + "-ffixed-x16", + "-ffixed-x17", + "-ffixed-x18", + "-ffixed-x19", + "-ffixed-x20", + "-ffixed-x21", + "-ffixed-x22", + "-ffixed-x23", + "-ffixed-x24", + "-ffixed-x25", + "-ffixed-x26", + "-ffixed-x27", + "-ffixed-x28", + "-ffixed-x29", + "-ffixed-x30", + "-ffixed-x31", +}; diff --git a/libs/bio-lib/src/c/clang2rustasm.py b/libs/bio-lib/src/c/clang2rustasm.py new file mode 100644 index 000000000..4f5f1c02c --- /dev/null +++ b/libs/bio-lib/src/c/clang2rustasm.py @@ -0,0 +1,662 @@ +#!/usr/bin/env python3 +""" +clang2rustasm.py - Convert clang RISC-V assembly output to Rust bio_code! macro invocations. + +Usage: + python3 clang2rustasm.py [options] + + is a subdirectory name such as "math_test". + The script looks for zig-out/.s (produced by "zig build dis -Dmodule=") + and writes the converted Rust source to /.rs. + +Options: + --zig-out DIR Override the zig-out search directory (default: zig-out) + --fn-name NAME Function name for bio_code! (default: derived from module) + --start-label L Start label name (default: derived from module) + --end-label L End label name (default: derived from module) + --label-base N Starting numeric label number (default: 20) + -o FILE Override output file path +""" + +import argparse +import re +import sys +import os + + +# ============================================================================ +# Register translation: x16-x31 ABI names -> raw xN form +# x0-x15 ABI names are left as-is +# ============================================================================ +HIGH_REG_MAP = { + "a6": "x16", + "a7": "x17", + "s2": "x18", + "s3": "x19", + "s4": "x20", + "s5": "x21", + "s6": "x22", + "s7": "x23", + "s8": "x24", + "s9": "x25", + "s10": "x26", + "s11": "x27", + "t3": "x28", + "t4": "x29", + "t5": "x30", + "t6": "x31", +} + +# Directives to strip entirely +STRIP_DIRECTIVES = { + ".attribute", + ".file", + ".ident", + ".addrsig", +} + +# Section directives to strip (matched by substring) +STRIP_SECTION_NAMES = { + '".note.GNU-stack"', +} + +# Data directives we know how to handle, mapped to their byte width +DATA_DIRECTIVE_WIDTH = { + ".byte": 1, + ".half": 2, + ".short": 2, + ".word": 4, + ".long": 4, +} + + +# ============================================================================ +# Argument parsing and path resolution +# ============================================================================ + +def parse_args(): + parser = argparse.ArgumentParser( + description="Convert clang RISC-V assembly to Rust bio_code! macro" + ) + parser.add_argument( + "module", + help=( + "Module name (subdirectory). " + "Reads zig-out/.s and writes /.rs." + ), + ) + parser.add_argument( + "-o", "--output", + help="Override output .rs file path", + ) + parser.add_argument( + "--zig-out", + default="zig-out", + metavar="DIR", + help="Directory where zig places compiled .s files (default: zig-out)", + ) + parser.add_argument("--fn-name", help="Function name for bio_code! (default: derived from module)") + parser.add_argument("--start-label", help="Start label name (default: derived from module)") + parser.add_argument("--end-label", help="End label name (default: derived from module)") + parser.add_argument( + "--label-base", + type=int, + default=20, + help="Starting numeric label number (default: 20)", + ) + return parser.parse_args() + + +def resolve_paths(args): + """ + Resolve the input .s path and output .rs path from the module name. + + Input: /.s + Output: /.rs (or -o override) + """ + module = args.module + module = module.rstrip("/\\") + if module.endswith(".s"): + module = module[:-2] + + safe = re.sub(r"[^a-zA-Z0-9]", "_", module).strip("_").lower() + + fn_name = args.fn_name or f"{safe}_bio_code" + start_label = args.start_label or f"BM_{safe.upper()}_BIO_START" + end_label = args.end_label or f"BM_{safe.upper()}_BIO_END" + + input_path = os.path.join(args.zig_out, f"{module}.s") + + if args.output: + output_path = args.output + else: + output_path = os.path.join(module, f"{module}.rs") + + return input_path, output_path, fn_name, start_label, end_label + + +# ============================================================================ +# Directive helpers +# ============================================================================ + +def should_strip_directive(stripped): + for directive in STRIP_DIRECTIVES: + if stripped.startswith(directive): + return True + return False + + +def is_strip_section(stripped): + if stripped.startswith(".section"): + for name in STRIP_SECTION_NAMES: + if name in stripped: + return True + return False + + +def replace_registers(text): + """Replace ABI register names for x16-x31 with raw xN form.""" + for abi_name in sorted(HIGH_REG_MAP.keys(), key=len, reverse=True): + raw_name = HIGH_REG_MAP[abi_name] + pattern = r"(?>= 8 + + # Pad to multiple of 4 + while len(byte_buf) % 4 != 0: + byte_buf.append(0) + + words = [] + for i in range(0, len(byte_buf), 4): + w = (byte_buf[i] + | (byte_buf[i+1] << 8) + | (byte_buf[i+2] << 16) + | (byte_buf[i+3] << 24)) + words.append(w) + return words + + +# ============================================================================ +# Label collection and unified mapping +# ============================================================================ + +def collect_all_labels(code_lines): + """ + Collect all labels defined in the code lines. + Returns dict: label_name -> line_index + """ + labels = {} + for i, line in enumerate(code_lines): + m = re.match(r"^(\.L\w+)\s*:", line) + if m: + labels[m.group(1)] = i + continue + m = re.match(r"^([a-zA-Z_]\w*)\s*:", line) + if m: + labels[m.group(1)] = i + continue + return labels + + +def build_label_map(code_labels, data_objects, label_base): + """ + Assign a unique numeric label to every code label and every data object + name. Code labels are ordered by source position; data labels follow + in source order. Data labels always get a higher number than code labels + because they appear after the code block in the macro output. + + Returns label_map: name -> int + """ + label_map = {} + n = label_base + for name in sorted(code_labels.keys(), key=lambda k: code_labels[k]): + label_map[name] = n + n += 1 + for obj in data_objects: + label_map[obj.name] = n + n += 1 + return label_map + + +# ============================================================================ +# Pass 2: Convert individual code lines +# ============================================================================ + +def convert_line(line, label_map, label_positions, current_line_idx): + """ + Convert a single code line to its Rust inline-asm string equivalent. + Returns (instruction_string_or_None, comment_or_None). + + label_positions must contain an entry for every name in label_map. + Data labels should be mapped to len(code_lines) so they always appear + as forward references from any code position. + """ + stripped = line.strip() + + if stripped == "#APP": + return None, "// --- inline asm begin ---" + if stripped == "#NO_APP": + return None, "// --- inline asm end ---" + + # Label definition + label_def_match = re.match(r"^(\.L\w+|[a-zA-Z_]\w*)\s*:\s*(.*)", stripped) + if label_def_match: + label_name = label_def_match.group(1) + rest = label_def_match.group(2).strip() + if label_name in label_map: + num = label_map[label_name] + result = f"{num}:" + trailing_comment = None + if rest: + comment_m = re.match(r"^#\s*(.*)", rest) + if comment_m: + trailing_comment = f"// {label_name}: {comment_m.group(1).strip()}" + else: + result += f" {rest}" + if not trailing_comment: + trailing_comment = f"// {label_name}" + return result, trailing_comment + return stripped, None + + # Pure comment / block marker lines + if stripped.startswith("#") or stripped.startswith("//"): + bb_match = re.match(r"^#\s*%bb\.\d+", stripped) + if bb_match: + rest = re.sub(r"^#\s*%bb\.\d+:?\s*", "", stripped).strip() + rest = re.sub(r"^#\s*", "", rest).strip() + if rest: + return None, f"// {rest}" + return None, None + comment_text = re.sub(r"^[#/]+\s*", "", stripped).strip() + if comment_text: + return None, f"// {comment_text}" + return None, None + + # Instruction line: split off trailing comment + comment = None + instr = stripped + comment_match = re.search(r"\s+#\s*(.*)", instr) + if comment_match: + comment = f"// {comment_match.group(1).strip()}" + instr = instr[: comment_match.start()].strip() + + # Replace %hi(label) and %lo(label) with numeric forward-ref equivalents. + # Data labels are always forward refs; code labels use position comparison. + def replace_reloc(m): + kind = m.group(1) + lname = m.group(2) + if lname in label_map: + num = label_map[lname] + lpos = label_positions.get(lname, current_line_idx + 1) + ref = f"{num}f" if lpos > current_line_idx else f"{num}b" + return f"%{kind}({ref})" + return m.group(0) + + instr = re.sub(r'%(\w+)\(([a-zA-Z_]\w*)\)', replace_reloc, instr) + + # Replace plain label references (branches, jumps, address loads). + # Longest names first to avoid partial matches. + for label_name in sorted(label_map.keys(), key=len, reverse=True): + num = label_map[label_name] + if label_name not in instr: + continue + lpos = label_positions.get(label_name, current_line_idx + 1) + ref = f"{num}f" if lpos > current_line_idx else f"{num}b" + pattern = r"(? + .p2align + : <- numeric label for the object + .word 0x... <- packed 32-bit words + """ + parts = [] + parts.append("use bao1x_api::bio_code;\n") + parts.append("#[rustfmt::skip]") + parts.append(f"bio_code!({fn_name}, {start_label}, {end_label},") + + # ---- Code ---- + filtered = [(instr, comment) for instr, comment in converted_lines + if instr is not None or comment is not None] + + for i, (instr, comment) in enumerate(filtered): + is_last_instr = (instr is not None) and all( + fi is None for fi, _ in filtered[i + 1:] + ) + + if instr is None and comment is not None: + parts.append(f" {comment}") + continue + + # A comma is needed after the last code instruction if data follows + needs_comma = not is_last_instr or bool(data_objects) + quoted = f' "{instr}"' + if needs_comma: + quoted += "," + if comment: + quoted += f" {comment}" + parts.append(quoted) + + # ---- Data sections ---- + for oi, obj in enumerate(data_objects): + num = label_map[obj.name] + words = pack_to_words(obj.entries) + pow2 = p2align_power(obj.align) + + parts.append(f" // --- rodata: {obj.name} ({len(obj.entries)} entries, {len(words)} words) ---") + # parts.append(f' ".section {obj.section}",') # don't emit this, we want the data in-lined + parts.append(f' ".p2align {pow2}",') + parts.append(f' "{num}:", // {obj.name}') + + is_last_obj = (oi == len(data_objects) - 1) + for wi, w in enumerate(words): + is_last_word = (wi == len(words) - 1) + is_very_last = is_last_obj and is_last_word + comma = "" if is_very_last else "," + # Annotate with the original values that went into this word + byte_offset = wi * 4 + n_entries_in_word = 4 // (obj.entries[0][0] if obj.entries else 4) + entry_start = wi * n_entries_in_word + entry_end = min(entry_start + n_entries_in_word, len(obj.entries)) + vals = ", ".join(str(obj.entries[j][1]) for j in range(entry_start, entry_end)) + parts.append(f' ".word 0x{w:08x}"{comma} // [{byte_offset}] {vals}') + + parts.append(");") + return "\n".join(parts) + + +# ============================================================================ +# Main +# ============================================================================ + +def main(): + args = parse_args() + + input_path, output_path, fn_name, start_label, end_label = resolve_paths(args) + + if not os.path.exists(input_path): + print( + f"Error: assembly file not found: {input_path}\n" + f" Run: python3 -m ziglang build dis -Dmodule={args.module}", + file=sys.stderr, + ) + sys.exit(1) + + out_dir = os.path.dirname(output_path) + if out_dir and not os.path.isdir(out_dir): + print( + f"Error: output directory does not exist: {out_dir}\n" + f" Create the module subdirectory first.", + file=sys.stderr, + ) + sys.exit(1) + + with open(input_path, "r") as f: + lines = f.readlines() + + # Pass 1a: extract code + code_lines = extract_all_code(lines) + if not code_lines: + print(f"Error: no code found in {input_path}", file=sys.stderr) + sys.exit(1) + + # Pass 1b: extract rodata + data_objects = extract_rodata(lines) + + # Build unified label map + code_label_positions = collect_all_labels(code_lines) + label_map = build_label_map(code_label_positions, data_objects, args.label_base) + + # Sentinel positions for data labels: they are always forward from code + all_label_positions = dict(code_label_positions) + for obj in data_objects: + all_label_positions[obj.name] = len(code_lines) + + # Diagnostics + data_names = {o.name for o in data_objects} + print("Label mapping:", file=sys.stderr) + for name, num in sorted(label_map.items(), key=lambda x: x[1]): + pos = all_label_positions[name] + kind = " (data)" if name in data_names else "" + print(f" {name:20s} -> {num}: (line {pos}){kind}", file=sys.stderr) + + if data_objects: + print(f"\nData objects ({len(data_objects)}):", file=sys.stderr) + for obj in data_objects: + words = pack_to_words(obj.entries) + print(f" {obj.name}: {len(obj.entries)} entries -> {len(words)} words " + f"(section={obj.section}, align={obj.align})", file=sys.stderr) + + # Pass 2: convert code lines + converted = [] + for i, line in enumerate(code_lines): + instr, comment = convert_line(line, label_map, all_label_positions, i) + if instr is not None or comment is not None: + converted.append((instr, comment)) + + while converted and converted[-1] == (None, None): + converted.pop() + + result = format_output(fn_name, start_label, end_label, converted, data_objects, label_map) + + with open(output_path, "w") as f: + f.write(result + "\n") + + print(f"\nWrote {output_path}", file=sys.stderr) + print(f" input: {input_path}", file=sys.stderr) + print(f" fn: {fn_name}()", file=sys.stderr) + print(f" labels: {start_label} / {end_label}", file=sys.stderr) + num_instrs = sum(1 for instr, _ in converted if instr is not None) + print(f" instructions: {num_instrs}", file=sys.stderr) + func_labels = [n for n in label_map if not n.startswith('.') and n not in data_names] + print(f" functions found: {len(func_labels)} ({', '.join(func_labels)})", file=sys.stderr) + + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/libs/bio-lib/src/c/include/bio.h b/libs/bio-lib/src/c/include/bio.h new file mode 100644 index 000000000..3708fac43 --- /dev/null +++ b/libs/bio-lib/src/c/include/bio.h @@ -0,0 +1,55 @@ +#include + +// pop_fifoN: read from reserved register xN. +// volatile prevents the compiler from caching or dropping the read. +static inline __attribute__((always_inline)) uint32_t pop_fifo0() { + uint32_t rx; + __asm__ volatile ("mv %0, x16" : "=r"(rx)); + return rx; +} + +static inline __attribute__((always_inline)) uint32_t pop_fifo1() { + uint32_t rx; + __asm__ volatile ("mv %0, x17" : "=r"(rx)); + return rx; +} + +static inline __attribute__((always_inline)) uint32_t pop_fifo2() { + uint32_t rx; + __asm__ volatile ("mv %0, x18" : "=r"(rx)); + return rx; +} + +static inline __attribute__((always_inline)) uint32_t pop_fifo3() { + uint32_t rx; + __asm__ volatile ("mv %0, x19" : "=r"(rx)); + return rx; +} + +// push_fifoN: write to reserved register xN. +// "memory" clobber is the key fix: it tells the compiler this asm has an +// observable side effect beyond the registers listed, so it cannot +// dead-code-eliminate the computation feeding the push even at -Os. +static inline __attribute__((always_inline)) void push_fifo0(uint32_t tx) { + __asm__ volatile ("mv x16, %0" : : "r"(tx) : "memory"); +} + +static inline __attribute__((always_inline)) void push_fifo1(uint32_t tx) { + __asm__ volatile ("mv x17, %0" : : "r"(tx) : "memory"); +} + +static inline __attribute__((always_inline)) void push_fifo2(uint32_t tx) { + __asm__ volatile ("mv x18, %0" : : "r"(tx) : "memory"); +} + +static inline __attribute__((always_inline)) void push_fifo3(uint32_t tx) { + __asm__ volatile ("mv x19, %0" : : "r"(tx) : "memory"); +} + +__attribute__((naked, section(".text._start"))) +void _start(void) { + __asm__ volatile ( + "li sp, 0x1000\n" // Load stack pointer to 0xE00 + "j main\n" // Jump to main + ); +} \ No newline at end of file diff --git a/libs/bio-lib/src/c/include/fp.h b/libs/bio-lib/src/c/include/fp.h new file mode 100644 index 000000000..51db83dc1 --- /dev/null +++ b/libs/bio-lib/src/c/include/fp.h @@ -0,0 +1,235 @@ +/* + * fp.h - Fixed-point math library + * + * Format: configurable Q format via FP_FRAC_BITS + * Default: Q20.12 (20 integer bits, 12 fractional bits) + * + * Representation: signed 32-bit integer + * Range (Q20.12): -524288.0 to +524287.9998 + * Resolution: 1/4096 ~= 0.000244 + */ + +#ifndef FP_H +#define FP_H + +#include +#include + +/* --- Configuration --- */ + +#ifndef FP_FRAC_BITS +#define FP_FRAC_BITS 12 +#endif + +#define FP_ONE (1 << FP_FRAC_BITS) +#define FP_MASK (FP_ONE - 1) + +typedef int32_t fp_t; + +/* --- Constants --- + * + * All computed at compile time from integer literals so the preprocessor + * never emits a divide or a float-to-int conversion at runtime. + * + * At Q12 (FP_ONE = 4096): + * PI = round(3.14159265 * 4096) = 12868 + * TWO_PI = 25736 + * HALF_PI = 6434 (== PI/2, exact: 3.14159265/2*4096 = 6433.98 -> 6434) + */ +#define FP_PI ((fp_t)(3.14159265f * FP_ONE + 0.5f)) +#define FP_TWO_PI ((fp_t)(6.28318530f * FP_ONE + 0.5f)) +#define FP_HALF_PI ((fp_t)(1.57079632f * FP_ONE + 0.5f)) + +/* --- Conversion --- */ + +#define FP_FROM_INT(x) ((fp_t)((x) << FP_FRAC_BITS)) +#define FP_TO_INT(x) ((int32_t)((x) >> FP_FRAC_BITS)) +#define FP_FROM_FLOAT(x) ((fp_t)((x) * FP_ONE + 0.5f)) +#define FP_TO_FLOAT(x) ((float)(x) / FP_ONE) + +/* --- Arithmetic --- */ + +static inline fp_t fp_add(fp_t a, fp_t b) +{ + return a + b; +} + +static inline fp_t fp_sub(fp_t a, fp_t b) +{ + return a - b; +} + +/* + * fp_mul - fixed-point multiply using RISC-V mulh/mul pair. + * + * Reconstructs the full 64-bit product from the high (mulh) and low (mul) + * 32-bit words, then shifts right by FP_FRAC_BITS to re-align the binary + * point. The early-clobber on 'hi' (&) prevents the compiler from aliasing + * it with an input register. + */ +static inline fp_t fp_mul(fp_t a, fp_t b) +{ + int32_t hi, lo; + __asm__ ( + "mulh %0, %2, %3\n" + "mul %1, %2, %3\n" + : "=&r"(hi), "=r"(lo) + : "r"(a), "r"(b) + ); + return (fp_t)(((uint32_t)hi << (32 - FP_FRAC_BITS)) | + ((uint32_t)lo >> FP_FRAC_BITS)); +} + +/* + * u32_divrem - unsigned 32-bit shift-and-subtract divider. + * + * 32 iterations of: shift one bit of the dividend into the partial + * remainder, subtract the divisor if it fits, record the quotient bit. + * No hardware divide instruction required. + */ +static inline uint32_t u32_divrem(uint32_t dividend, uint32_t divisor, + uint32_t *remainder) +{ + uint32_t quotient = 0; + uint32_t rem = 0; + int i; + + for (i = 31; i >= 0; i--) { + rem = (rem << 1) | ((dividend >> i) & 1); + if (rem >= divisor) { + rem -= divisor; + quotient |= (1u << i); + } + } + + if (remainder) *remainder = rem; + return quotient; +} + +/* + * fp_div - signed fixed-point division, no hardware divide. + * + * Works in two passes through u32_divrem: + * pass 1: integer quotient and remainder of |a| / |b| + * pass 2: fractional bits from (remainder << FP_FRAC_BITS) / |b| + * Sign is restored at the end. + * + * Note: r << FP_FRAC_BITS is safe because r < ub after pass 1, and + * ub is a Q12 value so fits comfortably within 32 bits after the shift. + */ +static inline fp_t fp_div(fp_t a, fp_t b) +{ + int32_t sign = ((a ^ b) < 0) ? -1 : 1; + uint32_t ua = (uint32_t)(a < 0 ? -a : a); + uint32_t ub = (uint32_t)(b < 0 ? -b : b); + uint32_t q, r; + fp_t res; + + q = u32_divrem(ua, ub, &r); + res = (fp_t)((q << FP_FRAC_BITS) | u32_divrem(r << FP_FRAC_BITS, ub, NULL)); + + return sign < 0 ? -res : res; +} + +/* --- Trigonometry --- */ + +#define COS_TABLE_ENTRIES 64 + +/* + * Lookup table for cos(i/64 * pi/2) in Q12, i = 0..64. + * + * Generated by: + * import math + * N, Q = 64, 4096 + * [round(math.cos(i/N * math.pi/2) * Q) for i in range(N+1)] + * + * Covers one quadrant [0, pi/2]; the other three are handled by symmetry. + * Values fit in int16_t (max 4096 <= 32767). + */ +static const int16_t cos_table[COS_TABLE_ENTRIES + 1] = { + 4096, 4096, 4095, 4094, 4092, 4090, 4087, 4083, + 4078, 4073, 4067, 4060, 4052, 4044, 4035, 4025, + 4014, 4003, 3991, 3978, 3964, 3950, 3935, 3919, + 3902, 3885, 3867, 3848, 3828, 3807, 3786, 3764, + 3741, 3718, 3694, 3669, 3643, 3617, 3590, 3563, + 3535, 3506, 3477, 3447, 3417, 3386, 3354, 3322, + 3289, 3256, 3222, 3188, 3153, 3118, 3082, 3046, + 3009, 2972, 2935, 2897, 2859, 2820, 2781, 2742, + 2702 +}; + +/* + * fp_cos - cosine via table lookup + linear interpolation. + * + * Symmetry used to cover the full circle from the [0, pi/2] table: + * [0, pi/2]: cos(x) -> table forward + * [pi/2, pi]: cos(pi - x) -> table forward, negated + * [pi, 3pi/2]: cos(x - pi) -> same as above by symmetry + * [3pi/2, 2pi]: cos(2pi - x) -> table forward + * + * Range reduction uses only addition/subtraction (no divide). + * The single fp_div call inside scales x to a table index. + * + * FP_HALF_PI, FP_PI, FP_TWO_PI are all compile-time constants so no + * runtime divide is emitted for them. + */ +static inline fp_t fp_cos(fp_t x) +{ + int32_t negate = 0; + int32_t idx; + fp_t offset, frac, lo, hi; + + /* --- Range-reduce to [0, 2*pi) using only add/subtract --- */ + /* Handle large negative values first */ + if (x < 0) { + /* How many full 2*pi below zero? Round up, then add. */ + int32_t periods = FP_TO_INT(-x) / FP_TO_INT(FP_TWO_PI) + 1; + x += (fp_t)(periods * FP_TWO_PI); + } + /* Handle large positive values */ + while (x >= FP_TWO_PI) { + x -= FP_TWO_PI; + } + + /* --- Quadrant reduction to [0, pi/2] --- */ + + /* [pi, 2*pi] -> [0, pi]: cos(2pi - x) = cos(x), no sign change */ + if (x > FP_PI) { + x = FP_TWO_PI - x; + } + + /* [pi/2, pi] -> [0, pi/2]: cos(pi - x) = -cos(x), flip sign */ + if (x > FP_HALF_PI) { + x = FP_PI - x; + negate = 1; + } + + /* --- Scale x in [0, pi/2] to a table index in [0, 64] --- */ + /* + * offset = x / (pi/2) * 64 + * = x * 64 / HALF_PI + * + * x <= HALF_PI = 6434, so x * 64 <= 411776, well within int32_t. + * We do the multiply first (shift left 6) then divide, keeping + * everything in fixed-point so the result is still Q12. + */ + offset = fp_div(x << 6, FP_HALF_PI); /* result in Q12, range [0, 64<<12] */ + + idx = FP_TO_INT(offset); /* integer table index, 0..64 */ + frac = offset & FP_MASK; /* fractional part for lerp, Q12 */ + + /* Clamp: x == pi/2 exactly maps to index 64, which is the last entry */ + if (idx >= COS_TABLE_ENTRIES) { + idx = COS_TABLE_ENTRIES - 1; + frac = FP_ONE; + } + + /* --- Linear interpolation between adjacent table entries --- */ + lo = (fp_t)cos_table[idx]; + hi = (fp_t)cos_table[idx + 1]; + offset = lo + fp_mul(hi - lo, frac); /* result is Q12 */ + + return negate ? -offset : offset; +} + +#endif /* FP_H */ \ No newline at end of file diff --git a/libs/bio-lib/src/c/math_test/main.c b/libs/bio-lib/src/c/math_test/main.c new file mode 100644 index 000000000..19bdb652e --- /dev/null +++ b/libs/bio-lib/src/c/math_test/main.c @@ -0,0 +1,32 @@ +#include +#include "fp.h" +#include "bio.h" + +void main(void) { + int32_t in; + fp_t arg; + fp_t result; + + // fp_t state = FP_FROM_INT(1); + // fp_t a; + // computes fifo1 <- cosine(fifo0), where the value presented is in degrees + while (1) { + in = pop_fifo0(); + + arg = FP_FROM_INT(in); + // arg = arg * pi / 180 + arg = fp_mul(arg, FP_PI); + arg = fp_div(arg, FP_FROM_INT(180)); + arg = fp_cos(arg); + result = fp_mul(arg, FP_FROM_INT(10)); + + /* + arg = FP_FROM_INT(in); + a = fp_mul(arg, FP_FROM_INT(2)); + a = fp_add(state, a); + result = fp_div(a, state); + state = arg; + */ + push_fifo1(FP_TO_INT(result)); + } +} diff --git a/libs/bio-lib/src/c/math_test/math_test.rs b/libs/bio-lib/src/c/math_test/math_test.rs new file mode 100644 index 000000000..6933e1ba1 --- /dev/null +++ b/libs/bio-lib/src/c/math_test/math_test.rs @@ -0,0 +1,291 @@ +use bao1x_api::bio_code; + +#[rustfmt::skip] +bio_code!(math_test_bio_code, BM_MATH_TEST_BIO_START, BM_MATH_TEST_BIO_END, + "20:", // _start: @_start + // --- inline asm begin --- + "lui sp, 1", + "j 21f", + // --- inline asm end --- + "21:", // main: @main + "addi sp, sp, -48", + "sw ra, 44(sp)", // 4-byte Folded Spill + "sw s0, 40(sp)", // 4-byte Folded Spill + "sw s1, 36(sp)", // 4-byte Folded Spill + "lui a1, 6", + "lui a3, 3", + "li ra, 1", + "lui s0, 1048396", + "li t0, -1", + "lui a4, 699051", + "lui a5, 0xa2f06", + "lui a2, 0x9", + "slli a2, a2, 4", + "add a5, a2, a5", + "lui a0, 2", + "lui s1, 1048574", + "addi a2, a1, 1160", + "sw a2, 12(sp)", // 4-byte Folded Spill + "addi a2, a3, 580", + "sw a2, 32(sp)", // 4-byte Folded Spill + "addi a2, a4, -1365", + "sw a2, 4(sp)", // 4-byte Folded Spill + "addi a1, a1, 1159", + "sw a1, 16(sp)", // 4-byte Folded Spill + "addi a1, a5, 1317", + "sw a1, 8(sp)", // 4-byte Folded Spill + "addi a0, a0, -1757", + "sw a0, 28(sp)", // 4-byte Folded Spill + "addi t1, s1, 1758", + "22:", // .LBB1_1: =>This Loop Header: Depth=1 + // Child Loop BB1_2 Depth 2 + // Child Loop BB1_4 Depth 2 + // Child Loop BB1_16 Depth 2 + // Child Loop BB1_18 Depth 2 + "li a3, 0", + "li s1, 0", + // --- inline asm begin --- + "mv a1, x16", + // --- inline asm end --- + "slli a1, a1, 12", + "lw a0, 32(sp)", // 4-byte Folded Reload + // --- inline asm begin --- + "mulh a4, a1, a0", + "mul a1, a1, a0", + // --- inline asm end --- + "srli a1, a1, 12", + "slli a4, a4, 19", + "slli a4, a4, 1", + "or t2, a4, a1", + "srai a4, a4, 31", + "xor a1, t2, a4", + "sub a4, a1, a4", + "li a5, 31", + "23:", // .LBB1_2: Parent Loop BB1_1 Depth=1 + // => This Inner Loop Header: Depth=2 + "slli a3, a3, 1", + "srl a1, a4, a5", + "sll a0, ra, a5", + "addi a5, a5, -1", + "andi a1, a1, 1", + "or a1, a1, a3", + "srli a3, a3, 14", + "sltiu a3, a3, 45", + "addi a3, a3, -1", + "and a0, a0, a3", + "and a3, a3, s0", + "or s1, s1, a0", + "add a3, a3, a1", + "bne a5, t0, 23b", + // in Loop: Header=BB1_1 Depth=1 + "li a1, 0", + "li a4, 0", + "slli a5, a3, 12", + "li a3, 31", + "24:", // .LBB1_4: Parent Loop BB1_1 Depth=1 + // => This Inner Loop Header: Depth=2 + "slli a1, a1, 1", + "srl a0, a5, a3", + "sll a2, ra, a3", + "addi a3, a3, -1", + "andi a0, a0, 1", + "or a0, a0, a1", + "srli a1, a1, 14", + "sltiu a1, a1, 45", + "addi a1, a1, -1", + "and a2, a2, a1", + "and a1, a1, s0", + "or a4, a4, a2", + "add a1, a1, a0", + "bne a3, t0, 24b", + // in Loop: Header=BB1_1 Depth=1 + "slli s1, s1, 12", + "or a4, a4, s1", + "bgez t2, 25f", + // in Loop: Header=BB1_1 Depth=1 + "neg a4, a4", + "25:", // .LBB1_7: in Loop: Header=BB1_1 Depth=1 + "lw a2, 12(sp)", // 4-byte Folded Reload + "bgez a4, 26f", + // in Loop: Header=BB1_1 Depth=1 + "neg a0, a4", + "lw a1, 4(sp)", // 4-byte Folded Reload + "mulhu a0, a0, a1", + "srli a0, a0, 14", + "mul a0, a0, a2", + "add a4, a4, a2", + "add a4, a4, a0", + "26:", // .LBB1_9: in Loop: Header=BB1_1 Depth=1 + "mv a1, a4", + "lw a0, 16(sp)", // 4-byte Folded Reload + "blt a0, a4, 27f", + // in Loop: Header=BB1_1 Depth=1 + "lw a1, 16(sp)", // 4-byte Folded Reload + "27:", // .LBB1_11: in Loop: Header=BB1_1 Depth=1 + "lw a0, 8(sp)", // 4-byte Folded Reload + "mulhu a0, a1, a0", + "sub a1, a1, a1", + "srli a0, a0, 14", + "mul a0, a0, a2", + "add a1, a1, a4", + "sub a1, a1, a0", + "lw a0, 32(sp)", // 4-byte Folded Reload + "bge a0, a1, 28f", + // in Loop: Header=BB1_1 Depth=1 + "sub a1, a2, a1", + "28:", // .LBB1_13: in Loop: Header=BB1_1 Depth=1 + "mv a3, a1", + "lw a0, 28(sp)", // 4-byte Folded Reload + "blt a1, a0, 29f", + // in Loop: Header=BB1_1 Depth=1 + "lw a0, 32(sp)", // 4-byte Folded Reload + "sub a3, a0, a1", + "29:", // .LBB1_15: in Loop: Header=BB1_1 Depth=1 + "sw a1, 24(sp)", // 4-byte Folded Spill + "li ra, 0", + "li s1, 0", + "slli a3, a3, 6", + "srai a0, a3, 31", + "sw a3, 20(sp)", // 4-byte Folded Spill + "xor a4, a3, a0", + "sub a4, a4, a0", + "li a3, 31", + "li s0, 1", + "lui a1, 2", + "30:", // .LBB1_16: Parent Loop BB1_1 Depth=1 + // => This Inner Loop Header: Depth=2 + "slli ra, ra, 1", + "srl a0, a4, a3", + "addi t2, a1, -1758", + "sll a2, s0, a3", + "addi a3, a3, -1", + "andi a0, a0, 1", + "or a0, a0, ra", + "sltu a5, ra, t2", + "addi a5, a5, -1", + "and a2, a2, a5", + "and a5, a5, t1", + "or s1, s1, a2", + "add ra, a5, a0", + "bne a3, t0, 30b", + // in Loop: Header=BB1_1 Depth=1 + "li a5, 0", + "li a4, 0", + "slli ra, ra, 12", + "li a3, 31", + "31:", // .LBB1_18: Parent Loop BB1_1 Depth=1 + // => This Inner Loop Header: Depth=2 + "slli a5, a5, 1", + "srl a0, ra, a3", + "sll a2, s0, a3", + "addi a3, a3, -1", + "andi a0, a0, 1", + "or a0, a0, a5", + "sltu a5, a5, t2", + "addi a5, a5, -1", + "and a2, a2, a5", + "and a5, a5, t1", + "or a4, a4, a2", + "add a5, a5, a0", + "bne a3, t0, 31b", + // in Loop: Header=BB1_1 Depth=1 + "slli a3, s1, 12", + "or a3, a3, a4", + "lw a1, 24(sp)", // 4-byte Folded Reload + "addi sp, sp, -4", + "lw a0, 24(sp)", // 4-byte Folded Reload + "addi sp, sp, 4", + "bgez a0, 32f", + // in Loop: Header=BB1_1 Depth=1 + "neg a3, a3", + "32:", // .LBB1_21: in Loop: Header=BB1_1 Depth=1 + "lui s0, 1048396", + "li ra, 1", + "srai a4, a3, 12", + "li a5, 63", + "bge a5, a4, 33f", + // in Loop: Header=BB1_1 Depth=1 + "lui a3, 1", + "bge a4, a5, 34f", + "j 35f", + "33:", // .LBB1_23: in Loop: Header=BB1_1 Depth=1 + "slli a3, a3, 19", + "slli a3, a3, 1", + "srli a3, a3, 19", + "srli a3, a3, 1", + "blt a4, a5, 35f", + "34:", // .LBB1_24: in Loop: Header=BB1_1 Depth=1 + "li a4, 63", + "35:", // .LBB1_25: in Loop: Header=BB1_1 Depth=1 + "slli a4, a4, 1", + "lui a0, %hi(37f)", + "addi a0, a0, %lo(37f)", + "add a4, a4, a0", + "lh a0, 0(a4)", + "lh a2, 2(a4)", + "sub a2, a2, a0", + // --- inline asm begin --- + "mulh a4, a2, a3", + "mul a2, a2, a3", + // --- inline asm end --- + "srli a2, a2, 12", + "slli a4, a4, 19", + "slli a4, a4, 1", + "or a2, a2, a4", + "add a3, a2, a0", + "lw a0, 28(sp)", // 4-byte Folded Reload + "blt a1, a0, 36f", + // in Loop: Header=BB1_1 Depth=1 + "neg a3, a3", + "36:", // .LBB1_27: in Loop: Header=BB1_1 Depth=1 + "lui a1, 10", + // --- inline asm begin --- + "mulh a0, a3, a1", + "mul a1, a3, a1", + // --- inline asm end --- + "srli a1, a1, 12", + "slli a0, a0, 19", + "slli a0, a0, 1", + "or a0, a0, a1", + "srai a0, a0, 12", + // --- inline asm begin --- + "mv x17, a0", + // --- inline asm end --- + "j 22b", + // --- rodata: cos_table (65 entries, 33 words) --- + ".p2align 1", + "37:", // cos_table + ".word 0x10001000", // [0] 4096, 4096 + ".word 0x0ffe0fff", // [4] 4095, 4094 + ".word 0x0ffa0ffc", // [8] 4092, 4090 + ".word 0x0ff30ff7", // [12] 4087, 4083 + ".word 0x0fe90fee", // [16] 4078, 4073 + ".word 0x0fdc0fe3", // [20] 4067, 4060 + ".word 0x0fcc0fd4", // [24] 4052, 4044 + ".word 0x0fb90fc3", // [28] 4035, 4025 + ".word 0x0fa30fae", // [32] 4014, 4003 + ".word 0x0f8a0f97", // [36] 3991, 3978 + ".word 0x0f6e0f7c", // [40] 3964, 3950 + ".word 0x0f4f0f5f", // [44] 3935, 3919 + ".word 0x0f2d0f3e", // [48] 3902, 3885 + ".word 0x0f080f1b", // [52] 3867, 3848 + ".word 0x0edf0ef4", // [56] 3828, 3807 + ".word 0x0eb40eca", // [60] 3786, 3764 + ".word 0x0e860e9d", // [64] 3741, 3718 + ".word 0x0e550e6e", // [68] 3694, 3669 + ".word 0x0e210e3b", // [72] 3643, 3617 + ".word 0x0deb0e06", // [76] 3590, 3563 + ".word 0x0db20dcf", // [80] 3535, 3506 + ".word 0x0d770d95", // [84] 3477, 3447 + ".word 0x0d3a0d59", // [88] 3417, 3386 + ".word 0x0cfa0d1a", // [92] 3354, 3322 + ".word 0x0cb80cd9", // [96] 3289, 3256 + ".word 0x0c740c96", // [100] 3222, 3188 + ".word 0x0c2e0c51", // [104] 3153, 3118 + ".word 0x0be60c0a", // [108] 3082, 3046 + ".word 0x0b9c0bc1", // [112] 3009, 2972 + ".word 0x0b510b77", // [116] 2935, 2897 + ".word 0x0b040b2b", // [120] 2859, 2820 + ".word 0x0ab60add", // [124] 2781, 2742 + ".word 0x00000a8e" // [128] 2702 +); diff --git a/libs/bio-lib/src/c/math_test/mod.rs b/libs/bio-lib/src/c/math_test/mod.rs new file mode 100644 index 000000000..9d24e9169 --- /dev/null +++ b/libs/bio-lib/src/c/math_test/mod.rs @@ -0,0 +1,88 @@ +mod math_test; +use bao1x_api::bio::*; +use bao1x_api::bio_resources::*; +use bao1x_hal::bio::{Bio, CoreCsr}; +use math_test::*; +use utralib::utra::bio_bdma; + +pub struct MathTest { + bio_ss: Bio, + // handles have to be kept around or else the underlying CSR is dropped + _tx_handle: CoreHandle, + _rx_handle: CoreHandle, + // the CoreCsr is a convenience object that manages the CSR view of the handle + tx: CoreCsr, + rx: CoreCsr, + // tracks the resources used by the object + resource_grant: ResourceGrant, +} + +impl Resources for MathTest { + fn resource_spec() -> ResourceSpec { + ResourceSpec { + claimer: "math-test".to_string(), + cores: vec![CoreRequirement::Any], + fifos: vec![Fifo::Fifo0, Fifo::Fifo1], + static_pins: vec![], + dynamic_pin_count: 0, + } + } +} + +impl Drop for MathTest { + fn drop(&mut self) { + for &core in self.resource_grant.cores.iter() { + self.bio_ss.de_init_core(core).unwrap(); + } + self.bio_ss.release_resources(self.resource_grant.grant_id).unwrap(); + } +} + +impl MathTest { + pub fn new() -> Result { + let mut bio_ss = Bio::new(); + // claim core resource and initialize it + let resource_grant = bio_ss.claim_resources(&Self::resource_spec())?; + let config = CoreConfig { clock_mode: bao1x_api::bio::ClockMode::FixedDivider(0, 0) }; + bio_ss.init_core(resource_grant.cores[0], &math_test_bio_code(), 0, config)?; + bio_ss.set_core_run_state(&resource_grant, true); + + // safety: fifo1 and fifo2 are stored in this object so they aren't Drop'd before the object is + // destroyed + let tx_handle = unsafe { bio_ss.get_core_handle(Fifo::Fifo0) }?.expect("Didn't get FIFO0 handle"); + let rx_handle = unsafe { bio_ss.get_core_handle(Fifo::Fifo1) }?.expect("Didn't get FIFO1 handle"); + + Ok(Self { + bio_ss, + tx: CoreCsr::from_handle(&tx_handle), + rx: CoreCsr::from_handle(&rx_handle), + // safety: tx and rx are wrapped in CSR objects whose lifetime matches that of the handles + _tx_handle: tx_handle, + _rx_handle: rx_handle, + resource_grant, + }) + } + + pub fn test_cos(&mut self) { + for i in (0..360).step_by(4) { + // self.bio_ss.debug(self.resource_grant.cores[0]); + self.tx.csr.wo(bio_bdma::SFR_TXF0, i); + // let mut dbg_count: usize = 0; + while self.rx.csr.rf(bio_bdma::SFR_FLEVEL_PCLK_REGFIFO_LEVEL1) == 0 { + /* + if dbg_count < 20 { + self.bio_ss.debug(self.resource_grant.cores[0]); + } + dbg_count = dbg_count.saturating_add(1); + */ + } + let result = self.rx.csr.r(bio_bdma::SFR_RXF1) as i32 + 11; // result should be -10 to 10 + let mut line = String::new(); + for _ in 0..result { + line.push(' '); + } + line.push('*'); + log::info!("{:3},{:2}:{}", i, result, line); + } + } +} diff --git a/libs/bio-lib/src/c/mod.rs b/libs/bio-lib/src/c/mod.rs new file mode 100644 index 000000000..c0c236bc6 --- /dev/null +++ b/libs/bio-lib/src/c/mod.rs @@ -0,0 +1 @@ +pub mod math_test; diff --git a/libs/bio-lib/src/c/test/main.c b/libs/bio-lib/src/c/test/main.c new file mode 100644 index 000000000..9523a506d --- /dev/null +++ b/libs/bio-lib/src/c/test/main.c @@ -0,0 +1,51 @@ +#include + +static inline __attribute__((always_inline)) volatile uint32_t pop_fifo0() { + uint32_t rx; + __asm__ volatile ( + "mv %0, x16" + : "=r"(rx) // output + ); + return rx; +} + +static inline __attribute__((always_inline)) volatile uint32_t pop_fifo1() { + uint32_t rx; + __asm__ volatile ( + "mv %0, x17" + : "=r"(rx) // output + ); + return rx; +} + +static inline __attribute__((always_inline)) void push_fifo0(uint32_t tx) { + __asm__ volatile ( + "mv x16, %0" + : // nil output + : "r"(tx) + ); +} + +__attribute__((naked, section(".text._start"))) +void _start(void) { + __asm__ volatile ( + "li sp, 0xe00\n" // Load stack pointer to 0xE00 + "j main\n" // Jump to main + ); +} + +void main(void) { + uint32_t a; + uint32_t b; + uint32_t i; + uint32_t c = 0; + + while (1) { + a = pop_fifo0(); + for(i = 0; i < a; i++) { + b = pop_fifo1(); + c = b * a + c; + } + push_fifo0(c); + } +} diff --git a/libs/bio-lib/src/c/test/mod.rs b/libs/bio-lib/src/c/test/mod.rs new file mode 100644 index 000000000..e69de29bb