Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 27 additions & 2 deletions tslang/lib/TypeScript/LowerToAffineLoops.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1500,11 +1500,17 @@ struct TryOpLowering : public TsPattern<mlir_ts::TryOp>
// - 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<Operation *> escapingOpsFinally;
auto finallyHasTry = false;
auto finallyMayThrow = false;
tryOp.getFinally().walk([&](Operation *op) {
finallyMayThrow |= unwindsToHandler(op);
if (isa<mlir_ts::ReturnOp, mlir_ts::ReturnValOp>(op) ||
(isa<mlir_ts::BreakOp, mlir_ts::ContinueOp>(op) && tsContext->jumps.contains(op)))
{
Expand Down Expand Up @@ -1634,22 +1640,41 @@ struct TryOpLowering : public TsPattern<mlir_ts::TryOp>
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<std::pair<Operation *, mlir::Block *>> 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;
Expand Down
80 changes: 80 additions & 0 deletions tslang/lib/TypeScript/MLIRGenCast.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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<mlir_ts::SymbolRefOp>();
auto inFuncType = dyn_cast<mlir_ts::FunctionType>(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<mlir_ts::VoidType>(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<mlir_ts::VoidType>(results.front());
auto entryOp = builder.create<mlir_ts::EntryOp>(
noLocation, hasResult ? mlir::Type(mlir_ts::RefType::get(results.front())) : mlir::Type());

auto callee = builder.create<mlir_ts::SymbolRefOp>(noLocation, inFuncType,
mlir::FlatSymbolRefAttr::get(builder.getContext(), calleeName));
auto callOp = builder.create<mlir_ts::CallIndirectOp>(noLocation, callee,
entryBlock.getArguments().take_front(inInputs.size()));
if (hasResult)
{
builder.create<mlir_ts::ReturnValOp>(noLocation, callOp.getResult(0), entryOp.getReference());
}

builder.create<mlir_ts::ExitOp>(noLocation, hasResult ? entryOp.getReference() : mlir::Value());

theModule.push_back(funcOp);
}

return builder.create<mlir_ts::SymbolRefOp>(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)) {
Expand Down Expand Up @@ -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);
Expand Down
2 changes: 2 additions & 0 deletions tslang/lib/TypeScript/MLIRGenImpl.h
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
6 changes: 6 additions & 0 deletions tslang/test/tester/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -737,6 +737,8 @@ 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-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")
Expand Down Expand Up @@ -1362,6 +1364,8 @@ 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-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")
Expand Down Expand Up @@ -2481,6 +2485,8 @@ set(TSLANG_CORPUS
00try_finally_funclet.ts
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
Expand Down
47 changes: 47 additions & 0 deletions tslang/test/tester/tests/00function_fewer_parameters.ts
Original file line number Diff line number Diff line change
@@ -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.");
}
65 changes: 65 additions & 0 deletions tslang/test/tester/tests/00try_finally_throws.ts
Original file line number Diff line number Diff line change
@@ -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.");
}
Loading