From a484f314b719aec5ed7bdc6f08403342b2125561 Mon Sep 17 00:00:00 2001 From: _ov4 Date: Tue, 13 Oct 2026 14:52:57 +0000 Subject: feat(compiler)!: add try-catch with C++ stack unwinding Add TRY/CATCH/ENDTRY and anonymous THROW statements. Use LLVM exception handling and the C++ ABI to propagate exceptions across function calls, clean up catch state, and handle uncaught exceptions at the program boundary. Register exception runtime symbols for the statically linked embedded runner. Verify runtime checks, nested catches, returns, loops, and invalid syntax with smoke programs; exercise unwinding with MCJIT, lli, and native binaries. BREAKING CHANGE: Runtime check failures now throw anonymous exceptions and print only a generic message when uncaught. Native binaries require linking the C++ runtime. Co-Authored-By: Claude Fable 5.1 --- include/cps/ExceptionHandler.h | 48 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 include/cps/ExceptionHandler.h (limited to 'include/cps/ExceptionHandler.h') diff --git a/include/cps/ExceptionHandler.h b/include/cps/ExceptionHandler.h new file mode 100644 index 0000000..5c846ae --- /dev/null +++ b/include/cps/ExceptionHandler.h @@ -0,0 +1,48 @@ +#pragma once +#include "llvm/IR/IRBuilder.h" +#include "llvm/IR/Module.h" +#include +#include + +namespace cps { + +// C++ ABI exception emission. State is keyed by function because file helper +// bodies and user functions are emitted using the same builder as their caller. +class ExceptionHandler { + struct Handler { + llvm::BasicBlock *Target; + llvm::AllocaInst *Exception; + unsigned CatchDepth; + }; + struct FunctionState { + std::vector Handlers; + unsigned CatchDepth = 0; + }; + + llvm::LLVMContext &Context; + llvm::IRBuilder<> &Builder; + llvm::Module &Module; + std::map States; + llvm::FunctionCallee Allocate, Throw, BeginCatch, EndCatch, Personality; + llvm::GlobalVariable *IntTypeInfo = nullptr; + + void ensureRuntime(); + llvm::BasicBlock *emitUnwindDestination(); + +public: + ExceptionHandler(llvm::LLVMContext &C, llvm::IRBuilder<> &B, llvm::Module &M) + : Context(C), Builder(B), Module(M) {} + + void prepareFunction(llvm::Function *F); + void pushHandler(llvm::BasicBlock *Target); + llvm::AllocaInst *popHandler(); + void beginCatch(llvm::AllocaInst *Exception); + void endCatch(); + void emitReturnCleanup(); + + llvm::Value *emitCall(llvm::FunctionCallee Callee, llvm::ArrayRef Args, + const llvm::Twine &Name = ""); + void emitThrow(); +}; + +} // namespace cps -- cgit v1.3.1-4-g156e