From baae9e00d4476524e6f5ab28f628dfe5679711de Mon Sep 17 00:00:00 2001 From: ASDAlexander77 Date: Thu, 29 Oct 2026 12:39:26 +0000 Subject: [PATCH 1/2] A finally that throws while an exception unwinds replaces it (Windows) On Windows the finally run on the way out of an exception was a cleanup funclet, which may not throw: a call or a throw there was a second exception during unwinding, and the process terminated. A finally that may throw is now entered through the catch-all pad a `return` in it already used, which rethrows at its end; thrown from it, an exception is a nested one, which replaces the first, as JavaScript's does. The copy of the finally on that path also lost its calls' unwind entries (cloneRegionBefore carried over jumps and parentTryOp only): a call there was a plain call, which in the funclet has no way out, and -O3 crashed on it. Its unwind entries, and the interface-field accesses of #732, are carried over now. Co-Authored-By: Claude Opus 5.5 --- tslang/lib/TypeScript/LowerToAffineLoops.cpp | 29 ++++++++- tslang/test/tester/CMakeLists.txt | 3 + .../test/tester/tests/00try_finally_throws.ts | 65 +++++++++++++++++++ 3 files changed, 95 insertions(+), 2 deletions(-) create mode 100644 tslang/test/tester/tests/00try_finally_throws.ts diff --git a/tslang/lib/TypeScript/LowerToAffineLoops.cpp b/tslang/lib/TypeScript/LowerToAffineLoops.cpp index 4e8cb80ba..ed8f0fde5 100644 --- a/tslang/lib/TypeScript/LowerToAffineLoops.cpp +++ b/tslang/lib/TypeScript/LowerToAffineLoops.cpp @@ -1500,11 +1500,17 @@ struct TryOpLowering : public TsPattern // - hold pads of its own (Windows): a try in the finally. LLVM numbers no EH state for a // pad in a cleanup funclet (the MSVC personality does not allow one), so an exception // thrown in that try was never caught there, and the process terminated. + // - throw (Windows): a call or a throw in a finally run while an exception unwinds is a second + // exception out of a cleanup funclet, which the MSVC personality takes for one thrown during + // unwinding, and terminates. Thrown from a catch it is a nested exception, which replaces the + // first, as JavaScript's does. // Such a finally is entered through a catch-all pad instead, which rethrows at its end // (see windowsFinallyCatches and linuxFinallyCatches). mlir::SmallVector escapingOpsFinally; auto finallyHasTry = false; + auto finallyMayThrow = false; tryOp.getFinally().walk([&](Operation *op) { + finallyMayThrow |= unwindsToHandler(op); if (isa(op) || (isa(op) && tsContext->jumps.contains(op))) { @@ -1634,22 +1640,41 @@ struct TryOpLowering : public TsPattern mlir::Block *exitBlockLast = nullptr; auto finallyPadId = 0; auto windowsFinallyCatches = - tsContext->compileOptions.isWindows && finallyHasOps && (!escapingOpsFinally.empty() || finallyHasTry); + tsContext->compileOptions.isWindows && finallyHasOps && (!escapingOpsFinally.empty() || finallyHasTry || finallyMayThrow); // with a try around it in the function the Itanium finally pad is a catch-all already auto linuxFinallyCatches = !tsContext->compileOptions.isWindows && finallyHasOps && !enclosingHandler && !escapingOpsFinally.empty(); if (finallyHasOps) { // cloneRegionBefore makes brand-new Operation* instances, so any tsContext - // side-table entry (jumps[], parentTryOp[]) keyed on the original finally + // side-table entry (jumps[], parentTryOp[], unwind[]) keyed on the original finally // region's ops -- populated by visitorTryOps above, or by an enclosing loop's // break/continue-scope walk that ran before this try was lowered -- would // silently be missing for the clones. Re-propagate those entries onto each // clone via the IRMapping so a nested try/break/continue inside `finally` // keeps correct wiring in all copies, not just the final inlined one. + // An enclosing try's handler, which a call or a throw in the finally unwinds to: without it a clone's + // call was a plain call, which in the funclet the exceptional copy runs in has no way out (optimized, + // WinEHPrepare took it for unreachable, and a throw in the finally crashed) auto propagateTsContextEntries = [&](const mlir::IRMapping &mapping) { + SmallVector> clonedAccessorUnwinds; + for (auto [accessorOp, unwindBlock] : tsFuncContext->accessorUnwinds) + { + if (auto *clone = mapping.lookupOrNull(accessorOp)) + { + clonedAccessorUnwinds.push_back({clone, unwindBlock}); + } + } + + tsFuncContext->accessorUnwinds.append(clonedAccessorUnwinds.begin(), clonedAccessorUnwinds.end()); + for (auto &[oldOp, newOp] : mapping.getOperationMap()) { + if (auto unwind = tsContext->unwind.lookup(oldOp)) + { + tsContext->unwind[newOp] = unwind; + } + if (auto jump = tsContext->jumps.lookup(oldOp)) { tsContext->jumps[newOp] = jump; diff --git a/tslang/test/tester/CMakeLists.txt b/tslang/test/tester/CMakeLists.txt index 2b21cc6c2..ed0f28483 100644 --- a/tslang/test/tester/CMakeLists.txt +++ b/tslang/test/tester/CMakeLists.txt @@ -737,6 +737,7 @@ tslang_add_test(NAME test-compile-00-catch-value-minimal COMMAND test-runner "${ tslang_add_test(NAME test-compile-01-try-catch COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/01try_catch.ts") tslang_add_test(NAME test-compile-00-try-catch-return COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00try_catch_return.ts") tslang_add_test(NAME test-compile-00-try-finally COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00try_finally.ts") +tslang_add_test(NAME test-compile-00-try-finally-throws COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00try_finally_throws.ts") tslang_add_test(NAME test-compile-01-try-finally COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/01try_finally.ts") tslang_add_test(NAME test-compile-00-try-finally-return COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00try_finally_return.ts") tslang_add_test(NAME test-compile-00-try-finally-funclet COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00try_finally_funclet.ts") @@ -1362,6 +1363,7 @@ tslang_add_test(NAME test-jit-00-catch-value-minimal COMMAND test-runner -jit "$ tslang_add_test(NAME test-jit-01-try-catch COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/01try_catch.ts") tslang_add_test(NAME test-jit-00-try-catch-return COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00try_catch_return.ts") tslang_add_test(NAME test-jit-00-try-finally COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00try_finally.ts") +tslang_add_test(NAME test-jit-00-try-finally-throws COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00try_finally_throws.ts") tslang_add_test(NAME test-jit-01-try-finally COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/01try_finally.ts") tslang_add_test(NAME test-jit-00-try-finally-return COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00try_finally_return.ts") tslang_add_test(NAME test-jit-00-try-finally-funclet COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00try_finally_funclet.ts") @@ -2481,6 +2483,7 @@ set(TSLANG_CORPUS 00try_finally_funclet.ts 00try_in_catch_with_finally.ts 00try_finally.ts + 00try_finally_throws.ts 00try_using_catch.ts 00tuple_named.ts 00tuple_with_array.ts diff --git a/tslang/test/tester/tests/00try_finally_throws.ts b/tslang/test/tester/tests/00try_finally_throws.ts new file mode 100644 index 000000000..11b140271 --- /dev/null +++ b/tslang/test/tester/tests/00try_finally_throws.ts @@ -0,0 +1,65 @@ +// A finally that throws while an exception unwinds replaces it, as in JavaScript. On Windows the finally run on +// the way out of an exception was a cleanup funclet, which may not throw: a second exception there terminated the +// process. A finally that may throw is now entered through a catch-all that rethrows at its end, and its calls +// unwind to the enclosing handler (the copy of the finally on that path had lost them, which -O3 turned into a +// crash). +function thrower(n: number) { + if (n > 0) { + throw n; + } +} + +function rethrowsOriginal() { + let ran = false; + let caught = 0.0; + try { + try { thrower(1); } finally { ran = true; thrower(0); } + } catch (e: number) { + caught = e; + } + + return ran && caught == 1; +} + +function main() { + let caught = 0.0; + try { + try { thrower(1); } finally { thrower(2); } + } catch (e: number) { + caught = e; + } + assert(caught == 2, "a call in the finally replaces the exception"); + + caught = 0; + try { + try { thrower(1); } finally { throw 3; } + } catch (e: number) { + caught = e; + } + assert(caught == 3, "a throw in the finally replaces it"); + + caught = 0; + try { + try { print("body"); } finally { thrower(4); } + } catch (e: number) { + caught = e; + } + assert(caught == 4, "a finally that throws on the normal path"); + + assert(rethrowsOriginal(), "a finally whose call does not throw rethrows the original"); + + let order = ""; + caught = 0; + try { + try { + try { thrower(1); } finally { order += "a"; thrower(5); } + } finally { + order += "b"; + } + } catch (e: number) { + caught = e; + } + assert(caught == 5 && order == "ab", "an outer finally runs on the new exception's way out"); + + print("done."); +} From 79cbfdff5b093bd417b3c64cedb5e88985210f4e Mon Sep 17 00:00:00 2001 From: ASDAlexander77 Date: Thu, 29 Oct 2026 12:50:46 +0000 Subject: [PATCH 2/2] A function with fewer parameters can be given as a wider function type `apply(one)` where `apply` takes `(a: number, b: number) => number` and `one` takes `a` only was an error ("it takes 1 argument(s), 2 expected"), though TypeScript lets a function ignore the parameters it does not declare. A named function or an arrow that captures nothing is now given as a private function of its own (`.args`) that takes them all and calls it with the first ones. No result and a `void` one count as the same. A closure is still an error: its wrapper would have to carry the captures. Co-Authored-By: Claude Opus 5.5 --- tslang/lib/TypeScript/MLIRGenCast.cpp | 80 +++++++++++++++++++ tslang/lib/TypeScript/MLIRGenImpl.h | 2 + tslang/test/tester/CMakeLists.txt | 3 + .../tests/00function_fewer_parameters.ts | 47 +++++++++++ 4 files changed, 132 insertions(+) create mode 100644 tslang/test/tester/tests/00function_fewer_parameters.ts diff --git a/tslang/lib/TypeScript/MLIRGenCast.cpp b/tslang/lib/TypeScript/MLIRGenCast.cpp index 639d909fd..bc160e1fe 100644 --- a/tslang/lib/TypeScript/MLIRGenCast.cpp +++ b/tslang/lib/TypeScript/MLIRGenCast.cpp @@ -2079,6 +2079,76 @@ namespace mlirgen } } + // A function taking fewer parameters than the function type it is given as (`apply(one)` where `apply` takes + // `(a: number, b: number) => number` and `one` takes `a` only): TypeScript lets it ignore the rest. A named + // function or an arrow that captures nothing is given as a function of its own that takes them all and calls + // it with the first ones - called with every argument the type says, it would read them where it does not + // expect them. Null where it is not that (a closure, a bound method, parameters or results that differ). + mlir::Value MLIRGenImpl::fewerParametersThunk(mlir::Location location, mlir::Value value, mlir::Type type) + { + auto symbolRefOp = value.getDefiningOp(); + auto inFuncType = dyn_cast(value.getType()); + auto resFuncType = mth.GetFunctionType(type); + if (!symbolRefOp || !inFuncType || !resFuncType || inFuncType.isVarArg() || inFuncType.isCVarArg() + || resFuncType.isVarArg() || resFuncType.isCVarArg()) + { + return mlir::Value(); + } + + // no result and a `void` one are the same (a declared `=> void` keeps its result) + auto isVoid = [](mlir::TypeRange results) { + return results.empty() || (results.size() == 1 && isa(results.front())); + }; + + auto inInputs = inFuncType.getInputs(); + auto resInputs = resFuncType.getInputs(); + auto sameResults = inFuncType.getResults() == resFuncType.getResults() + || (isVoid(inFuncType.getResults()) && isVoid(resFuncType.getResults())); + if (inInputs.size() >= resInputs.size() || !sameResults + || !llvm::equal(inInputs, resInputs.take_front(inInputs.size()))) + { + return mlir::Value(); + } + + auto calleeName = symbolRefOp.getIdentifier(); + auto thunkName = (calleeName + ".args" + std::to_string(resInputs.size())).str(); + auto thunkType = mlir_ts::FunctionType::get(builder.getContext(), resInputs, resFuncType.getResults(), false); + if (!theModule.lookupSymbol(thunkName)) + { + mlir::OpBuilder::InsertionGuard guard(builder); + + // compiler glue with no source to step through, as INSTANCEOF_NONE_NAME's + auto noLocation = mlir::UnknownLoc::get(builder.getContext()); + auto funcOp = mlir_ts::FuncOp::create(noLocation, thunkName, thunkType); + funcOp.setPrivate(); + funcOp->setAttr("internal_linkage", builder.getUnitAttr()); + + auto &entryBlock = *funcOp.addEntryBlock(); + builder.setInsertionPointToStart(&entryBlock); + + auto results = inFuncType.getResults(); + auto hasResult = !results.empty() && !isa(results.front()); + auto entryOp = builder.create( + noLocation, hasResult ? mlir::Type(mlir_ts::RefType::get(results.front())) : mlir::Type()); + + auto callee = builder.create(noLocation, inFuncType, + mlir::FlatSymbolRefAttr::get(builder.getContext(), calleeName)); + auto callOp = builder.create(noLocation, callee, + entryBlock.getArguments().take_front(inInputs.size())); + if (hasResult) + { + builder.create(noLocation, callOp.getResult(0), entryOp.getReference()); + } + + builder.create(noLocation, hasResult ? entryOp.getReference() : mlir::Value()); + + theModule.push_back(funcOp); + } + + return builder.create(location, thunkType, + mlir::FlatSymbolRefAttr::get(builder.getContext(), thunkName)); + } + mlir::LogicalResult MLIRGenImpl::verifyFunctionCastRules(mlir::Location location, mlir::Type type, mlir::Value &value, mlir::Type &valueType, const GenContext &genContext) { if (mth.isAnyFunctionType(valueType) && mth.isAnyFunctionType(type)) { @@ -2122,6 +2192,16 @@ namespace mlirgen { // test fun types auto test = mth.TestFunctionTypesMatchWithObjectMethods(location, valueType, type); + if (test.result == MatchResultType::NotMatchArgCount) + { + if (auto thunk = fewerParametersThunk(location, value, type)) + { + value = thunk; + valueType = thunk.getType(); + test = mth.TestFunctionTypesMatchWithObjectMethods(location, valueType, type); + } + } + if (test.result != MatchResultType::Match) { emitFunctionTypeMismatch(location, valueType, type, test); diff --git a/tslang/lib/TypeScript/MLIRGenImpl.h b/tslang/lib/TypeScript/MLIRGenImpl.h index 1099653c8..8f9613170 100644 --- a/tslang/lib/TypeScript/MLIRGenImpl.h +++ b/tslang/lib/TypeScript/MLIRGenImpl.h @@ -14623,6 +14623,8 @@ class MLIRGenImpl // reports which part of a function signature does not match the one it is assigned to void emitFunctionTypeMismatch(mlir::Location location, mlir::Type valueType, mlir::Type type, MatchResult match); + mlir::Value fewerParametersThunk(mlir::Location location, mlir::Value value, mlir::Type type); + // optional // TODO: it is in CastLogic as well, review usage and remove from here // but if optional points to interface then it will not work diff --git a/tslang/test/tester/CMakeLists.txt b/tslang/test/tester/CMakeLists.txt index ed0f28483..1874676cd 100644 --- a/tslang/test/tester/CMakeLists.txt +++ b/tslang/test/tester/CMakeLists.txt @@ -738,6 +738,7 @@ tslang_add_test(NAME test-compile-01-try-catch COMMAND test-runner "${PROJECT_SO tslang_add_test(NAME test-compile-00-try-catch-return COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00try_catch_return.ts") tslang_add_test(NAME test-compile-00-try-finally COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00try_finally.ts") tslang_add_test(NAME test-compile-00-try-finally-throws COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00try_finally_throws.ts") +tslang_add_test(NAME test-compile-00-function-fewer-parameters COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00function_fewer_parameters.ts") tslang_add_test(NAME test-compile-01-try-finally COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/01try_finally.ts") tslang_add_test(NAME test-compile-00-try-finally-return COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00try_finally_return.ts") tslang_add_test(NAME test-compile-00-try-finally-funclet COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/00try_finally_funclet.ts") @@ -1364,6 +1365,7 @@ tslang_add_test(NAME test-jit-01-try-catch COMMAND test-runner -jit "${PROJECT_S tslang_add_test(NAME test-jit-00-try-catch-return COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00try_catch_return.ts") tslang_add_test(NAME test-jit-00-try-finally COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00try_finally.ts") tslang_add_test(NAME test-jit-00-try-finally-throws COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00try_finally_throws.ts") +tslang_add_test(NAME test-jit-00-function-fewer-parameters COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00function_fewer_parameters.ts") tslang_add_test(NAME test-jit-01-try-finally COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/01try_finally.ts") tslang_add_test(NAME test-jit-00-try-finally-return COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00try_finally_return.ts") tslang_add_test(NAME test-jit-00-try-finally-funclet COMMAND test-runner -jit "${PROJECT_SOURCE_DIR}/test/tester/tests/00try_finally_funclet.ts") @@ -2484,6 +2486,7 @@ set(TSLANG_CORPUS 00try_in_catch_with_finally.ts 00try_finally.ts 00try_finally_throws.ts + 00function_fewer_parameters.ts 00try_using_catch.ts 00tuple_named.ts 00tuple_with_array.ts diff --git a/tslang/test/tester/tests/00function_fewer_parameters.ts b/tslang/test/tester/tests/00function_fewer_parameters.ts new file mode 100644 index 000000000..9a5e78bb3 --- /dev/null +++ b/tslang/test/tester/tests/00function_fewer_parameters.ts @@ -0,0 +1,47 @@ +// A function taking fewer parameters than the function type it is given as ignores the rest, as TypeScript lets +// it: a named function or an arrow that captures nothing is given as a function that takes them all and calls +// it with the first ones. It was an error, "it takes 1 argument(s), 2 expected". +type Visit = (name: string, index: number) => void; + +function each(names: string[], visit: Visit) { + for (let i = 0; i < names.length; i++) { + visit(names[i], i); + } +} + +function apply(f: (a: number, b: number) => number) { + return f(2, 3); +} + +let seen = ""; +function onlyName(name: string) { seen += name; } +function nothing() { seen += "."; } +function twice(a: number): number { return a * 2; } +function seven(): number { return 7; } + +class Holder { + constructor(public cb: (a: number, b: number) => number) {} + run() { return this.cb(4, 5); } +} + +function main() { + assert(apply(twice) == 4, "one of two parameters"); + assert(apply(seven) == 7, "none of two"); + assert(apply((a) => a + 1) == 3, "an arrow with fewer parameters"); + + each(["a", "b"], onlyName); + each(["c"], nothing); + assert(seen == "ab.", "a void callback, a string parameter"); + + // the same function given twice is one wrapper + each(["d"], onlyName); + assert(seen == "ab.d", "again"); + + const h = new Holder(twice); + assert(h.run() == 8, "kept in a field"); + + const f: (a: number, b: number) => number = (a) => a * 10; + assert(f(1, 2) == 10, "assigned to a variable"); + + print("done."); +}