From f88523fa88b41b8e68500fc6904dfab7232165b4 Mon Sep 17 00:00:00 2001 From: ASDAlexander77 Date: Thu, 12 Nov 2026 00:12:27 +0000 Subject: [PATCH 1/2] wasm: try/catch and finally catch, through wasm exception handling wasm32/wasm64 (not Emscripten) compile with the exception-handling feature and the wasm exception model, set before the target machine is made (its MCAsmInfo takes it from there; without it every invoke was lowered to a call). WasmExceptionPass turns each Itanium landing pad into a catch-all catchpad left at once (catchswitch, catchpad [ptr null], llvm.wasm.get.exception, catchret), so the code after the pad runs as ordinary code, as it does on Linux; `resume` becomes llvm.wasm.throw. What the personality would decide is decided after the catch: a pad's selector is the first clause that takes the exception (__tslang_wasm_catches: the same type, or a base class's pointer), a pad of typed clauses only rethrows what none takes, and a matched pointer clause binds the thrown pointer. The C++ runtime's type_infos and type_info vtables get definitions, so each has an address of its own. The JS host imports the __cpp_exception tag (i32 or i64, read from the module by host.instantiate), throws a WebAssembly.Exception of it from __cxa_throw, and keeps begin/end catch and rethrow as libc++abi does. It also maps Node's ERR_FS_* codes and refuses an environment name with '='. run_tests.mjs no longer skips tests that catch; json.ts under none is listed (5 GB of strings). Co-Authored-By: Claude Opus 5.5 --- docs/how/wasm/test/README.md | 11 +- docs/how/wasm/test/host.mjs | 121 ++++- docs/how/wasm/test/index.html | 2 +- docs/how/wasm/test/run.mjs | 2 +- docs/how/wasm/test/run_tests.mjs | 4 +- docs/how/wasm/test/wasm_skips.txt | 1 + tslang/include/TypeScript/DataStructs.h | 3 + .../TypeScript/Pass/WasmExceptionPass.h | 23 + .../TypeScriptExceptionPass/CMakeLists.txt | 1 + .../WasmExceptionPass.cpp | 434 ++++++++++++++++++ tslang/tslang/obj.cpp | 25 +- tslang/tslang/opts.cpp | 1 + tslang/tslang/transform.cpp | 5 + 13 files changed, 616 insertions(+), 17 deletions(-) create mode 100644 tslang/include/TypeScript/Pass/WasmExceptionPass.h create mode 100644 tslang/lib/TypeScriptExceptionPass/WasmExceptionPass.cpp diff --git a/docs/how/wasm/test/README.md b/docs/how/wasm/test/README.md index 7936309e1..f48487dce 100644 --- a/docs/how/wasm/test/README.md +++ b/docs/how/wasm/test/README.md @@ -27,6 +27,16 @@ uncaught exception. wasm64 needs Node 24 or later. LLVM gives a wasm64 module 64-bit tables, which older V8 cannot instantiate. +## Exceptions + +`try`/`catch` and `finally` are wasm exception handling (the `exception-handling` feature, in every +current browser and Node). The tslang compiler's `WasmExceptionPass` turns each landing pad into a +catch of the C++ exception tag, `__cpp_exception`, which the module imports. The host creates the +tag, so instantiate through `host.instantiate(bytes)`, which reads the tag's parameter type from the +module: a pointer, i32 or i64. The host also keeps what a C++ runtime would: `__cxa_throw` throws a +`WebAssembly.Exception` of that tag, and it tracks each exception's type and the exceptions being +handled. A JS exception (`exit()`, a failed assert) is not of that tag, so no `catch` sees it. + ## The tests node run_tests.mjs [--suite=tester,defaultlib] [--triple=wasm32,wasm64] [--mm=none,rc,own] [--debug] [-j] [filter] @@ -43,7 +53,6 @@ and every failure are written to `out/results.txt`. Some tests are skipped, each with its reason: -- tests that catch an exception (`try`/`catch` does not catch on wasm yet; a throw ends the program) - async tests (the async runtime has no wasm build) - tests that use threads - default-library tests marked `// gc only`, `// linux only`, or (under own) `// not own` diff --git a/docs/how/wasm/test/host.mjs b/docs/how/wasm/test/host.mjs index 29ec1b35e..bd9985368 100644 --- a/docs/how/wasm/test/host.mjs +++ b/docs/how/wasm/test/host.mjs @@ -11,7 +11,7 @@ // tslang's `long`) is an i64 on both and so always a BigInt. // // const host = createHost({ args, write, node }); -// const { instance } = await WebAssembly.instantiate(bytes, host.imports); +// const instance = await host.instantiate(bytes); // const exitCode = host.run(instance); export class ExitSignal extends Error @@ -23,7 +23,7 @@ export class ExitSignal extends Error } } -// a C++ exception nothing caught: on wasm try/catch does not catch yet, so every throw ends here +// a C++ exception nothing caught: run() turns the WebAssembly.Exception that left main into this export class UncaughtThrow extends Error { constructor(objectAddress) @@ -33,6 +33,25 @@ export class UncaughtThrow extends Error } } +// Whether a module's memory is a memory64 one (wasm64): the limits flags of its memory section. +// The C++ exception tag the module imports carries a pointer, an i64 there. +export function isMemory64(bytes) +{ + const b = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes.buffer ?? bytes, bytes.byteOffset ?? 0, bytes.byteLength); + let p = 8; + const leb = () => { let r = 0, scale = 1, c; do { c = b[p++]; r += (c & 0x7f) * scale; scale *= 128; } while (c & 0x80); return r; }; + while (p < b.length) + { + const id = b[p++]; + const size = leb(); + const end = p + size; + if (id === 5 && leb() > 0) return (b[p] & 0x04) !== 0; + p = end; + } + + return false; +} + const WEEKDAYS = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]; const MONTHS = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]; @@ -46,6 +65,12 @@ export function createHost(options = {}) let memory; let is64 = false; + // C++ exceptions (see __cxa_throw): the module's tag, made by instantiate(); each thrown object's + // type_info and handler count; the exceptions being handled, innermost last + let cppExceptionTag; + const exceptions = new Map(); + const handled = []; + const N = (v) => Number(v); const P = (v) => (is64 ? BigInt(v) : v); @@ -563,11 +588,18 @@ export function createHost(options = {}) const setResult = (bytes) => { resultBytes = typeof bytes === "string" ? utf8Encoder.encode(bytes) : bytes; return resultBytes.length; }; const fsFail = (e, op, path, dest) => { - const code = e?.code ?? "EIO"; - const text = (e?.message ?? String(e)).replace(/^[A-Z]+: /, "").replace(/, .*$/, ""); + // Node words a few errors of its own (fs.rmSync of a directory: ERR_FS_EISDIR, "Path is a + // directory: rm returned EISDIR (is a directory) ..."): the system error is in them + const nodeError = /^ERR_FS_(E[A-Z]+)$/.exec(e?.code ?? ""); + const code = nodeError ? nodeError[1] : (e?.code ?? "EIO"); + const text = nodeError + ? (/\(([^)]*)\)/.exec(e.message)?.[1] ?? e.message) + : (e?.message ?? String(e)).replace(/^[A-Z]+: /, "").replace(/, .*$/, ""); setResult(`${code}: ${text}, ${op}${path !== undefined ? ` '${path}'` : ""}${dest !== undefined ? ` -> '${dest}'` : ""}`); return -1; }; + const validEnvName = (name) => name.length > 0 && !name.includes("="); + const invalidEnvName = (op, name) => { setResult(`EINVAL: invalid argument, ${op} '${name}'`); return -1; }; const needNode = (what) => { if (!node) throw new Error(`${what} needs the Node host`); }; let stdinLine = new Uint8Array(0); @@ -693,10 +725,59 @@ export function createHost(options = {}) return n; }, - // C++ exceptions: nothing catches them on wasm yet + // C++ exceptions, as a C++ runtime keeps them. A throw is a WebAssembly.Exception of the + // module's __cpp_exception tag carrying the thrown object's address; tslang's catches + // (WasmExceptionPass) catch that tag, ask here for the type_info the object was thrown with, + // and begin and end handling it here. __cxa_allocate_exception: (size) => P(malloc(size)), __cxa_free_exception: (p) => free(p), - __cxa_throw: (object) => { throw new UncaughtThrow(N(object)); }, + // As libc++abi does it: an exception being handled has a handler count, negative once it + // is rethrown. A catch of the exception already innermost does not stack it again, and the + // last end of a catch destroys it unless it was rethrown, when it lives on to its next catch. + __cxa_throw: (object, type) => + { + exceptions.set(N(object), { type, handlers: 0 }); + throw new WebAssembly.Exception(cppExceptionTag, [object]); + }, + __tslang_wasm_exception_type: (object) => exceptions.get(N(object))?.type ?? P(0), + __cxa_begin_catch: (object) => + { + const exception = exceptions.get(N(object)); + if (exception) + { + exception.handlers = Math.abs(exception.handlers) + 1; + if (handled[handled.length - 1] !== N(object)) handled.push(N(object)); + } + + return object; + }, + __cxa_current_exception_type: () => (handled.length ? exceptions.get(handled[handled.length - 1])?.type : undefined) ?? P(0), + __cxa_end_catch: () => + { + if (!handled.length) return; + const object = handled[handled.length - 1]; + const exception = exceptions.get(object); + if (exception.handlers < 0) + { + if (++exception.handlers === 0) handled.pop(); + return; + } + + if (--exception.handlers === 0) + { + handled.pop(); + exceptions.delete(object); + free(object); + } + }, + __cxa_rethrow: () => + { + if (!handled.length) throw new Error("rethrow with no exception being handled"); + const object = handled[handled.length - 1]; + const exception = exceptions.get(object); + exception.handlers = -exception.handlers; + throw new WebAssembly.Exception(cppExceptionTag, [P(object)]); + }, __assert_fail: (msg, file, line, fn) => { throw new Error(`Assertion failed: ${readStr(msg)}, file ${readStr(file)}, line ${line}`); }, abort: () => { throw new Error("abort()"); }, exit: (code) => { throw new ExitSignal(code); }, @@ -805,8 +886,19 @@ export function createHost(options = {}) tslang_process_argc: () => args.length, tslang_process_argv: (i) => (i < 0 || i >= args.length ? -1 : setResult(args[i])), tslang_process_getenv: (name) => { const v = node?.process.env[readStr(name)]; return v === undefined ? -1 : setResult(v); }, - tslang_process_setenv: (name, value) => { if (node) node.process.env[readStr(name)] = readStr(value); return 0; }, - tslang_process_unsetenv: (name) => { if (node) delete node.process.env[readStr(name)]; return 0; }, + // a name that is empty or has an '=' is EINVAL, as the C++ wrappers say it (setenv's own error) + tslang_process_setenv: (name, value) => + { + if (!validEnvName(readStr(name))) return invalidEnvName("setenv", readStr(name)); + if (node) node.process.env[readStr(name)] = readStr(value); + return 0; + }, + tslang_process_unsetenv: (name) => + { + if (!validEnvName(readStr(name))) return invalidEnvName("unsetenv", readStr(name)); + if (node) delete node.process.env[readStr(name)]; + return 0; + }, tslang_process_env_count: () => { entries = node ? Object.entries(node.process.env).map(([k, v]) => `${k}=${v}`) : []; return entries.length; }, tslang_process_cwd: () => setResult(node ? node.process.cwd() : "/"), tslang_process_chdir: (path) => { needNode("process.chdir"); try { node.process.chdir(readStr(path)); return 0; } catch (e) { return fsFail(e, "chdir", readStr(path)); } }, @@ -898,9 +990,20 @@ export function createHost(options = {}) catch (e) { if (e instanceof ExitSignal) return e.code; + if (cppExceptionTag && e instanceof WebAssembly.Exception && e.is(cppExceptionTag)) throw new UncaughtThrow(N(e.getArg(cppExceptionTag, 0))); throw e; } }; - return { imports, run, env }; + // Instantiates a module with these imports. The C++ exception tag it imports is made here, its + // parameter a pointer: an i32, or an i64 in a memory64 module. + const instantiate = async (bytes) => + { + cppExceptionTag = new WebAssembly.Tag({ parameters: [isMemory64(bytes) ? "i64" : "i32"] }); + env.__cpp_exception = cppExceptionTag; + const { instance } = await WebAssembly.instantiate(bytes, imports); + return instance; + }; + + return { imports, run, instantiate, env }; } diff --git a/docs/how/wasm/test/index.html b/docs/how/wasm/test/index.html index 8c4e745f8..d03e235cb 100644 --- a/docs/how/wasm/test/index.html +++ b/docs/how/wasm/test/index.html @@ -31,7 +31,7 @@ let status; try { - const { instance } = await WebAssembly.instantiateStreaming(fetch(path), host.imports); + const instance = await host.instantiate(await (await fetch(path)).arrayBuffer()); status = `exit code ${host.run(instance)}`; } catch (e) diff --git a/docs/how/wasm/test/run.mjs b/docs/how/wasm/test/run.mjs index 0eb0e43db..4ff2cff08 100644 --- a/docs/how/wasm/test/run.mjs +++ b/docs/how/wasm/test/run.mjs @@ -23,7 +23,7 @@ const host = createHost({ let code; try { - const { instance } = await WebAssembly.instantiate(fs.readFileSync(file), host.imports); + const instance = await host.instantiate(fs.readFileSync(file)); code = host.run(instance); } catch (e) diff --git a/docs/how/wasm/test/run_tests.mjs b/docs/how/wasm/test/run_tests.mjs index 4e526b525..ff1511b8e 100644 --- a/docs/how/wasm/test/run_tests.mjs +++ b/docs/how/wasm/test/run_tests.mjs @@ -24,8 +24,7 @@ // The tester's tests are the single-file ones its CMakeLists.txt runs (`test-compile-*`): the others // in the folder are multi-file tests, tests that expect a compile error, or not run at all. // -// Skipped, and listed as such: tests that catch an exception (try/catch does not catch on wasm yet: -// a throw ends the program), async tests (no async runtime for wasm), threads (none on wasm), the +// Skipped, and listed as such: async tests (no async runtime for wasm), threads (none on wasm), the // default library's tests marked "// gc only", "// linux only" or (under own) "// not own", and the // tests in wasm_skips.txt, each with its reason. // @@ -151,7 +150,6 @@ const skipReason = (suite, file, source, leg) => const marked = suite.marker?.(source, leg); if (marked) return marked; - if (/\bcatch\s*[({]/.test(source)) return "catches an exception: try/catch does not catch on wasm yet"; if (/\basync\b|\bawait\b|\bPromise\b/.test(source)) return "async: the async runtime (TypeScriptAsyncRuntime) has no wasm build"; if (/\bThread\.spawn\b|\bnew Worker\b|\bAtomics\.wait\b/.test(source)) return "threads: none on wasm"; return null; diff --git a/docs/how/wasm/test/wasm_skips.txt b/docs/how/wasm/test/wasm_skips.txt index 010e96f69..541fafb4f 100644 --- a/docs/how/wasm/test/wasm_skips.txt +++ b/docs/how/wasm/test/wasm_skips.txt @@ -9,6 +9,7 @@ internals.ts # inline_asm with x86 instructions 00tslang_issue_29_thread.ts # starts threads through _beginthreadex: no threads on wasm 00cppvtable_hidden_return.ts # a @cpp class returning a struct needs the MSVC or a 64-bit Itanium ABI (excluded on i686 too) fetch.ts # (default library) fetch(): the host has no network, so the request throws +json.ts none # (default library) builds a 100000-character string a character at a time: -mm=none frees none of the ~5 GB, more than a wasm memory holds # fails natively under the same model too (not run natively under it by ctest) 01tuple.ts own # frees a block it does not own (native own: the program does not finish either) diff --git a/tslang/include/TypeScript/DataStructs.h b/tslang/include/TypeScript/DataStructs.h index 581738153..d26e4558a 100644 --- a/tslang/include/TypeScript/DataStructs.h +++ b/tslang/include/TypeScript/DataStructs.h @@ -30,6 +30,9 @@ struct CompileOptions bool isWindows; // Bionic has its own assert entry points (__assert/__assert2), not glibc's __assert_fail bool isAndroid = false; + // wasm32/wasm64 other than Emscripten: try/catch is wasm exception handling (the + // exception-handling feature), its landing pads made funclets by WasmExceptionPass + bool wasmExceptions = false; bool isExecutable; bool isDLL; diff --git a/tslang/include/TypeScript/Pass/WasmExceptionPass.h b/tslang/include/TypeScript/Pass/WasmExceptionPass.h new file mode 100644 index 000000000..ee928f11d --- /dev/null +++ b/tslang/include/TypeScript/Pass/WasmExceptionPass.h @@ -0,0 +1,23 @@ +#ifndef WASMEXCEPTIONPASS__H +#define WASMEXCEPTIONPASS__H + +#include "llvm/Pass.h" +#include "llvm/IR/PassManager.h" + +namespace ts +{ + // wasm32/wasm64 (not Emscripten): turns the Itanium landing pads tslang emits into the funclets + // wasm exception handling is built on. See WasmExceptionPass.cpp. + class WasmExceptionPass : public llvm::PassInfoMixin + { + public: + llvm::PreservedAnalyses run(llvm::Module &M, llvm::ModuleAnalysisManager &AM); + + static bool isRequired() + { + return true; + } + }; +} + +#endif // WASMEXCEPTIONPASS__H diff --git a/tslang/lib/TypeScriptExceptionPass/CMakeLists.txt b/tslang/lib/TypeScriptExceptionPass/CMakeLists.txt index 956901bf0..301d3fad8 100644 --- a/tslang/lib/TypeScriptExceptionPass/CMakeLists.txt +++ b/tslang/lib/TypeScriptExceptionPass/CMakeLists.txt @@ -8,6 +8,7 @@ add_llvm_library(TypeScriptExceptionPass Win32ExceptionPass.cpp LandingPadFixPass.cpp CxxThrowCallingConvPass.cpp + WasmExceptionPass.cpp ADDITIONAL_HEADER_DIRS diff --git a/tslang/lib/TypeScriptExceptionPass/WasmExceptionPass.cpp b/tslang/lib/TypeScriptExceptionPass/WasmExceptionPass.cpp new file mode 100644 index 000000000..873ae742f --- /dev/null +++ b/tslang/lib/TypeScriptExceptionPass/WasmExceptionPass.cpp @@ -0,0 +1,434 @@ +#include "TypeScript/Pass/WasmExceptionPass.h" + +#include "llvm/IR/IRBuilder.h" +#include "llvm/IR/InstIterator.h" +#include "llvm/IR/Instructions.h" +#include "llvm/IR/IntrinsicInst.h" +#include "llvm/IR/Intrinsics.h" +#include "llvm/IR/IntrinsicsWebAssembly.h" +#include "llvm/IR/Module.h" + +using namespace llvm; + +#define DEBUG_TYPE "pass" + +// wasm exception handling (the exception-handling feature, -wasm-enable-eh) is built on funclets, +// the catchswitch/catchpad/cleanuppad form MSVC's EH uses; the backend has nothing for a +// `landingpad`. tslang emits the Itanium form on wasm, as it does on Linux, so this pass turns each +// landing pad into a catch that is left at once: +// +// invoke ... unwind label %lpad invoke ... unwind label %wasm.dispatch +// wasm.dispatch: +// %cs = catchswitch within none [label %wasm.catch] unwind to caller +// wasm.catch: +// %cp = catchpad within %cs [ptr null] +// store (llvm.wasm.get.exception(%cp)), %wasm.exn +// catchret from %cp to label %lpad +// lpad: lpad: +// %lp = landingpad {ptr, i32} ... %lp = { load %wasm.exn, selector } +// +// The code after an Itanium landing pad already runs as ordinary code - the handler, the cleanup, +// and the `resume` or rethrow that ends it - so the funclet holds nothing but the catch. A catch of +// `ptr null` catches every C++ exception (the __cpp_exception tag) and needs no personality +// routine, no LSDA and no C++ runtime: the host (docs/how/wasm/test/host.mjs) keeps what a C++ +// runtime keeps - each exception's type_info, the exceptions being handled - and throws a thrown +// object as a WebAssembly.Exception of that tag. A JS exception (exit(), an assert) is not one, so +// no catch sees it. +// +// What the personality routine would decide is decided after the catch instead: +// - the selector a typed catch clause compares (llvm.eh.typeid.for) is the type_info's address, +// and the pad's selector that of the first clause that takes the exception - the same type, or +// a base class's pointer for a class's (__tslang_wasm_catches) - or 0; +// - a pad with only typed clauses, which the personality would skip for any other type, rethrows +// an exception none of them matches; +// - `resume` rethrows (llvm.wasm.throw). +// +// The C++ runtime's type_infos for the fundamental types (_ZTIi, _ZTIPc, ...) and the vtables of +// its type_info classes are not there to link against, and wasm-ld with --allow-undefined puts an +// undefined data symbol at address 0, so every one of them would be the same type: each gets a +// definition here. + +namespace +{ + +constexpr const char *EXCEPTION_TYPE_FUNC_NAME = "__tslang_wasm_exception_type"; +constexpr const char *PERSONALITY_FUNC_NAME = "__gxx_wasm_personality_v0"; + +struct WasmExceptionPassCode +{ + Module &M; + LLVMContext &C; + PointerType *ptrTy; + IntegerType *i32Ty; + IntegerType *intPtrTy; + + WasmExceptionPassCode(Module &M) + : M(M), C(M.getContext()), ptrTy(PointerType::get(M.getContext(), 0)), i32Ty(Type::getInt32Ty(M.getContext())), + intPtrTy(M.getDataLayout().getIntPtrType(M.getContext())) + { + } + + bool defineRuntimeTypeInfos() + { + SmallVector declarations; + for (auto &G : M.globals()) + { + auto name = G.getName(); + if (G.isDeclaration() && (name.starts_with("_ZTI") || name.starts_with("_ZTS") || name.starts_with("_ZTV"))) + { + declarations.push_back(&G); + } + } + + for (auto *G : declarations) + { + // room for what is read through one: a vtable is referenced at an offset into it + auto *type = ArrayType::get(ptrTy, 4); + auto *definition = new GlobalVariable(M, type, /*isConstant=*/true, GlobalValue::LinkOnceODRLinkage, + Constant::getNullValue(type), "", G); + definition->takeName(G); + G->replaceAllUsesWith(definition); + G->eraseFromParent(); + } + + return !declarations.empty(); + } + + // the selector of a type_info: its address, as an i32 like llvm.eh.typeid.for's + Value *selectorOf(IRBuilder<> &builder, Value *typeInfo) + { + return builder.CreateTrunc(builder.CreatePtrToInt(typeInfo, intPtrTy), i32Ty); + } + + // i1 __tslang_wasm_catches(ptr thrown, ptr clause): whether a catch clause of type_info `clause` + // takes an exception thrown with type_info `thrown`, as the C++ personality decides it for what + // tslang throws: the same type, or a pointer to a class and a pointer to one of its bases (a + // class is thrown as a pointer to it; TypeScript classes have one base, an + // __si_class_type_info's). + Function *catchesFunction = nullptr; + Function *getCatchesFunction() + { + if (catchesFunction) + { + return catchesFunction; + } + + auto *i1Ty = Type::getInt1Ty(C); + catchesFunction = Function::Create(FunctionType::get(i1Ty, {ptrTy, ptrTy}, false), GlobalValue::InternalLinkage, + "__tslang_wasm_catches", M); + auto *thrown = catchesFunction->getArg(0); + auto *clause = catchesFunction->getArg(1); + + auto pointerSize = M.getDataLayout().getPointerSize(); + // a type_info's vtable pointer points two pointers into its class's vtable + auto vtableOf = [&](StringRef name) -> Constant * { + auto *vtable = M.getOrInsertGlobal(name, ptrTy); + return ConstantExpr::getGetElementPtr(Type::getInt8Ty(C), vtable, + ConstantInt::get(intPtrTy, 2 * pointerSize)); + }; + auto *pointerTypeInfoVtable = vtableOf("_ZTVN10__cxxabiv119__pointer_type_infoE"); + auto *singleBaseTypeInfoVtable = vtableOf("_ZTVN10__cxxabiv120__si_class_type_infoE"); + // __pointer_type_info { vtable, name, i32 flags, pointee }; __si_class_type_info { vtable, name, base } + auto *pointerTypeInfoType = StructType::get(C, {ptrTy, ptrTy, i32Ty, ptrTy}); + auto pointeeOffset = M.getDataLayout().getStructLayout(pointerTypeInfoType)->getElementOffset(3); + + auto *entry = BasicBlock::Create(C, "entry", catchesFunction); + auto *pointers = BasicBlock::Create(C, "pointers", catchesFunction); + auto *walk = BasicBlock::Create(C, "walk", catchesFunction); + auto *next = BasicBlock::Create(C, "next", catchesFunction); + auto *base = BasicBlock::Create(C, "base", catchesFunction); + auto *yes = BasicBlock::Create(C, "yes", catchesFunction); + auto *no = BasicBlock::Create(C, "no", catchesFunction); + + IRBuilder<> b(entry); + auto *nullPtr = ConstantPointerNull::get(ptrTy); + auto *eitherNull = b.CreateOr(b.CreateICmpEQ(thrown, nullPtr), b.CreateICmpEQ(clause, nullPtr)); + auto *same = BasicBlock::Create(C, "same", catchesFunction, pointers); + b.CreateCondBr(eitherNull, no, same); + + b.SetInsertPoint(same); + auto *bothPointersCheck = BasicBlock::Create(C, "kinds", catchesFunction, pointers); + b.CreateCondBr(b.CreateICmpEQ(thrown, clause), yes, bothPointersCheck); + + b.SetInsertPoint(bothPointersCheck); + auto *thrownIsPointer = b.CreateICmpEQ(b.CreateLoad(ptrTy, thrown), pointerTypeInfoVtable); + auto *clauseIsPointer = b.CreateICmpEQ(b.CreateLoad(ptrTy, clause), pointerTypeInfoVtable); + b.CreateCondBr(b.CreateAnd(thrownIsPointer, clauseIsPointer), pointers, no); + + b.SetInsertPoint(pointers); + auto pointeeOf = [&](Value *typeInfo) { + return b.CreateLoad(ptrTy, b.CreateConstGEP1_64(Type::getInt8Ty(C), typeInfo, pointeeOffset)); + }; + auto *thrownClass = pointeeOf(thrown); + auto *clauseClass = pointeeOf(clause); + b.CreateBr(walk); + + b.SetInsertPoint(walk); + auto *current = b.CreatePHI(ptrTy, 2, "class"); + current->addIncoming(thrownClass, pointers); + b.CreateCondBr(b.CreateICmpEQ(current, clauseClass), yes, next); + + b.SetInsertPoint(next); + auto *hasBase = b.CreateAnd(b.CreateICmpNE(current, nullPtr), + b.CreateICmpEQ(b.CreateLoad(ptrTy, current), singleBaseTypeInfoVtable)); + b.CreateCondBr(hasBase, base, no); + + b.SetInsertPoint(base); + auto *baseClass = b.CreateLoad(ptrTy, b.CreateConstGEP1_64(Type::getInt8Ty(C), current, 2 * pointerSize)); + current->addIncoming(baseClass, base); + b.CreateBr(walk); + + b.SetInsertPoint(yes); + b.CreateRet(b.getTrue()); + b.SetInsertPoint(no); + b.CreateRet(b.getFalse()); + + return catchesFunction; + } + + // A clause of a pointer type (a string is a char *, a class instance is thrown as a pointer to + // it) that matches binds the pointer itself: the C++ runtime's __cxa_begin_catch returns the + // thrown pointer then, not the address of the thrown object, which it returns for any other + // clause and for a catch-all. The host's returns the object's address, always - it does not know + // which clause matched - so where a pointer clause did, the pointer is read from there. + void adjustPointerCatches(IRBuilder<> &builder, Instruction *padValue, Value *selector, ArrayRef typedClauses) + { + SmallVector pointerClauses; + for (auto *clause : typedClauses) + { + if (auto *global = dyn_cast(clause->stripPointerCasts()); global && global->getName().starts_with("_ZTIP")) + { + pointerClauses.push_back(clause); + } + } + + if (pointerClauses.empty()) + { + return; + } + + SmallVector beginCatches; + for (auto *user : padValue->users()) + { + auto *extract = dyn_cast(user); + if (!extract || extract->getNumIndices() != 1 || extract->getIndices()[0] != 0) + { + continue; + } + + for (auto *extractUser : extract->users()) + { + if (auto *call = dyn_cast(extractUser); + call && call->getCalledFunction() && call->getCalledFunction()->getName() == "__cxa_begin_catch") + { + beginCatches.push_back(call); + } + } + } + + for (auto *beginCatch : beginCatches) + { + builder.SetInsertPoint(beginCatch->getNextNode()); + Value *pointerMatched = builder.getFalse(); + for (auto *clause : pointerClauses) + { + pointerMatched = builder.CreateOr(pointerMatched, builder.CreateICmpEQ(selector, selectorOf(builder, clause))); + } + + auto *thrownPointer = builder.CreateLoad(ptrTy, beginCatch, "wasm.exn.pointer"); + auto *adjusted = builder.CreateSelect(pointerMatched, thrownPointer, beginCatch, "wasm.exn.adjusted"); + beginCatch->replaceUsesWithIf(adjusted, [&](Use &use) { + return use.getUser() != thrownPointer && use.getUser() != adjusted; + }); + } + } + + bool runOnFunction(Function &F) + { + SmallVector pads; + SmallVector resumes; + SmallVector typeIds; + for (auto &I : instructions(F)) + { + if (auto *landingPad = dyn_cast(&I)) + { + pads.push_back(landingPad); + } + else if (auto *resume = dyn_cast(&I)) + { + resumes.push_back(resume); + } + else if (auto *intrinsic = dyn_cast(&I); intrinsic && intrinsic->getIntrinsicID() == Intrinsic::eh_typeid_for) + { + typeIds.push_back(intrinsic); + } + } + + if (pads.empty() && resumes.empty() && typeIds.empty()) + { + return false; + } + + IRBuilder<> builder(C); + auto *getException = Intrinsic::getOrInsertDeclaration(&M, Intrinsic::wasm_get_exception); + auto *wasmThrow = Intrinsic::getOrInsertDeclaration(&M, Intrinsic::wasm_throw); + auto cppExceptionTag = builder.getInt32(0); + + auto rethrow = [&](Value *exception) { + builder.CreateCall(wasmThrow, {cppExceptionTag, exception}); + builder.CreateUnreachable(); + }; + + if (!pads.empty()) + { + F.setPersonalityFn(cast( + M.getOrInsertFunction(PERSONALITY_FUNC_NAME, FunctionType::get(i32Ty, /*isVarArg=*/true)).getCallee())); + } + + // the exception, from the catch to the code after it (the catch is a funclet of its own) + AllocaInst *exceptionSlot = nullptr; + if (!pads.empty()) + { + auto &entry = F.getEntryBlock(); + exceptionSlot = new AllocaInst(ptrTy, M.getDataLayout().getAllocaAddrSpace(), "wasm.exn", entry.getFirstInsertionPt()); + } + + for (auto *landingPad : pads) + { + auto *padBlock = landingPad->getParent(); + auto *dispatchBlock = BasicBlock::Create(C, "wasm.dispatch", &F, padBlock); + auto *catchBlock = BasicBlock::Create(C, "wasm.catch", &F, padBlock); + + for (auto *pred : SmallVector(predecessors(padBlock))) + { + auto *invoke = dyn_cast(pred->getTerminator()); + if (!invoke || invoke->getUnwindDest() != padBlock) + { + report_fatal_error(Twine("wasm exceptions: a landing pad in '") + F.getName() + + "' is reached other than by an invoke's unwind edge"); + } + + invoke->setUnwindDest(dispatchBlock); + } + + builder.SetInsertPoint(dispatchBlock); + auto *catchSwitch = builder.CreateCatchSwitch(ConstantTokenNone::get(C), nullptr, 1, "wasm.cs"); + catchSwitch->addHandler(catchBlock); + + // the pad's phis merge the invokes' values, which now come to the catchswitch + for (auto &phi : make_early_inc_range(padBlock->phis())) + { + phi.moveBefore(catchSwitch->getIterator()); + } + + builder.SetInsertPoint(catchBlock); + auto *catchPad = builder.CreateCatchPad(catchSwitch, {ConstantPointerNull::get(ptrTy)}, "wasm.cp"); + auto *exception = builder.CreateCall(getException, {catchPad}, "wasm.exn.value"); + builder.CreateStore(exception, exceptionSlot); + builder.CreateCatchRet(catchPad, padBlock); + + auto catchesAll = landingPad->isCleanup(); + SmallVector typedClauses; + for (unsigned i = 0, n = landingPad->getNumClauses(); i < n; i++) + { + auto *clause = landingPad->getClause(i); + if (landingPad->isFilter(i) || isa(clause->stripPointerCasts())) + { + catchesAll = true; + } + else + { + typedClauses.push_back(clause); + } + } + + builder.SetInsertPoint(landingPad); + auto *caught = builder.CreateLoad(ptrTy, exceptionSlot, "wasm.exn.caught"); + Value *selector = builder.getInt32(0); + if (!typedClauses.empty()) + { + // the selector of the first clause that takes the exception, as the personality + // picks it; 0 for none (a catch-all clause's, or none at all - see below) + auto exceptionTypeFunc = M.getOrInsertFunction(EXCEPTION_TYPE_FUNC_NAME, FunctionType::get(ptrTy, {ptrTy}, false)); + auto *thrownType = builder.CreateCall(exceptionTypeFunc, {caught}, "wasm.exn.type"); + for (auto *clause : llvm::reverse(typedClauses)) + { + auto *takes = builder.CreateCall(getCatchesFunction(), {thrownType, clause}); + selector = builder.CreateSelect(takes, selectorOf(builder, clause), selector); + } + } + + Value *value = PoisonValue::get(landingPad->getType()); + value = builder.CreateInsertValue(value, caught, 0); + auto *lastInsert = cast(builder.CreateInsertValue(value, selector, 1)); + landingPad->replaceAllUsesWith(lastInsert); + landingPad->eraseFromParent(); + + adjustPointerCatches(builder, lastInsert, selector, typedClauses); + + if (!catchesAll && !typedClauses.empty()) + { + // what the personality would have skipped goes on to the caller + builder.SetInsertPoint(lastInsert->getNextNode()); + auto *matchesInst = cast(builder.CreateICmpNE(selector, builder.getInt32(0), "wasm.matched")); + auto *matches = matchesInst; + auto *continueBlock = padBlock->splitBasicBlock(matchesInst->getNextNode(), "wasm.matched"); + auto *rethrowBlock = BasicBlock::Create(C, "wasm.unmatched", &F, continueBlock); + padBlock->getTerminator()->eraseFromParent(); + builder.SetInsertPoint(padBlock); + builder.CreateCondBr(matches, continueBlock, rethrowBlock); + builder.SetInsertPoint(rethrowBlock); + rethrow(caught); + } + } + + for (auto *resume : resumes) + { + builder.SetInsertPoint(resume); + auto *exception = builder.CreateExtractValue(resume->getValue(), 0); + rethrow(exception); + resume->eraseFromParent(); + } + + for (auto *typeId : typeIds) + { + builder.SetInsertPoint(typeId); + typeId->replaceAllUsesWith(selectorOf(builder, typeId->getArgOperand(0))); + typeId->eraseFromParent(); + } + + return true; + } + + bool run() + { + auto changed = false; + for (auto &F : make_early_inc_range(M)) + { + if (!F.isDeclaration() && &F != catchesFunction) + { + changed |= runOnFunction(F); + } + } + + // last: __tslang_wasm_catches refers to the type_info vtables + changed |= defineRuntimeTypeInfos(); + return changed; + } +}; + +} // namespace + +namespace ts +{ +llvm::PreservedAnalyses WasmExceptionPass::run(llvm::Module &M, llvm::ModuleAnalysisManager &AM) +{ + WasmExceptionPassCode code(M); + if (!code.run()) + { + return llvm::PreservedAnalyses::all(); + } + + return llvm::PreservedAnalyses::none(); +} +} // namespace ts diff --git a/tslang/tslang/obj.cpp b/tslang/tslang/obj.cpp index 083dd139a..8a3ea3cae 100644 --- a/tslang/tslang/obj.cpp +++ b/tslang/tslang/obj.cpp @@ -225,9 +225,23 @@ int setupTargetTriple(llvm::Module *llvmModule, std::unique_ptrsetPIELevel(llvm::PIELevel::Level::Large); } - auto CPUStr = llvm::codegen::getCPUStr(), + auto CPUStr = llvm::codegen::getCPUStr(), FeaturesStr = llvm::codegen::getFeaturesStr(); + // wasm (not Emscripten): try/catch is wasm exception handling - see WasmExceptionPass. The + // backend takes it from -wasm-enable-eh (which picks the wasm exception model), and the + // instructions from the exception-handling feature. + if (TheTriple.isWasm() && !TheTriple.isOSEmscripten()) + { + auto ®isteredOptions = llvm::cl::getRegisteredOptions(); + if (auto it = registeredOptions.find("wasm-enable-eh"); it != registeredOptions.end()) + { + static_cast *>(it->second)->setValue(true); + } + + FeaturesStr += FeaturesStr.empty() ? "+exception-handling" : ",+exception-handling"; + } + llvm::CodeGenOptLevel OLvl; // TODO: finish it, optimization // optimizing for size generates code as -O2 does, whatever the speed level: clang's -Os and -Oz @@ -243,7 +257,14 @@ int setupTargetTriple(llvm::Module *llvmModule, std::unique_ptr(TheTarget->createTargetMachine( + // before the target machine is made: its MCAsmInfo takes the exception model from here, and + // with none the code generator lowers every invoke to a call (see wasm-enable-eh above) + if (TheTriple.isWasm() && !TheTriple.isOSEmscripten()) + { + Options.ExceptionModel = llvm::ExceptionHandling::Wasm; + } + + Target =std::unique_ptr(TheTarget->createTargetMachine( TheTriple, CPUStr, FeaturesStr, Options, RM, CM, OLvl)); assert(Target && "Could not allocate target machine!"); diff --git a/tslang/tslang/opts.cpp b/tslang/tslang/opts.cpp index f296251b1..a58397783 100644 --- a/tslang/tslang/opts.cpp +++ b/tslang/tslang/opts.cpp @@ -60,6 +60,7 @@ CompileOptions prepareOptions() compileOptions.isWindows = TheTriple.isKnownWindowsMSVCEnvironment(); compileOptions.isAndroid = TheTriple.isAndroid(); compileOptions.isWasm = TheTriple.getArch() == llvm::Triple::wasm64 || TheTriple.getArch() == llvm::Triple::wasm32; + compileOptions.wasmExceptions = compileOptions.isWasm && !TheTriple.isOSEmscripten(); compileOptions.targetInfo = TargetInfo::fromTriple( TheTriple, llvm::Triple(llvm::sys::getDefaultTargetTriple())); compileOptions.isExecutable = emitAction == Action::BuildExe; diff --git a/tslang/tslang/transform.cpp b/tslang/tslang/transform.cpp index 14d1d527e..88a1a8f6e 100644 --- a/tslang/tslang/transform.cpp +++ b/tslang/tslang/transform.cpp @@ -13,6 +13,7 @@ #ifdef ENABLE_EXCEPTIONS #include "TypeScript/Pass/LandingPadFixPass.h" #include "TypeScript/Pass/Win32ExceptionPass.h" +#include "TypeScript/Pass/WasmExceptionPass.h" #include "TypeScript/Pass/CxxThrowCallingConvPass.h" #endif #include "TypeScript/Pass/ExportFixPass.h" @@ -1296,6 +1297,10 @@ std::function makeCustomPassesWithOptimizingTransfo { mpm.addPass(llvm::createModuleToFunctionPassAdaptor(ts::Win32ExceptionPass())); } + else if (compileOptions.wasmExceptions) + { + mpm.addPass(ts::WasmExceptionPass()); + } // After Win32ExceptionPass, which adds throw calls and turns calls into invokes, and // before the optimization pipeline, which treats a calling-convention mismatch as UB. From 370ba5a8ee8ff494ac828972cfdf5b21eaa7bbe9 Mon Sep 17 00:00:00 2001 From: ASDAlexander77 Date: Thu, 12 Nov 2026 00:16:20 +0000 Subject: [PATCH 2/2] wasm_skips.txt: tests that catch are run now Co-Authored-By: Claude Opus 5.5 --- docs/how/wasm/test/wasm_skips.txt | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/docs/how/wasm/test/wasm_skips.txt b/docs/how/wasm/test/wasm_skips.txt index 541fafb4f..f32e90878 100644 --- a/docs/how/wasm/test/wasm_skips.txt +++ b/docs/how/wasm/test/wasm_skips.txt @@ -1,6 +1,5 @@ # Tests run_tests.mjs does not run for wasm: ` [,...] # `, every leg -# when none is given. Tests that catch an exception and async tests are skipped without being -# listed here. +# when none is given. Async tests and tests that use threads are skipped without being listed here. # cannot work on wasm internals.ts # inline_asm with x86 instructions