From 7d762cd22f4855f8397296b99563b49ec93a3201 Mon Sep 17 00:00:00 2001 From: ASDAlexander77 Date: Sat, 14 Nov 2026 00:59:39 +0000 Subject: [PATCH 1/5] own: a use after an escaping capture is an error; (() => T) | null; boolean assignment errors - -mm=own: an object a `const` names, captured by copy by a closure that escapes, is the closure's from the capture on; a later use is "captured by a closure that escapes, and is still used here". A closure stored once into a field of the object it captures is a back-reference and borrows it. - `(() => T) | null` fields and locals: the closure is the function value itself. - Assigning a boolean to a number or a string, or a number to a boolean, is an error, as in tsc. The CMake registrations and the shared ownership-facts helpers these use are in the next commit. Co-Authored-By: Claude Opus 5.5 --- .../TypeScript/LowerToLLVM/CastLogicHelper.h | 7 + .../LowerToLLVM/UnaryBinLogicalOrHelper.h | 14 ++ tslang/lib/TypeScript/MLIRGenCast.cpp | 9 ++ tslang/lib/TypeScript/MLIRGenExpressions.cpp | 14 +- .../TypeScript/OwnershipInferenceClosures.cpp | 73 +++++++++ .../lib/TypeScript/OwnershipInferencePass.h | 7 + .../tests/00closure_back_reference_local.ts | 67 +++++++++ .../test/tester/tests/00function_or_null.ts | 140 ++++++++++++++++++ .../tester/tests/00tslang_issues_31_33.ts | 3 +- .../tests/argument_boolean_to_number_error.ts | 10 ++ .../tests/assign_boolean_to_number_error.ts | 8 + .../tests/assign_boolean_to_string_error.ts | 7 + .../tests/assign_number_to_boolean_error.ts | 8 + .../own_escaping_capture_used_after_error.ts | 30 ++++ 14 files changed, 395 insertions(+), 2 deletions(-) create mode 100644 tslang/test/tester/tests/00closure_back_reference_local.ts create mode 100644 tslang/test/tester/tests/00function_or_null.ts create mode 100644 tslang/test/tester/tests/argument_boolean_to_number_error.ts create mode 100644 tslang/test/tester/tests/assign_boolean_to_number_error.ts create mode 100644 tslang/test/tester/tests/assign_boolean_to_string_error.ts create mode 100644 tslang/test/tester/tests/assign_number_to_boolean_error.ts create mode 100644 tslang/test/tester/tests/own_escaping_capture_used_after_error.ts diff --git a/tslang/include/TypeScript/LowerToLLVM/CastLogicHelper.h b/tslang/include/TypeScript/LowerToLLVM/CastLogicHelper.h index e3f03929e..6fac01b98 100644 --- a/tslang/include/TypeScript/LowerToLLVM/CastLogicHelper.h +++ b/tslang/include/TypeScript/LowerToLLVM/CastLogicHelper.h @@ -622,6 +622,13 @@ class CastLogicHelper if (!needTag) { auto llvmBoolType = tch.convertType(boolType); + // `(() => void) | null` is the function's own value, and a function is true when + // it has code to run (GetMethodOp below): that op takes a function, not the union + if (isa(baseType) && isa(in.getType())) + { + in = rewriter.create(loc, baseType, in); + } + auto valAsBool = cast(in, baseType, tch.convertType(baseType), boolType, llvmBoolType); return valAsBool; } diff --git a/tslang/include/TypeScript/LowerToLLVM/UnaryBinLogicalOrHelper.h b/tslang/include/TypeScript/LowerToLLVM/UnaryBinLogicalOrHelper.h index 857687926..3332a8738 100644 --- a/tslang/include/TypeScript/LowerToLLVM/UnaryBinLogicalOrHelper.h +++ b/tslang/include/TypeScript/LowerToLLVM/UnaryBinLogicalOrHelper.h @@ -365,6 +365,20 @@ mlir::Value LogicOp(Operation *binOp, SyntaxKind op, mlir::Value left, mlir::Typ auto value = builder.create(loc, v1, leftPtrValue, rightPtrValue); return value; } + // a function value compared with null (`f !== null` of a `(() => void) | null`, which is the + // function's own value): it is null when it has no code to run. Without it the comparison fell + // to the "not applicable" warning at the bottom and was constant false + else if (isa(leftType) + && (right.getDefiningOp() || right.getDefiningOp() || matchPattern(right, m_Zero()))) + { + auto llvmFuncType = typeConverter.convertType(leftType); + mlir::Value llvmFunc = left.getType() == llvmFuncType + ? left + : builder.create(loc, llvmFuncType, left).getResult(); + auto codePointer = builder.create(loc, llvmFunc, ArrayRef{DATA_VALUE_INDEX}); + auto zero = builder.create(loc, codePointer.getType()); + return builder.create(loc, v1, codePointer, zero); + } else if (auto unionType = dyn_cast(leftType)) { ::typescript::MLIRTypeHelper mth(builder.getContext(), compileOptions); diff --git a/tslang/lib/TypeScript/MLIRGenCast.cpp b/tslang/lib/TypeScript/MLIRGenCast.cpp index f41a9bea6..dea46c2d5 100644 --- a/tslang/lib/TypeScript/MLIRGenCast.cpp +++ b/tslang/lib/TypeScript/MLIRGenCast.cpp @@ -2715,6 +2715,15 @@ namespace mlirgen // it does not match, instead of naming the whole union if (auto unionType = dyn_cast(type)) { + // `(() => number) | null` has no tag: it is the function's own value, null an empty + // one, as `C | null` is the class's pointer. A function of that type is stored as it is + // (castToNullableUnionType has made one of any other) + mlir::Type baseType; + if (!mth.isUnionTypeNeedsTag(location, unionType, baseType) && baseType == valueType) + { + return mlir::success(); + } + for (auto memberType : unionType.getTypes()) { if (!mth.isAnyFunctionType(memberType)) diff --git a/tslang/lib/TypeScript/MLIRGenExpressions.cpp b/tslang/lib/TypeScript/MLIRGenExpressions.cpp index 9aaad48f7..ac865d8ce 100644 --- a/tslang/lib/TypeScript/MLIRGenExpressions.cpp +++ b/tslang/lib/TypeScript/MLIRGenExpressions.cpp @@ -1274,8 +1274,20 @@ namespace mlirgen LLVM_DEBUG(llvm::dbgs() << "\n!! evaluate function: " << funcResult << "\n";); + // `(() => void) | null` has no tag: it is the function's own value (isUnionTypeNeedsTag), as + // `C | null` is the class's pointer, and is called as that function - a field `this.f` read + // again after `if (this.f)` is the union still + if (auto funcUnionType = dyn_cast(funcResult.getType())) + { + mlir::Type baseType; + if (!mth.isUnionTypeNeedsTag(location, funcUnionType, baseType) && baseType && mth.isAnyFunctionType(baseType)) + { + funcResult = builder.create(location, baseType, funcResult); + } + } + auto funcType = funcResult.getType(); - if (!mth.isAnyFunctionType(funcType) + if (!mth.isAnyFunctionType(funcType) && !mth.isBuiltinFunctionType(funcResult) // TODO: do I need to use ConstructFunction instead? // to support constructor calls diff --git a/tslang/lib/TypeScript/OwnershipInferenceClosures.cpp b/tslang/lib/TypeScript/OwnershipInferenceClosures.cpp index 4d75774cd..7cfb7fc3d 100644 --- a/tslang/lib/TypeScript/OwnershipInferenceClosures.cpp +++ b/tslang/lib/TypeScript/OwnershipInferenceClosures.cpp @@ -118,6 +118,12 @@ namespace own_inference })); if (!closure->borrowsCopies) { + // what a closure that escapes took a copy of is the closure's: nothing uses it after + if (closure->escape) + { + checkEscapingCopies(*closure); + } + if (!closure->escape && closure->aliased) { closures.push_back(std::move(closure)); @@ -1399,6 +1405,12 @@ namespace own_inference } }; + // what a closure that escapes took a copy of is the closure's: nothing uses it after + if (closure->escape && !checkEscapingCopies(*closure)) + { + continue; + } + if (!closure->hasCells && !closure->borrowsCopies) { keepAliasedReleases(); @@ -1646,6 +1658,67 @@ namespace own_inference toErase.insert(closure.retains.begin(), closure.retains.end()); } + bool OwnershipInferencePass::checkEscapingCopies(Closure &closure) + { + if (closure.borrowsValues || closure.borrowsCopies) + { + return true; + } + + for (auto &fill : closure.fills) + { + auto value = fill.second.getValue(); + mlir::Operation *move = fill.second; + if (mlir::isa(value.getType())) + { + continue; // a cell: decideEscaping + } + + auto root = rootOf(value); + if (holdsNoBlock(value) || !ownsHeap(root) || isHandle(root) || isConstantData(root) || + isImmortalGlobalRead(root) || isKeptForGood(root)) + { + continue; + } + + mlir::Operation *usedAfter = nullptr; + if (auto slotLoad = slotLoadOf(root)) + { + // a `let`: every later read of it, until it is given a new value + auto slot = slotLoad.getReference(); + auto assignments = slotAssignments(slot); + llvm::SmallVector kills(assignments.begin(), assignments.end()); + for (auto *user : slot.getUsers()) + { + if (!usedAfter && user != slotLoad.getOperation() && mlir::isa(user) && + reachableAfter(move, user, kills)) + { + usedAfter = user; + } + } + } + else if (isFresh(root)) + { + forEachUse(root, [&](mlir::Operation *user, mlir::Value) { + auto isUse = user != move && !llvm::is_contained(closure.retains, user) && + !mlir::isa(user); + if (!usedAfter && isUse && reachableAfter(move, user, root.getDefiningOp())) + { + usedAfter = user; + } + }); + } + + if (usedAfter) + { + reportUsedAfterEscapingCapture(usedAfter, move, ownerName(root)); + return false; + } + } + + return true; + } + void OwnershipInferencePass::decideCells() { getFunction().walk([&](mlir_ts::VariableOp varOp) { diff --git a/tslang/lib/TypeScript/OwnershipInferencePass.h b/tslang/lib/TypeScript/OwnershipInferencePass.h index 7d8e1086c..3beda949b 100644 --- a/tslang/lib/TypeScript/OwnershipInferencePass.h +++ b/tslang/lib/TypeScript/OwnershipInferencePass.h @@ -376,6 +376,13 @@ class OwnershipInferencePass // nothing to move. And nothing may call through the box once the closure has gone. void decideEscaping(Closure &closure, llvm::SetVector &toErase); + // A closure that escapes owns what it took a copy of as well: the object a `const` names moves + // into its box, which gives it back when the closure goes (`c.onTick = null`). A use of the + // object after the capture read it freed once the closure was gone, so it is an error, as a use + // of a captured variable is. False, with the error reported, when something uses a copy's + // object after the closure took it. + bool checkEscapingCopies(Closure &closure); + // A captured variable whose value this function does not own - a parameter, `this` - has a cell // that borrows the value: the cell's release frees the cell only (OWN_CELL_BORROWS_ATTR_NAME), // and nothing may assign the variable, here or in a closure over it, since the old value is the diff --git a/tslang/test/tester/tests/00closure_back_reference_local.ts b/tslang/test/tester/tests/00closure_back_reference_local.ts new file mode 100644 index 000000000..a5c3048c6 --- /dev/null +++ b/tslang/test/tester/tests/00closure_back_reference_local.ts @@ -0,0 +1,67 @@ +// A closure stored into a field of the object it captures: `c.onTick = () => { c.seen++ }`. Under +// -mm=own the closure's box owned `c`, which owned the closure, and clearing the field freed `c` +// itself. The box borrows the object, as one that captures `this` in a method does: the field owns +// the closure and the object bounds it. + +class Counter { + onTick: ((n: number) => void) | null = null; + onDone: (n: number) => void = (n: number) => {}; + count = 0; + seen = 0; + + tick() { + this.count++; + if (this.onTick !== null) { + this.onTick(this.count); + } + + this.onDone(this.count); + } +} + +function testNullableField() { + const c = new Counter(); + c.onTick = (n: number) => { + c.seen += n; + }; + c.tick(); + assert(c.seen == 1); + c.onTick = null; + c.tick(); + assert(c.seen == 1); + assert(c.count == 2); +} + +function testPlainField() { + const c = new Counter(); + c.onDone = (n: number) => { + c.seen += n; + }; + c.tick(); + c.tick(); + assert(c.seen == 3); + c.onDone = (n: number) => {}; + c.tick(); + assert(c.seen == 3); + assert(c.count == 3); +} + +function testReplaced() { + const c = new Counter(); + for (let i = 0; i < 100; i++) { + c.onTick = (n: number) => { + c.seen += n; + }; + c.tick(); + } + + assert(c.count == 100); + assert(c.seen == 5050); +} + +function main() { + testNullableField(); + testPlainField(); + testReplaced(); + print("done."); +} diff --git a/tslang/test/tester/tests/00function_or_null.ts b/tslang/test/tester/tests/00function_or_null.ts new file mode 100644 index 000000000..37236004d --- /dev/null +++ b/tslang/test/tester/tests/00function_or_null.ts @@ -0,0 +1,140 @@ +// `(() => T) | null`: a function or null. It has no tag - it is the function's own value, null when +// it has no code to run. A function could not be stored in one ("invalid cast from () => number to +// () => number | null"), `if (f)` did not narrow it and `f()` was "not a function to call". + +class Holder { + f: (() => number) | null = null; + g: (() => number) | undefined = undefined; + h?: () => number; + + set(t: () => number) { + this.f = t; + } + + run(): number { + if (this.f) { + return this.f(); + } + + return -1; + } +} + +class Sink { + seen = 0; +} + +let seenTotal = 0; + +class Counter { + onTick: ((n: number) => void) | null = null; + count = 0; + + tick() { + this.count++; + if (this.onTick !== null) { + this.onTick(this.count); + } + } +} + +function run(f: (() => string) | null): string { + if (!f) { + return "none"; + } + + return f(); +} + +function testField() { + const h = new Holder(); + assert(h.run() == -1); + h.set((): number => 42); + assert(h.run() == 42); + + h.f = (): number => 1; + h.g = (): number => 2; + h.h = (): number => 3; + if (h.f) assert(h.f() == 1); + if (h.g) assert(h.g() == 2); + if (h.h) assert(h.h() == 3); + + h.f = null; + assert(h.run() == -1); +} + +function testLocal() { + let f: (() => number) | null = null; + assert(!f); + assert(f === null); + const t = (): number => 42; + f = t; + assert(f !== null); + if (f) { + assert(f() == 42); + } else { + assert(false); + } + + f = null; + assert((f ? "set" : "null") == "null"); +} + +function testCompare() { + // the closure keeps another object: one that captured the counter it is stored in would own + // its own owner + const c = new Counter(); + const sink = new Sink(); + c.tick(); + c.onTick = (n: number) => { + sink.seen += n; + seenTotal += sink.seen; + }; + c.tick(); + c.tick(); + assert(seenTotal == 7); + c.onTick = null; + c.tick(); + assert(seenTotal == 7); + assert(c.count == 4); +} + +// null adds no field: the union is as wide as the function value, which holds its code and what it +// runs with (a closure's captures, a method's `this`) +function testLayout() { + const plain = (): number => 1; + let fn: () => number = plain; + let fnOrNull: (() => number) | null = plain; + assert(sizeof(fnOrNull) == sizeof(fn)); + assert(fn() == 1); + + const first = "first"; + const second = "second"; + let capturing: () => string = () => first; + let capturingOrNull: (() => string) | null = () => second; + assert(sizeof(capturingOrNull) == sizeof(capturing)); + assert(capturing() == "first"); + if (capturingOrNull) { + assert(capturingOrNull() == "second"); + } else { + assert(false); + } + + capturingOrNull = null; + assert(capturingOrNull === null); +} + +function testParameter() { + const name = "captured"; + assert(run(null) == "none"); + assert(run(() => name) == "captured"); +} + +function main() { + testField(); + testLocal(); + testCompare(); + testLayout(); + testParameter(); + print("done."); +} diff --git a/tslang/test/tester/tests/00tslang_issues_31_33.ts b/tslang/test/tester/tests/00tslang_issues_31_33.ts index 4d646f160..7f98727ff 100644 --- a/tslang/test/tester/tests/00tslang_issues_31_33.ts +++ b/tslang/test/tester/tests/00tslang_issues_31_33.ts @@ -141,7 +141,8 @@ function resultsKept() { arrow.runInTry(); churn(); assert(arrow.get().value == 42); - assert(captured.value == 1); + // `captured` is the closure's from the capture on: under -mm=own a use of it here is an error + // (own_escaping_capture_used_after_error.ts) // one nobody keeps is given back for (let i = 0; i < 1000; i++) { diff --git a/tslang/test/tester/tests/argument_boolean_to_number_error.ts b/tslang/test/tester/tests/argument_boolean_to_number_error.ts new file mode 100644 index 000000000..1315800af --- /dev/null +++ b/tslang/test/tester/tests/argument_boolean_to_number_error.ts @@ -0,0 +1,10 @@ +// a boolean given for a number parameter is an error (TS2345) +function twice(n: number): number { + return n * 2; +} + +function main() { + const flag: boolean = true; + print(twice(flag)); + print("done."); +} diff --git a/tslang/test/tester/tests/assign_boolean_to_number_error.ts b/tslang/test/tester/tests/assign_boolean_to_number_error.ts new file mode 100644 index 000000000..e7801dfbf --- /dev/null +++ b/tslang/test/tester/tests/assign_boolean_to_number_error.ts @@ -0,0 +1,8 @@ +// a boolean given to a number is an error (TS2322): converted, `n = flag` made n 1 +function main() { + let n: number = 1; + const flag: boolean = true; + n = flag; + print(n); + print("done."); +} diff --git a/tslang/test/tester/tests/assign_boolean_to_string_error.ts b/tslang/test/tester/tests/assign_boolean_to_string_error.ts new file mode 100644 index 000000000..81ae10baa --- /dev/null +++ b/tslang/test/tester/tests/assign_boolean_to_string_error.ts @@ -0,0 +1,7 @@ +// a boolean given to a string is an error (TS2322): converted, `s = flag` made s "true" +function main() { + const flag: boolean = true; + let s: string = flag; + print(s); + print("done."); +} diff --git a/tslang/test/tester/tests/assign_number_to_boolean_error.ts b/tslang/test/tester/tests/assign_number_to_boolean_error.ts new file mode 100644 index 000000000..3e67ef11b --- /dev/null +++ b/tslang/test/tester/tests/assign_number_to_boolean_error.ts @@ -0,0 +1,8 @@ +// a number given to a boolean is an error (TS2322): converted, `flag = 5` made flag true +function main() { + let flag: boolean = false; + const n: number = 5; + flag = n; + print(flag); + print("done."); +} diff --git a/tslang/test/tester/tests/own_escaping_capture_used_after_error.ts b/tslang/test/tester/tests/own_escaping_capture_used_after_error.ts new file mode 100644 index 000000000..0e2ae2a5e --- /dev/null +++ b/tslang/test/tester/tests/own_escaping_capture_used_after_error.ts @@ -0,0 +1,30 @@ +// -mm=own: a closure that escapes owns the object it captured, and gives it back when the closure +// goes (`c.onTick = null`). A use of the object after the capture read it freed: an error. + +class Counter { + onTick: ((n: number) => void) | null = null; + count = 0; + + tick() { + this.count++; + if (this.onTick !== null) { + this.onTick(this.count); + } + } +} + +class Sink { + seen = 0; +} + +function main() { + const c = new Counter(); + const s = new Sink(); + c.onTick = (n: number) => { + s.seen += n; + }; + c.tick(); + c.onTick = null; + print(s.seen); + print("done."); +} From 4d12236a55281a767eb914e522e124188def17f2 Mon Sep 17 00:00:00 2001 From: ASDAlexander77 Date: Sat, 14 Nov 2026 00:59:51 +0000 Subject: [PATCH 2/5] own: a lazily cached field returned through a local; @final methods (TSLANG 47, 48) TSLANG 47 (-mm=own): `let r = this.cached; if (!r) { r = new Q(); this.cached = r; } return r;` - Before the facts, a read of a local where it provably holds what a field holds is read as the field (OwnershipSignatureFieldLocals.cpp): a local declared from the field, or given a value just moved into it. The local's first value, read by nothing then, is dropped. - A store into a field tested empty on the way (`!f`, `f == null`, `f === undefined`, the else of `if (f)`) frees nothing (fillsEmptyField). The signature pass decides each fill once, judging a call in between by facts that count every fill as a drop, and pins it on the release. - Diagnostics name a folded const under --di; "another variable" is gone. TSLANG 48: a method can be @final. It can't be overridden or be abstract, a call of it runs it (directly, or through the vtable with the one callee known when imported), and the -shared declaration printer writes it. Under own, a borrow ended by a call of an overridable method gets a note naming the method and pointing at @final. Also: dropsInBody's `!releasesNothing(r) && a || b` counted a store into a number field as a drop. Item 49 (three reduced own errors from powder_sandbox) is filed open in TSLANG_ISSUES.md. Co-Authored-By: Claude Opus 5.5 --- TSLANG_ISSUES.md | 75 +++ docs/own-memory-model.md | 8 +- .../TypeScript/MLIRLogic/MLIRGenStore.h | 2 + tslang/lib/TypeScript/CMakeLists.txt | 1 + tslang/lib/TypeScript/DeclarationPrinter.cpp | 8 + tslang/lib/TypeScript/MLIRGenImpl.h | 70 +- tslang/lib/TypeScript/OwnershipFacts.h | 452 ++++++++++++- .../OwnershipInferenceDiagnostics.cpp | 20 +- .../OwnershipInferenceKeptParams.cpp | 2 +- .../lib/TypeScript/OwnershipInferencePass.cpp | 4 +- .../OwnershipSignatureFieldLocals.cpp | 606 ++++++++++++++++++ .../lib/TypeScript/OwnershipSignaturePass.cpp | 107 +++- .../lib/TypeScript/OwnershipSignaturePass.h | 25 +- tslang/test/tester/CMakeLists.txt | 63 +- .../tester/own/own_err_fill_after_call.ts | 22 + .../own/own_err_fill_after_fill_call.ts | 29 + .../test/tester/own/own_err_fill_in_loop.ts | 24 + .../tester/own/own_err_fill_other_field.ts | 21 + .../tester/own/own_err_overridable_call.ts | 22 + .../test/tester/own/own_final_method_lib.ts | 8 + .../test/tester/own/own_final_method_main.ts | 11 + tslang/test/tester/own/own_lazy_cache_lib.ts | 24 + tslang/test/tester/own/own_lazy_cache_main.ts | 11 + tslang/test/tester/tests/00tslang_issue_47.ts | 134 ++++ tslang/test/tester/tests/00tslang_issue_48.ts | 43 ++ .../tests/final_method_abstract_error.ts | 6 + .../tests/final_method_override_error.ts | 10 + tslang/test/tester/verify-ownership.cmake | 9 + 28 files changed, 1783 insertions(+), 34 deletions(-) create mode 100644 tslang/lib/TypeScript/OwnershipSignatureFieldLocals.cpp create mode 100644 tslang/test/tester/own/own_err_fill_after_call.ts create mode 100644 tslang/test/tester/own/own_err_fill_after_fill_call.ts create mode 100644 tslang/test/tester/own/own_err_fill_in_loop.ts create mode 100644 tslang/test/tester/own/own_err_fill_other_field.ts create mode 100644 tslang/test/tester/own/own_err_overridable_call.ts create mode 100644 tslang/test/tester/own/own_final_method_lib.ts create mode 100644 tslang/test/tester/own/own_final_method_main.ts create mode 100644 tslang/test/tester/own/own_lazy_cache_lib.ts create mode 100644 tslang/test/tester/own/own_lazy_cache_main.ts create mode 100644 tslang/test/tester/tests/00tslang_issue_47.ts create mode 100644 tslang/test/tester/tests/00tslang_issue_48.ts create mode 100644 tslang/test/tester/tests/final_method_abstract_error.ts create mode 100644 tslang/test/tester/tests/final_method_override_error.ts diff --git a/TSLANG_ISSUES.md b/TSLANG_ISSUES.md index fd1d74686..3330aa82f 100644 --- a/TSLANG_ISSUES.md +++ b/TSLANG_ISSUES.md @@ -142,3 +142,78 @@ the call, `x instanceof A` of the borrowed union was refused ("borrows ... and c was of a field read (`const x = this.f; x instanceof A`) before: the object seen as an opaque pointer, whose vtable is read for its class's `.instanceOf`, is a test that keeps nothing, as for an owned value. Regression test `tslang/test/tester/tests/00tslang_issue_46.ts`, JIT and compiled, under every model. + +Items 47 and 48, found on 2026-11-13 porting powder_sandbox and native_ts_graphics to `-mm=own`, are +fixed. 47 (a lazily cached field could not be returned through a local: `let result = this.cached; if +(!result) { result = new Q(1); this.cached = result; } return result;` was refused three ways): two +changes. First, before the facts, a read of a local where it holds what a field holds is read as the +field. That is a `let` or a `const` declared from the field and not assigned since, or a local given a +value that was just moved into the field. So `return result` is `return this.cached`, a borrow of +`this`, and the local's first value, read by nothing now, is dropped. The check-then-return form +(`const hit = this.cached; if (hit) return hit; ... return result;`) and `r = n` after +`this.cached = n` work the same. Second, a store into a field that was tested empty on the way (`!f`, +`f == null`, `f === undefined`, or the else branch of `if (f)`, reading the field or such a local) frees +nothing. A method whose only overwrites are such fills drops nothing, so a second `d.getQ()` no longer +ends the borrow the first one returned, and `main` prints `1 1 true`. A loop between the test and the +store, a test of another field, or a call in between that may write the field leaves the store a drop. +A call in between is judged by facts that count every fill as a drop, since a method that only fills +may still fill this field. An exported method still says what it returns (`@lends("this")`), and +an importer calling it twice needs it `@final` (48). The diagnostics name the variable now: a folded +`const` by its debug name under `--di`, and "while another read of it still borrows it" where no local +does. Regression tests `tslang/test/tester/tests/00tslang_issue_47.ts` (every model), +`own/own_lazy_cache_main.ts` with `own_lazy_cache_lib.ts` (an exported class in a namespace, imported, +every model), and `own/own_err_fill_after_call.ts`, `own_err_fill_in_loop.ts`, `own_err_fill_other_field.ts`, +`own_err_fill_after_fill_call.ts`. + +48 (in an exported class that isn't `@final`, any `this.method()` may overwrite any field): a method can +be `@final` now, as a class can. No subclass may override it ("method 'x' overrides the @final method of +'Base'"), and it cannot be abstract. A call of it runs that method: directly when its class is defined in +the module, through the vtable with the one callee known when it is imported. The `-shared` declaration +printer writes `@final`, so an importer knows it too. Under `-mm=own` the call goes by the method's own +facts: `this.factor()` reading a number drops nothing, and a borrow of `this.items[1]` held across it +compiles. The error for a borrow ended by such a call has a note: "'Base.factor' may be overridden in +another module by a method that does; '@final' on the method, or on its class, says it is not". Also +fixed: the store into a field whose type holds no block was still counted a drop when the body was +checked for drops (`!releasesNothing(...) && a || b` read as `(... && a) || b`). Regression tests +`tslang/test/tester/tests/00tslang_issue_48.ts` (every model), `own/own_final_method_main.ts` with +`own_final_method_lib.ts` (a `@final` method of an imported class), `own/own_err_overridable_call.ts`, +`tests/final_method_override_error.ts` and `final_method_abstract_error.ts`. + +Still open from 48: +- Whole-program facts: a method that no module of the program overrides is still taken as overridable + when its class is exported. `--own-facts` reads the facts of the modules a module imports, not of the + ones that import it, so the base's module can't know its subclasses. `@final` is the way to say it. +- `@final` on an accessor (`get`/`set`) is accepted but changes nothing at the call site yet. +- The other errors seen in powder_sandbox's own build are item 49. The one in `levels.ts`, `'x' is + moved inside a loop but was made outside it` (the same `box` array kept by several `LevelStroke`s), + is the game's to fix. + +### 49. `-mm=own`: a nullable fresh local stored into a field, and a field moved into another + +Reduced on 2026-11-14 by the powder_sandbox session from the errors left in its own build. All three +fail on alpha127 and on the branch with the 47/48 fixes (`tslang -mm=own --emit=obj r1.ts`): + +```ts +class Level { name: string = "a"; } +export class App { + level: Level | null = null; + read(n: string): Level | null { return n == "" ? null : new Level(); } + // 6:58 "moved here on some paths only" + "takes a second reference" + startA(n: string) { const l = this.read(n); if (l) { this.level = l; } } + // 8:49 "takes a second reference": unconditional store of a nullable fresh local + startB(n: string) { const l = this.read(n); this.level = l; } + other: Level | null = null; + // 11:19 "borrows a field and cannot be stored": moving one field into another (a swap works) + moveAside() { this.other = this.level; this.level = null; } +} +function main() { const a = new App(); a.startA("x"); a.startB("x"); a.moveAside(); print(a.other != null); } +``` + +- `startA`: the store moves `l` on the path where it is not null. On the other path `l` is null and + holds nothing to release, so moving it on some paths only should be fine. +- `startB` compiles when `App` is `@final`, so the second reference likely comes from the call to + `this.read` going through the vtable. +- `moveAside`: a field read stored into another field, with the source cleared right after, is a move + of the field's value, as `[a, b] = [b, a]` already is. + +Worked around in powder_sandbox with the exchange `[l, this.level] = [this.level, l]`. diff --git a/docs/own-memory-model.md b/docs/own-memory-model.md index a427caec7..3ffb4c8a1 100644 --- a/docs/own-memory-model.md +++ b/docs/own-memory-model.md @@ -25,7 +25,7 @@ about it, and `Shared` gives opt-in shared ownership. - [`@borrows`](#borrows) - the arguments a generator borrows - [`@immortalizes`](#immortalizes) - the parameters a function keeps for good - [`@nodrops`](#nodrops) - a C function that frees nothing - - [`@final`](#final) - a class nobody extends + - [`@final`](#final) - a class nobody extends, a method nobody overrides - [`@value`](#value) - a type that is copied, not shared - [Separate compilation](#separate-compilation) - [Code for one memory model](#code-for-one-memory-model) @@ -704,11 +704,17 @@ m8_virtual_err.ts:11:16: error: 'this value' borrows a field but is used here af m8_virtual_err.ts:11:38: note: it may be released or overwritten here return `${this.color} area=${this.area()}`; ^ +m8_virtual_err.ts:11:38: note: 'S.area' may be overridden in another module by a method that does; '@final' on the method, or on its class, says it is not ``` With `@final export class S` it compiles and prints `red area=4`. Mark exported classes `@final` unless another module has to extend them. +A class that other modules extend can mark single methods instead: `@final area()` may not be +overridden (a subclass that does is an error, and an abstract method can't be `@final`), so a call +of it runs that method, and `-mm=own` goes by what its body does. That holds for a class imported +from another module too: the declaration it is imported by says `@final`. + ### `@value` `@value class C` and `@value interface R`: a type whose values are copied, like numbers, not diff --git a/tslang/include/TypeScript/MLIRLogic/MLIRGenStore.h b/tslang/include/TypeScript/MLIRLogic/MLIRGenStore.h index 5a4ca6f7a..684c774aa 100644 --- a/tslang/include/TypeScript/MLIRLogic/MLIRGenStore.h +++ b/tslang/include/TypeScript/MLIRLogic/MLIRGenStore.h @@ -174,6 +174,8 @@ struct MethodInfo int cppSlot = -1; // @destructor: the C++ virtual destructor of a @cpp class, which can't be called bool isCppDestructor = false; + // @final: no subclass may override it, so a call of it runs this very method (TSLANG 48) + bool isFinal = false; // a slot of a @cpp class's vtable that no method names (ClassInfo::getVirtualTable) bool isCppSlotGap = false; // `@keeps`, `@borrows`, `@lends` (OWN_DECLARED_KEEPS_ATTR_NAME): argument indices, `this` 0, for diff --git a/tslang/lib/TypeScript/CMakeLists.txt b/tslang/lib/TypeScript/CMakeLists.txt index 02ffb8cda..076eb5593 100644 --- a/tslang/lib/TypeScript/CMakeLists.txt +++ b/tslang/lib/TypeScript/CMakeLists.txt @@ -47,6 +47,7 @@ add_mlir_dialect_library(MLIRTypeScript OwnershipSignaturePass.cpp OwnershipSignatureCallbacks.cpp OwnershipSignatureClosedWorld.cpp + OwnershipSignatureFieldLocals.cpp OwnershipSignatureGenerators.cpp OwnershipSignatureGlobals.cpp OwnershipSignatureInterfaces.cpp diff --git a/tslang/lib/TypeScript/DeclarationPrinter.cpp b/tslang/lib/TypeScript/DeclarationPrinter.cpp index 6858f750c..2c1b5f5d1 100644 --- a/tslang/lib/TypeScript/DeclarationPrinter.cpp +++ b/tslang/lib/TypeScript/DeclarationPrinter.cpp @@ -798,6 +798,14 @@ namespace typescript } } + // no override: the importer's calls of it run it (TSLANG 48) + if (method.isFinal && !method.isStatic) + { + os.indent(4); + os << "@" FINAL_DECORATOR; + newline(); + } + os.indent(4); if (method.accessLevel == mlir_ts::AccessLevel::Protected) diff --git a/tslang/lib/TypeScript/MLIRGenImpl.h b/tslang/lib/TypeScript/MLIRGenImpl.h index 6de6893ef..28b3c4947 100644 --- a/tslang/lib/TypeScript/MLIRGenImpl.h +++ b/tslang/lib/TypeScript/MLIRGenImpl.h @@ -3219,13 +3219,14 @@ class MLIRGenImpl return std::make_tuple(type, init, typeProvided); } - // a string, or a number of any width, as TypeScript sees it: what a value of each converts to - // silently is a type error there, and here + // a string, a number of any width or a boolean, as TypeScript sees it: what a value of each + // converts to silently is a type error there, and here enum class StringOrNumber { Neither, String, - Number + Number, + Boolean }; StringOrNumber stringOrNumber(mlir::Type type) @@ -3251,6 +3252,12 @@ class MLIRGenImpl return StringOrNumber::Number; } + // a `boolean`, not an `i1`: that one is a one-bit integer, given a number as a C `bool` is + if (isa(type)) + { + return StringOrNumber::Boolean; + } + return StringOrNumber::Neither; } @@ -3263,7 +3270,8 @@ class MLIRGenImpl [](auto &entry) { return entry.getKey().starts_with("TGenParam_"); }); } - // a string given where a number is wanted, or a number where a string is (checkStringNumberAssignment) + // a string given where a number is wanted, a number where a string is, or a boolean and either of + // them (checkStringNumberAssignment) bool isStringNumberMismatch(mlir::Type valueType, mlir::Type destType, const GenContext &genContext) { auto from = stringOrNumber(valueType); @@ -3275,7 +3283,8 @@ class MLIRGenImpl } // `x = "1"` with `x: number`, `let s: string = 5`: TypeScript rejects them (TS2322). Converted, - // they hid a mistake - "x" became 0. A union, `any` or an enum on either side is left to the cast. + // they hid a mistake - "x" became 0. So does `n = flag` with `n: number` (it became 1) and + // `flag = 5`. A union, `any` or an enum on either side is left to the cast. mlir::LogicalResult checkStringNumberAssignment(mlir::Location location, mlir::Type valueType, mlir::Type destType, const GenContext &genContext) { @@ -4905,14 +4914,15 @@ class MLIRGenImpl // which has none, an array holding null in its own pointer. What is truthy is not null, as // after `x !== null`; what is not may be null or a falsy value (0, ""), so only the branch // where it is truthy is narrowed - the then branch of `if (x)`, the else of `if (!x)`. - // Without the array case `if (a) a[0]` of a `string[] | null` indexed the union. (A - // `Shared | null` is a counted handle, which own reads through the variable itself.) + // Without the array case `if (a) a[0]` of a `string[] | null` indexed the union, and without + // the function case `if (f) f()` of a `(() => void) | null` called it ("not a function to + // call"). (A `Shared | null` is a counted handle, which own reads through the variable itself.) if (auto unionType = dyn_cast_or_null(exprEval)) { auto isNull = [](mlir::Type member) { return isa(member); }; mlir::Type baseType; auto arrayOrNull = llvm::all_of(unionType.getTypes(), [&](mlir::Type member) { - return isNull(member) || isa(member); + return isNull(member) || isa(member) || mth.isAnyFunctionType(member); }); if ((mth.isUnionTypeNeedsTag(loc(exprVal), unionType, baseType) || arrayOrNull) && llvm::any_of(unionType.getTypes(), isNull)) @@ -9503,6 +9513,8 @@ class MLIRGenImpl LLVM_DEBUG(llvm::dbgs() << "\n!! method index access: " << methodIndex << "\n";); auto methodInfo = classInfo->methods[methodIndex]; + // a @final method is the one every object that has it runs, whatever its class (TSLANG 48) + finalReceiver = finalReceiver || methodInfo.isFinal; if (accessingFromLevel < methodInfo.accessLevel) { emitError(location, "Class member '") << methodInfo.name << "' is not accessable"; return mlir::Value(); @@ -14508,6 +14520,7 @@ class MLIRGenImpl isForceVirtual |= !isConstructor && !newClassPtr->isValue; #endif isVirtual = isForceVirtual; + isFinal = !isConstructor && MLIRHelper::hasDecorator(classMember, FINAL_DECORATOR); }; bool isFunctionLike() @@ -14545,6 +14558,23 @@ class MLIRGenImpl { auto &methodInfos = newClassPtr->methods; + // @final (TSLANG 48): a method no subclass overrides, which an abstract one cannot be + if (isFinal && isAbstract) + { + emitError(location) << "method '" << methodName << "' cannot be both abstract and @" FINAL_DECORATOR; + return false; + } + + if (!isStatic) + { + if (auto finalOwner = finalMethodOwner(newClassPtr, methodName)) + { + emitError(location) << "method '" << methodName << "' overrides the @" FINAL_DECORATOR " method of '" + << finalOwner->name << "'"; + return false; + } + } + auto methodIndex = newClassPtr->getMethodIndex(methodName); auto dllNameAttr = funcOp ? funcOp->getAttrOfType(DLL_NAME) : mlir::StringAttr(); auto dllName = dllNameAttr ? dllNameAttr.getValue().str() : std::string(); @@ -14565,11 +14595,13 @@ class MLIRGenImpl }); methodInfos.back().cppSlot = cppSlot; methodInfos.back().isCppDestructor = isCppDestructor; + methodInfos.back().isFinal = isFinal; } else { methodInfos[methodIndex].orderWeight = orderWeight; methodInfos[methodIndex].accessLevel = accessLevel; + methodInfos[methodIndex].isFinal = isFinal; if (newClassPtr->isCppVTable) { methodInfos[methodIndex].cppSlot = cppSlot; @@ -14741,6 +14773,28 @@ class MLIRGenImpl // @slot(N) of a method of a @cpp class (MethodInfo::cppSlot) int cppSlot = -1; bool isCppDestructor = false; + // @final (TSLANG 48) + bool isFinal = false; + + // The base class, up the chain, whose method of this name is @final, if any + static ClassInfo::TypePtr finalMethodOwner(ClassInfo::TypePtr classInfo, mlir::StringRef name) + { + for (auto &base : classInfo->baseClasses) + { + auto index = base->getMethodIndex(name); + if (index >= 0 && base->methods[index].isFinal && !base->methods[index].isStatic) + { + return base; + } + + if (auto owner = finalMethodOwner(base, name)) + { + return owner; + } + } + + return nullptr; + } mlir_ts::FuncOp funcOp; }; diff --git a/tslang/lib/TypeScript/OwnershipFacts.h b/tslang/lib/TypeScript/OwnershipFacts.h index d5953fede..2dbcde646 100644 --- a/tslang/lib/TypeScript/OwnershipFacts.h +++ b/tslang/lib/TypeScript/OwnershipFacts.h @@ -5,6 +5,7 @@ #include "TypeScript/Defines.h" #include "TypeScript/MLIRLogic/MLIRTypeHelper.h" +#include "mlir/Dialect/ControlFlow/IR/ControlFlowOps.h" #include "mlir/Interfaces/ControlFlowInterfaces.h" #include "llvm/ADT/DenseMap.h" @@ -68,6 +69,12 @@ namespace mlir_ts = mlir::typescript; // through an interface), -1 for an element - judged as those stores would be if they were the // caller's own (OwnershipInferencePass::overwritesChain). #define OWN_DROP_FIELDS_ATTR_NAME "__own_drop_fields" +// A virtual call that may destroy anything only because another module may override the method it +// names (TSLANG 48): the method's symbol, for the error that a borrow ends there +#define OWN_OVERRIDABLE_CALL_ATTR_NAME "__own_overridable_call" +// On a `ts.ReleaseSlot` of a field: a fill of the field, tested empty on the way (fillsEmptyField, +// TSLANG 47), which frees nothing. The signature pass decides it, with what calls in between may write. +#define OWN_FILL_ATTR_NAME "__own_fill" // The position a place reached through an interface is given: its position in the object is not // known (spec 28) constexpr int64_t OWN_INTERFACE_FIELD_POSITION = -3; @@ -386,8 +393,11 @@ inline bool isView(mlir::Operation *op) // a string or an array widened to a union that holds it as it is (`string | null`), or narrowed // back from one whose other members are only null or undefined. A union with other members can // convert on the way out (a number printed into a string), and an array of another element type - // is a new array. - auto isStringOrArray = [](mlir::Type type) { return mlir::isa(type); }; + // is a new array. A closure likewise: `(() => void) | null` is the function value itself, null + // when it has no code to run. + auto isStringOrArray = [&](mlir::Type type) { + return mlir::isa(type) || isClosure(type); + }; auto in = castOp.getIn().getType(); auto out = castOp.getType(); auto isNullableView = (isStringOrArray(in) && holdsAsIs(out, in, false)) || @@ -1031,6 +1041,390 @@ inline bool releasesNothing(mlir_ts::ReleaseSlotOp releaseSlotOp) return refType && !ownsHeap(releaseSlotOp.getLoc(), refType.getElementType()); } +// ---- Fills (TSLANG 47) ---- +// +// A lazy cache is filled only when it is empty: `if (!this.cached) this.cached = new Q()`. The store's +// release of the old value then frees nothing, so a call of the method destroys nothing a caller +// borrows, and a borrow of the cache taken before the call still reads the same object after it. + +// Does a value of this type that tests falsy hold no block? An object, an array or an interface is +// truthy whenever it is there; a string is not (`""`), nor anything else that may be falsy and own one. +inline bool falsyHoldsNoBlock(mlir::Location location, mlir::Type type) +{ + if (!ownsHeap(location, type)) + { + return true; + } + + if (auto optionalType = mlir::dyn_cast(type)) + { + return falsyHoldsNoBlock(location, optionalType.getElementType()); + } + + if (auto unionType = mlir::dyn_cast(type)) + { + return llvm::all_of(unionType.getTypes(), [&](mlir::Type member) { return falsyHoldsNoBlock(location, member); }); + } + + return mlir::isa(type); +} + +// The cond_br that ends `block`'s one predecessor, when `block` is one of its two ways and not both: +// the condition (seen through its `ts.DialectCast` to i1), and whether `block` is the way taken when +// it holds. Null otherwise. +inline std::pair branchInto(mlir::Block *block) +{ + auto *predecessor = block->getSinglePredecessor(); + auto condBrOp = predecessor ? mlir::dyn_cast(predecessor->getTerminator()) : mlir::cf::CondBranchOp(); + if (!condBrOp || condBrOp.getTrueDest() == condBrOp.getFalseDest()) + { + return {}; + } + + mlir::Value condition = condBrOp.getCondition(); + if (auto castOp = condition.getDefiningOp()) + { + condition = castOp->getOperand(0); + } + + return {condition, condBrOp.getTrueDest() == block}; +} + +// The value a truthiness test reads, when it tests falsy and falsy means it holds no block: `HasValue(v)`, +// `v`, `Value(v)`, and MLIRGen's `HasValue(v) ? Value(v) : false` lowered to +// a merge whose `false` comes only from the way `HasValue(v)` did not take. Null otherwise. +inline mlir::Value truthinessOf(mlir::Value test, int depth = 0) +{ + mlir::Value tested; + if (auto hasValueOp = test.getDefiningOp()) + { + tested = hasValueOp.getIn(); + } + else if (auto castOp = test.getDefiningOp()) + { + tested = castOp.getIn(); + if (auto valueOp = tested.getDefiningOp()) + { + tested = valueOp.getIn(); + } + } + else if (auto argument = mlir::dyn_cast(test); argument && depth < 2) + { + auto *block = argument.getOwner(); + if (block->isEntryBlock()) + { + return {}; + } + + for (auto *predecessor : block->getPredecessors()) + { + auto brOp = mlir::dyn_cast(predecessor->getTerminator()); + if (!brOp) + { + return {}; + } + + auto passed = brOp.getDestOperands()[argument.getArgNumber()]; + mlir::Value from; + if (passed.getDefiningOp()) + { + // false, on the way HasValue(v) did not take + auto [condition, holds] = branchInto(predecessor); + auto hasValueOp = condition ? condition.getDefiningOp() : mlir_ts::HasValueOp(); + if (!hasValueOp || holds) + { + return {}; + } + + from = hasValueOp.getIn(); + } + else + { + from = truthinessOf(passed, depth + 1); + } + + if (!from || (tested && tested != from)) + { + return {}; + } + + tested = from; + } + } + + if (!tested || !falsyHoldsNoBlock(tested.getLoc(), tested.getType())) + { + return {}; + } + + return tested; +} + +// The value `condition` tests to be empty when it is `holds` (the way taken when it is true, or +// false): `!v`, `v == null`, `v === undefined` when true; `v`, `v != null`, `v !== undefined` when +// false. Null when it proves nothing. +inline mlir::Value testedEmpty(mlir::Value condition, bool holds) +{ + auto isNullish = [](mlir::Value value) { + return mlir::isa(value.getType()) && + mlir::isa_and_nonnull(value.getDefiningOp()); + }; + + if (auto unaryOp = condition.getDefiningOp(); + unaryOp && unaryOp.getOpCode() == static_cast(SyntaxKind::ExclamationToken)) + { + return testedEmpty(unaryOp.getOperand1(), !holds); + } + + if (auto binaryOp = condition.getDefiningOp()) + { + auto opCode = static_cast(binaryOp.getOpCode()); + auto equals = opCode == SyntaxKind::EqualsEqualsToken || opCode == SyntaxKind::EqualsEqualsEqualsToken; + auto differs = opCode == SyntaxKind::ExclamationEqualsToken || opCode == SyntaxKind::ExclamationEqualsEqualsToken; + if ((equals && holds) || (differs && !holds)) + { + if (isNullish(binaryOp.getOperand2())) + { + return binaryOp.getOperand1(); + } + + if (isNullish(binaryOp.getOperand1())) + { + return binaryOp.getOperand2(); + } + } + + return {}; + } + + return holds ? mlir::Value() : truthinessOf(condition); +} + +inline bool isUnassignedSlot(mlir::Value slot); + +// Is `object` the same object `other` is: the same value, or read out of the same local or +// parameter that nothing assigns or captures (`this`, read again for each `this.f`)? +inline bool sameObject(mlir::Value object, mlir::Value other) +{ + if (object == other) + { + return true; + } + + auto loadOp = object.getDefiningOp(); + auto otherLoadOp = other.getDefiningOp(); + return loadOp && otherLoadOp && loadOp.getReference() == otherLoadOp.getReference() && + isUnassignedSlot(loadOp.getReference()); +} + +// A local or a parameter that nothing assigns or captures: every read of it is the same value. +inline bool isUnassignedSlot(mlir::Value slot) +{ + auto *def = slot.getDefiningOp(); + if (auto varOp = mlir::dyn_cast_or_null(def); !(varOp && !varOp.getCaptured().value_or(false))) + { + auto paramOp = mlir::dyn_cast_or_null(def); + if (!paramOp || paramOp.getCaptured().value_or(false)) + { + return false; + } + } + + return llvm::none_of(slot.getUsers(), [&](mlir::Operation *user) { + auto storeOp = mlir::dyn_cast(user); + return (storeOp && storeOp.getReference() == slot) || mlir::isa(user); + }); +} + +// Is `field` the same field of the same object as `other`? +inline bool sameField(mlir_ts::PropertyRefOp field, mlir_ts::PropertyRefOp other) +{ + return field.getPosition() == other.getPosition() && field.getType() == other.getType() && + sameObject(field.getObjectRef(), other.getObjectRef()); +} + +// May `op`, or anything in its regions, write `field` (or the local `local`, when given)? An overwrite +// of a field at its position and of its type, of a place that may be any field (an interface's), a +// delete, a call `callMayWrite` does not clear, or a point where other code runs (a generator's +// state switch, an await). +inline bool mayWriteField(mlir::Operation *op, mlir_ts::PropertyRefOp field, mlir::Value local, + llvm::function_ref callMayWrite) +{ + auto writesPlace = [&](mlir::Value ref) { + if (local && ref == local) + { + return true; + } + + if (auto propertyRefOp = ref.getDefiningOp()) + { + return propertyRefOp.getPosition() == field.getPosition() && propertyRefOp.getType() == field.getType(); + } + + // a local, a parameter, a global or an element is never a field of an object + return !mlir::isa_and_nonnull( + ref.getDefiningOp()); + }; + + auto writes = false; + op->walk([&](mlir::Operation *inner) { + if (auto storeOp = mlir::dyn_cast(inner)) + { + writes = writesPlace(storeOp.getReference()); + } + else if (auto releaseSlotOp = mlir::dyn_cast(inner)) + { + writes = writesPlace(releaseSlotOp.getSlot()); + } + else if (auto swapOp = mlir::dyn_cast(inner)) + { + writes = writesPlace(swapOp.getFirst()) || writesPlace(swapOp.getSecond()); + } + else if (isCall(inner)) + { + writes = callMayWrite(inner); + } + else + { + writes = mlir::isa(inner) || + inner->getDialect() == nullptr || inner->getDialect()->getNamespace() == "async"; + } + + return writes ? mlir::WalkResult::interrupt() : mlir::WalkResult::advance(); + }); + + return writes; +} + +// Is this release of a field's old value a fill (TSLANG 47): the field was tested empty on the way +// here, and nothing that may write it ran since? The test reads the field itself, or a `let` or +// `const` declared from it that nothing assigns before the test (`let r = this.cached; if (!r) {...}`), +// in the block that reads the field. Every way to the release comes from that block, through no +// loop that skips it, and nothing on those ways may write the field. `callMayWrite` answers for +// each call on the way. +inline bool fillsEmptyField(mlir_ts::ReleaseSlotOp releaseSlotOp, llvm::function_ref callMayWrite) +{ + auto field = releaseSlotOp.getSlot().getDefiningOp(); + auto *block = releaseSlotOp->getBlock(); + if (!field || field->getParentRegion() != releaseSlotOp->getParentRegion()) + { + return false; + } + + // the branch that proves the field empty: on the way into the release's block, or into a block + // that is the only way to it + mlir_ts::LoadOp testOp; + llvm::SmallPtrSet chain; + for (auto *on = block; on && !testOp && chain.insert(on).second; on = on->getSinglePredecessor()) + { + auto [condition, holds] = branchInto(on); + if (!condition) + { + continue; + } + + auto tested = testedEmpty(condition, holds); + testOp = tested ? tested.getDefiningOp() : mlir_ts::LoadOp(); + } + + if (!testOp || testOp->getParentRegion() != releaseSlotOp->getParentRegion()) + { + return false; + } + + // what the test reads holds the field's value: the field, or a local declared from it in its block + mlir::Operation *fieldRead = testOp; + mlir::Value local; + if (auto propertyRefOp = testOp.getReference().getDefiningOp()) + { + if (!sameField(propertyRefOp, field)) + { + return false; + } + } + else if (auto varOp = testOp.getReference().getDefiningOp(); + varOp && !varOp.getCaptured().value_or(false) && varOp.getInitializer()) + { + auto initOp = varOp.getInitializer().getDefiningOp(); + auto initField = initOp ? initOp.getReference().getDefiningOp() : mlir_ts::PropertyRefOp(); + if (!initField || !sameField(initField, field) || initOp->getBlock() != testOp->getBlock() || + varOp->getBlock() != testOp->getBlock() || !initOp->isBeforeInBlock(varOp) || !varOp->isBeforeInBlock(testOp)) + { + return false; + } + + fieldRead = initOp; + local = varOp.getResult(); + } + else + { + return false; + } + + auto *start = fieldRead->getBlock(); + if (start == block) + { + return false; // the test branches away from its own block + } + + // the blocks on the ways from the read to the release: every way into them comes from the read's + // block, and none comes round to the release's block again + llvm::SmallPtrSet between; + llvm::SmallVector work(block->getPredecessors().begin(), block->getPredecessors().end()); + if (work.empty()) + { + return false; + } + + while (!work.empty()) + { + auto *on = work.pop_back_val(); + if (on == block || (on != start && on->isEntryBlock())) + { + return false; + } + + if (on == start || !between.insert(on).second) + { + continue; + } + + work.append(on->getPredecessors().begin(), on->getPredecessors().end()); + } + + // nothing on those ways writes the field, nor the local before the test + for (auto *op = fieldRead->getNextNode(); op; op = op->getNextNode()) + { + auto beforeTest = op->isBeforeInBlock(testOp); + if (mayWriteField(op, field, beforeTest ? local : mlir::Value(), callMayWrite)) + { + return false; + } + } + + for (auto *on : between) + { + for (auto &op : *on) + { + if (mayWriteField(&op, field, mlir::Value(), callMayWrite)) + { + return false; + } + } + } + + for (auto *op = &block->front(); op != releaseSlotOp.getOperation(); op = op->getNextNode()) + { + if (mayWriteField(op, field, mlir::Value(), callMayWrite)) + { + return false; + } + } + + return true; +} + // Holds no block: a number, `null` or `undefined` widened, an empty optional, a string literal. // Also a view of a value whose type owns none: a union's number payload made into another union // (`GetValueFromUnion`, then `CreateUnionInstance`) is a number all the way. A `value_ref` is not @@ -1230,10 +1624,15 @@ inline bool isConstantData(mlir::Value value) return true; } - // a function, which a `ts.SymbolRef` names, seen as a function value: it has no capture box - if (auto castOp = mlir::dyn_cast(def); castOp && castOp.getIn().getDefiningOp()) + // a function, which a `ts.SymbolRef` names, seen as a function value: it has no capture box. + // Seen through its views too - that function value given as a `(() => void) | null` + if (auto castOp = mlir::dyn_cast(def)) { - return true; + auto functionCastOp = rootOf(value).getDefiningOp(); + if (functionCastOp && functionCastOp.getIn().getDefiningOp()) + { + return true; + } } // a field of such data: of a `ts.Constant`, or of a tuple of literals re-made as a named one @@ -1537,10 +1936,36 @@ inline bool isFieldOfMemberThis(mlir::Value ref) return isMemberThis(object); } +// A field of the object `object` is: of the object itself, or of a base class's storage in it +inline bool isFieldOfObject(mlir::Value ref, mlir::Value object) +{ + auto propertyRefOp = ref.getDefiningOp(); + if (!propertyRefOp || !object) + { + return false; + } + + auto base = propertyRefOp->getOperand(0); + while (auto baseRefOp = base.getDefiningOp()) + { + auto refType = mlir::dyn_cast(baseRefOp.getType()); + if (!refType || !mlir::isa(refType.getElementType())) + { + return false; + } + + base = baseRefOp->getOperand(0); + } + + return rootOf(base) == object; +} + // A back-reference's box (spec 70): it holds the member's `this` and nothing else that owns a block, // and the closure over it is stored once, into a field of that `this`; anything else done with the // closure is a call through it, a view of it, or a count of it. The box borrows the object: the // field owns the closure, and the object bounds it. +// The same of an object a `const` of this function names, made here: `c.onTick = () => { c.seen++ }`. +// Owned by its box, `c` was owned by a closure it owned itself, and clearing the field freed it. inline bool isBackReferenceBox(mlir::Value box) { auto boundOp = closureOfBox(box); @@ -1550,6 +1975,8 @@ inline bool isBackReferenceBox(mlir::Value box) } auto holdsThis = false; + // the object made here that the box holds, when it is not the member's `this` + mlir::Value object; for (auto *user : box.getUsers()) { if (user == boundOp.getOperation() || mlir::isa(user)) @@ -1577,14 +2004,20 @@ inline bool isBackReferenceBox(mlir::Value box) } else if (!holdsNoBlock(storeOp.getValue())) { - return false; + auto held = rootOf(storeOp.getValue()); + if (!mlir::isa(held.getType()) || !isFresh(held) || (object && object != held)) + { + return false; + } + + object = held; } } } - if (!holdsThis) + if (holdsThis == static_cast(object)) { - return false; + return false; // neither, or both: the box would borrow one and own the other } auto stores = 0; @@ -1600,7 +2033,8 @@ inline bool isBackReferenceBox(mlir::Value box) } if (auto storeOp = mlir::dyn_cast(user); - storeOp && storeOp.getValue() == value && isFieldOfMemberThis(storeOp.getReference())) + storeOp && storeOp.getValue() == value && + (holdsThis ? isFieldOfMemberThis(storeOp.getReference()) : isFieldOfObject(storeOp.getReference(), object))) { ++stores; continue; diff --git a/tslang/lib/TypeScript/OwnershipInferenceDiagnostics.cpp b/tslang/lib/TypeScript/OwnershipInferenceDiagnostics.cpp index 348584b1f..492885553 100644 --- a/tslang/lib/TypeScript/OwnershipInferenceDiagnostics.cpp +++ b/tslang/lib/TypeScript/OwnershipInferenceDiagnostics.cpp @@ -232,7 +232,8 @@ namespace own_inference } }); - return name; + // a folded `const` has no ts.Variable, but under --di it has a ts.DebugVariable (TSLANG 47) + return name == "this value" ? ownerName(value) : name; } void OwnershipInferencePass::reportSecondReference(mlir::Operation *op, mlir::Value value) @@ -750,6 +751,14 @@ namespace own_inference auto diag = use->emitError("'") << name << "' borrows " << place << " but is used here after it may be released or overwritten"; diag.attachNote(drop->getLoc()) << "it may be released or overwritten here"; + // why a call of a method that writes nothing may: an override (TSLANG 48) + if (auto method = drop->getAttrOfType(OWN_OVERRIDABLE_CALL_ATTR_NAME)) + { + diag.attachNote(drop->getLoc()) + << "'" << method.getValue() << "' may be overridden in another module by a method that does; '@" FINAL_DECORATOR + << "' on the method, or on its class, says it is not"; + } + signalPassFailure(); } @@ -783,6 +792,15 @@ namespace own_inference return; } + // no local borrows it by name: another of its reads does (TSLANG 47 named it 'another variable') + if (borrower.empty()) + { + op->emitError("'") << owner << "' is moved here while another read of it still borrows it; a borrowed " + "value cannot be moved"; + signalPassFailure(); + return; + } + op->emitError("'") << owner << "' is moved here while '" << borrower << "' borrows it; a borrowed value cannot be moved"; signalPassFailure(); diff --git a/tslang/lib/TypeScript/OwnershipInferenceKeptParams.cpp b/tslang/lib/TypeScript/OwnershipInferenceKeptParams.cpp index 96b627877..e71cdf0cc 100644 --- a/tslang/lib/TypeScript/OwnershipInferenceKeptParams.cpp +++ b/tslang/lib/TypeScript/OwnershipInferenceKeptParams.cpp @@ -185,7 +185,7 @@ namespace own_inference llvm::SetVector unused; if (checkSlotMove(receiver.retain, receiver.value, receiver.load, unused)) { - reportMovedWhileBorrowed(receiver.retain, owner, someBorrower ? varName(someBorrower) : "another variable"); + reportMovedWhileBorrowed(receiver.retain, owner, someBorrower ? varName(someBorrower) : llvm::StringRef()); } } } diff --git a/tslang/lib/TypeScript/OwnershipInferencePass.cpp b/tslang/lib/TypeScript/OwnershipInferencePass.cpp index bd3e9be03..f79303494 100644 --- a/tslang/lib/TypeScript/OwnershipInferencePass.cpp +++ b/tslang/lib/TypeScript/OwnershipInferencePass.cpp @@ -529,7 +529,8 @@ namespace own_inference // an overwrite of a field or an element, or an assignment to a captured variable or // a global (spec 29: the global may hold what `this` or a parameter is) auto slot = releaseSlotOp.getSlot(); - if (!releasesNothing(releaseSlotOp) && + // a fill of an empty field frees nothing (TSLANG 47, the signature pass's verdict) + if (!releasesNothing(releaseSlotOp) && !releaseSlotOp->hasAttr(OWN_FILL_ATTR_NAME) && (isPlace(slot) || isCellVariable(slot) || isLoadedCell(slot) || slot.getDefiningOp())) { drops.push_back(op); @@ -792,6 +793,7 @@ namespace own_inference OWN_RESULT_RECORD_ATTR_NAME, OWN_RESULT_RECORD_UNBOXED_ATTR_NAME, OWN_RECORD_UNBOXED_FIELDS_ATTR_NAME, OWN_RECORD_TEMPORARY_ATTR_NAME, OWN_NO_DROPS_ATTR_NAME, OWN_DROP_FIELDS_ATTR_NAME, OWN_FACTS_LOST_ATTR_NAME, + OWN_OVERRIDABLE_CALL_ATTR_NAME, OWN_FILL_ATTR_NAME, OWN_FRESH_RESULT_ATTR_NAME, OWN_ASSIGNS_CAPTURES_ATTR_NAME, OWN_RESULT_BOUNDED_ATTR_NAME, OWN_STATE_BORROW_ATTR_NAME, diff --git a/tslang/lib/TypeScript/OwnershipSignatureFieldLocals.cpp b/tslang/lib/TypeScript/OwnershipSignatureFieldLocals.cpp new file mode 100644 index 000000000..cce9245d8 --- /dev/null +++ b/tslang/lib/TypeScript/OwnershipSignatureFieldLocals.cpp @@ -0,0 +1,606 @@ +// OwnershipSignaturePass (see OwnershipSignaturePass.h): a local that holds what a field holds is +// read as the field (TSLANG 47). +// +// A lazy cache keeps its object in a field and hands out a borrow of it: +// +// let result = this.cached; +// if (!result) { result = new Q(1); this.cached = result; } +// return result; +// +// On both ways to the return `result` is the object `this.cached` holds: read from it, or moved into +// it. Own's checks follow values, not equalities, so they saw a borrow of a field returned on one +// way and a local used after its value moved on the other. Each read of the local where it holds +// what the field holds is made a read of the field, which the checks take for the borrow it is: +// `return this.cached`. The local's own value, if no read is left to see it, is then never used, +// and the local is declared empty: `let result = undefined`, given a new object and moving it into +// the field, as `if (!this.cached) this.cached = new Q(1)` does. + +#include "OwnershipSignaturePass.h" + +#define DEBUG_TYPE "own" + +namespace own_signature +{ + + namespace + { + // The value a store puts into a place, seen through the views that widen it to the place's + // type (`OptionalValue(v)`, a class widened to a union with null): the read of `local` it + // is, when nothing writes `local` between that read and the store, in its block. + bool storesLocal(mlir_ts::StoreOp storeOp, mlir::Value local) + { + auto value = storeOp.getValue(); + while (auto *def = value.getDefiningOp()) + { + if (mlir::isa(def) || (mlir::isa(def) && isView(def))) + { + value = def->getOperand(0); + continue; + } + + break; + } + + auto loadOp = value.getDefiningOp(); + if (!loadOp || loadOp.getReference() != local || loadOp->getBlock() != storeOp->getBlock()) + { + return false; + } + + for (auto *op = loadOp->getNextNode(); op && op != storeOp.getOperation(); op = op->getNextNode()) + { + auto writes = false; + op->walk([&](mlir::Operation *inner) { + auto innerStore = mlir::dyn_cast(inner); + auto innerRelease = mlir::dyn_cast(inner); + writes |= (innerStore && innerStore.getReference() == local) || + (innerRelease && innerRelease.getSlot() == local) || isCall(inner); + }); + + if (writes) + { + return false; + } + } + + return true; + } + + // The read of the field that replaces a read of the local, made right before it: the object + // read again out of the local or parameter that holds it (sameObject), and the value seen as + // the local's type - itself, or the payload of the optional the field holds. + mlir::Value readFieldAt(mlir::OpBuilder &builder, mlir::Location location, mlir::Type type, mlir_ts::PropertyRefOp field) + { + auto objectLoad = field.getObjectRef().getDefiningOp(); + mlir::Value object = field.getObjectRef(); + if (objectLoad) + { + object = builder.create(location, objectLoad.getType(), objectLoad.getReference()); + } + + auto ref = builder.create(location, field.getType(), object, field.getPositionAttr()); + auto fieldType = mlir::cast(field.getType()).getElementType(); + mlir::Value value = builder.create(location, fieldType, ref); + if (fieldType != type) + { + // the local held the field's value, so it is there: no warning about an empty optional + auto valueOp = builder.create(location, type, value); + valueOp->setAttr(EXPLICIT_CAST_ATTR_NAME, builder.getUnitAttr()); + value = valueOp; + } + + return value; + } + + // Can a read of `field` stand in for a read of a local of this type? + bool fieldReadsAs(mlir_ts::PropertyRefOp field, mlir::Type localType) + { + auto fieldType = mlir::cast(field.getType()).getElementType(); + if (fieldType == localType) + { + return true; + } + + auto optionalType = mlir::dyn_cast(fieldType); + return optionalType && optionalType.getElementType() == localType; + } + + // The object a field is reached through can be read again anywhere in the function: a value + // defined in the entry block, or read out of a local or parameter nothing assigns. + bool objectReadable(mlir_ts::PropertyRefOp field) + { + // read out of a local or parameter that nothing assigns: two reads of it are one object + auto loadOp = field.getObjectRef().getDefiningOp(); + if (!loadOp) + { + return false; + } + + return isUnassignedSlot(loadOp.getReference()); + } + + // `value` seen through the views that keep its block: an optional made of it or opened, a + // widening or narrowing cast that is a view. + mlir::Value stripViews(mlir::Value value) + { + while (auto *def = value.getDefiningOp()) + { + if (mlir::isa(def) || + (mlir::isa(def) && isView(def))) + { + value = def->getOperand(0); + continue; + } + + break; + } + + return value; + } + + // Does nothing that may write `field` run on any way from `from` to `at`, both ops of `body`'s + // blocks? A must-analysis over the blocks: it holds right after `from`, and stops at anything + // that may write the field, at any call. + bool unwrittenSince(mlir::Region *body, mlir::Operation *from, mlir::Operation *at, mlir_ts::PropertyRefOp field) + { + auto conservative = [](mlir::Operation *) { return true; }; + auto run = [&](mlir::Block *block, bool holds, mlir::Operation *stopAt) { + for (auto &op : *block) + { + if (&op == stopAt) + { + break; + } + + holds = &op == from ? true : holds && !mayWriteField(&op, field, mlir::Value(), conservative); + } + + return holds; + }; + + llvm::DenseMap in; + for (auto &block : *body) + { + in[&block] = !block.isEntryBlock(); + } + + for (auto changed = true; changed;) + { + changed = false; + for (auto &block : *body) + { + if (block.isEntryBlock()) + { + continue; + } + + auto holds = !block.hasNoPredecessors() && llvm::all_of(block.getPredecessors(), [&](mlir::Block *predecessor) { + return run(predecessor, in[predecessor], nullptr); + }); + if (holds != in[&block]) + { + in[&block] = holds; + changed = true; + } + } + } + + return run(at->getBlock(), in[at->getBlock()], at); + } + + // One local and one field: where the local holds what the field holds, a must-analysis over + // the function's blocks. It starts to hold where the local is declared from a read of the + // field, or where the field is given a read of the local; it stops at a store into the local, + // at anything that may write the field, and at any call. + struct LocalField + { + mlir_ts::VariableOp local; + mlir_ts::PropertyRefOp field; + + // the state after `op`, given the state before it + bool step(mlir::Operation *op, bool holds) + { + auto slot = local.getResult(); + if (op == local.getOperation()) + { + auto init = local.getInitializer(); + auto initLoad = init ? init.getDefiningOp() : mlir_ts::LoadOp(); + auto initField = + initLoad ? initLoad.getReference().getDefiningOp() : mlir_ts::PropertyRefOp(); + if (!initField || !sameField(initField, field) || initLoad->getBlock() != op->getBlock() || + !initLoad->isBeforeInBlock(op)) + { + return false; + } + + for (auto *between = initLoad->getNextNode(); between != op; between = between->getNextNode()) + { + if (mayWriteField(between, field, slot, [](mlir::Operation *) { return true; })) + { + return false; + } + } + + return true; + } + + if (auto storeOp = mlir::dyn_cast(op)) + { + if (storeOp.getReference() == slot) + { + // given a read of the field made right before, in its block (as the stores + // rewritten above are), it holds what the field holds again + auto loadOp = stripViews(storeOp.getValue()).getDefiningOp(); + auto readField = loadOp ? loadOp.getReference().getDefiningOp() : mlir_ts::PropertyRefOp(); + if (!readField || !sameField(readField, field) || loadOp->getBlock() != op->getBlock() || + !loadOp->isBeforeInBlock(op)) + { + return false; + } + + for (auto *between = loadOp->getNextNode(); between != op; between = between->getNextNode()) + { + if (mayWriteField(between, field, mlir::Value(), [](mlir::Operation *) { return true; })) + { + return false; + } + } + + return true; + } + + if (auto propertyRefOp = storeOp.getReference().getDefiningOp(); + propertyRefOp && sameField(propertyRefOp, field)) + { + return storesLocal(storeOp, slot); + } + } + + if (auto releaseSlotOp = mlir::dyn_cast(op); releaseSlotOp && releaseSlotOp.getSlot() == slot) + { + return false; + } + + return holds && !mayWriteField(op, field, slot, [](mlir::Operation *) { return true; }); + } + }; + } // namespace + + void OwnershipSignaturePass::readFieldsForLocals(mlir::ModuleOp module) + { + llvm::SmallVector bodies; + module.walk([&](mlir::FunctionOpInterface funcOp) { + if (!funcOp.isExternal()) + { + bodies.push_back(&funcOp.getFunctionBody()); + } + }); + + for (auto *body : bodies) + { + // A value stored into a local while it is what a field holds - a read of the field nothing + // has written since (`const hit = this.cached; if (hit) return hit;`), or what was just + // moved into the field (`this.cached = result; return result;`, `result` a `const`) - is + // stored as a read of the field made right there, and so is rc's retain of it for that + // store. + llvm::SmallVector fieldStores; + llvm::SmallVector localStores; + for (auto &block : *body) + { + for (auto &op : block) + { + auto storeOp = mlir::dyn_cast(&op); + if (!storeOp) + { + continue; + } + + auto field = storeOp.getReference().getDefiningOp(); + auto varOp = storeOp.getReference().getDefiningOp(); + if (field && objectReadable(field)) + { + fieldStores.push_back(storeOp); + } + else if (varOp && !varOp.getCaptured().value_or(false) && varOp->getParentRegion() == body) + { + localStores.push_back(storeOp); + } + } + } + + for (auto storeOp : localStores) + { + auto value = storeOp.getValue(); + auto root = stripViews(value); + mlir_ts::PropertyRefOp field; + if (auto loadOp = root.getDefiningOp()) + { + field = loadOp.getReference().getDefiningOp(); + if (!field || field->getParentRegion() != body || loadOp->getParentRegion() != body || !objectReadable(field) || + !unwrittenSince(body, loadOp, storeOp, field)) + { + field = {}; + } + } + else if (own_facts::ownsHeap(root)) + { + for (auto fieldStore : fieldStores) + { + auto stored = fieldStore.getReference().getDefiningOp(); + if (stripViews(fieldStore.getValue()) == root && unwrittenSince(body, fieldStore, storeOp, stored)) + { + field = stored; + break; + } + } + } + + if (!field || !fieldReadsAs(field, value.getType())) + { + continue; + } + + // rc's retain for the store, right before it, or before its release of the old value + auto *before = storeOp->getPrevNode(); + if (auto releaseSlotOp = mlir::dyn_cast_or_null(before); + releaseSlotOp && releaseSlotOp.getSlot() == storeOp.getReference()) + { + before = before->getPrevNode(); + } + + auto retainOp = mlir::dyn_cast_or_null(before); + if (retainOp && retainOp->getOperand(0) != value) + { + retainOp = {}; + } + + mlir::OpBuilder builder(retainOp ? retainOp.getOperation() : storeOp.getOperation()); + auto read = readFieldAt(builder, storeOp.getLoc(), value.getType(), field); + storeOp->setOperand(0, read); + if (retainOp) + { + retainOp->setOperand(0, read); + } + } + + // the pairs: a local not captured, and a field it is declared from or that is given it + llvm::SmallVector pairs; + body->walk([&](mlir_ts::VariableOp varOp) { + if (varOp.getCaptured().value_or(false) || varOp->getParentRegion() != body) + { + return; + } + + auto slot = varOp.getResult(); + auto localType = mlir::cast(slot.getType()).getElementType(); + auto addField = [&](mlir_ts::PropertyRefOp field) { + if (!field || field->getParentRegion() != body || !fieldReadsAs(field, localType) || !objectReadable(field) || + llvm::any_of(pairs, [&](LocalField &pair) { return pair.local == varOp && sameField(pair.field, field); })) + { + return; + } + + pairs.push_back({varOp, field}); + }; + + if (auto init = varOp.getInitializer()) + { + if (auto initLoad = init.getDefiningOp()) + { + addField(initLoad.getReference().getDefiningOp()); + } + } + + for (auto *user : slot.getUsers()) + { + auto loadOp = mlir::dyn_cast(user); + if (!loadOp) + { + continue; + } + + for (auto *loadUser : loadOp->getUsers()) + { + auto *storeUser = loadUser; + while (storeUser && storeUser->getNumResults() == 1 && !mlir::isa(storeUser) && + (mlir::isa(storeUser) || + (mlir::isa(storeUser) && isView(storeUser))) && + storeUser->getResult(0).hasOneUse()) + { + storeUser = *storeUser->getResult(0).getUsers().begin(); + } + + if (auto storeOp = mlir::dyn_cast_or_null(storeUser)) + { + addField(storeOp.getReference().getDefiningOp()); + } + } + } + }); + + for (auto &pair : pairs) + { + // where the local holds what the field holds, at each block's entry: optimistic, to a + // fixed point; nothing holds at the entry + llvm::DenseMap in; + for (auto &block : *body) + { + in[&block] = !block.isEntryBlock(); + } + + auto outOf = [&](mlir::Block *block) { + auto holds = in[block]; + for (auto &op : *block) + { + holds = pair.step(&op, holds); + } + + return holds; + }; + + for (auto changed = true; changed;) + { + changed = false; + for (auto &block : *body) + { + if (block.isEntryBlock()) + { + continue; + } + + auto holds = !block.hasNoPredecessors() && + llvm::all_of(block.getPredecessors(), [&](mlir::Block *predecessor) { return outOf(predecessor); }); + if (holds != in[&block]) + { + in[&block] = holds; + changed = true; + } + } + } + + // each read of the local where it holds the field's value, but the one given to the field + auto slot = pair.local.getResult(); + llvm::SmallVector reads; + for (auto &block : *body) + { + auto holds = in[&block]; + for (auto &op : block) + { + if (auto loadOp = mlir::dyn_cast(&op); loadOp && holds && loadOp.getReference() == slot) + { + auto feedsField = llvm::any_of(loadOp->getUsers(), [&](mlir::Operation *user) { + auto storeOp = mlir::dyn_cast(user); + return storeOp && storeOp.getValue() == loadOp.getResult(); + }); + if (!feedsField) + { + reads.push_back(loadOp); + } + } + + holds = pair.step(&op, holds); + } + } + + for (auto read : reads) + { + mlir::OpBuilder builder(read); + auto value = readFieldAt(builder, read.getLoc(), read.getType(), pair.field); + read.getResult().replaceAllUsesWith(value); + read->erase(); + } + + // the local's own value, when no read is left to see it: the local is declared empty + auto init = pair.local.getInitializer(); + auto localType = mlir::cast(slot.getType()).getElementType(); + if (reads.empty() || !init || !mlir::isa(localType) || !init.getDefiningOp()) + { + continue; + } + + // a may-analysis: where the declared value may still be in the local + llvm::DenseMap mayIn; + auto declared = [&](mlir::Operation *op, bool holds) { + if (op == pair.local.getOperation()) + { + return true; + } + + auto storeOp = mlir::dyn_cast(op); + return holds && !(storeOp && storeOp.getReference() == slot); + }; + + for (auto changed = true; changed;) + { + changed = false; + for (auto &block : *body) + { + auto holds = llvm::any_of(block.getPredecessors(), [&](mlir::Block *predecessor) { + auto out = mayIn[predecessor]; + for (auto &op : *predecessor) + { + out = declared(&op, out); + } + + return out; + }); + if (holds != mayIn[&block]) + { + mayIn[&block] = holds; + changed = true; + } + } + } + + auto seen = false; + for (auto &block : *body) + { + auto holds = mayIn[&block]; + for (auto &op : block) + { + auto loadOp = mlir::dyn_cast(&op); + seen |= holds && loadOp && loadOp.getReference() == slot; + // a read in a nested region sees whatever the local holds + op.walk([&](mlir_ts::LoadOp nested) { + seen |= nested != loadOp && nested.getReference() == slot; + }); + holds = declared(&op, holds); + } + } + + if (seen) + { + continue; + } + + mlir::OpBuilder builder(pair.local); + auto empty = builder.create(pair.local.getLoc(), localType); + pair.local->setOperand(0, empty); + } + + // A local whose reads all became reads of the field holds what nobody reads: an assignment + // of a field read to it (`r = n` once `this.cached = n`) is dropped, with rc's retain of + // the value and release of the old one, `Retain(v); ReleaseSlot(r); Store(v, r)`. The + // local keeps its old value until its own release. + for (auto &pair : pairs) + { + auto slot = pair.local.getResult(); + auto read = llvm::any_of(slot.getUsers(), [](mlir::Operation *user) { return mlir::isa(user); }); + if (read) + { + continue; + } + + llvm::SmallVector dead; + for (auto *user : slot.getUsers()) + { + auto storeOp = mlir::dyn_cast(user); + if (!storeOp || storeOp.getReference() != slot) + { + continue; + } + + auto loadOp = stripViews(storeOp.getValue()).getDefiningOp(); + auto releaseSlotOp = mlir::dyn_cast_or_null(storeOp->getPrevNode()); + auto retainOp = releaseSlotOp ? mlir::dyn_cast_or_null(releaseSlotOp->getPrevNode()) + : mlir_ts::RetainOp(); + if (!loadOp || !loadOp.getReference().getDefiningOp() || + !retainOp || releaseSlotOp.getSlot() != slot || retainOp->getOperand(0) != storeOp.getValue()) + { + continue; + } + + dead.append({storeOp.getOperation(), releaseSlotOp.getOperation(), retainOp.getOperation()}); + } + + for (auto *op : dead) + { + op->erase(); + } + } + } + } + +} // namespace own_signature + +#undef DEBUG_TYPE diff --git a/tslang/lib/TypeScript/OwnershipSignaturePass.cpp b/tslang/lib/TypeScript/OwnershipSignaturePass.cpp index 04cd85184..73dfeba84 100644 --- a/tslang/lib/TypeScript/OwnershipSignaturePass.cpp +++ b/tslang/lib/TypeScript/OwnershipSignaturePass.cpp @@ -102,6 +102,7 @@ namespace own_signature { auto module = getOperation(); stubCannotShare(module); + readFieldsForLocals(module); module.walk([&](mlir_ts::FuncOp funcOp) { functions[funcOp.getSymName()] = funcOp; }); module.walk([&](mlir_ts::GlobalOp globalOp) { globals[globalOp.getSymName()] = globalOp; }); module.walk([&](mlir_ts::AddressOfOp addressOfOp) { @@ -246,6 +247,22 @@ namespace own_signature call.op->removeAttr(OWN_DROP_FIELDS_ATTR_NAME); if (!call.callees.known) { + // a method of a class another module may extend, called through its vtable: say so + // where a borrow ends at the call (TSLANG 48) + auto callee = mlir::isa(call.op) + ? calleeValue(call.op) + : mlir::Value(); + if (auto getMethodOp = callee ? callee.getDefiningOp() : mlir_ts::GetMethodOp()) + { + callee = getMethodOp.getBoundFunc(); + } + + auto refOp = callee ? callee.getDefiningOp() : mlir_ts::ThisVirtualSymbolRefOp(); + if (refOp && !refOp->hasAttr(FINAL_RECEIVER_ATTR_NAME)) + { + call.op->setAttr(OWN_OVERRIDABLE_CALL_ATTR_NAME, refOp.getIdentifierAttr()); + } + continue; } @@ -1606,6 +1623,63 @@ namespace own_signature } void OwnershipSignaturePass::computeDrops() + { + callOf.clear(); + for (auto &call : calls) + { + callOf[call.op] = &call; + } + + computeDropsRound(false); + + // A fill of an empty field (TSLANG 47) frees nothing, unless a call between the test and the + // store may write the field. Each is decided once, by the facts that count every fill as a + // drop: a callee that only fills may still write the field (it is no-drops once fills are + // not drops). The verdict is pinned on the release, for the second round and the inference. + getOperation().walk([&](mlir_ts::ReleaseSlotOp releaseSlotOp) { + if (releaseSlotOp->getParentOfType() && decideFill(releaseSlotOp)) + { + releaseSlotOp->setAttr(OWN_FILL_ATTR_NAME, mlir::UnitAttr::get(&getContext())); + } + else + { + releaseSlotOp->removeAttr(OWN_FILL_ATTR_NAME); + } + }); + + computeDropsRound(true); + } + + bool OwnershipSignaturePass::isFill(mlir_ts::ReleaseSlotOp releaseSlotOp) + { + return releaseSlotOp->hasAttr(OWN_FILL_ATTR_NAME); + } + + bool OwnershipSignaturePass::decideFill(mlir_ts::ReleaseSlotOp releaseSlotOp) + { + auto field = releaseSlotOp.getSlot().getDefiningOp(); + return field && fillsEmptyField(releaseSlotOp, [&](mlir::Operation *op) { + auto *call = callOf.lookup(op); + // another module's facts count its fills as no drops: they cannot clear a call + if (!call || call->callees.imported) + { + return true; + } + + if (!callMayDrop(call->callees)) + { + return false; + } + + auto drops = calleesFieldDrops(call->callees); + return !drops || drops->any || llvm::any_of(drops->places, [&](auto &place) { + return place.first == OWN_INTERFACE_FIELD_POSITION || + (place.first == field.getPosition() && place.second == field.getType()); + }); + }); + } + + void OwnershipSignaturePass::computeDropsRound(bool fills) { llvm::DenseMap> callsIn; for (auto &call : calls) @@ -1613,15 +1687,30 @@ namespace own_signature callsIn[call.op->getParentOfType()].push_back(&call); } + // the bodies first, all against the previous round's facts + llvm::DenseSet bodyNoDrops; + llvm::DenseMap bodyFieldDrops; for (auto &entry : functions) { auto funcOp = entry.second; - if (!funcOp.isDeclaration() && !dropsInBody(funcOp)) + if (funcOp.isDeclaration()) + { + continue; + } + + if (!dropsInBody(funcOp, fills)) { - noDrops.insert(funcOp); + bodyNoDrops.insert(funcOp); + } + else + { + bodyFieldDrops[funcOp] = fieldDropsInBody(funcOp, fills); } } + noDrops = std::move(bodyNoDrops); + fieldDrops.clear(); + for (auto changed = true; changed;) { changed = false; @@ -1654,7 +1743,8 @@ namespace own_signature auto funcOp = entry.second; if (!funcOp.isDeclaration() && !noDrops.contains(funcOp)) { - fieldDrops[funcOp] = fieldDropsInBody(funcOp); + auto found = bodyFieldDrops.find(funcOp); + fieldDrops[funcOp] = found != bodyFieldDrops.end() ? found->second : FieldDrops(); } } @@ -1736,7 +1826,7 @@ namespace own_signature return all; } - OwnershipSignaturePass::FieldDrops OwnershipSignaturePass::fieldDropsInBody(mlir_ts::FuncOp funcOp) + OwnershipSignaturePass::FieldDrops OwnershipSignaturePass::fieldDropsInBody(mlir_ts::FuncOp funcOp, bool fills) { // what dropsInBody counts, with the overwrites of places it can name kept apart FieldDrops drops; @@ -1754,7 +1844,7 @@ namespace own_signature { auto slot = releaseSlotOp.getSlot(); auto slotType = mlir::dyn_cast(slot.getType()); - if (releasesNothing(releaseSlotOp)) + if (releasesNothing(releaseSlotOp) || (fills && isFill(releaseSlotOp))) { return; } @@ -2008,7 +2098,7 @@ namespace own_signature return counted; } - bool OwnershipSignaturePass::dropsInBody(mlir_ts::FuncOp funcOp) + bool OwnershipSignaturePass::dropsInBody(mlir_ts::FuncOp funcOp, bool fills) { auto drops = false; funcOp.walk([&](mlir::Operation *op) { @@ -2030,8 +2120,9 @@ namespace own_signature // a captured variable assigned through its cell, by a closure's body: the variable // is its declaring function's auto slot = releaseSlotOp.getSlot(); - drops = !releasesNothing(releaseSlotOp) &&slot.getDefiningOp() || (isPlace(slot) && reachesOutside(slot, funcOp)) || - isLoadedCell(slot) || (!isPlace(slot) && touchesHandle(op) && !isCountedReadSlot(slot)); + drops = !releasesNothing(releaseSlotOp) && !(fills && isFill(releaseSlotOp)) && + (slot.getDefiningOp() || (isPlace(slot) && reachesOutside(slot, funcOp)) || + isLoadedCell(slot) || (!isPlace(slot) && touchesHandle(op) && !isCountedReadSlot(slot))); } else if (mlir::isa(op)) { diff --git a/tslang/lib/TypeScript/OwnershipSignaturePass.h b/tslang/lib/TypeScript/OwnershipSignaturePass.h index 5b494ab1e..c94854f9a 100644 --- a/tslang/lib/TypeScript/OwnershipSignaturePass.h +++ b/tslang/lib/TypeScript/OwnershipSignaturePass.h @@ -616,8 +616,18 @@ class OwnershipSignaturePass : public mlir::PassWrapper callOf; // The FieldDrops of a call's callees together, when every one has them. std::optional calleesFieldDrops(const Callees &callees); @@ -1113,6 +1123,11 @@ class OwnershipSignaturePass : public mlir::PassWrapper T) | null`: a function is stored in it, `if (f)` and `f !== null` narrow it, and it is called +foreach(issues_mm gc rc none own) + tslang_add_test(NAME test-jit-00-function-or-null-${issues_mm} COMMAND test-runner -jit -mm=${issues_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00function_or_null.ts") + tslang_add_test(NAME test-compile-00-function-or-null-${issues_mm} COMMAND test-runner -mm=${issues_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00function_or_null.ts") +endforeach() +# a closure stored into a field of the local object it captures borrows that object (own: it owned it, +# and clearing the field freed the object) +foreach(issues_mm gc rc none own) + tslang_add_test(NAME test-jit-00-closure-back-reference-local-${issues_mm} COMMAND test-runner -jit -mm=${issues_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00closure_back_reference_local.ts") + tslang_add_test(NAME test-compile-00-closure-back-reference-local-${issues_mm} COMMAND test-runner -mm=${issues_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00closure_back_reference_local.ts") +endforeach() +# ...and an object another closure that escapes captured is the closure's: a use after it is an error +add_test(NAME test-compile-own-escaping-capture-used-after-error + COMMAND test-runner -mm=own "${PROJECT_SOURCE_DIR}/test/tester/tests/own_escaping_capture_used_after_error.ts") +set_tests_properties(test-compile-own-escaping-capture-used-after-error PROPERTIES PASS_REGULAR_EXPRESSION "'s' is captured by a closure that escapes, and is still used here" + FAIL_REGULAR_EXPRESSION "Stack dump|Assertion failed") # TSLANG_ISSUES 30: a generic sees no local of the function it is instantiated from foreach(issues_mm gc rc none own) tslang_add_test(NAME test-jit-00-tslang-issue-30-${issues_mm} COMMAND test-runner -jit -mm=${issues_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00tslang_issue_30.ts") @@ -1885,8 +1901,10 @@ endforeach() # TSLANG_ISSUES 45: a union widened to one with all its members is a plain cast; -mm=own takes an # exported class's `..instanceOf` for a call that destroys nothing # TSLANG_ISSUES 46: a function returning its union parameter, given a new object, freed it twice +# TSLANG_ISSUES 47: a lazily cached field returned through a local; a fill of an empty field frees nothing +# TSLANG_ISSUES 48: a @final method of an exported class is called directly, by its own facts foreach(issues_mm gc rc none own) - foreach(issues_test 00tslang_issue_44 00tslang_issue_45 00tslang_issue_46) + foreach(issues_test 00tslang_issue_44 00tslang_issue_45 00tslang_issue_46 00tslang_issue_47 00tslang_issue_48) tslang_add_test(NAME test-jit-${issues_test}-${issues_mm} COMMAND test-runner -jit -mm=${issues_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/${issues_test}.ts") tslang_add_test(NAME test-compile-${issues_test}-${issues_mm} COMMAND test-runner -mm=${issues_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/${issues_test}.ts") endforeach() @@ -1898,6 +1916,15 @@ foreach(issues_mm gc rc none own) tslang_add_test(NAME test-compile-${symbol_test}-${issues_mm} COMMAND test-runner -mm=${issues_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/${symbol_test}.ts") endforeach() endforeach() +# TSLANG_ISSUES 48: a @final method is not overridden, nor abstract +add_test(NAME test-compile-final-method-override-error + COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/final_method_override_error.ts") +set_tests_properties(test-compile-final-method-override-error PROPERTIES PASS_REGULAR_EXPRESSION "method 'factor' overrides the @final method of 'Base'" + FAIL_REGULAR_EXPRESSION "Stack dump|Assertion failed") +add_test(NAME test-compile-final-method-abstract-error + COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/final_method_abstract_error.ts") +set_tests_properties(test-compile-final-method-abstract-error PROPERTIES PASS_REGULAR_EXPRESSION "method 'factor' cannot be both abstract and @final" + FAIL_REGULAR_EXPRESSION "Stack dump|Assertion failed") add_test(NAME test-compile-symbol-value-error COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/symbol_value_error.ts") set_tests_properties(test-compile-symbol-value-error PROPERTIES PASS_REGULAR_EXPRESSION "a symbol has no value at run time yet" @@ -1964,6 +1991,23 @@ add_test(NAME test-compile-argument-string-to-number-error COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/argument_string_to_number_error.ts") set_tests_properties(test-compile-argument-string-to-number-error PROPERTIES PASS_REGULAR_EXPRESSION "argument of type '\"7\"' is not assignable to parameter of type 'number'" FAIL_REGULAR_EXPRESSION "Stack dump|Assertion failed") +# ...and so is a boolean given to a number or a string, or a number to a boolean +add_test(NAME test-compile-assign-boolean-to-number-error + COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/assign_boolean_to_number_error.ts") +set_tests_properties(test-compile-assign-boolean-to-number-error PROPERTIES PASS_REGULAR_EXPRESSION "type 'boolean' is not assignable to type 'number'" + FAIL_REGULAR_EXPRESSION "Stack dump|Assertion failed") +add_test(NAME test-compile-assign-boolean-to-string-error + COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/assign_boolean_to_string_error.ts") +set_tests_properties(test-compile-assign-boolean-to-string-error PROPERTIES PASS_REGULAR_EXPRESSION "type 'boolean' is not assignable to type 'string'" + FAIL_REGULAR_EXPRESSION "Stack dump|Assertion failed") +add_test(NAME test-compile-assign-number-to-boolean-error + COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/assign_number_to_boolean_error.ts") +set_tests_properties(test-compile-assign-number-to-boolean-error PROPERTIES PASS_REGULAR_EXPRESSION "type 'number' is not assignable to type 'boolean'" + FAIL_REGULAR_EXPRESSION "Stack dump|Assertion failed") +add_test(NAME test-compile-argument-boolean-to-number-error + COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/argument_boolean_to_number_error.ts") +set_tests_properties(test-compile-argument-boolean-to-number-error PROPERTIES PASS_REGULAR_EXPRESSION "argument of type 'boolean' is not assignable to parameter of type 'number'" + FAIL_REGULAR_EXPRESSION "Stack dump|Assertion failed") # ...a class extending a class value known at run time only is an error add_test(NAME test-compile-mixin-runtime-base-error COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/mixin_runtime_base_error.ts") @@ -5039,6 +5083,16 @@ foreach(override_mm rc none gc) tslang_add_test(NAME test-compile-${override_mm}-shared-override-imported-class COMMAND test-runner -shared -mm=${override_mm} "${PROJECT_SOURCE_DIR}/test/tester/own/own_err_override_imported_class.ts" "${PROJECT_SOURCE_DIR}/test/tester/own/own_override_base_lib.ts") endforeach() +# TSLANG_ISSUES 48: a @final method of a class another module defines: its declaration says it, and +# an importer holds a borrow of a field across the call +# TSLANG_ISSUES 47: the cached getter of an exported class in a namespace, called twice by an importer +foreach(final_mm own rc none gc) + tslang_add_test(NAME test-jit-${final_mm}-shared-final-method COMMAND test-runner -jit -shared -mm=${final_mm} "${PROJECT_SOURCE_DIR}/test/tester/own/own_final_method_main.ts" "${PROJECT_SOURCE_DIR}/test/tester/own/own_final_method_lib.ts") + tslang_add_test(NAME test-compile-${final_mm}-shared-final-method COMMAND test-runner -shared -mm=${final_mm} "${PROJECT_SOURCE_DIR}/test/tester/own/own_final_method_main.ts" "${PROJECT_SOURCE_DIR}/test/tester/own/own_final_method_lib.ts") + tslang_add_test(NAME test-jit-${final_mm}-shared-lazy-cache COMMAND test-runner -jit -shared -mm=${final_mm} "${PROJECT_SOURCE_DIR}/test/tester/own/own_lazy_cache_main.ts" "${PROJECT_SOURCE_DIR}/test/tester/own/own_lazy_cache_lib.ts") + tslang_add_test(NAME test-compile-${final_mm}-shared-lazy-cache COMMAND test-runner -shared -mm=${final_mm} "${PROJECT_SOURCE_DIR}/test/tester/own/own_lazy_cache_main.ts" "${PROJECT_SOURCE_DIR}/test/tester/own/own_lazy_cache_lib.ts") +endforeach() + # The ownership verifier runs under own too, on the IR before inference erases its birth takes. add_test(NAME test-own-verify-ownership COMMAND $ --emit=mlir-affine --no-default-lib -mm=own --verify-ownership @@ -5376,7 +5430,12 @@ set(own_error_cases "own_err_back_reference_stored|:15:5: error: '[^']*' borrows a field and cannot be stored, returned or captured" "own_err_back_reference_captures|:13:20: error: a closure that escapes owns what it captures, but -mm=own cannot move 'this' into it: its value is the caller's" "own_err_closure_kept_param_used|:19:11: error: '[^']*' is used here after its value was moved" - "own_err_this_result_other|:7:5: error: 'A.copy' has the result type 'this', but its body returns something else than the object it is called on") + "own_err_this_result_other|:7:5: error: 'A.copy' has the result type 'this', but its body returns something else than the object it is called on" + "own_err_overridable_call|:17:19: note: 'Base.factor' may be overridden in another module by a method that does. '@final' on the method, or on its class, says it is not" + "own_err_fill_after_call|:21:11: error: '[^']*' borrows the result of 'Dev.getQ' but is used here after it may be released or overwritten" + "own_err_fill_in_loop|:23:11: error: '[^']*' borrows the result of 'Dev.getQ' but is used here after it may be released or overwritten" + "own_err_fill_other_field|:20:11: error: '[^']*' borrows the result of 'Dev.getQ' but is used here after it may be released or overwritten" + "own_err_fill_after_fill_call|:19:20: error: '[^']*' borrows the result of 'Dev.fill' but is used here after it may be released or overwritten") foreach(own_error_case ${own_error_cases}) string(FIND "${own_error_case}" "|" own_error_sep) string(SUBSTRING "${own_error_case}" 0 ${own_error_sep} own_error_name) diff --git a/tslang/test/tester/own/own_err_fill_after_call.ts b/tslang/test/tester/own/own_err_fill_after_call.ts new file mode 100644 index 000000000..b8c0b69a4 --- /dev/null +++ b/tslang/test/tester/own/own_err_fill_after_call.ts @@ -0,0 +1,22 @@ +// TSLANG_ISSUES 47: a store into a field tested empty frees nothing - but not when a call between +// the test and the store may write the field. `clear` fills it, and the store then frees what +// `clear` stored, which the first call's result borrows. +class Q { + constructor(public h: number) {} +} + +class Dev { + cached: Q | undefined; + clear() { this.cached = new Q(5); } + getQ(): Q { + if (!this.cached) { this.clear(); this.cached = new Q(1); } + return this.cached; + } +} + +function main() { + const d = new Dev(); + const a = d.getQ(); + const b = d.getQ(); + print(a.h, b.h); +} diff --git a/tslang/test/tester/own/own_err_fill_after_fill_call.ts b/tslang/test/tester/own/own_err_fill_after_fill_call.ts new file mode 100644 index 000000000..3e29714a8 --- /dev/null +++ b/tslang/test/tester/own/own_err_fill_after_fill_call.ts @@ -0,0 +1,29 @@ +// TSLANG_ISSUES 47: `fill` only fills `cached`, so its own calls free nothing - but called between +// `bad`'s test and its store, it may have filled the field, and the store then frees what `fill` +// returned. A call in between is judged by facts that count every fill as a drop. +class Q { + constructor(public h: number) {} +} + +class Dev { + cached: Q | undefined; + fill(): Q { + if (!this.cached) this.cached = new Q(1); + return this.cached; + } + + bad(): number { + if (!this.cached) { + const x = this.fill(); + this.cached = new Q(2); + return x.h; + } + + return 0; + } +} + +function main() { + const d = new Dev(); + print(d.bad()); +} diff --git a/tslang/test/tester/own/own_err_fill_in_loop.ts b/tslang/test/tester/own/own_err_fill_in_loop.ts new file mode 100644 index 000000000..b2e772b60 --- /dev/null +++ b/tslang/test/tester/own/own_err_fill_in_loop.ts @@ -0,0 +1,24 @@ +// TSLANG_ISSUES 47: the field tested empty once, outside a loop, and stored into on each round: the +// second round frees what the first stored. Not a fill. +class Q { + constructor(public h: number) {} +} + +class Dev { + cached: Q | undefined; + getQ(): Q { + const r = this.cached; + for (let i = 0; i < 2; i++) { + if (!r) this.cached = new Q(i); + } + + return this.cached!; + } +} + +function main() { + const d = new Dev(); + const a = d.getQ(); + const b = d.getQ(); + print(a.h, b.h); +} diff --git a/tslang/test/tester/own/own_err_fill_other_field.ts b/tslang/test/tester/own/own_err_fill_other_field.ts new file mode 100644 index 000000000..cebe944f3 --- /dev/null +++ b/tslang/test/tester/own/own_err_fill_other_field.ts @@ -0,0 +1,21 @@ +// TSLANG_ISSUES 47: the test reads another field than the store writes: not a fill, and the second +// call frees what the first one's result borrows. +class Q { + constructor(public h: number) {} +} + +class Dev { + cached: Q | undefined; + other: Q | undefined; + getQ(): Q { + if (!this.other) this.cached = new Q(1); + return this.cached!; + } +} + +function main() { + const d = new Dev(); + const a = d.getQ(); + const b = d.getQ(); + print(a.h, b.h); +} diff --git a/tslang/test/tester/own/own_err_overridable_call.ts b/tslang/test/tester/own/own_err_overridable_call.ts new file mode 100644 index 000000000..06d12bb69 --- /dev/null +++ b/tslang/test/tester/own/own_err_overridable_call.ts @@ -0,0 +1,22 @@ +// TSLANG_ISSUES 48: a borrow of a field held across `this.factor()`, a method of an exported class +// another module may override. The error says why the call may release the field, and that +// `@final` says it does not. +export class Item { + constructor(public n: number) {} +} + +export class Base { + items: Item[] = [new Item(1), new Item(2)]; + scale: number = 2.0; + factor(): number { return this.scale; } +} + +export class App extends Base { + total(): number { + const item = this.items[1]; + const f = this.factor(); + return item.n * f; + } +} + +function main() { print(new App().total()); } diff --git a/tslang/test/tester/own/own_final_method_lib.ts b/tslang/test/tester/own/own_final_method_lib.ts new file mode 100644 index 000000000..f770342a2 --- /dev/null +++ b/tslang/test/tester/own/own_final_method_lib.ts @@ -0,0 +1,8 @@ +// TSLANG_ISSUES 48: the library own_final_method_main imports - an exported base class whose +// `@final` method reads a number. Its declaration says `@final`, so the importer's calls of it run it. +export class Item { constructor(public n: number) {} } +export class Base { + items: Item[] = [new Item(1), new Item(2)]; + scale: number = 2.0; + @final factor(): number { return this.scale; } +} diff --git a/tslang/test/tester/own/own_final_method_main.ts b/tslang/test/tester/own/own_final_method_main.ts new file mode 100644 index 000000000..9fbfbad12 --- /dev/null +++ b/tslang/test/tester/own/own_final_method_main.ts @@ -0,0 +1,11 @@ +// TSLANG_ISSUES 48: a borrow of a field held across `this.factor()`, a `@final` method of a class +// another module defines: no override can run, so the call drops nothing the method's facts don't. +import './own_final_method_lib' +class App extends Base { + total(): number { + const item = this.items[1]; + const f = this.factor(); + return item.n * f; + } +} +function main() { const t = new App().total(); print(t); assert(t == 4); print("done."); } diff --git a/tslang/test/tester/own/own_lazy_cache_lib.ts b/tslang/test/tester/own/own_lazy_cache_lib.ts new file mode 100644 index 000000000..c089f370b --- /dev/null +++ b/tslang/test/tester/own/own_lazy_cache_lib.ts @@ -0,0 +1,24 @@ +// TSLANG_ISSUES 47: the library own_lazy_cache_main imports - native_ts_graphics' cached getter, in +// an exported class in a namespace. An exported method says it returns a borrow of `this` +// (`@lends`), and `@final` that no override of it may overwrite the field (TSLANG 48). +export namespace Nri { + export class Queue { + constructor(public h: number) {} + } + + export class Device { + cachedQueue: Queue | undefined; + made = 0; + + @final @lends("this") getGraphicsQueue(): Queue { + let result = this.cachedQueue; + if (!result) { + this.made++; + result = new Queue(7); + this.cachedQueue = result; + } + + return result; + } + } +} diff --git a/tslang/test/tester/own/own_lazy_cache_main.ts b/tslang/test/tester/own/own_lazy_cache_main.ts new file mode 100644 index 000000000..538255795 --- /dev/null +++ b/tslang/test/tester/own/own_lazy_cache_main.ts @@ -0,0 +1,11 @@ +// TSLANG_ISSUES 47: the getter of own_lazy_cache_lib called twice from another module. Its fill of +// the empty field frees nothing, so the first call's result is still there after the second. +import './own_lazy_cache_lib' +function main() { + const d = new Nri.Device(); + const a = d.getGraphicsQueue(); + const b = d.getGraphicsQueue(); + print(a.h, b.h, a === b); + assert(a === b && a.h == 7 && d.made == 1); + print("done."); +} diff --git a/tslang/test/tester/tests/00tslang_issue_47.ts b/tslang/test/tester/tests/00tslang_issue_47.ts new file mode 100644 index 000000000..37eef169d --- /dev/null +++ b/tslang/test/tester/tests/00tslang_issue_47.ts @@ -0,0 +1,134 @@ +// TSLANG_ISSUES 47 (-mm=own): a lazily cached field could not be returned through a local. +// `let r = this.cached; if (!r) { r = new Q(); this.cached = r; } return r;` returns on both ways +// the object the field holds: a read of the local where it holds what the field holds is read as +// the field. And a store that fills an empty field (`if (!this.cached) this.cached = ...`) frees +// nothing, so a second call of the getter does not end the borrow the first one returned. + +class Q { + constructor(public h: number) {} +} + +class Dev { + cached: Q | undefined; + other: Q | null = null; + made = 0; + + // the issue's getter: through a `let` + viaLet(): Q { + let result = this.cached; + if (!result) { + this.made++; + result = new Q(1); + this.cached = result; + } + + return result; + } + + // the new one given to the `let` after the field + viaAssign(): Q { + let r = this.cached; + if (!r) { + this.made++; + const n = new Q(1); + this.cached = n; + r = n; + } + + return r; + } + + // check, then return the narrowed `const`; or the new one, once stored + viaConst(): Q { + const hit = this.cached; + if (hit) return hit; + this.made++; + const result = new Q(1); + this.cached = result; + return result; + } + + // the field read twice + viaField(): Q { + if (!this.cached) { + this.made++; + this.cached = new Q(1); + } + + return this.cached; + } + + // tested with `=== undefined`, `== null`, and filled in the else branch + viaEquals(): Q { + if (this.cached === undefined) { + this.made++; + this.cached = new Q(1); + } + + return this.cached; + } + + viaNull(): Q { + if (this.other == null) { + this.made++; + this.other = new Q(2); + } + + return this.other; + } + + viaElse(): Q { + if (this.cached) { + return this.cached; + } else { + this.made++; + this.cached = new Q(1); + return this.cached; + } + } +} + +function main() { + // the borrow of the first result outlives the second call + const d = new Dev(); + const a = d.viaLet(); + const b = d.viaLet(); + print(a.h, b.h, a === b); + assert(a === b && d.made === 1); + + const e = new Dev(); + const c1 = e.viaConst(); + const c2 = e.viaConst(); + assert(c1 === c2 && e.made === 1); + + const f = new Dev(); + const f1 = f.viaField(); + const f2 = f.viaField(); + assert(f1 === f2 && f.made === 1); + + const g = new Dev(); + const g1 = g.viaEquals(); + const g2 = g.viaEquals(); + const g3 = g.viaNull(); + const g4 = g.viaNull(); + assert(g1 === g2 && g3 === g4 && g.made === 2); + + const v = new Dev(); + const v1 = v.viaAssign(); + const v2 = v.viaAssign(); + assert(v1 === v2 && v.made === 1); + + const h = new Dev(); + const h1 = h.viaElse(); + const h2 = h.viaElse(); + assert(h1 === h2 && h.made === 1); + + // a getter of one object, then the same of another + const x = new Dev(); + const y = new Dev(); + const xq = x.viaLet(); + const yq = y.viaLet(); + assert(xq !== yq && xq.h === yq.h); + + print("done."); +} diff --git a/tslang/test/tester/tests/00tslang_issue_48.ts b/tslang/test/tester/tests/00tslang_issue_48.ts new file mode 100644 index 000000000..8a06a85d4 --- /dev/null +++ b/tslang/test/tester/tests/00tslang_issue_48.ts @@ -0,0 +1,43 @@ +// TSLANG_ISSUES 48 (-mm=own): in an exported class that isn't @final, any `this.method()` may be +// overridden in another module by a method that overwrites any field, so a borrow of a field held +// across it was refused. `@final` on the method says no subclass overrides it: its calls run it, and +// -mm=own goes by its body. + +export class Item { + constructor(public n: number) {} +} + +export class Base { + items: Item[] = [new Item(1), new Item(2)]; + scale: number = 2.0; + + @final factor(): number { + return this.scale; + } + + // a method that is not final, overridden below: still called through the vtable + bonus(): number { + return 0; + } +} + +export class App extends Base { + total(): number { + const item = this.items[1]; + const f = this.factor(); + return item.n * f + this.bonus(); + } + + bonus(): number { + return 1; + } +} + +function main() { + const app = new App(); + print(app.total()); + assert(app.total() === 5); + const base: Base = app; + assert(base.factor() === 2 && base.bonus() === 1); + print("done."); +} diff --git a/tslang/test/tester/tests/final_method_abstract_error.ts b/tslang/test/tester/tests/final_method_abstract_error.ts new file mode 100644 index 000000000..9799baded --- /dev/null +++ b/tslang/test/tester/tests/final_method_abstract_error.ts @@ -0,0 +1,6 @@ +// TSLANG_ISSUES 48: an abstract method has no body to run, so it cannot be @final +abstract class Base { + @final abstract factor(): number; +} + +function main() { } diff --git a/tslang/test/tester/tests/final_method_override_error.ts b/tslang/test/tester/tests/final_method_override_error.ts new file mode 100644 index 000000000..a7a468a41 --- /dev/null +++ b/tslang/test/tester/tests/final_method_override_error.ts @@ -0,0 +1,10 @@ +// TSLANG_ISSUES 48: a @final method cannot be overridden +class Base { + @final factor(): number { return 1; } +} + +class App extends Base { + factor(): number { return 2; } +} + +function main() { print(new App().factor()); } diff --git a/tslang/test/tester/verify-ownership.cmake b/tslang/test/tester/verify-ownership.cmake index 85eb4ea27..e9054ae94 100644 --- a/tslang/test/tester/verify-ownership.cmake +++ b/tslang/test/tester/verify-ownership.cmake @@ -66,10 +66,19 @@ set(not_compilable_alone assign_number_to_string_error.ts # an error by design (test-compile-argument-string-to-number-error) argument_string_to_number_error.ts + # errors by design (test-compile-assign-boolean-to-number-error, -boolean-to-string-error, + # -number-to-boolean-error, test-compile-argument-boolean-to-number-error) + assign_boolean_to_number_error.ts + assign_boolean_to_string_error.ts + assign_number_to_boolean_error.ts + argument_boolean_to_number_error.ts # an error by design (test-compile-cdecl-closure-error) cdecl_closure_error.ts # an error by design (test-compile-computed-name-failed-error) computed_name_failed_error.ts + # errors by design (test-compile-final-method-override-error, -abstract-error) + final_method_override_error.ts + final_method_abstract_error.ts # an error by design (test-compile-generic-self-recursion-untyped-error) generic_self_recursion_untyped_error.ts) From e0f1df8f267bc518e15cb933bb29c19852ba3c60 Mon Sep 17 00:00:00 2001 From: ASDAlexander77 Date: Sat, 14 Nov 2026 00:59:52 +0000 Subject: [PATCH 3/5] CMake: TSLANG_ENABLE_LTCG option for the compiler's own targets (MSVC Release, off by default) Co-Authored-By: Claude Opus 5.5 --- tslang/CMakeLists.txt | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/tslang/CMakeLists.txt b/tslang/CMakeLists.txt index bd1243234..9dffeb611 100644 --- a/tslang/CMakeLists.txt +++ b/tslang/CMakeLists.txt @@ -204,6 +204,33 @@ add_subdirectory(tslang) add_subdirectory(tsbindgen) add_subdirectory(ts-new-parser) +# Whole-program optimization of the compiler itself (MSVC /GL + /LTCG, with /Ob3 inlining): +# slower links, a little smaller and faster tslang/tsbindgen. Only the compiler's own code: the LLVM +# it links (~90% of the executable) comes prebuilt, and /GL objects only link with the exact MSVC +# toolset that compiled them. +# Only the compiler's own targets: the runtime libraries (TypeScriptMimalloc, the async runtime, +# TypeScriptRuntime, gc) are linked into the programs tslang builds, by lld, which cannot read /GL +# objects. +option(TSLANG_ENABLE_LTCG "Build the compiler with link-time code generation (MSVC Release)" OFF) +if (TSLANG_ENABLE_LTCG AND MSVC) + set(TSLANG_LTCG_TARGETS + MLIRTypeScript + TypeScriptAliasPass + TypeScriptDebugInfoPass + TypeScriptExceptionPass + TypeScriptExportPass + TypeScriptMemAllocPass + TsClangImporter + ts-new-parser-lib + tslang + tsbindgen) + foreach(target ${TSLANG_LTCG_TARGETS}) + set_property(TARGET ${target} PROPERTY INTERPROCEDURAL_OPTIMIZATION_RELEASE ON) + target_compile_options(${target} PRIVATE $<$:/Ob3>) + endforeach() + message(STATUS "LTCG for: ${TSLANG_LTCG_TARGETS}") +endif() + if (NOT DEFINED TYPESCRIPT_IGNORE_UNIT_TESTS) # enable unit tests set (MLIRTYPESCRIPT_LLVM_THIRD_PARTY_DIR "${CMAKE_SOURCE_DIR}/../3rdParty/llvm-project/third-party") From 2816f3bf4a3e578b58585588d1a888b8c1d450a5 Mon Sep 17 00:00:00 2001 From: ASDAlexander77 Date: Sat, 14 Nov 2026 01:26:37 +0000 Subject: [PATCH 4/5] own: a nullable local moved when not null, a virtual call's own result, a field moved into another (TSLANG 49) - A value moved on some ways only is fine when, on every other way to its release, a branch tested it empty (`if (l) { this.f = l; }`): its release there frees nothing (emptyWhereNotMoved). - The result of a virtual call another module may override is the caller's when no method of the family says it borrows and each one defined here returns its own (familyResultsFresh). Under own, an override may not say it borrows when the method it overrides does not (checkOverrideResultFacts). - `this.other = this.level; this.level = null;` is a move: the source field refilled right after the taker, with only reads, constants and rc's counts of `null` between (spec 77 extended). Co-Authored-By: Claude Opus 5.5 --- TSLANG_ISSUES.md | 40 ++++++----- tslang/lib/TypeScript/MLIRGenClasses.cpp | 66 +++++++++++++++++++ tslang/lib/TypeScript/MLIRGenImpl.h | 8 +++ tslang/lib/TypeScript/OwnershipFacts.h | 56 ++++++++++++++++ .../TypeScript/OwnershipInferenceMoves.cpp | 4 +- .../OwnershipInferencePlaceReads.cpp | 42 ++++++++++++ .../lib/TypeScript/OwnershipSignaturePass.cpp | 25 +++++++ .../lib/TypeScript/OwnershipSignaturePass.h | 5 ++ tslang/test/tester/CMakeLists.txt | 8 ++- .../own/own_err_field_moved_call_between.ts | 18 +++++ .../own/own_err_moved_when_tested_other.ts | 18 +++++ .../test/tester/own/own_err_override_lends.ts | 16 +++++ tslang/test/tester/tests/00tslang_issue_49.ts | 62 +++++++++++++++++ 13 files changed, 347 insertions(+), 21 deletions(-) create mode 100644 tslang/test/tester/own/own_err_field_moved_call_between.ts create mode 100644 tslang/test/tester/own/own_err_moved_when_tested_other.ts create mode 100644 tslang/test/tester/own/own_err_override_lends.ts create mode 100644 tslang/test/tester/tests/00tslang_issue_49.ts diff --git a/TSLANG_ISSUES.md b/TSLANG_ISSUES.md index 3330aa82f..cb8a669cf 100644 --- a/TSLANG_ISSUES.md +++ b/TSLANG_ISSUES.md @@ -184,36 +184,40 @@ Still open from 48: when its class is exported. `--own-facts` reads the facts of the modules a module imports, not of the ones that import it, so the base's module can't know its subclasses. `@final` is the way to say it. - `@final` on an accessor (`get`/`set`) is accepted but changes nothing at the call site yet. -- The other errors seen in powder_sandbox's own build are item 49. The one in `levels.ts`, `'x' is +- The other errors seen in powder_sandbox's own build were item 49 (fixed). The one in `levels.ts`, `'x' is moved inside a loop but was made outside it` (the same `box` array kept by several `LevelStroke`s), is the game's to fix. -### 49. `-mm=own`: a nullable fresh local stored into a field, and a field moved into another - -Reduced on 2026-11-14 by the powder_sandbox session from the errors left in its own build. All three -fail on alpha127 and on the branch with the 47/48 fixes (`tslang -mm=own --emit=obj r1.ts`): +Item 49, three `-mm=own` errors powder_sandbox reduced on 2026-11-14 from what was left in its build, +is fixed. Before the fix, `startA`, `startB` and `moveAside` below were refused: ```ts class Level { name: string = "a"; } export class App { level: Level | null = null; + other: Level | null = null; read(n: string): Level | null { return n == "" ? null : new Level(); } - // 6:58 "moved here on some paths only" + "takes a second reference" startA(n: string) { const l = this.read(n); if (l) { this.level = l; } } - // 8:49 "takes a second reference": unconditional store of a nullable fresh local startB(n: string) { const l = this.read(n); this.level = l; } - other: Level | null = null; - // 11:19 "borrows a field and cannot be stored": moving one field into another (a swap works) moveAside() { this.other = this.level; this.level = null; } } -function main() { const a = new App(); a.startA("x"); a.startB("x"); a.moveAside(); print(a.other != null); } ``` -- `startA`: the store moves `l` on the path where it is not null. On the other path `l` is null and - holds nothing to release, so moving it on some paths only should be fine. -- `startB` compiles when `App` is `@final`, so the second reference likely comes from the call to - `this.read` going through the vtable. -- `moveAside`: a field read stored into another field, with the source cleared right after, is a move - of the field's value, as `[a, b] = [b, a]` already is. - -Worked around in powder_sandbox with the exchange `[l, this.level] = [this.level, l]`. +- `startA` ("moved here on some paths only"): a value moved on some ways only is fine when, on every + other way to its release, a branch tested it empty (`if (l)`, `if (!l) return;`, `l !== null`). There + it holds nothing, so the release frees nothing and goes (`emptyWhereNotMoved`). `if (l && n == "y")` + is still an error. +- `startB` ("takes a second reference"): `this.read(n)` goes through the vtable, since another module + may override `read`. The result of such a call is the caller's when no method of the family says it + borrows (`@lends`, `@borrows`, `@record`, a `this` result) and each one defined here returns its own. + An override in another module may not say it borrows when the method it overrides does not. Under + own that is an error now: "method 'read' returns a borrow ..., but the method of 'Base' it overrides + does not". +- `moveAside` ("borrows a field and cannot be stored"): a field read stored into another place and the + source field refilled right after is a move, as the exchange `[a, this.f] = [this.f, a]` (spec 77) + already was. Between the store and the refill there may be only reads, constants and rc's counts of + `null`. A call in between is still an error. + +Regression tests `tslang/test/tester/tests/00tslang_issue_49.ts` (every model), +`own/own_err_moved_when_tested_other.ts`, `own_err_field_moved_call_between.ts` and +`own_err_override_lends.ts`. powder_sandbox's exchange workaround still works. diff --git a/tslang/lib/TypeScript/MLIRGenClasses.cpp b/tslang/lib/TypeScript/MLIRGenClasses.cpp index c979025db..fa57483f3 100644 --- a/tslang/lib/TypeScript/MLIRGenClasses.cpp +++ b/tslang/lib/TypeScript/MLIRGenClasses.cpp @@ -4918,6 +4918,11 @@ genContext); classMethodMemberInfo.setFuncOp(funcOp); if (classMethodMemberInfo.registerClassMethodMember(loc(funcLikeDeclaration), orderWeight, accessLevel)) { + if (mlir::failed(checkOverrideResultFacts(loc(funcLikeDeclaration), newClassPtr, classMethodMemberInfo))) + { + return mlir::failure(); + } + // C++ methods: not a constructor, nor `.new` (static) if (!classMethodMemberInfo.isConstructor && !classMethodMemberInfo.isStatic && mlir::failed(mlirGenClassCppVTableHiddenReturn(loc(funcLikeDeclaration), newClassPtr, funcOp, @@ -5483,5 +5488,66 @@ genContext); return instance; } + mlir::LogicalResult MLIRGenImpl::checkOverrideResultFacts(mlir::Location location, ClassInfo::TypePtr classInfo, + ClassMethodMemberInfo &member) + { + if (compileOptions.memoryModel != MemoryModelOwn || member.isStatic || member.isConstructor) + { + return mlir::success(); + } + + auto index = classInfo->getMethodIndex(member.methodName); + if (index < 0) + { + return mlir::success(); + } + + auto saysBorrow = [](const MethodInfo &method) { + return method.ownLendsMask != 0 || !method.ownBorrows.empty() || method.ownRecord || method.ownReturnsThis; + }; + + auto &method = classInfo->methods[index]; + if (!saysBorrow(method)) + { + return mlir::success(); + } + + // the nearest base that has the method + std::function overridden = [&](ClassInfo::TypePtr of) -> ClassInfo::TypePtr { + for (auto &baseClass : of->baseClasses) + { + if (baseClass->getMethodIndex(member.methodName) >= 0) + { + return baseClass; + } + + if (auto found = overridden(baseClass)) + { + return found; + } + } + + return nullptr; + }; + + auto baseClass = overridden(classInfo); + if (!baseClass) + { + return mlir::success(); + } + + auto &baseMethod = baseClass->methods[baseClass->getMethodIndex(member.methodName)]; + if (baseMethod.isStatic || saysBorrow(baseMethod)) + { + return mlir::success(); + } + + emitError(location) << "method '" << member.methodName << "' returns a borrow ('@lends', '@borrows', '@record' or " + << "the result type 'this'), but the method of '" << baseClass->name + << "' it overrides does not: under -mm=own a call through '" << baseClass->name + << "' takes the result for its own"; + return mlir::failure(); + } + } // namespace mlirgen } // namespace typescript diff --git a/tslang/lib/TypeScript/MLIRGenImpl.h b/tslang/lib/TypeScript/MLIRGenImpl.h index 28b3c4947..814f45d6e 100644 --- a/tslang/lib/TypeScript/MLIRGenImpl.h +++ b/tslang/lib/TypeScript/MLIRGenImpl.h @@ -14491,6 +14491,14 @@ class MLIRGenImpl mlir::LogicalResult mlirGenClassVirtualTableDefinition(mlir::Location location, ClassInfo::TypePtr newClassPtr, const GenContext &genContext); + struct ClassMethodMemberInfo; + + // -mm=own (TSLANG 49): a caller through the base takes the result of a method it cannot resolve for + // its own when no method of the family says the result borrows. So an override may not say so + // (`@lends`, `@borrows`, `@record`, a result of type `this`) when the method it overrides does not. + mlir::LogicalResult checkOverrideResultFacts(mlir::Location location, ClassInfo::TypePtr classInfo, + ClassMethodMemberInfo &member); + struct ClassMethodMemberInfo { ClassMethodMemberInfo(ClassInfo::TypePtr newClassPtr, ClassElement classMember) : newClassPtr(newClassPtr), classMember(classMember) diff --git a/tslang/lib/TypeScript/OwnershipFacts.h b/tslang/lib/TypeScript/OwnershipFacts.h index 2dbcde646..300487f7d 100644 --- a/tslang/lib/TypeScript/OwnershipFacts.h +++ b/tslang/lib/TypeScript/OwnershipFacts.h @@ -1297,6 +1297,62 @@ inline bool mayWriteField(mlir::Operation *op, mlir_ts::PropertyRefOp field, mli return writes; } +// Does every way from `definition`, where `value` is made, to `release` that does not run `move`'s +// block leave a branch on which `value` was tested empty (testedEmpty): `if (l) { this.f = l; }`? On +// those ways the value holds no block, and its release there frees nothing (TSLANG 49). A way back to +// the definition's block makes a new value; it ends there. +inline bool emptyWhereNotMoved(mlir::Value value, mlir::Operation *definition, mlir::Operation *move, mlir::Operation *release) +{ + auto *start = definition ? definition->getBlock() : nullptr; + if (!start || !move || start == release->getBlock() || start->getParent() != release->getBlock()->getParent() || + start->getParent() != move->getBlock()->getParent()) + { + return false; + } + + auto root = rootOf(value); + llvm::SmallPtrSet seen{start}; + llvm::SmallVector work{start}; + while (!work.empty()) + { + auto *block = work.pop_back_val(); + auto *terminator = block->getTerminator(); + auto condBrOp = mlir::dyn_cast_or_null(terminator); + for (unsigned index = 0; terminator && index < terminator->getNumSuccessors(); ++index) + { + auto *successor = terminator->getSuccessor(index); + if (condBrOp && condBrOp.getTrueDest() != condBrOp.getFalseDest()) + { + mlir::Value condition = condBrOp.getCondition(); + if (auto castOp = condition.getDefiningOp()) + { + condition = castOp->getOperand(0); + } + + auto tested = testedEmpty(condition, successor == condBrOp.getTrueDest()); + if (tested && rootOf(tested) == root) + { + continue; // empty from here on + } + } + + if (successor == release->getBlock()) + { + return false; + } + + if (successor == move->getBlock() || successor == start || !seen.insert(successor).second) + { + continue; + } + + work.push_back(successor); + } + } + + return true; +} + // Is this release of a field's old value a fill (TSLANG 47): the field was tested empty on the way // here, and nothing that may write it ran since? The test reads the field itself, or a `let` or // `const` declared from it that nothing assigns before the test (`let r = this.cached; if (!r) {...}`), diff --git a/tslang/lib/TypeScript/OwnershipInferenceMoves.cpp b/tslang/lib/TypeScript/OwnershipInferenceMoves.cpp index f6e0c4448..730b83176 100644 --- a/tslang/lib/TypeScript/OwnershipInferenceMoves.cpp +++ b/tslang/lib/TypeScript/OwnershipInferenceMoves.cpp @@ -1003,7 +1003,9 @@ namespace own_inference continue; } - if (!dominance->properlyDominates(acquire, release)) + // moved on some ways only: on the others it must be empty (TSLANG 49) + if (!dominance->properlyDominates(acquire, release) && + !emptyWhereNotMoved(value, definition, acquire, release)) { reportMovedOnSomePaths(taker, release, name); return false; diff --git a/tslang/lib/TypeScript/OwnershipInferencePlaceReads.cpp b/tslang/lib/TypeScript/OwnershipInferencePlaceReads.cpp index 0369d0ac3..489360adb 100644 --- a/tslang/lib/TypeScript/OwnershipInferencePlaceReads.cpp +++ b/tslang/lib/TypeScript/OwnershipInferencePlaceReads.cpp @@ -1364,6 +1364,13 @@ namespace own_inference continue; } + // the release of what the taker's place held, right before the store into it (TSLANG 49) + if (auto releaseSlotOp = mlir::dyn_cast(op); + releaseSlotOp && !intoLocal && releaseSlotOp.getSlot() == storeOp.getReference() && op->getNextNode() == taker) + { + continue; + } + if (auto releaseSlotOp = mlir::dyn_cast(op)) { // a local's own release (the taker's assignment), never of the place's object @@ -1397,6 +1404,41 @@ namespace own_inference return false; } + // ...or refilled right after the taker (TSLANG 49): `this.other = this.level; this.level = null;` + // moves the field into another. The same field of the same object, its release right before + // the store that refills it, with only reads, constants and views between - nothing that could + // free or read what both places hold until then. + if (!refillRelease && retained) + { + auto field = place.getDefiningOp(); + for (auto *op = field ? taker->getNextNode() : nullptr; op; op = op->getNextNode()) + { + if (auto releaseSlotOp = mlir::dyn_cast(op)) + { + auto refillField = releaseSlotOp.getSlot().getDefiningOp(); + auto refillStore = mlir::dyn_cast_or_null(op->getNextNode()); + if (refillField && sameField(refillField, field) && refillStore && + refillStore.getReference() == releaseSlotOp.getSlot()) + { + refillRelease = op; + } + + break; + } + + // rc's retain of the refill's value, when that holds no block (`null`) + auto retainsNothing = mlir::isa(op) && holdsNoBlock(op->getOperand(0)); + // ...and that value, `null` cast to the field's union + auto castsNothing = mlir::isa(op) && holdsNoBlock(op->getResult(0)); + if (!mlir::isa(op) && + !isView(op) && !retainsNothing && !castsNothing) + { + break; + } + } + } + if (!refillRelease) { return false; diff --git a/tslang/lib/TypeScript/OwnershipSignaturePass.cpp b/tslang/lib/TypeScript/OwnershipSignaturePass.cpp index 73dfeba84..af05f1c35 100644 --- a/tslang/lib/TypeScript/OwnershipSignaturePass.cpp +++ b/tslang/lib/TypeScript/OwnershipSignaturePass.cpp @@ -261,6 +261,15 @@ namespace own_signature if (refOp && !refOp->hasAttr(FINAL_RECEIVER_ATTR_NAME)) { call.op->setAttr(OWN_OVERRIDABLE_CALL_ATTR_NAME, refOp.getIdentifierAttr()); + + // ...whose result is the caller's when no method of the family says it borrows: an + // override in another module may not say so either (checkOverrideResultFacts), and + // one that returns a borrow without saying it is an error there (TSLANG 49) + if (call.op->getNumResults() == 1 && !isRecordResult(call.op) && + familyResultsFresh(refOp.getIndex(), refOp.getIdentifierAttr().getAttr())) + { + call.op->setAttr(OWN_FRESH_RESULT_ATTR_NAME, mlir::UnitAttr::get(&getContext())); + } } continue; @@ -1650,6 +1659,22 @@ namespace own_signature computeDropsRound(true); } + bool OwnershipSignaturePass::familyResultsFresh(int64_t index, mlir::StringAttr identifier) + { + for (auto member : familyOf(index, identifier)) + { + auto funcOp = functions.lookup(member.getValue()); + if (!funcOp || funcOp->hasAttr(OWN_DECLARED_LENDS_ATTR_NAME) || funcOp->hasAttr(OWN_DECLARED_BORROWS_ATTR_NAME) || + funcOp->hasAttr(OWN_DECLARED_RECORD_ATTR_NAME) || funcOp->hasAttr(OWN_IMPLIED_LENDS_ATTR_NAME) || + (!funcOp.isDeclaration() && !returnsFresh(funcOp))) + { + return false; + } + } + + return true; + } + bool OwnershipSignaturePass::isFill(mlir_ts::ReleaseSlotOp releaseSlotOp) { return releaseSlotOp->hasAttr(OWN_FILL_ATTR_NAME); diff --git a/tslang/lib/TypeScript/OwnershipSignaturePass.h b/tslang/lib/TypeScript/OwnershipSignaturePass.h index c94854f9a..1172dfc79 100644 --- a/tslang/lib/TypeScript/OwnershipSignaturePass.h +++ b/tslang/lib/TypeScript/OwnershipSignaturePass.h @@ -626,6 +626,11 @@ class OwnershipSignaturePass : public mlir::PassWrapper callOf; diff --git a/tslang/test/tester/CMakeLists.txt b/tslang/test/tester/CMakeLists.txt index 4a9eb095e..cc06b41f3 100644 --- a/tslang/test/tester/CMakeLists.txt +++ b/tslang/test/tester/CMakeLists.txt @@ -1903,8 +1903,9 @@ endforeach() # TSLANG_ISSUES 46: a function returning its union parameter, given a new object, freed it twice # TSLANG_ISSUES 47: a lazily cached field returned through a local; a fill of an empty field frees nothing # TSLANG_ISSUES 48: a @final method of an exported class is called directly, by its own facts +# TSLANG_ISSUES 49: a nullable local moved when not null, a virtual call's own result, a field moved into another foreach(issues_mm gc rc none own) - foreach(issues_test 00tslang_issue_44 00tslang_issue_45 00tslang_issue_46 00tslang_issue_47 00tslang_issue_48) + foreach(issues_test 00tslang_issue_44 00tslang_issue_45 00tslang_issue_46 00tslang_issue_47 00tslang_issue_48 00tslang_issue_49) tslang_add_test(NAME test-jit-${issues_test}-${issues_mm} COMMAND test-runner -jit -mm=${issues_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/${issues_test}.ts") tslang_add_test(NAME test-compile-${issues_test}-${issues_mm} COMMAND test-runner -mm=${issues_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/${issues_test}.ts") endforeach() @@ -5435,7 +5436,10 @@ set(own_error_cases "own_err_fill_after_call|:21:11: error: '[^']*' borrows the result of 'Dev.getQ' but is used here after it may be released or overwritten" "own_err_fill_in_loop|:23:11: error: '[^']*' borrows the result of 'Dev.getQ' but is used here after it may be released or overwritten" "own_err_fill_other_field|:20:11: error: '[^']*' borrows the result of 'Dev.getQ' but is used here after it may be released or overwritten" - "own_err_fill_after_fill_call|:19:20: error: '[^']*' borrows the result of 'Dev.fill' but is used here after it may be released or overwritten") + "own_err_fill_after_fill_call|:19:20: error: '[^']*' borrows the result of 'Dev.fill' but is used here after it may be released or overwritten" + "own_err_moved_when_tested_other|:13:13: error: '[^']*' is moved here on some paths only" + "own_err_field_moved_call_between|:12:9: error: '[^']*' borrows a field and cannot be stored, returned or captured" + "own_err_override_lends|:13:5: error: method 'read' returns a borrow .* but the method of 'Base' it overrides does not") foreach(own_error_case ${own_error_cases}) string(FIND "${own_error_case}" "|" own_error_sep) string(SUBSTRING "${own_error_case}" 0 ${own_error_sep} own_error_name) diff --git a/tslang/test/tester/own/own_err_field_moved_call_between.ts b/tslang/test/tester/own/own_err_field_moved_call_between.ts new file mode 100644 index 000000000..3fe1fa178 --- /dev/null +++ b/tslang/test/tester/own/own_err_field_moved_call_between.ts @@ -0,0 +1,18 @@ +// TSLANG_ISSUES 49: one field moved into another and the source cleared - but a call in between may +// free or read what both fields hold, so the move is refused. +class Level { + name: string = "a"; +} + +class App { + level: Level | null = new Level(); + other: Level | null = null; + side() { this.other = null; } + moveAside() { + this.other = this.level; + this.side(); + this.level = null; + } +} + +function main() { const a = new App(); a.moveAside(); print(a.other != null); } diff --git a/tslang/test/tester/own/own_err_moved_when_tested_other.ts b/tslang/test/tester/own/own_err_moved_when_tested_other.ts new file mode 100644 index 000000000..ab70c9726 --- /dev/null +++ b/tslang/test/tester/own/own_err_moved_when_tested_other.ts @@ -0,0 +1,18 @@ +// TSLANG_ISSUES 49: a fresh local moved into a field on some ways only is fine when on the others it +// was tested empty - not here, where `n == "y"` may be false while `l` holds an object. +class Level { + name: string = "a"; +} + +class App { + level: Level | null = null; + read(n: string): Level | null { return n == "" ? null : new Level(); } + start(n: string) { + const l = this.read(n); + if (l && n == "y") { + this.level = l; + } + } +} + +function main() { const a = new App(); a.start("x"); print(a.level != null); } diff --git a/tslang/test/tester/own/own_err_override_lends.ts b/tslang/test/tester/own/own_err_override_lends.ts new file mode 100644 index 000000000..ac32165d8 --- /dev/null +++ b/tslang/test/tester/own/own_err_override_lends.ts @@ -0,0 +1,16 @@ +// TSLANG_ISSUES 49: a caller through `Base` takes `read`'s result for its own, since `Base.read` does not +// say it borrows; so an override may not say it does. +class Level { + name: string = "a"; +} + +export class Base { + keep: Level = new Level(); + read(): Level { return new Level(); } +} + +export class Der extends Base { + @lends("this") read(): Level { return this.keep; } +} + +function main() { print(new Der().read().name); } diff --git a/tslang/test/tester/tests/00tslang_issue_49.ts b/tslang/test/tester/tests/00tslang_issue_49.ts new file mode 100644 index 000000000..77ad82169 --- /dev/null +++ b/tslang/test/tester/tests/00tslang_issue_49.ts @@ -0,0 +1,62 @@ +// TSLANG_ISSUES 49 (-mm=own), reduced by powder_sandbox: +// - startA: a nullable fresh local moved into a field when it is not null. On the other way it is +// null and holds nothing, so its release there frees nothing. +// - startB: the result of a method of an exported class, called through its vtable, is the caller's +// when no method of its family says it borrows (an override may not say it either). +// - moveAside: one field moved into another, the source cleared right after. + +class Level { + name: string = "a"; +} + +export class App { + level: Level | null = null; + other: Level | null = null; + + read(n: string): Level | null { + return n == "" ? null : new Level(); + } + + startA(n: string) { + const l = this.read(n); + if (l) { + this.level = l; + } + } + + startA2(n: string) { + const l = this.read(n); + if (!l) { + return; + } + + this.level = l; + } + + startB(n: string) { + const l = this.read(n); + this.level = l; + } + + moveAside() { + this.other = this.level; + this.level = null; + } +} + +function main() { + const a = new App(); + a.startA(""); + assert(a.level == null); + a.startA("x"); + assert(a.level != null); + a.startA2(""); + a.startA2("y"); + a.startB("x"); + a.moveAside(); + print(a.level != null, a.other != null); + assert(a.level == null && a.other != null && a.other.name == "a"); + a.startB(""); + assert(a.level == null); + print("done."); +} From a00a8f1e71caf3941f1f34ee75a68d955a58d028 Mon Sep 17 00:00:00 2001 From: ASDAlexander77 Date: Sat, 14 Nov 2026 02:01:08 +0000 Subject: [PATCH 5/5] @final accessors; a function value given as a C pointer is checked; Opaque-first closures (TSLANG 48, 29) - @final on a get/set accessor works as on a method: a direct call, the override error ("accessor 'x' overrides the @final accessor of 'Base'"), the declaration printer writes it, and the own note for an overridable call names an accessor's slot too. - TSLANG 29: a function value (a const of function type, a callback parameter) passed to a @cdecl callback parameter is checked at run time: a closure throws "a closure or a bound method can't be used as a plain function pointer" instead of being run later without its captures. A function named directly is not checked. - A capturing arrow can be assigned to `(a: Opaque, b: Opaque) => s32`: the function type match tries the parameters as they are before taking leading Opaque/object parameters for a receiver. Co-Authored-By: Claude Opus 5.5 --- TSLANG_ISSUES.md | 15 ++++-- .../TypeScript/MLIRLogic/MLIRTypeHelper.h | 21 ++++++-- tslang/lib/TypeScript/DeclarationPrinter.cpp | 9 ++++ tslang/lib/TypeScript/MLIRGenAccessCall.cpp | 7 +++ tslang/lib/TypeScript/MLIRGenCast.cpp | 48 +++++++++++++++++++ tslang/lib/TypeScript/MLIRGenImpl.h | 19 +++++++- .../lib/TypeScript/OwnershipSignaturePass.cpp | 14 ++++-- tslang/test/tester/CMakeLists.txt | 8 ++++ .../tests/00tslang_issue_29_comparator.ts | 21 ++++++++ .../tests/00tslang_issue_29_function_value.ts | 32 +++++++++++++ tslang/test/tester/tests/00tslang_issue_48.ts | 8 +++- .../tests/final_accessor_override_error.ts | 10 ++++ tslang/test/tester/verify-ownership.cmake | 3 +- tslang/test/wasm/wasm_skips.txt | 1 + 14 files changed, 200 insertions(+), 16 deletions(-) create mode 100644 tslang/test/tester/tests/00tslang_issue_29_comparator.ts create mode 100644 tslang/test/tester/tests/00tslang_issue_29_function_value.ts create mode 100644 tslang/test/tester/tests/final_accessor_override_error.ts diff --git a/TSLANG_ISSUES.md b/TSLANG_ISSUES.md index cb8a669cf..f4fd4604b 100644 --- a/TSLANG_ISSUES.md +++ b/TSLANG_ISSUES.md @@ -24,9 +24,14 @@ Regression test `tslang/test/tester/tests/00tslang_issue_28.ts`. so `_beginthreadex(..., entry, arg, ...)` shifted `arg` and every argument after the callback): a function declared `@cdecl` takes each function-typed parameter as a C function pointer. A function or an arrow that captures nothing passes; a capturing arrow or a bound method passed straight to it is a -compile error ("a closure or a bound method can't be used as a plain function pointer"). Not checked -yet: a closure already stored in a variable of function type, passed on to a `@cdecl` parameter, still -loses its captures at run time. Regression tests `tslang/test/tester/tests/00tslang_issue_29.ts`, +compile error ("a closure or a bound method can't be used as a plain function pointer"). A function +value (a `const` of function type, a callback parameter) passed on to a `@cdecl` parameter is checked at +run time: a closure throws that error there, instead of the C function running it without its captures +later (an `atexit` handler crashed at exit). A function named directly skips the check. Also, a +capturing arrow can now be assigned to a function type whose leading parameters are `Opaque` +(`(a: Opaque, b: Opaque) => s32`, a C comparator). The type match took a leading `Opaque` for a receiver +and refused it; the parameters are now first matched as they are. Regression tests +`00tslang_issue_29_function_value.ts` and `00tslang_issue_29_comparator.ts`, and `tslang/test/tester/tests/00tslang_issue_29.ts`, `00tslang_issue_29_thread.ts` (Windows), `00tslang_issue_29_pthread.ts` (Linux) and `cdecl_closure_error.ts`. 30 (a generic's body, compiled where it is first instantiated, resolved a name to a local of the @@ -183,7 +188,9 @@ Still open from 48: - Whole-program facts: a method that no module of the program overrides is still taken as overridable when its class is exported. `--own-facts` reads the facts of the modules a module imports, not of the ones that import it, so the base's module can't know its subclasses. `@final` is the way to say it. -- `@final` on an accessor (`get`/`set`) is accepted but changes nothing at the call site yet. +- `@final` on an accessor (`get`/`set`) works now, as on a method: a direct call, an error for an + override ("accessor 'x' overrides the @final accessor of 'Base'"), and the declaration printer writes + it. - The other errors seen in powder_sandbox's own build were item 49 (fixed). The one in `levels.ts`, `'x' is moved inside a loop but was made outside it` (the same `box` array kept by several `LevelStroke`s), is the game's to fix. diff --git a/tslang/include/TypeScript/MLIRLogic/MLIRTypeHelper.h b/tslang/include/TypeScript/MLIRLogic/MLIRTypeHelper.h index 6390d1b56..7eebd2d28 100644 --- a/tslang/include/TypeScript/MLIRLogic/MLIRTypeHelper.h +++ b/tslang/include/TypeScript/MLIRLogic/MLIRTypeHelper.h @@ -1455,8 +1455,19 @@ class MLIRTypeHelper } MatchResult TestFunctionTypesMatchWithObjectMethods(mlir::Location location, mlir_ts::FunctionType inFuncType, mlir_ts::FunctionType resFuncType, - unsigned startParamIn = 0, unsigned startParamRes = 0) + unsigned startParamIn = 0, unsigned startParamRes = 0, bool asGiven = false) { + // The parameters as they are first: a leading `Opaque` may be a real one, not a receiver - + // `(a: Opaque, b: Opaque) => s32`, a C comparator, given a closure over a variable + if (!asGiven) + { + auto plain = TestFunctionTypesMatchWithObjectMethods(location, inFuncType, resFuncType, startParamIn, startParamRes, true); + if (plain.result == MatchResultType::Match) + { + return plain; + } + } + LLVM_DEBUG(llvm::dbgs() << "\n!!" << "@ TestFunctionTypesMatchWithObjectMethods:" << inFuncType << " -> " << resFuncType << "\n";); @@ -1466,25 +1477,25 @@ class MLIRTypeHelper // 1 we need to skip opaque and objects // TODO: we need to refactor func types the way that we can understand if this is func with "captured var", bound to object etc - if (startParamIn <= 0 && inFuncType.getNumInputs() > 0 && + if (!asGiven && startParamIn <= 0 && inFuncType.getNumInputs() > 0 && (isa(inFuncType.getInput(0)) || isa(inFuncType.getInput(0)))) { startParamIn = 1; } - if (startParamIn <= 1 && inFuncType.getNumInputs() > 1 && + if (!asGiven && startParamIn <= 1 && inFuncType.getNumInputs() > 1 && (isa(inFuncType.getInput(1)) || isa(inFuncType.getInput(1)))) { startParamIn = 2; } - if (startParamRes <= 0 && resFuncType.getNumInputs() > 0 && + if (!asGiven && startParamRes <= 0 && resFuncType.getNumInputs() > 0 && (isa(resFuncType.getInput(0)) || isa(resFuncType.getInput(0)))) { startParamRes = 1; } - if (startParamRes <= 1 && resFuncType.getNumInputs() > 1 && + if (!asGiven && startParamRes <= 1 && resFuncType.getNumInputs() > 1 && (isa(resFuncType.getInput(1)) || isa(resFuncType.getInput(1)))) { startParamRes = 2; diff --git a/tslang/lib/TypeScript/DeclarationPrinter.cpp b/tslang/lib/TypeScript/DeclarationPrinter.cpp index 2c1b5f5d1..e60cab6c2 100644 --- a/tslang/lib/TypeScript/DeclarationPrinter.cpp +++ b/tslang/lib/TypeScript/DeclarationPrinter.cpp @@ -724,6 +724,15 @@ namespace typescript if (filterName(accessor.name)) continue; + // no override (TSLANG 48) + if (method.isFinal && !method.isStatic && + ((accessor.get && accessor.get.name == method.funcName) || (accessor.set && accessor.set.name == method.funcName))) + { + os.indent(4); + os << "@" FINAL_DECORATOR; + newline(); + } + if (accessor.get && accessor.get.name == method.funcName) { printAccessorGet(accessor); diff --git a/tslang/lib/TypeScript/MLIRGenAccessCall.cpp b/tslang/lib/TypeScript/MLIRGenAccessCall.cpp index 56a476f2e..5f580eca7 100644 --- a/tslang/lib/TypeScript/MLIRGenAccessCall.cpp +++ b/tslang/lib/TypeScript/MLIRGenAccessCall.cpp @@ -769,6 +769,13 @@ namespace mlirgen auto getMethodInfo = findMethodInfo(getFunc); auto setMethodInfo = findMethodInfo(setFunc); + // @final accessors (TSLANG 48): no subclass overrides them, so the ones this class has run + if ((getMethodInfo || setMethodInfo) && (!getMethodInfo || getMethodInfo->isFinal) && + (!setMethodInfo || setMethodInfo->isFinal)) + { + finalReceiver = true; + } + // a @final receiver's accessor is the one this class has, called directly when the class // is defined in this module, as a method is (ClassMethodAccess) auto direct = finalReceiver && !classInfo->isDeclaration && !classInfo->isImport && diff --git a/tslang/lib/TypeScript/MLIRGenCast.cpp b/tslang/lib/TypeScript/MLIRGenCast.cpp index dea46c2d5..67ba61a2e 100644 --- a/tslang/lib/TypeScript/MLIRGenCast.cpp +++ b/tslang/lib/TypeScript/MLIRGenCast.cpp @@ -409,6 +409,54 @@ namespace mlirgen }); } + mlir::LogicalResult MLIRGenImpl::checkNotClosureAtRunTime(mlir::Location location, mlir::Value value, const GenContext &genContext) + { + // a function by name, made a function value: nothing to test + for (auto current = value; current;) + { + auto *def = current.getDefiningOp(); + if (!def) + { + break; + } + + if (auto castOp = dyn_cast(def)) + { + if (castOp.getIn().getDefiningOp() && isa(castOp.getIn().getType())) + { + return mlir::success(); + } + + current = castOp.getIn(); + continue; + } + + break; + } + + auto thisVal = builder.create(location, getOpaqueType(), value); + auto isBound = builder.create(location, getBooleanType(), thisVal); + auto ifOp = builder.create(location, isBound, false); + mlir::OpBuilder::InsertionGuard guard(builder); + builder.setInsertionPointToStart(&ifOp.getThenRegion().front()); + auto message = builder.create( + location, getStringType(), + getStringAttr("a closure or a bound method can't be used as a plain function pointer: the pointer carries " + "no captured variables and no 'this'")); + builder.create(location, message); + + MLIRRTTIHelperVC rtti(builder, theModule, compileOptions); + setCatchCopyThunkBuilder(rtti); + if (!rtti.setRTTIForType(location, message.getType(), + [&](StringRef classFullName) { return getClassInfoByFullName(classFullName); })) + { + emitError(location, "Not supported type in throw"); + return mlir::failure(); + } + + return mlir::success(); + } + ValueOrLogicalResult MLIRGenImpl::castFieldsToClass(mlir::Location location, mlir::Value value, ::llvm::ArrayRef<::mlir::typescript::FieldInfo> fields, mlir_ts::ClassType classType, const GenContext &genContext, bool errorAsWarning) diff --git a/tslang/lib/TypeScript/MLIRGenImpl.h b/tslang/lib/TypeScript/MLIRGenImpl.h index 814f45d6e..ce1bce53c 100644 --- a/tslang/lib/TypeScript/MLIRGenImpl.h +++ b/tslang/lib/TypeScript/MLIRGenImpl.h @@ -11133,6 +11133,15 @@ class MLIRGenImpl return mlir::failure(); } + // A function value (`const f: () => void = ...`, a callback parameter) may be a closure + // at run time: its bound value is checked, and a closure is an error there instead of + // a C function that reads its captures through garbage (TSLANG_ISSUES 29) + if (isa(value.getType()) && isa(argTypeDestFuncType) && + mlir::failed(checkNotClosureAtRunTime(location, value, genContext))) + { + return mlir::failure(); + } + CAST_A(castValue, location, argTypeDestFuncType, value, genContext); if (auto castOp = castValue.getDefiningOp(); @@ -14493,6 +14502,11 @@ class MLIRGenImpl struct ClassMethodMemberInfo; + // TSLANG_ISSUES 29: a function value given as a C function pointer must not hold a closure's + // captures or a bound `this`: unless it is a function named directly (seen through its views + // and the `const`s that hold it), a run-time test throws when it does. + mlir::LogicalResult checkNotClosureAtRunTime(mlir::Location location, mlir::Value value, const GenContext &genContext); + // -mm=own (TSLANG 49): a caller through the base takes the result of a method it cannot resolve for // its own when no method of the family says the result borrows. So an override may not say so // (`@lends`, `@borrows`, `@record`, a result of type `this`) when the method it overrides does not. @@ -14577,8 +14591,9 @@ class MLIRGenImpl { if (auto finalOwner = finalMethodOwner(newClassPtr, methodName)) { - emitError(location) << "method '" << methodName << "' overrides the @" FINAL_DECORATOR " method of '" - << finalOwner->name << "'"; + auto isAccessor = classMember == SyntaxKind::GetAccessor || classMember == SyntaxKind::SetAccessor; + emitError(location) << (isAccessor ? "accessor '" : "method '") << getName() << "' overrides the @" FINAL_DECORATOR + << (isAccessor ? " accessor of '" : " method of '") << finalOwner->name << "'"; return false; } } diff --git a/tslang/lib/TypeScript/OwnershipSignaturePass.cpp b/tslang/lib/TypeScript/OwnershipSignaturePass.cpp index af05f1c35..12ce9eb4e 100644 --- a/tslang/lib/TypeScript/OwnershipSignaturePass.cpp +++ b/tslang/lib/TypeScript/OwnershipSignaturePass.cpp @@ -257,16 +257,24 @@ namespace own_signature callee = getMethodOp.getBoundFunc(); } - auto refOp = callee ? callee.getDefiningOp() : mlir_ts::ThisVirtualSymbolRefOp(); + // a method's slot, or an accessor's + auto *refDef = callee ? callee.getDefiningOp() : nullptr; + auto methodRef = mlir::dyn_cast_or_null(refDef); + auto accessorRef = mlir::dyn_cast_or_null(refDef); + auto *refOp = methodRef ? methodRef.getOperation() : accessorRef ? accessorRef.getOperation() : nullptr; + auto identifier = methodRef ? methodRef.getIdentifierAttr() : accessorRef ? accessorRef.getIdentifierAttr() + : mlir::FlatSymbolRefAttr(); + int64_t slotIndex = methodRef ? static_cast(methodRef.getIndex()) + : accessorRef ? static_cast(accessorRef.getIndex()) : -1; if (refOp && !refOp->hasAttr(FINAL_RECEIVER_ATTR_NAME)) { - call.op->setAttr(OWN_OVERRIDABLE_CALL_ATTR_NAME, refOp.getIdentifierAttr()); + call.op->setAttr(OWN_OVERRIDABLE_CALL_ATTR_NAME, identifier); // ...whose result is the caller's when no method of the family says it borrows: an // override in another module may not say so either (checkOverrideResultFacts), and // one that returns a borrow without saying it is an error there (TSLANG 49) if (call.op->getNumResults() == 1 && !isRecordResult(call.op) && - familyResultsFresh(refOp.getIndex(), refOp.getIdentifierAttr().getAttr())) + familyResultsFresh(slotIndex, identifier.getAttr())) { call.op->setAttr(OWN_FRESH_RESULT_ATTR_NAME, mlir::UnitAttr::get(&getContext())); } diff --git a/tslang/test/tester/CMakeLists.txt b/tslang/test/tester/CMakeLists.txt index cc06b41f3..d37c10372 100644 --- a/tslang/test/tester/CMakeLists.txt +++ b/tslang/test/tester/CMakeLists.txt @@ -1922,6 +1922,10 @@ add_test(NAME test-compile-final-method-override-error COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/final_method_override_error.ts") set_tests_properties(test-compile-final-method-override-error PROPERTIES PASS_REGULAR_EXPRESSION "method 'factor' overrides the @final method of 'Base'" FAIL_REGULAR_EXPRESSION "Stack dump|Assertion failed") +add_test(NAME test-compile-final-accessor-override-error + COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/final_accessor_override_error.ts") +set_tests_properties(test-compile-final-accessor-override-error PROPERTIES PASS_REGULAR_EXPRESSION "accessor 'factor' overrides the @final accessor of 'Base'" + FAIL_REGULAR_EXPRESSION "Stack dump|Assertion failed") add_test(NAME test-compile-final-method-abstract-error COMMAND test-runner "${PROJECT_SOURCE_DIR}/test/tester/tests/final_method_abstract_error.ts") set_tests_properties(test-compile-final-method-abstract-error PROPERTIES PASS_REGULAR_EXPRESSION "method 'factor' cannot be both abstract and @final" @@ -1949,6 +1953,10 @@ endif() foreach(issues_mm gc rc none own) tslang_add_test(NAME test-jit-00-tslang-issue-29-${issues_mm} COMMAND test-runner -jit -mm=${issues_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00tslang_issue_29.ts") tslang_add_test(NAME test-compile-00-tslang-issue-29-${issues_mm} COMMAND test-runner -mm=${issues_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00tslang_issue_29.ts") + tslang_add_test(NAME test-jit-00-tslang-issue-29-function-value-${issues_mm} COMMAND test-runner -jit -mm=${issues_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00tslang_issue_29_function_value.ts") + tslang_add_test(NAME test-compile-00-tslang-issue-29-function-value-${issues_mm} COMMAND test-runner -mm=${issues_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00tslang_issue_29_function_value.ts") + tslang_add_test(NAME test-jit-00-tslang-issue-29-comparator-${issues_mm} COMMAND test-runner -jit -mm=${issues_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00tslang_issue_29_comparator.ts") + tslang_add_test(NAME test-compile-00-tslang-issue-29-comparator-${issues_mm} COMMAND test-runner -mm=${issues_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00tslang_issue_29_comparator.ts") tslang_add_test(NAME test-jit-00-tslang-issue-29-thread-${issues_mm} COMMAND test-runner -jit -mm=${issues_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/${issue_29_thread_test}") tslang_add_test(NAME test-compile-00-tslang-issue-29-thread-${issues_mm} COMMAND test-runner -mm=${issues_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/${issue_29_thread_test}") endforeach() diff --git a/tslang/test/tester/tests/00tslang_issue_29_comparator.ts b/tslang/test/tester/tests/00tslang_issue_29_comparator.ts new file mode 100644 index 000000000..d94b3f97a --- /dev/null +++ b/tslang/test/tester/tests/00tslang_issue_29_comparator.ts @@ -0,0 +1,21 @@ +// TSLANG_ISSUES 29: a C comparator given as a function value. A capturing arrow assigned to a type whose +// parameters are `Opaque` (`(a: Opaque, b: Opaque) => s32`) was refused: the leading `Opaque` was taken +// for a receiver. It is a closure now, callable directly; given to qsort through a variable or a +// parameter, a plain function sorts and a closure throws (it has captures the C pointer can't carry). +@cdecl declare function qsort(base: Opaque, count: index, size: index, compare: (a: Opaque, b: Opaque) => s32): void; +type Cmp = (a: Opaque, b: Opaque) => s32; +function byValue(a: Opaque, b: Opaque): s32 { return Deref(>a) - Deref(>b); } +function sortWith(items: s32[], compare: Cmp): boolean { + try { qsort(Ref(items[0]), items.length, 4, compare); } catch (e) { return false; } + return true; +} +function main() { + const items: s32[] = [3, 1, 2]; + const viaPlain: Cmp = byValue; + assert(sortWith(items, viaPlain) && items[0] == 1 && items[1] == 2 && items[2] == 3, "a plain function"); + const offset = 0; + const capturing: Cmp = (a: Opaque, b: Opaque) => (byValue(b, a) + offset); + assert(capturing(Ref(items[0]), Ref(items[1])) > 0, "a closure called directly"); + assert(!sortWith(items, capturing), "a closure as a C comparator throws"); + print("done."); +} diff --git a/tslang/test/tester/tests/00tslang_issue_29_function_value.ts b/tslang/test/tester/tests/00tslang_issue_29_function_value.ts new file mode 100644 index 000000000..757c477c0 --- /dev/null +++ b/tslang/test/tester/tests/00tslang_issue_29_function_value.ts @@ -0,0 +1,32 @@ +// TSLANG_ISSUES 29: a function value - a `const` of function type, a callback parameter - given to a +// @cdecl function's callback parameter. A plain function passes as a C function pointer; a closure, +// whose captures the pointer can't carry, throws there instead of running later with none. +@cdecl declare function atexit(fn: () => void): s32; + +function plain() { + print("plain at exit"); +} + +function register(f: () => void) { + atexit(f); +} + +function main() { + let n = 42; + const viaPlain: () => void = plain; + atexit(viaPlain); + register(plain); + + let caught = false; + try { + const viaClosure: () => void = () => { + print("closure sees", n); + }; + register(viaClosure); + } catch (e) { + caught = true; + } + + assert(caught, "a closure as a C function pointer throws"); + print("done."); +} diff --git a/tslang/test/tester/tests/00tslang_issue_48.ts b/tslang/test/tester/tests/00tslang_issue_48.ts index 8a06a85d4..036bcfe96 100644 --- a/tslang/test/tester/tests/00tslang_issue_48.ts +++ b/tslang/test/tester/tests/00tslang_issue_48.ts @@ -15,6 +15,11 @@ export class Base { return this.scale; } + // a @final getter, as a @final method + @final get doubled(): number { + return this.scale * 2; + } + // a method that is not final, overridden below: still called through the vtable bonus(): number { return 0; @@ -25,7 +30,8 @@ export class App extends Base { total(): number { const item = this.items[1]; const f = this.factor(); - return item.n * f + this.bonus(); + const d = this.doubled; + return item.n * f + this.bonus() + d - 4; } bonus(): number { diff --git a/tslang/test/tester/tests/final_accessor_override_error.ts b/tslang/test/tester/tests/final_accessor_override_error.ts new file mode 100644 index 000000000..2127a28ea --- /dev/null +++ b/tslang/test/tester/tests/final_accessor_override_error.ts @@ -0,0 +1,10 @@ +// TSLANG_ISSUES 48: a @final accessor cannot be overridden +class Base { + @final get factor(): number { return 1; } +} + +class App extends Base { + get factor(): number { return 2; } +} + +function main() { print(new App().factor); } diff --git a/tslang/test/tester/verify-ownership.cmake b/tslang/test/tester/verify-ownership.cmake index e9054ae94..ebe14774a 100644 --- a/tslang/test/tester/verify-ownership.cmake +++ b/tslang/test/tester/verify-ownership.cmake @@ -76,9 +76,10 @@ set(not_compilable_alone cdecl_closure_error.ts # an error by design (test-compile-computed-name-failed-error) computed_name_failed_error.ts - # errors by design (test-compile-final-method-override-error, -abstract-error) + # errors by design (test-compile-final-method-override-error, -abstract-error, final-accessor-override-error) final_method_override_error.ts final_method_abstract_error.ts + final_accessor_override_error.ts # an error by design (test-compile-generic-self-recursion-untyped-error) generic_self_recursion_untyped_error.ts) diff --git a/tslang/test/wasm/wasm_skips.txt b/tslang/test/wasm/wasm_skips.txt index 32b30e1a1..0d10e9777 100644 --- a/tslang/test/wasm/wasm_skips.txt +++ b/tslang/test/wasm/wasm_skips.txt @@ -6,6 +6,7 @@ internals.ts # inline_asm with x86 instructions 00any_to_opaque_narrow.ts wasm32 # stores a u64 in an Opaque: a pointer is 4 bytes on wasm32 00tslang_issue_29_pthread.ts # starts threads through pthread_create: the host starts them only through Thread.spawn 00tslang_issue_29_thread.ts # starts threads through _beginthreadex: the host starts them only through Thread.spawn +00tslang_issue_29_function_value.ts # registers C exit handlers through atexit, which the host may not provide 00stdcall_winapi.ts # calls the Windows API (GetCurrentProcessId): the host has none of it 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