From 7d077d30f0ec48603b77183be1d0e367478bf7fb Mon Sep 17 00:00:00 2001 From: ASDAlexander77 Date: Sun, 15 Nov 2026 19:29:15 +0000 Subject: [PATCH 1/5] -mm=own: the inference pass no longer walks other functions' bodies (compiler crashed about once in 500 runs) OwnershipInferencePass runs on the functions of a module at once, on several threads. For a field read through an interface whose value leaves its function (`function dirOf(r: R) { return r.dir; }`) releaseCellReads asks accessorFiller whether a class fills the field with a getter, and accessorFiller looked for the accessor cell's global with module.walk - which goes into the body of every function of the module, among them the ones the other threads were putting releases in and erasing reads from at that moment. It read an operation list as it was relinked, and the compiler ended with an access violation: about once in 300 to 700 compiles of test/tester/own/own_field_chain_let.ts, and once in a run of the suite. It now looks at the module's own operations only: that is where globals are, and no function's pass changes that list. Found from a crash dump: two worker threads in releaseCellReads, both in the module walk. The compiler from before the fix failed 2 of 1,000 and 1 of 725 compiles of that test; with the fix, 0 of 4,000. Release suite on Windows x64; LLVM IR of the 190 tests of test/tester/own that compile without the default library is unchanged. Co-Authored-By: Claude Fable 5.2 --- .../lib/TypeScript/OwnershipInferencePass.cpp | 20 ++++++++++++++----- 1 file changed, 15 insertions(+), 5 deletions(-) diff --git a/tslang/lib/TypeScript/OwnershipInferencePass.cpp b/tslang/lib/TypeScript/OwnershipInferencePass.cpp index a3edc5be9..c5ff09db6 100644 --- a/tslang/lib/TypeScript/OwnershipInferencePass.cpp +++ b/tslang/lib/TypeScript/OwnershipInferencePass.cpp @@ -230,7 +230,19 @@ namespace own_inference auto suffix = (llvm::Twine(".") + field + ".accessor").str(); auto module = getFunction()->getParentOfType(); llvm::StringRef found; - module.walk([&](mlir_ts::GlobalOp globalOp) { + // Only the module's own operations, which no function's pass changes: this pass runs on the + // module's functions at once, on several threads, and module.walk went into the bodies of + // the functions the other threads were putting releases in and erasing reads from. It read a + // list as it was relinked, and the compiler ended with an access violation about once in + // 500 runs (test/tester/own/own_field_chain_let.ts). + for (auto &moduleOp : *module.getBody()) + { + auto globalOp = mlir::dyn_cast(&moduleOp); + if (!globalOp) + { + continue; + } + auto name = globalOp.getSymName(); auto vtbl = name.find("..vtbl."); if (vtbl != llvm::StringRef::npos && name.ends_with(suffix) && vtbl + 6 + suffix.size() == name.size()) @@ -238,11 +250,9 @@ namespace own_inference // the class: up to the interface's name auto head = name.take_front(vtbl); found = head.take_front(head.rfind('.') == llvm::StringRef::npos ? head.size() : head.rfind('.')); - return mlir::WalkResult::interrupt(); + break; } - - return mlir::WalkResult::advance(); - }); + } return found; } From bb91cbc55b071f5587ddb40c881d80f41acf2a33 Mon Sep 17 00:00:00 2001 From: ASDAlexander77 Date: Sun, 15 Nov 2026 19:52:57 +0000 Subject: [PATCH 2/5] -mm=own: a parameter the body assigns is kept; delete ends an owner Two refusals that said "yet", which stopped 14 of the 621 corpus files. A parameter the body assigns starts a local of its own for every type that owns a block, as rc does (it did under own only for a string and a Shared). The local owns what it holds, so the function keeps the parameter and its callers give the argument up, by the rules of a parameter stored in a field; no pass changed. `p.length = n` starts a local only for a string. `delete place` is written as the assignment that clears the place when the place owns its value; a value no storage holds is released where its block ends; a parameter or a local that owns nothing is an error. Corpus under own: 466 -> 473 of 621. Co-Authored-By: Claude Fable 5.2 --- docs/own-memory-model.md | 40 ++++ .../2026-09-24-own-memory-model-design.md | 34 ++- tslang/lib/TypeScript/MLIRGenExpressions.cpp | 36 ++++ tslang/lib/TypeScript/MLIRGenFunctions.cpp | 17 +- tslang/test/tester/CMakeLists.txt | 24 ++- tslang/test/tester/own/own_delete.ts | 110 ++++++++++ .../tester/own/own_err_delete_borrowed.ts | 13 ++ .../test/tester/own/own_err_delete_param.ts | 13 ++ .../test/tester/own/own_err_param_assigned.ts | 4 +- .../own/own_err_param_assigned_exported.ts | 15 ++ .../own/own_err_param_assigned_local.ts | 22 -- tslang/test/tester/own/own_param_assigned.ts | 202 ++++++++++++++++++ 12 files changed, 498 insertions(+), 32 deletions(-) create mode 100644 tslang/test/tester/own/own_delete.ts create mode 100644 tslang/test/tester/own/own_err_delete_borrowed.ts create mode 100644 tslang/test/tester/own/own_err_delete_param.ts create mode 100644 tslang/test/tester/own/own_err_param_assigned_exported.ts delete mode 100644 tslang/test/tester/own/own_err_param_assigned_local.ts create mode 100644 tslang/test/tester/own/own_param_assigned.ts diff --git a/docs/own-memory-model.md b/docs/own-memory-model.md index 3ffb4c8a1..908485fde 100644 --- a/docs/own-memory-model.md +++ b/docs/own-memory-model.md @@ -89,6 +89,46 @@ stores a parameter keeps it, so its callers have to move the argument in; a func returns a field of its argument returns a borrow, so its callers may only borrow the result. Callers in other modules cannot see the body, which is what the [decorators](#decorators) are for. +## Assigned parameters and `delete` + +A parameter is lent by the caller. A function that assigns one keeps it instead: the parameter +then owns each value it is given, so the caller moves the argument in and may not use it after +the call. + +```typescript +class B { constructor(public b: number) {} } + +function pick(x: B, fresh: boolean) { + if (fresh) { + x = new B(7); // pick assigns x, so it keeps it + } + + return x.b; +} + +function main() { + print(pick(new B(1), true)); // a new object moves in + + const b = new B(2); + print(pick(b, false)); // b moves in + // print(b.b); // error: 'b' is used here after its value was moved +} +``` + +An exported function, or a method reached through an interface, says so in its signature with +[`@keeps("x")`](#keeps). A parameter captured or assigned by a closure, one a generator assigns, +and `x ??= value` are not accepted yet. + +`delete` ends an owner. `delete c` of a local or a field that owns its value frees the value now +and leaves null there, so reading it afterwards fails as a null read does. If the value was moved +out before (`h.child = c; delete c`), nothing is freed. A `const` holding a new object is freed +where its block ends. `delete` of a parameter, or of anything else the function does not own, is +an error: + +```text +error: 'delete' of a value this function does not own: under -mm=own only a local or a field that owns its value can be deleted +``` + ## Reading the errors A value is named `'this value'` in the messages below; the position points at it. diff --git a/tslang/docs/superpowers/specs/2026-09-24-own-memory-model-design.md b/tslang/docs/superpowers/specs/2026-09-24-own-memory-model-design.md index dd7172e8d..de8418ed7 100644 --- a/tslang/docs/superpowers/specs/2026-09-24-own-memory-model-design.md +++ b/tslang/docs/superpowers/specs/2026-09-24-own-memory-model-design.md @@ -1627,7 +1627,7 @@ place, so all four places that report it get the same names. Each message has a | a function returns a borrow of a parameter on one path and something else on another | `'f' returns a borrow of its argument on some paths and another value on others; -mm=own cannot tell its callers whether they own the result`, with a note at the other return | `own_err_mixed_return`; `own_err_unbox_string` until §22, which copies the string and deleted it | | a parameter's value, returned, where the callers cannot learn the fact (§15) | `'x' is a parameter, returned here, but -mm=own cannot tell the callers of 'f' that the result borrows it`, with §15's facts-lost note | `own_err_param_returned_exported` | | a parameter's value, kept (stored, pushed, given away) | `'x' is a parameter, kept here, but -mm=own cannot make the callers of 'f' give it up`, with the note | `own_err_param_kept_exported` | -| a store into a parameter's slot | `'x' is a parameter and cannot be assigned under -mm=own yet` | `own_err_param_assigned` | +| a store into a parameter's slot (one with no local of its own, §81) | `'x' is a parameter and cannot be assigned under -mm=own yet` | - | | a store into a local that owns nothing | `'x' owns nothing under -mm=own (it is declared without a value, or in a catch or finally clause), so it cannot be given a new value here` | `own_err_local_owns_nothing` | | a value merged from branches or loop iterations (a conditional, `&&`, `\|\|`, `??`, a loop) | 'x' is merged from several branches (the operators, a loop); -mm=own cannot prove which one owns it yet | `own_err_merged_result` | | a global's value, stored, returned or boxed | `'x' borrows the global 'g' and cannot be stored, returned or captured` | `own_err_global_returned` | @@ -5763,3 +5763,35 @@ it does not read. Not here: an array written (`push`, an element stored), stored, returned, captured or given to a call (the call's array of §49 aside); a literal with a fresh element beside borrowed ones; a local's value as an element (`[background, tile]`), whose bound is the local's own ends. + +## 81. An assigned parameter is kept; `delete` ends an owner, 2026-11-15 + +Two refusals that said "yet". Of the 621 corpus files, nine stopped at the first and five at the second. + +**A parameter the body assigns.** rc gives such a parameter a local of its own (#512), and own did so +only for a string (§22.3) and a `Shared` handle; any other was "a parameter and cannot be assigned +under -mm=own yet". `mlirGenFunctionOwnAssignedParams` now starts the local for every parameter that owns +a block. The local owns what it holds, so the caller's value moves into it: the parameter is a kept one, +by the rules a parameter stored in a field already follows (`__own_params`, `@keeps("x")` for a function +another module may call), and no pass changed. What follows from that: +- a caller that reads the argument after the call gets "is used here after its value was moved", with the + call as the place it moved (`own_err_param_assigned`); +- a function whose callers cannot be told - exported, reached through an interface - gets "is a parameter, + kept here, but -mm=own cannot make the callers ... give it up" (`own_err_param_assigned_exported`); +- `x = n` of a local moves `n` into the parameter's local, where it was the error #752 added + (`own_err_param_assigned_local`, now a case of `own_param_assigned`). + +`p.length = n` starts a local only for a string; an array is resized where it is, and its callers keep it. +`assignsParameter` stays for a parameter with no local (a binding pattern). Still refused, by other rules: +a parameter a closure captures or assigns, one a generator assigns, and `x ??= v` (a merge). + +**`delete`.** Own has no `ts.Delete`. MLIRGen writes `delete place` as the assignment that clears the place +when the place owns its value (`isOwningSlot`: a local, a field, an element, a global): the release and the +store an assignment makes, which the passes follow already - a local whose value moved frees nothing, a +borrow of it ends (`own_err_delete_borrowed`), the function may drop. A value no storage holds (`delete new +C()`, a `const` kept as a value) is released where its block ends, as before, and a value that owns no +block is left alone. Anything else - a parameter, a local that owns nothing - is "'delete' of a value this +function does not own" (`own_err_delete_param`). A local read after its `delete` holds null. + +Tests: `own_param_assigned` (own, rc, gc), `own_delete` (own, rc), and the seven corpus files only these +two stopped, under own (`test-*-own-flipped-*`). diff --git a/tslang/lib/TypeScript/MLIRGenExpressions.cpp b/tslang/lib/TypeScript/MLIRGenExpressions.cpp index ac865d8ce..aedb76911 100644 --- a/tslang/lib/TypeScript/MLIRGenExpressions.cpp +++ b/tslang/lib/TypeScript/MLIRGenExpressions.cpp @@ -1907,6 +1907,8 @@ namespace mlirgen auto result = mlirGen(deleteExpression->expression, genContext); EXIT_IF_FAILED_OR_NO_VALUE(result) auto expr = V(result); + // what the expression named, before an array is turned into a reference to its elements + auto place = expr; if (!isa(expr.getType()) && !isa(expr.getType()) && !isa(expr.getType())) @@ -1936,6 +1938,40 @@ namespace mlirgen } } + // -mm=own: `delete` ends the owner the expression names, and only an owner can be ended. There is no + // ts.Delete: a local or a field that owns its value is released and cleared the way an assignment + // releases what it replaces, which the ownership passes already follow - what was moved out of the local + // is not freed, a borrow of it ends, and a caller learns the function may drop. A value no storage holds + // (`delete new C()`, or a `const` the compiler kept as a value) is released where its block ends, as it + // would have been. Anything else - a parameter, a local that owns nothing, a value read out of another + // owner - belongs to someone who would free it again. + if (compileOptions.memoryModel == MemoryModelOwn) + { + // a discovery run marks no value as carrying a reference, so it cannot tell whose the value is + // ...and a value that owns no block (`new` of a number) has no owner to end: own frees it no more than + // reference counting does + if (genContext.dummyRun || !mth.ownsHeapMemory(location, place.getType()) || producesOwnedReferenceAtLastUse(place)) + { + return mlir::success(); + } + + MLIRCodeLogic mcl(builder, compileOptions); + auto reference = mcl.GetReferenceFromValue(location, place); + if (!reference || !isOwningSlot(location, reference)) + { + emitError(location, "'delete' of a value this function does not own: under -mm=own only a local or a field " + "that owns its value can be deleted"); + return mlir::failure(); + } + + auto nullValue = builder.create(location, getNullType()); + auto clearedResult = cast(location, place.getType(), nullValue, genContext, /*disableStrictNullCheck*/ true); + EXIT_IF_FAILED_OR_NO_VALUE(clearedResult) + auto saved = mlirGenSaveLogicOneItem(location, place, V(clearedResult), genContext); + EXIT_IF_FAILED(saved) + return mlir::success(); + } + builder.create(location, expr); // Under reference counting `delete` gives up the reference the expression named, so the diff --git a/tslang/lib/TypeScript/MLIRGenFunctions.cpp b/tslang/lib/TypeScript/MLIRGenFunctions.cpp index c8c7cd3dc..26822e806 100644 --- a/tslang/lib/TypeScript/MLIRGenFunctions.cpp +++ b/tslang/lib/TypeScript/MLIRGenFunctions.cpp @@ -1794,8 +1794,14 @@ namespace mlirgen // -mm=own: a Shared parameter the body assigns is copied too. Own steps aside for Shared handles - their // counts are rc's - so it accepts the assignment, and the slot held a handle that only borrowed the new // value: assigned in a loop, the handle was released at the end of the loop body and a later `p.value` read - // freed memory. Any other parameter own refuses to assign (OwnershipInferencePass), and a collector needs - // none of this. + // freed memory. + // + // -mm=own: any other parameter the body assigns - an object, an array - starts a local as well. The local + // owns what it holds, so the caller's value has to become its own: the function keeps the parameter, as one + // that stores it in a field does, and its callers give the argument up (the ownership passes' kept + // parameters; '@keeps' says it for a function another module may call). A caller that reads the argument + // after the call is told it was moved. A parameter left without a local (one with a binding pattern) own + // still refuses to assign (OwnershipInferencePass). A collector needs none of this. mlir::LogicalResult MLIRGenImpl::mlirGenFunctionOwnAssignedParams(mlir::Location location, FunctionLikeDeclarationBase functionLikeDeclarationBaseAST, FunctionPrototypeDOM::TypePtr funcProto, @@ -1812,8 +1818,7 @@ namespace mlirgen auto scanned = false; for (const auto ¶m : funcProto->getParams()) { - if (param->getBindingPattern() || !mth.ownsHeapMemory(location, param->getType()) || - (own && !mlir::isa(param->getType()))) + if (param->getBindingPattern() || !mth.ownsHeapMemory(location, param->getType())) { continue; } @@ -1824,7 +1829,9 @@ namespace mlirgen scanned = true; } - if (!assignedNames.contains(param->getName()) && !lengthNames.contains(param->getName())) + // `p.length = n` makes a new value only of a string: an array is resized where it is + if (!assignedNames.contains(param->getName()) && + !(lengthNames.contains(param->getName()) && mlir::isa(param->getType()))) { continue; } diff --git a/tslang/test/tester/CMakeLists.txt b/tslang/test/tester/CMakeLists.txt index b6070fd6b..3aa8520c4 100644 --- a/tslang/test/tester/CMakeLists.txt +++ b/tslang/test/tester/CMakeLists.txt @@ -4959,6 +4959,24 @@ foreach(reassign_mm rc gc) tslang_add_test(NAME test-compile-${reassign_mm}-own_move_reassign COMMAND test-runner -mm=${reassign_mm} "${PROJECT_SOURCE_DIR}/test/tester/own/own_move_reassign.ts") endforeach() +# A parameter the body assigns is one the function keeps under own: it starts a local that owns what it holds, +# and the callers give the argument up. The same program under rc and gc. +# `delete` under own ends the owner it names: a local or a field is released and cleared, a value no storage +# holds goes where its block ends. Under rc too (not gc: a delete after a move frees what the field holds). +foreach(param_assigned_mm own rc gc) + tslang_add_test(NAME test-jit-${param_assigned_mm}-own_param_assigned COMMAND test-runner -jit -mm=${param_assigned_mm} "${PROJECT_SOURCE_DIR}/test/tester/own/own_param_assigned.ts") + tslang_add_test(NAME test-compile-${param_assigned_mm}-own_param_assigned COMMAND test-runner -mm=${param_assigned_mm} "${PROJECT_SOURCE_DIR}/test/tester/own/own_param_assigned.ts") +endforeach() +foreach(own_delete_mm own rc) + tslang_add_test(NAME test-jit-${own_delete_mm}-own_delete COMMAND test-runner -jit -mm=${own_delete_mm} "${PROJECT_SOURCE_DIR}/test/tester/own/own_delete.ts") + tslang_add_test(NAME test-compile-${own_delete_mm}-own_delete COMMAND test-runner -mm=${own_delete_mm} "${PROJECT_SOURCE_DIR}/test/tester/own/own_delete.ts") +endforeach() +# ...and the corpus files that only these two stopped under own +foreach(own_flipped_test 00class_accessor 00class_discover_types 00new_delete 00ns5 00owned_delete 00narrowed_assign_other_member 00const_of_let) + tslang_add_test(NAME test-jit-own-flipped-${own_flipped_test} COMMAND test-runner -jit -mm=own "${PROJECT_SOURCE_DIR}/test/tester/tests/${own_flipped_test}.ts") + tslang_add_test(NAME test-compile-own-flipped-${own_flipped_test} COMMAND test-runner -mm=own "${PROJECT_SOURCE_DIR}/test/tester/tests/${own_flipped_test}.ts") +endforeach() + # Strings as values (spec 22): no model but own makes a copy, and each program means the same # under every model. foreach(strings_mm rc none gc) @@ -5263,7 +5281,10 @@ set(own_error_cases "own_err_call_result_record|:47:12: error: '[^']*' borrows a field but is used here after it may be released or overwritten" "own_err_param_returned_exported|is a parameter, returned here, but -mm=own cannot tell the callers of 'identity' that the result borrows it" "own_err_param_kept_exported|is a parameter, kept here, but -mm=own cannot make the callers of 'Animal.constructor' give it up" - "own_err_param_assigned|:7:5: error: '[^']*' is a parameter and cannot be assigned under -mm=own yet" + "own_err_param_assigned|:12:21: error: '[^']*' is used here after its value was moved" + "own_err_param_assigned_exported|is a parameter, kept here, but -mm=own cannot make the callers of 'pick' give it up" + "own_err_delete_param|:7:5: error: 'delete' of a value this function does not own" + "own_err_delete_borrowed|:12:11: error: '[^']*' borrows a field but is used here after it may be released or overwritten" "own_err_local_owns_nothing|:8:5: error: '[^']*' owns nothing under -mm=own [(]it is declared without a value, or in a catch or finally clause[)], so it cannot be given a new value here" "own_err_merged_result|:7:5: error: '[^']*' is merged from several branches [(]`[?]:`, `&&`, `[|][|]`, `[?][?]`, a loop[)]" "own_err_global_borrowed_result|the initializer of global 'c' holds the result of 'child', which borrows its argument" @@ -5296,7 +5317,6 @@ set(own_error_cases "own_err_global_read_callee_assigns|borrows 'G' but is used here after 'G' is released or overwritten" "own_err_global_read_callee_assigns_transitive|borrows 'G' but is used here after 'G' is released or overwritten" "own_err_argument_assigned|is lent to 'g', but is given a new value before the call takes it" - "own_err_param_assigned_local|:15:5: error: a parameter cannot be assigned under -mm=own yet" "own_err_argument_assigned_conditional|is lent to 'g', but is given a new value before the call takes it" "own_err_argument_assigned_closure|is lent to 'g', but is given a new value before the call takes it" "own_err_global_method_transitive|:19:11: error: a value read out of the global 'G' is lent to a call that may release or overwrite it" diff --git a/tslang/test/tester/own/own_delete.ts b/tslang/test/tester/own/own_delete.ts new file mode 100644 index 000000000..485bc0c14 --- /dev/null +++ b/tslang/test/tester/own/own_delete.ts @@ -0,0 +1,110 @@ +// -mm=own: `delete` ends the owner the expression names - a local or a field that owns its value is released +// and cleared, as an assignment releases what it replaces; a value no storage holds goes where its block ends. +function churn(): number { + let n = 0; + for (let i = 0; i < 400; i++) { + const s = "filler " + i; + n = n + s.length; + } + + return n; +} + +class Leaf { + name: string = "leaf"; + constructor(public v: number) {} +} + +class Holder { + child?: Leaf; + other: Leaf = new Leaf(2); + + drop() { + delete this.other; + } +} + +function deleteALet() { + let c = new Leaf(1); + c.name = "let" + c.v; + assert(c.name == "let1"); + delete c; + churn(); +} + +function deleteAConst() { + const c = new Leaf(3); + assert(c.v == 3); + delete c; + churn(); +} + +function deleteATemporary() { + delete new Leaf(4); + churn(); +} + +function deleteAfterAMove() { + let c = new Leaf(5); + const h = new Holder(); + h.child = c; + // what `c` held is the field's now: nothing is freed here + delete c; + churn(); + assert(h.child!.v == 5, "moved out before the delete"); +} + +function deleteAField() { + const h = new Holder(); + h.child = new Leaf(6); + assert(h.other.v == 2); + h.drop(); + churn(); + assert(h.child.v == 6, "the other field is untouched"); + const g = new Holder(); + delete g.other; + churn(); +} + +function deleteOnOnePath() { + let total = 0; + for (let i = 0; i < 100; i++) { + let c = new Leaf(i); + if (i % 2 == 0) { + total += c.v; + delete c; + } else { + total += c.v; + } + } + + churn(); + assert(total == 4950); +} + +function deleteAnArray() { + let a: Leaf[] = [new Leaf(8), new Leaf(9)]; + assert(a[1].v == 9); + delete a; + churn(); +} + +function deleteThenAssign() { + let c = new Leaf(10); + delete c; + c = new Leaf(11); + churn(); + assert(c.v == 11); +} + +function main() { + deleteALet(); + deleteAConst(); + deleteATemporary(); + deleteAfterAMove(); + deleteAField(); + deleteOnOnePath(); + deleteAnArray(); + deleteThenAssign(); + print("done."); +} diff --git a/tslang/test/tester/own/own_err_delete_borrowed.ts b/tslang/test/tester/own/own_err_delete_borrowed.ts new file mode 100644 index 000000000..6f47e94c6 --- /dev/null +++ b/tslang/test/tester/own/own_err_delete_borrowed.ts @@ -0,0 +1,13 @@ +// -mm=own rejects: `delete h` ends `h`, and `f` still borrows a field of it. +class C { + v = 1; +} +class H { + child = new C(); +} +function main() { + let h = new H(); + const f = h.child; + delete h; + print(f.v); +} diff --git a/tslang/test/tester/own/own_err_delete_param.ts b/tslang/test/tester/own/own_err_delete_param.ts new file mode 100644 index 000000000..c236f7ef6 --- /dev/null +++ b/tslang/test/tester/own/own_err_delete_param.ts @@ -0,0 +1,13 @@ +// -mm=own rejects: `delete` ends an owner, and a parameter's value is its caller's - the caller +// would free it again. +class N { + v = 1; +} +function drop(p: N) { + delete p; +} +function main() { + const n = new N(); + drop(n); + print(n.v); +} diff --git a/tslang/test/tester/own/own_err_param_assigned.ts b/tslang/test/tester/own/own_err_param_assigned.ts index 811dde0b1..689b10273 100644 --- a/tslang/test/tester/own/own_err_param_assigned.ts +++ b/tslang/test/tester/own/own_err_param_assigned.ts @@ -1,5 +1,5 @@ -// -mm=own rejects: a parameter's value is its caller's; this function cannot put a value of its -// own in its place. +// -mm=own rejects: a function that assigns a parameter keeps it - its local owns the caller's value +// until it is given another - so the caller gave `c` up at the call and may not read it after. class C { constructor(public x: number) {} } diff --git a/tslang/test/tester/own/own_err_param_assigned_exported.ts b/tslang/test/tester/own/own_err_param_assigned_exported.ts new file mode 100644 index 000000000..503daa2a9 --- /dev/null +++ b/tslang/test/tester/own/own_err_param_assigned_exported.ts @@ -0,0 +1,15 @@ +// -mm=own rejects: a function that assigns a parameter keeps it, and one another module may call +// cannot make its callers give the argument up unless its signature says so (`@keeps("x")`). +class B { + constructor(public b: number) {} +} +export function pick(x: B) { + if (x.b > 0) { + x = new B(1); + } + + return x.b; +} +function main() { + print(pick(new B(2))); +} diff --git a/tslang/test/tester/own/own_err_param_assigned_local.ts b/tslang/test/tester/own/own_err_param_assigned_local.ts deleted file mode 100644 index 536b1beff..000000000 --- a/tslang/test/tester/own/own_err_param_assigned_local.ts +++ /dev/null @@ -1,22 +0,0 @@ -// -mm=own rejects: `p = n` puts `n`'s object in a parameter's slot, which owns nothing, so the -// object is neither taken from `n` nor counted again - and `n = mk(9)` frees it while `p` still -// reads it. Own accepted this (it reported an assigned parameter only where a retain stood for the -// store, and a store into a parameter has none), and `p.x` read freed memory (mm_fuzz seed 70377). -class N { - constructor(public x: number) {} -} - -function mk(i: number): N { - return new N(i); -} - -function f(p: N): number { - let n: N = mk(2); - p = n; - n = mk(9); - return p.x; -} - -function main() { - print(f(mk(5))); -} diff --git a/tslang/test/tester/own/own_param_assigned.ts b/tslang/test/tester/own/own_param_assigned.ts new file mode 100644 index 000000000..145583b67 --- /dev/null +++ b/tslang/test/tester/own/own_param_assigned.ts @@ -0,0 +1,202 @@ +// -mm=own: a parameter the body assigns is one the function keeps. It starts a local of its own, which owns what +// it holds - the caller's value first, then each value assigned - so the callers give the argument up, as they do +// to a function that stores it in a field, and may not read it after the call (own_err_param_assigned). The +// same shapes as tests/00param_assigned_owned.ts, less the ones own cannot follow yet: a parameter a closure +// captures or assigns, one a generator assigns, and one given a value by `??=`. +class A { + constructor(public a: number) {} +} + +class B { + constructor(public b: number) {} +} + +// reuses freed blocks, so a read of one sees another value rather than the old one +function churn() { + let fill: B[] = []; + for (let i = 0; i < 200; i++) { + fill.push(new B(1000 + i)); + } + + return fill.length; +} + +function loopInstanceOf(x: A | B) { + let n = 0; + while (x instanceof A) { + x = new B(1); + n++; + } + + return n; +} + +function forInstanceOf(x: A | B) { + let n = 0; + for (; x instanceof A; x = new B(1)) { + n++; + } + + return n; +} + +function inIf(x: B, c: boolean) { + if (c) { + x = new B(7); + } + + churn(); + return x.b; +} + +function inLoop(x: B) { + for (let i = 0; i < 3; i++) { + x = new B(i); + } + + churn(); + return x.b; +} + +function optional(x?: B) { + if (!x) { + x = new B(7); + } + + churn(); + return x.b; +} + +function withDefault(x: B = new B(1)) { + { + x = new B(6); + } + + churn(); + return x.b; +} + +function returned(x: B) { + { + x = new B(5); + } + + return x; +} + +function destructured(x: B) { + { + [x] = [new B(4)]; + } + + churn(); + return x.b; +} + +function forOf(x: B) { + const arr = [new B(1), new B(3)]; + for (x of arr) { + } + + churn(); + return x.b; +} + +class M { + m(x: B) { + for (let i = 0; i < 2; i++) { + x = new B(10 + i); + } + + churn(); + return x.b; + } +} + +const arrow = (x: B) => { + { + x = new B(12); + } + + churn(); + return x.b; +}; + +function strings(s: string) { + for (let i = 0; i < 3; i++) { + s = s + i; + } + + churn(); + return s; +} + +async function asynchronous(x: B) { + { + x = new B(3); + } + + await 0; + churn(); + return x.b; +} + +function rest(...xs: B[]) { + { + xs = [new B(4)]; + } + + churn(); + return xs[0].b; +} + +// given a local's value: the parameter's local takes it over, and the local is free to hold another +function fromLocal(x: B) { + let n = new B(30); + x = n; + n = new B(31); + churn(); + return x.b + n.b; +} + +function unassigned(x: B) { + churn(); + return x.b; +} + +async function main() { + assert(loopInstanceOf(new A(5)) == 1, "while on instanceof"); + assert(loopInstanceOf(new B(5)) == 0, "while on instanceof, not entered"); + assert(forInstanceOf(new A(5)) == 1, "for on instanceof"); + assert(inIf(new B(0), true) == 7, "assigned in an if"); + assert(inIf(new B(3), false) == 3, "not assigned"); + assert(inLoop(new B(0)) == 2, "assigned in a loop"); + assert(optional() == 7, "optional, assigned"); + assert(optional(new B(2)) == 2, "optional, given"); + assert(withDefault() == 6, "default, assigned"); + assert(withDefault(new B(0)) == 6, "default given, assigned"); + + const r = returned(new B(0)); + churn(); + assert(r.b == 5, "returned after assignment"); + + assert(destructured(new B(0)) == 4, "destructuring assignment"); + assert(forOf(new B(0)) == 3, "for...of into the parameter"); + assert(new M().m(new B(0)) == 11, "method"); + assert(arrow(new B(0)) == 12, "arrow function"); + assert(strings("s") == "s012", "string"); + assert(fromLocal(new B(0)) == 61, "given a local's value"); + assert(unassigned(new B(14)) == 14, "unassigned"); + + assert((await asynchronous(new B(0))) == 3, "async function"); + assert(rest(new B(0)) == 4, "rest parameter"); + + // an argument the caller holds in a local moves in, and the local may be given another value after + let held = new B(20); + assert(inLoop(held) == 2, "a local moved in"); + held = new B(21); + assert(unassigned(held) == 21, "and assigned again"); + assert(held.b == 21, "a parameter nothing assigns is only lent"); + + print("done."); +} From 0d2fec35ecb7e3b7f8e85e95dc69f312132f5e0a Mon Sep 17 00:00:00 2001 From: ASDAlexander77 Date: Sun, 15 Nov 2026 19:59:45 +0000 Subject: [PATCH 3/5] Compile output is the same from run to run: constants relocated in program order RelocateConstantPass gathered the constants it moves to the top of a function in a SmallPtrSet and recreated them in the set's iteration order. With more than 16 of them the set is a hash table keyed by address, so the order - and with it the order of the string globals lowered from them - changed from run to run: 00param_assigned_owned.ts gave four different LLVM IR files in eight compiles (the same lines in another order). They are now kept in a vector in the order the function holds them; 12 compiles each of that file and the ray tracer, with and without --opt, under gc, rc and own, give one output. Co-Authored-By: Claude Opus 5.5 --- docs/compile-time-work.md | 5 +++-- tslang/lib/TypeScript/RelocateConstantPass.cpp | 13 ++++++++----- 2 files changed, 11 insertions(+), 7 deletions(-) diff --git a/docs/compile-time-work.md b/docs/compile-time-work.md index 4317dd378..bcbbe0ced 100644 --- a/docs/compile-time-work.md +++ b/docs/compile-time-work.md @@ -143,8 +143,9 @@ Every table answers a question a scan used to answer, and must give the same ans `TSLANG_LIB_PATH`, `TSLANG_HOME`; set `TSLANG_VERIFY_LLVM_GLOBALS_INDEX`; `ctest -C Release -j 10 --timeout 300`. Then the suite without it. 4. Compare LLVM IR with a compiler from before the change (`--emit=llvm`, default options, - `--opt --opt_level=3`, `--mm=rc`) on the largest tests. `00param_assigned_owned.ts` differs - from run to run with any compiler (the same lines in another order) and is not a finding. + `--opt --opt_level=3`, `--mm=rc`) on the largest tests. The output is the same from run to run; + a compiler before #868 put the constants of a function with more than 16 of them (and the + globals made for them) in another order on each run - `00param_assigned_owned.ts` showed it. Known on the development machine: `test-borrow-facts-*` (5 tests) fail because the build cache's `CMAKE_AR` names an MSVC toolset that is no longer installed. They pass when their commands are diff --git a/tslang/lib/TypeScript/RelocateConstantPass.cpp b/tslang/lib/TypeScript/RelocateConstantPass.cpp index 776e28cf3..cf1c7a093 100644 --- a/tslang/lib/TypeScript/RelocateConstantPass.cpp +++ b/tslang/lib/TypeScript/RelocateConstantPass.cpp @@ -9,7 +9,7 @@ #include "mlir/Dialect/LLVMIR/LLVMDialect.h" -#include "llvm/ADT/SmallPtrSet.h" +#include "llvm/ADT/SmallVector.h" #include "llvm/Support/Debug.h" #include "llvm/Support/raw_ostream.h" @@ -30,7 +30,10 @@ class RelocateConstantPass : public mlir::PassWrapper workSetConst; + // in the order the function holds them: a set of pointers gave them back in the order of their addresses + // once there were more than 16, so the same source compiled to constants - and the globals made for + // them - in another order on every run + SmallVector workSetConst; getOps(f, workSetConst); /*auto lastConstOp =*/relocateConst(f, workSetConst); @@ -48,7 +51,7 @@ class RelocateConstantPass : public mlir::PassWrapper &workSet) + Operation *relocateConst(mlir_ts::FuncOp &f, SmallVector &workSet) { // find first non-constant op auto firstNonConstOp = seekFirstNonConstOp(f); @@ -75,7 +78,7 @@ class RelocateConstantPass : public mlir::PassWrapper void getOps(mlir_ts::FuncOp &f, SmallPtrSet &workSet, Operation *startFrom = nullptr) + template void getOps(mlir_ts::FuncOp &f, SmallVector &workSet, Operation *startFrom = nullptr) { auto startFromStage = startFrom != nullptr; auto skipFirstOps = true; @@ -101,7 +104,7 @@ class RelocateConstantPass : public mlir::PassWrappergetParentOp() == f) { // select only those consts which are not at the beginning - workSet.insert(typedOp); + workSet.push_back(typedOp); } } } From c7e6f5862101edf6f9a2ab3184771c89b5f53866 Mon Sep 17 00:00:00 2001 From: ASDAlexander77 Date: Sun, 15 Nov 2026 19:59:45 +0000 Subject: [PATCH 4/5] -mm=own: a parameter a closure mentions keeps its own error; delete tests follow the new rule A parameter a nested function mentions gets no local of its own under own, so a closure that captures and assigns it is still "a captured parameter and cannot be assigned" rather than a kept parameter. own_err_delete compiles now (own_delete covers it), and own-mlirgen-matches-rc checks moves and field stores instead of delete, which own now writes as a clearing assignment. Co-Authored-By: Claude Opus 5.5 --- tslang/lib/TypeScript/MLIRGenFunctions.cpp | 40 +++++++++++++++++++- tslang/test/tester/CMakeLists.txt | 9 ++--- tslang/test/tester/own/own_err_delete.ts | 7 ---- tslang/test/tester/own/own_mlirgen_delete.ts | 6 --- tslang/test/tester/own/own_mlirgen_moves.ts | 15 ++++++++ 5 files changed, 57 insertions(+), 20 deletions(-) delete mode 100644 tslang/test/tester/own/own_err_delete.ts delete mode 100644 tslang/test/tester/own/own_mlirgen_delete.ts create mode 100644 tslang/test/tester/own/own_mlirgen_moves.ts diff --git a/tslang/lib/TypeScript/MLIRGenFunctions.cpp b/tslang/lib/TypeScript/MLIRGenFunctions.cpp index 26822e806..94ae914d0 100644 --- a/tslang/lib/TypeScript/MLIRGenFunctions.cpp +++ b/tslang/lib/TypeScript/MLIRGenFunctions.cpp @@ -1778,6 +1778,27 @@ namespace mlirgen visitor.visit(body); } + // Every name a function nested in this body mentions: what a closure there may capture. A name too many only + // keeps a parameter as it was. + static void collectNestedFunctionNames(ts::Node body, llvm::StringSet<> &names) + { + ts::VisitorAST visitor([&](ts::Node node) { + if (node == SyntaxKind::ArrowFunction || node == SyntaxKind::FunctionExpression || + node == SyntaxKind::FunctionDeclaration || node == SyntaxKind::MethodDeclaration || + node == SyntaxKind::GetAccessor || node == SyntaxKind::SetAccessor || node == SyntaxKind::Constructor) + { + ts::VisitorAST nested([&](ts::Node inner) { + if (inner == SyntaxKind::Identifier) + { + names.insert(MLIRHelper::getName(inner.as())); + } + }); + nested.visit(node); + } + }); + visitor.visit(body); + } + // -mm=rc: a parameter is borrowed - the caller owns its value (takeOwnershipOfLocal), so its slot neither // retains nor releases. One the body assigns holds values the frame made, though: `x = new B(1)` stored the // instance with no reference of its own, the block it was made in released it, and `x` pointed at freed @@ -1800,8 +1821,9 @@ namespace mlirgen // owns what it holds, so the caller's value has to become its own: the function keeps the parameter, as one // that stores it in a field does, and its callers give the argument up (the ownership passes' kept // parameters; '@keeps' says it for a function another module may call). A caller that reads the argument - // after the call is told it was moved. A parameter left without a local (one with a binding pattern) own - // still refuses to assign (OwnershipInferencePass). A collector needs none of this. + // after the call is told it was moved. A parameter left without a local own still refuses to assign + // (OwnershipInferencePass): one with a binding pattern, and one a nested function mentions - a closure's + // cell borrows the caller's value, and the error for that names the capture. A collector needs none of this. mlir::LogicalResult MLIRGenImpl::mlirGenFunctionOwnAssignedParams(mlir::Location location, FunctionLikeDeclarationBase functionLikeDeclarationBaseAST, FunctionPrototypeDOM::TypePtr funcProto, @@ -1815,6 +1837,7 @@ namespace mlirgen llvm::StringSet<> assignedNames; llvm::StringSet<> lengthNames; + llvm::StringSet<> nestedNames; auto scanned = false; for (const auto ¶m : funcProto->getParams()) { @@ -1826,9 +1849,22 @@ namespace mlirgen if (!scanned) { collectAssignedNames(functionLikeDeclarationBaseAST->body, assignedNames, own ? &lengthNames : nullptr); + if (own) + { + collectNestedFunctionNames(functionLikeDeclarationBaseAST->body, nestedNames); + } + scanned = true; } + // own: a string or a Shared handle is a copy whoever captures it; any other parameter a closure may + // capture stays the caller's + if (own && !mlir::isa(param->getType()) && + nestedNames.contains(param->getName())) + { + continue; + } + // `p.length = n` makes a new value only of a string: an array is resized where it is if (!assignedNames.contains(param->getName()) && !(lengthNames.contains(param->getName()) && mlir::isa(param->getType()))) diff --git a/tslang/test/tester/CMakeLists.txt b/tslang/test/tester/CMakeLists.txt index 3aa8520c4..96b1e648e 100644 --- a/tslang/test/tester/CMakeLists.txt +++ b/tslang/test/tester/CMakeLists.txt @@ -4567,12 +4567,12 @@ add_test(NAME test-own-flag-accepted "${PROJECT_SOURCE_DIR}/test/tester/tests/00assert.ts") set_tests_properties(test-own-flag-accepted PROPERTIES FAIL_REGULAR_EXPRESSION "error|Stack dump") -# Under own MLIRGen emits exactly what it emits under rc: an awaited, deleted or captured value -# still carries its ownership ops for the inference pass to judge. Checked on `delete`, whose -# claim (MLIRGenExpressions.cpp) is one of the four MLIRGen sites. +# Under own MLIRGen emits what it emits under rc - moves, field stores, a reassigned local and a returned +# `const` carry their ownership ops for the inference pass to judge. Not `delete` (a clearing assignment +# under own, spec 81), a captured variable or an assigned parameter, which own writes its own way. add_test(NAME test-own-mlirgen-matches-rc COMMAND ${CMAKE_COMMAND} -DTSLANG=$ - "-DFILE=${PROJECT_SOURCE_DIR}/test/tester/own/own_mlirgen_delete.ts" + "-DFILE=${PROJECT_SOURCE_DIR}/test/tester/own/own_mlirgen_moves.ts" -P "${CMAKE_CURRENT_SOURCE_DIR}/own-mlirgen-matches-rc.cmake") # The lowering backstop: a retain that reaches LLVM lowering under own is an error, never @@ -5259,7 +5259,6 @@ set(own_error_cases "own_err_any_unboxed_outlives|:11:11: error: '[^']*' borrows the result of '___unbox>>' but is used here after it may be released or overwritten" "own_err_param_kept_loop|:19:9: error: '[^']*' is moved inside a loop but was made outside it" "own_err_param_kept_not_owned|is given to 'keep', which keeps it, but -mm=own cannot move it here" - "own_err_delete|'delete' is not supported by -mm=own yet" "own_err_mixed_return|:13:28: error: '[^']*' is used here after its value was moved" "own_err_mixed_return_join_use|:14:15: error: '[^']*' is moved here on some paths only" "own_err_callback_escapes|cannot make the callers of 'pick' give it up" diff --git a/tslang/test/tester/own/own_err_delete.ts b/tslang/test/tester/own/own_err_delete.ts deleted file mode 100644 index 0653ac901..000000000 --- a/tslang/test/tester/own/own_err_delete.ts +++ /dev/null @@ -1,7 +0,0 @@ -// -mm=own, phase 0 rejects: `delete` destroys the value while the slot still releases it at scope exit. -class C { v = 1; } -function main() { - let c = new C(); - delete c; - print("done."); -} diff --git a/tslang/test/tester/own/own_mlirgen_delete.ts b/tslang/test/tester/own/own_mlirgen_delete.ts deleted file mode 100644 index 8bddaec24..000000000 --- a/tslang/test/tester/own/own_mlirgen_delete.ts +++ /dev/null @@ -1,6 +0,0 @@ -class C { v = 1; } -function main() { - let c = new C(); - delete c; - print("done."); -} diff --git a/tslang/test/tester/own/own_mlirgen_moves.ts b/tslang/test/tester/own/own_mlirgen_moves.ts new file mode 100644 index 000000000..6a44391b9 --- /dev/null +++ b/tslang/test/tester/own/own_mlirgen_moves.ts @@ -0,0 +1,15 @@ +class C { v = 1; } +class H { c: C | null = null; } +function make(): C { + const c = new C(); + return c; +} +function main() { + let c = make(); + const h = new H(); + h.c = c; + let d = new C(); + d = new C(); + print(h.c!.v, d.v); + print("done."); +} From 753ee69feeee5cbbe87c89f242ac82cd3fb56eed Mon Sep 17 00:00:00 2001 From: ASDAlexander77 Date: Sun, 15 Nov 2026 19:59:53 +0000 Subject: [PATCH 5/5] docs: compile-time-work names the fix, not a PR number Co-Authored-By: Claude Opus 5.5 --- docs/compile-time-work.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/compile-time-work.md b/docs/compile-time-work.md index bcbbe0ced..fc9507528 100644 --- a/docs/compile-time-work.md +++ b/docs/compile-time-work.md @@ -144,7 +144,7 @@ Every table answers a question a scan used to answer, and must give the same ans --timeout 300`. Then the suite without it. 4. Compare LLVM IR with a compiler from before the change (`--emit=llvm`, default options, `--opt --opt_level=3`, `--mm=rc`) on the largest tests. The output is the same from run to run; - a compiler before #868 put the constants of a function with more than 16 of them (and the + a compiler before RelocateConstantPass kept program order put the constants of a function with more than 16 of them (and the globals made for them) in another order on each run - `00param_assigned_owned.ts` showed it. Known on the development machine: `test-borrow-facts-*` (5 tests) fail because the build cache's