A model for constructors, destructors in IR: QXVMIRv2

Modeling constructors and destructors in IR can be a tricky task. However, their application in C++ is relatively straightforward, but the IR generation for the return path can be quite involved.

Rather than generate this in the frontend, I’m letting the middle Constexpr VM and QXVMIR->LLVM translation layer handle these by making destructors implicit.

An IR routine requires a few things, in addition to the arguments, and the instructions, it takes a list of used types with non-trivial destructors (basically, anything it needs to trigger a procedure invoke for).

Like LLVM IR, there are blocks which end in terminator instructions. But unlike LLVM which uses a SSA model, QXVMIRv2 uses “slots”, which are a bit more analogous to a stack based virtual machine like JVM. Currently these do double duty, slots are used both during codegen (e.g. bindings, literals) and as locals for instructions. Actual instructions can only operate on locals and arguments, but I haven’t yet created the clean separation between codegen-only slots and slots used to actually execute code. This will, I hope, eventually be cleaned up.

Slots can roughly be viewed as LLVM allocas, but they have an attached lifetime to them. This lifetime tracking serves two purposes, the first purpose behind lifetime tracking is that it allows us to automatically run destructor functions when a value goes out of scope. Each block of instructions has an entry state, and we cannot transition to a block where a slot is alive at entry if that slot is not alive in the exiting block. All slots alive in the entering block must also be alive in the exiting block. If there are slots that are alive in the exiting block but dead in the entering block, then the appropriate destructors are called as part of that transition.

The second purpose behind these slots lifetime is that of optimization. Since we implement slots essentially as memory cells, adding “live” state allows generation of LLVM lifetime intrinsics for optimization.

Leave a comment