# `EHLS.NIF`
[🔗](https://github.com/elixir-hls/elixir-hls/blob/v0.1.0/lib/ehls/nif.ex#L1)

A `defhls` function as a NIF: its C, built into the runtime and run on the CPU as machine code, outside the VM,
instead of as a circuit or as Elixir in the VM (`cpu: :nif`; NIF: a Native Implemented Function, as Erlang calls a
function the VM calls but does not run itself). The C is checked on the host before it becomes one.

`EHLS.MLIR`'s output (`func` / `arith` / `cf` / `memref`) is written as C: every SSA value is a
`uint64_t` holding its value cut to its width (zero-extended), so an `iN` of up to 64 bits needs no
more. The kernel then gets a batch function on the packed format of `EHLS.packed_size/1`
(each scalar in 1, 2, 4 or 8 bytes, little-endian, a tuple left to right), so a binary from
the FPGA's CPU end is read in place, with nothing converted:

    typedef struct { uint64_t s[..]; uint32_t mem[..]; } <kernel>_t;   // the state and the memory space
    void   <kernel>_init(<kernel>_t *st);                              // the initial state
    size_t <kernel>_run(<kernel>_t *st, const uint8_t *in, size_t n,  // n elements in, bytes out
                        uint8_t *out, const uint64_t *levels);

`mix ehls.compile --target cpu` writes the C and checks it: each kernel is built with the host's
C compiler and run on the vectors of `mix ehls.compile` (edge values, random ones, a stream from
the initial state restarted halfway, here also in chunks of 1, 3 and 7 elements, so that the state
is kept between calls), against the same function run by Elixir. Needs `gcc` (or `cc`), no CIRCT.

# `c_source`

The C source of a kernel: `mlir` is its `<kernel>.mlir`, `sig` the decoded `<kernel>.sig`. With
`test: true` it ends with a `main` (`EHLS_TEST`) that the check runs.

# `check`

Writes the C of every kernel of `<dir>/*.sig` (with its `.mlir`) as `<dir>/<kernel>.c`, builds it with the
host's C compiler and compares it with the Elixir function, which must be loaded. Returns
`[{kernel, vectors, errors}]`. `n` random vectors per kernel.

# `registry`

The kernels of `<dir>/*.sig` as one C file (their sources and the table `ehls_nif_kernels` of
priv/backend/atomvm/src/ehls_nif.h) and the Erlang module `hw_nif` that numbers them
(`kernel/1`) and gives their layouts (`layouts/1`, for `pack` / `unpack`). `{c, erl}`.

---

*Consult [api-reference.md](api-reference.md) for complete listing*
