Inline asm & FFI
Two escape hatches connect TryC to the machine and to the rest of the system: asminline blocks for raw x86-64 or aarch64 assembly (this is how libstd wraps every syscall), and extern declarations plus libextern to call functions from C shared libraries.
asminline
An asminline( ... ) endasm block inserts NASM assembly verbatim (comments inside it use NASM's ;). It can appear at top level or as the body of a function. Macros defined with #define are substituted inside it too, which is how syscall numbers are written.
#include <libstd/stdio>
msg = "Hello World\n"
asminline(
mov rdi, [msg] ; a global by name: its value (the pointer)
call rt_print_raw ; a runtime function
) endasm
Functions written in assembly
When the body of a function is a single asminline block, the parameters are still in the argument registers of the SysV ABI and whatever is left in rax is the return value. This is the pattern of every syscall wrapper in libstd:
#define SYS_READ 0
def sys_read(fd: int, start_offs: str, length: long) -> int:
asminline(
mov rax, SYS_READ ; rdi = fd, rsi = buffer, rdx = length: already in place
syscall
) endasm
def char_to_int(c: char) -> int:
asminline(
movzx eax, dil ; the char arrives in dil
) endasm
Put the asminline block first, with no TryC statement before it: a preceding statement may reuse the argument registers.
Register conventions (V_ABI, x86-64)
| Role | Registers |
|---|---|
| Integer/pointer arguments | rdi rsi rdx rcx r8 r9, then the stack |
| Float arguments and float return | xmm0–xmm7 (counted separately from the integer ones) |
| Return value | rax (second value of a pair: rdx) |
| Preserved across calls | rbx rbp r12 r13 r14 r15: if your block uses them, save and restore them |
| Scratch | rax rdi rsi rdx rcx r8 r9 r10 r11, all xmm |
The generated code keeps values in callee-saved registers across calls, so an assembly block that clobbers rbx or r12–r15 without restoring them corrupts the caller. The runtime exports its functions under their asm names (rt_alloc, rt_promote, rt_print_raw, rt_strlen, ...); with --llvm-static a few of them are renamed to avoid libc clashes, which does not affect TryC code.
Allocating inside asm
Memory obtained with rt_alloc inside an assembly block belongs to the current scope like any other allocation. When the block ends the function and leaves the pointer in rax, the compiler promotes it to the caller exactly as it does for a return, also when the pointer points inside the buffer:
def cwd() -> str:
asminline(
mov rdi, OS_PATH_MAX
call rt_alloc
mov r8, rax ; r8 = base of the buffer
mov rdi, r8
mov rsi, OS_PATH_MAX
call sys_getcwd
mov rax, r8 ; returned: the compiler promotes it
) endasm
What the block writes into memory is invisible to the compiler: a pointer stored raw needs a pin (rt_promote_to_root, which in TryC code is allowed only inside unsafe:). The full rules are in The arena.
aarch64
With --target linux-aarch64 (see Compiler options) an asminline block is AArch64 assembly in GNU syntax. The rules are the same, with that architecture's registers. A module that supports both architectures puts each version under #ifdef __x86_64__ or #ifdef __aarch64__, as libstd/cpuinfo does.
| Role | Registers |
|---|---|
| Integer/pointer arguments | x0–x7; w0–w7 for int, char and short (there are no 8- or 16-bit registers) |
| Float arguments and float return | d0–d7 (counted separately from the integer ones) |
| Return value | x0 (w0 for an int) |
Address of a [name] | x19–x23 |
| Never touched | x29 (frame pointer) and sp; x30 is overwritten by every bl |
def add3(a: int, b: long, c: int) -> long:
asminline(
add x0, x1, w0, sxtw ; b + a, with a sign-extended
add x0, x0, w2, sxtw // comments with ';' or '//'
) endasm
def midr() -> long:
asminline(
mrs x0, MIDR_EL1 ; Linux emulates the ID registers for user space
) endasm
def program_argc() -> long:
asminline(
adrp x9, argc ; a symbol takes two instructions
ldr x0, [x9, :lo12:argc]
) endasm
Calls are bl, system calls svc #0 with the number in x8. A [name] of a parameter, local or global works as on x86-64. A runtime symbol cannot be read with a single [name] as it can on x86-64: write adrp and :lo12: as above, otherwise the compiler stops with an error. Only the labels a block defines are renamed: v0.16b or v1.d[0] stay as written.
Calling C libraries
Three declarations link a shared library and describe what you use from it. The compiler passes the library to the linker and calls the functions with the C calling convention of the target system, so structs and pointers must be laid out as C expects.
#include <libstd/stdio>
libextern <libsqlite3.so>
extern class sqlite3 // opaque: only ever a pointer
extern class sqlite3_stmt
extern def sqlite3_libversion() -> str
extern def sqlite3_open(filename: str, ppDb: &sqlite3) -> int
extern def sqlite3_close(dbs: sqlite3) -> int
print(sqlite3_libversion(), "\n")
db =: sqlite3
rc = sqlite3_open("./test.db", &db)
sqlite3_close(db)
| Declaration | Meaning |
|---|---|
libextern <library> | The shared object to link. A bare name (libsqlite3.so, libX11.so, libc.so.6) is looked up at compile time the way the loader would: in the ldconfig cache (an unversioned name also matches libsqlite3.so.0 or libLLVM-15.so, the highest version wins), then in the standard library directories, then with clang -print-file-name; libLLVM.so is the library of the LLVM toolchain on PATH, found through the llvm-config next to opt. On Windows the library is a DLL: a bare name (ws2_32.dll, vulkan-1.dll) is looked up in the System32 folder of the running Windows (%SystemRoot%, whatever drive it is installed on), then on PATH, and the compiler makes the import library from the DLL's exports, so no .lib file is needed. A name with a / (for a DLL also \ or :) is a path and must exist. Several are allowed; the program is then linked dynamically, with /lib64/ld-linux-x86-64.so.2 as interpreter and the system's libc so that the libraries find theirs. |
extern def name(params) -> type | Prototype of a C function. Map C types as: int → int, size_t and opaque handles → long, char* → ptr char (copy it into a real string with str_from_c: a C string has no length header), other pointers → ref (an object passed to C coerces to it; a long parameter needs an unsafe: cast), double → float, out-pointers → &T, void → None. |
extern class Name | An opaque C struct, handled through pointers only; declare variables with =:. |
name: byval Class | In an extern def, a struct passed by value, as Class name in C. Without byval an object is passed as its address, as Class *name. |
C structs whose fields you access are declared as normal classes with the same field order and explicit padding fields (see Classes). A bare function name passed as a str argument becomes its address (a C callback). There is no C header parser: the prototypes are written by hand, and libstd already contains the bindings for SQLite (sqlite3), MariaDB (mysql), Xlib (xlib) and Vulkan (vulkan).
Structs by value
Some C functions take a struct itself rather than a pointer to it: cabs(double complex), inet_ntoa(struct in_addr), and many Windows APIs, such as the HTTPAPI_VERSION of HttpInitialize. Declare the struct as a class with the same fields in the same order, and mark the parameter byval:
#include <libstd/stdio>
#include <libstd/string>
libextern <libm.so.6>
class Complex:
re float
im float
extern def cabs(z: byval Complex) -> float
z = new Complex()
z.re = 3.0
z.im = 4.0
print(ftoa(cabs(z)), "\n") // 5.000000
The object keeps the TryC layout, where every field takes 8 bytes. At the call its fields are copied, one by one, into the C layout: natural alignment, and an embedded class becomes a nested struct. The copy is then passed the way the C ABI of the target system prescribes, which LLVM leaves to the language front end:
| System | Rule |
|---|---|
| Linux, x86-64 (SysV) | Up to 16 bytes, every 8-byte block goes in a register: an SSE register if it holds only float fields, an integer register otherwise. Beyond 16 bytes, or when the registers left are not enough for the whole struct, the struct is copied onto the stack. |
| Windows x64 | A struct of 1, 2, 4 or 8 bytes goes in an integer register; any other size is passed as a pointer to a copy made by the caller. |
The fields can be char, bool, short, int, long, float (a C double), pointers (str, ref, ptr T, a class, an array) and embedded classes. Not supported yet: fixed-size array fields, the 32-bit C float, and a struct returned by value. byval is refused on a normal def: between TryC functions an object is always passed by reference.
Memory across the boundary
- A
strpassed to C is a plainchar*, valid for the whole call. A library that keeps it after the call needs it pinned: insideunsafe:,rt_promote_to_root(s), ordict_poke64into the structure the library reads. - Memory returned by C (
malloced inside the library) is not in the arena: free it with the library's own function. - Structures that the library keeps a pointer to for a long time are safest in
raw_allocmemory (see Pointers).
Static linking of LLVM
The self-hosted compiler declares libextern <libLLVM.so> to run the optimiser in-process: whatever the distribution calls the library (libLLVM-14.so on Debian, libLLVM.so.18 elsewhere), the compiler links the one that belongs to the opt and llc on PATH. --llvm-static replaces that one library with the static archives that the same llvm-config lists, to save the 12 ms that loading the shared object costs on every start.
Syscalls without libc
Every OS interaction in libstd is a wrapper of this shape, one per syscall, grouped by module: stdio (read/write), file, os, process, net, time, mem, sync. The syscall numbers are #defines in libstd/macro and in each module. A program compiled with --nosyscall must not include any of them.