From 119bd3401093d012f561f66b17e0c1e08dd3ac2d Mon Sep 17 00:00:00 2001 From: ASDAlexander77 Date: Tue, 24 Nov 2026 17:23:23 +0000 Subject: [PATCH 01/18] -mm=rc: an argument read out of a place a closure may overwrite is held across the call A parameter borrows its argument. When the argument was read out of a field or an element of an object a closure can reach - a captured local's array, a const object captured by value - and the callee (or what it calls) gave that place a new value (`arr[0] = mk(i)`, `h.o = mk(i)`), took the element out (pop/shift/splice) or gave the captured local a new array, the parameter read freed memory (U10: rc printed 195751491, gc 4495501; main too). holdGlobalArguments now also holds such an argument (readsCapturedPlace) when the call may write a place (writesPlace, propagated through callees; a call through a value may write any). The destructured-parameter form (U06, `([o]: N[]) => { arr[0] = mk(i); o.x }`) is fixed in the callee: under rc the names a destructured parameter binds own what they read, as locals do, and are given back at exit. Own refuses these programs, as before. IR impact on the corpus (rc only; own, gc, none unchanged): 9 files, a RetainSlot/ReleaseSlot for destructured parameter names; no corpus file gains a caller-side hold. Co-Authored-By: Claude Opus 5.5 --- tslang/lib/TypeScript/MLIRGenFunctions.cpp | 15 +++- .../TypeScript/OwnedReturnConsumptionPass.cpp | 87 +++++++++++++++++++ tslang/test/tester/CMakeLists.txt | 8 ++ .../tests/00rc_argument_place_overwritten.ts | 43 +++++++++ 4 files changed, 151 insertions(+), 2 deletions(-) create mode 100644 tslang/test/tester/tests/00rc_argument_place_overwritten.ts diff --git a/tslang/lib/TypeScript/MLIRGenFunctions.cpp b/tslang/lib/TypeScript/MLIRGenFunctions.cpp index 201134b7c..746295f25 100644 --- a/tslang/lib/TypeScript/MLIRGenFunctions.cpp +++ b/tslang/lib/TypeScript/MLIRGenFunctions.cpp @@ -2705,6 +2705,15 @@ namespace mlirgen GenContext bindingGenContext(genContext); bindingGenContext.bindingParamPatterns = true; + // -mm=rc: a name a destructured parameter binds owns what it reads, as a local does: it borrowed the + // argument's element or field, which the callee may give a new value (`([o]: N[]) => { arr[0] = + // mk(i); o.x }`, `arr` the array given) - the store freed the block `o` read. Listed with the + // parameters' storage when the prologue is done (mlirGenFunctionBody), given back at exit. + SmallVector bindingOwned; + if (compileOptions.memoryModel == MemoryModelRC && !bindingGenContext.ownedVars) + { + bindingGenContext.ownedVars = &bindingOwned; + } if (bindingPattern == SyntaxKind::ArrayBindingPattern) { auto arrayBindingPattern = bindingPattern.as(); @@ -2981,9 +2990,11 @@ namespace mlirgen paramCells->push_back(prologueOp.getResult(0)); } // ...and the slot owning a parameter's default value (processOptionalParam), or, under own, a default in a - // destructured parameter (ownPatternDefaultSlot), given back at exit + // destructured parameter (ownPatternDefaultSlot), or, under rc, a name a destructured parameter binds + // (mlirGenFunctionParamsBindings), given back at exit else if (isa(prologueOp) && - (prologueOp.hasAttr(DEFAULT_VALUE_SLOT_ATTR_NAME) || prologueOp.hasAttr(PATTERN_DEFAULT_SLOT_ATTR_NAME))) + (prologueOp.hasAttr(DEFAULT_VALUE_SLOT_ATTR_NAME) || prologueOp.hasAttr(PATTERN_DEFAULT_SLOT_ATTR_NAME) || + (compileOptions.memoryModel == MemoryModelRC && prologueOp.hasAttr(OWNED_LOCAL_ATTR_NAME)))) { paramCells->push_back(prologueOp.getResult(0)); } diff --git a/tslang/lib/TypeScript/OwnedReturnConsumptionPass.cpp b/tslang/lib/TypeScript/OwnedReturnConsumptionPass.cpp index 3c2445e86..1013a1325 100644 --- a/tslang/lib/TypeScript/OwnedReturnConsumptionPass.cpp +++ b/tslang/lib/TypeScript/OwnedReturnConsumptionPass.cpp @@ -1393,11 +1393,26 @@ class OwnedReturnConsumptionPass llvm::StringMap> assigns; llvm::StringMap> callees; llvm::StringSet<> assignsAny; + // ...and the functions that may give a field or an element a new value, or take one out of an array + // (`pop`, `shift`, `splice`), or give a captured local a new value through its cell: what a place + // in a captured local's object read may be freed by (rc, readsCapturedPlace) + llvm::StringSet<> writesPlace; module.walk([&](mlir_ts::FuncOp funcOp) { auto name = funcOp.getSymName(); funcOp.walk([&](mlir::Operation *op) { + if (mlir::isa(op)) + { + writesPlace.insert(name); + } + if (auto storeOp = mlir::dyn_cast(op)) { + auto reference = storeOp.getReference(); + if (own_facts::isPlace(reference) || reference.getDefiningOp()) + { + writesPlace.insert(name); + } + if (auto global = globalOf(storeOp.getReference(), true); !global.empty()) { assigns[name].insert(global); @@ -1430,6 +1445,11 @@ class OwnedReturnConsumptionPass changed = true; } + if (writesPlace.contains(callee) && writesPlace.insert(caller).second) + { + changed = true; + } + if (auto it = assigns.find(callee); it != assigns.end()) { // copied first: `assigns[caller]` may move the entry being read @@ -1490,6 +1510,65 @@ class OwnedReturnConsumptionPass return false; }; + auto mayWritePlace = [&](mlir::Operation *op) { + auto callee = calleeOf(op); + return callee.empty() || assignsAny.contains(callee) || writesPlace.contains(callee); + }; + + // Is this a read out of a field or an element of the object a captured local holds (`f(arr[0])`, `arr` + // captured by a closure)? A closure - the callee, or one it calls - may give that place a new value + // (`arr[0] = mk(i)`), take the element out (`arr.pop()`), or give the local a new value, while the + // callee still reads its parameter: the place's release freed the block the argument read. A `const` + // object a closure captures by value (`const h = new H(); () => { h.o = mk(i) }`, then `f(h.o)`) is the + // same object in the closure's box. + auto capturedByValue = [](mlir::Value object) { + std::function captured = [&](mlir::Value value, int depth) { + return depth < 4 && llvm::any_of(value.getUsers(), [&](mlir::Operation *user) { + return mlir::isa(user) || + (mlir::isa(user) && captured(user->getResult(0), depth + 1)); + }); + }; + return captured(object, 0); + }; + auto readsCapturedPlace = [&](mlir::Value value) { + while (auto castOp = value.getDefiningOp()) + { + value = castOp.getIn(); + } + + auto loadOp = value.getDefiningOp(); + if (!loadOp || !own_facts::isPlace(loadOp.getReference())) + { + return false; + } + + if (auto varOp = mlir::dyn_cast_or_null(own_facts::slotOfRef(loadOp.getReference()))) + { + return varOp.getCaptured().value_or(false); + } + + // the object the place is in, through places, when no slot holds it + auto object = loadOp.getReference(); + for (auto depth = 0; depth < 16 && object && own_facts::isPlace(object); depth++) + { + object = object.getDefiningOp()->getOperand(0); + while (auto castOp = object.getDefiningOp()) + { + object = castOp.getIn(); + } + + if (capturedByValue(object)) + { + return true; + } + + auto innerLoad = object.getDefiningOp(); + object = innerLoad ? innerLoad.getReference() : mlir::Value(); + } + + return false; + }; + auto mayAssign = [&](mlir::Operation *op, mlir::StringRef global) { auto callee = calleeOf(op); if (callee.empty() || assignsAny.contains(callee)) @@ -1640,6 +1719,14 @@ class OwnedReturnConsumptionPass continue; } + // Out of a field or an element of a captured local's object, to a call that may write a place + // (readsCapturedPlace). Under rc the caller holds it. + if (compileOptions.isRefCounted() && readsCapturedPlace(argument) && mayWritePlace(op)) + { + held.push_back({op, argument}); + continue; + } + auto global = globalOf(argument, false); if (global.empty()) { diff --git a/tslang/test/tester/CMakeLists.txt b/tslang/test/tester/CMakeLists.txt index 8cc71ea0e..50cc3bac2 100644 --- a/tslang/test/tester/CMakeLists.txt +++ b/tslang/test/tester/CMakeLists.txt @@ -5691,6 +5691,14 @@ foreach(past_end_mm gc rc own) tslang_add_test(NAME test-jit-${past_end_mm}-destructuring-default-past-end COMMAND test-runner -jit -mm=${past_end_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00destructuring_default_past_end.ts") tslang_add_test(NAME test-compile-${past_end_mm}-destructuring-default-past-end COMMAND test-runner -mm=${past_end_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00destructuring_default_past_end.ts") endforeach() +# -mm=rc: an argument read out of a field or an element of an object a closure can reach (a captured local's array, a +# const object captured by value), given to a call that may write a place (the closure setting it, pop/shift/splice, +# a new array for the local), is held by the caller across the call; a destructured parameter's names own what they +# read. They read freed memory. gc and none print the same; own refuses these programs. +foreach(arg_place_mm gc rc none) + tslang_add_test(NAME test-jit-${arg_place_mm}-rc-argument-place-overwritten COMMAND test-runner -jit -mm=${arg_place_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00rc_argument_place_overwritten.ts") + tslang_add_test(NAME test-compile-${arg_place_mm}-rc-argument-place-overwritten COMMAND test-runner -mm=${arg_place_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00rc_argument_place_overwritten.ts") +endforeach() # USER RULING 11-24: an element past the end of an array value, without a default, is undefined, as node has it. A # name bound to an element of a reference type (`const [a, b] = [mk(5)] as N[]`, `(N | null)[]`, nested, for-of, a # parameter) is `T | undefined` (it read null); number[]/string[] keep their type's default. The assignment form gives diff --git a/tslang/test/tester/tests/00rc_argument_place_overwritten.ts b/tslang/test/tester/tests/00rc_argument_place_overwritten.ts new file mode 100644 index 000000000..026f19ad9 --- /dev/null +++ b/tslang/test/tester/tests/00rc_argument_place_overwritten.ts @@ -0,0 +1,43 @@ +// -mm=rc: an argument read out of a field or an element of an object a closure can reach (a captured local's +// array, a `const` object captured by value) is borrowed by the parameter; the callee - the closure - gave that +// place a new value (`arr[0] = mk(i)`, `h.o = mk(i)`), took the element out (`pop`, `shift`, `splice`) or gave the +// captured local a new array, then read its parameter: freed memory (rc printed garbage, main too). The caller now +// holds the argument across the call. A name a destructured parameter binds (`([p]: N[]) => ...`) owns what it reads +// under rc, as a local does. A global's element given to a function that sets it was held already. gc and none +// print the same; own refuses these programs (it cannot prove the borrow outlives the write). +class N { x: number; s: string; constructor(x: number) { this.x = x; this.s = "n" + x; } } +class H { o: N; constructor(o: N) { this.o = o; } } +@noinline function mk(i: number): N { return new N(i); } +function churn() { const junk: N[] = []; for (let i = 0; i < 16; i++) junk.push(new N(100 + i)); } +function v(p: N): number { return p.x + (p.s == "n" + p.x ? 0 : 1000000); } +let G: N[] = [mk(0)]; +function setG(i: number) { G[0] = mk(i); } +function gf(p: N, i: number): number { setG(i); churn(); return v(p); } +function main() { + let t: number = 0; + G = [mk(0)]; + let arr: N[] = [mk(0), mk(1)]; + const h = new H(mk(0)); + for (let i = 0; i < 2000; i++) { + const fe = (p: N) => { arr[0] = mk(i); churn(); return v(p); }; + t += fe(arr[0]); + const ff = (p: N) => { h.o = mk(i); churn(); return v(p); }; + t += ff(h.o); + const fp = (p: N) => { arr.pop(); arr.push(mk(i)); churn(); return v(p); }; + t += fp(arr[arr.length - 1]); + const fs = (p: N) => { arr.shift(); arr.unshift(mk(i)); churn(); return v(p); }; + t += fs(arr[0]); + const fz = (p: N) => { arr.splice(0, 1, mk(i)); churn(); return v(p); }; + t += fz(arr[0]); + const fr = (p: N) => { arr = [mk(i), mk(i)]; churn(); return v(p); }; + t += fr(arr[1]); + t += gf(G[0], i); + const fd = ([p]: N[]) => { arr[0] = mk(i); churn(); return v(p); }; + t += fd(arr); + const fo = ({ o }: H) => { h.o = mk(i); churn(); return v(o); }; + t += fo(h); + } + print(t); + assert(t == 17983005, "total"); + print("done."); +} From 3fc0e02aa20ed413c0748292e6a424ddc159ad9d Mon Sep 17 00:00:00 2001 From: ASDAlexander77 Date: Tue, 24 Nov 2026 17:39:46 +0000 Subject: [PATCH 02/18] -mm=own: an array literal of no values given straight to a call is given back after it `po([undefined], i)`, `pn([null])` and `ln([])` leaked their array every call under own (3M calls: 110-190 MB on main, 5.3 MB now; `[mk(i)]` and `[i]` were flat already). The literal neither owned nor borrowed anything, so ownNewArrayArguments left it to nobody: holdsWhatItIsGiven now counts a literal of undefined/null elements as owning what it holds, and the empty constant array cast to an array (`[]`) holds nothing. IR: own only, the four corpus files that pass `[]` or `[undefined]` to a call (an owned result and its release). Co-Authored-By: Claude Opus 5.5 --- .../TypeScript/OwnedReturnConsumptionPass.cpp | 39 ++++++++++++++++++- tslang/test/tester/CMakeLists.txt | 12 ++++++ .../tests/00own_literal_argument_no_values.ts | 37 ++++++++++++++++++ 3 files changed, 87 insertions(+), 1 deletion(-) create mode 100644 tslang/test/tester/tests/00own_literal_argument_no_values.ts diff --git a/tslang/lib/TypeScript/OwnedReturnConsumptionPass.cpp b/tslang/lib/TypeScript/OwnedReturnConsumptionPass.cpp index 1013a1325..9b519d39e 100644 --- a/tslang/lib/TypeScript/OwnedReturnConsumptionPass.cpp +++ b/tslang/lib/TypeScript/OwnedReturnConsumptionPass.cpp @@ -402,13 +402,24 @@ class OwnedReturnConsumptionPass auto anyNew = false; auto allTakenAreLocals = true; + // (`po([undefined])`, `[null]`: elements that are no value at all, so nothing to own or to borrow - such a + // literal given to a call was never given back, own leaked it every call) + auto onlyNoValues = true; for (auto element : arrayOp->getOperands()) { + if (isNoValue(element)) + { + continue; + } + if (!mth.ownsHeapMemory(arrayOp->getLoc(), element.getType()) || isBorrowedText(element)) { + onlyNoValues = onlyNoValues && !isBorrowedText(element); continue; } + onlyNoValues = false; + if (isMovedIn(arrayOp, element) || isNestedLiteral(mth, arrayOp, element)) { anyNew = true; @@ -423,11 +434,37 @@ class OwnedReturnConsumptionPass allTakenAreLocals = allTakenAreLocals && isLocalsOwn(element); } - return anyNew || (allTakenAreLocals && !givenToCall); + return anyNew || onlyNoValues || (allTakenAreLocals && !givenToCall); + } + + // undefined or null, through the casts and the optional that only widen it + static bool isNoValue(mlir::Value value) + { + for (auto *op = value.getDefiningOp(); op; op = op->getNumOperands() == 1 ? op->getOperand(0).getDefiningOp() : nullptr) + { + if (mlir::isa(op)) + { + return true; + } + + if (!mlir::isa(op)) + { + return false; + } + } + + return false; } static bool holdsOnlyMovedInElements(MLIRTypeHelper &mth, mlir::Operation *op, bool givenToCall) { + // `f([])`: the empty constant array, copied to the heap where it is cast to an array - it holds nothing + auto castOp = mlir::dyn_cast_or_null(op); + if (auto constArrayType = castOp ? mlir::dyn_cast(castOp.getIn().getType()) : mlir_ts::ConstArrayType()) + { + return constArrayType.getSize() == 0; + } + auto arrayOp = mlir::dyn_cast_or_null(op); return arrayOp && holdsWhatItIsGiven(mth, arrayOp, givenToCall); } diff --git a/tslang/test/tester/CMakeLists.txt b/tslang/test/tester/CMakeLists.txt index 50cc3bac2..9a74df0d7 100644 --- a/tslang/test/tester/CMakeLists.txt +++ b/tslang/test/tester/CMakeLists.txt @@ -5699,6 +5699,18 @@ foreach(arg_place_mm gc rc none) tslang_add_test(NAME test-jit-${arg_place_mm}-rc-argument-place-overwritten COMMAND test-runner -jit -mm=${arg_place_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00rc_argument_place_overwritten.ts") tslang_add_test(NAME test-compile-${arg_place_mm}-rc-argument-place-overwritten COMMAND test-runner -mm=${arg_place_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00rc_argument_place_overwritten.ts") endforeach() +# -mm=own: an array literal holding no value at all (`[undefined]`, `[null]`, `[]`) given straight to a call is owned +# and given back after it (it leaked every call); the same program under gc and rc. IR: the literal is an owned result. +foreach(no_values_mm gc rc own) + tslang_add_test(NAME test-jit-${no_values_mm}-own-literal-argument-no-values COMMAND test-runner -jit -mm=${no_values_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00own_literal_argument_no_values.ts") + tslang_add_test(NAME test-compile-${no_values_mm}-own-literal-argument-no-values COMMAND test-runner -mm=${no_values_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00own_literal_argument_no_values.ts") +endforeach() +add_test(NAME test-own-literal-argument-no-values-ir + COMMAND $ --emit=mlir --no-default-lib -mm=own + "${PROJECT_SOURCE_DIR}/test/tester/tests/00own_literal_argument_no_values.ts") +set_tests_properties(test-own-literal-argument-no-values-ir + PROPERTIES PASS_REGULAR_EXPRESSION "\"ts[.]CreateArray\"[(]%[0-9]+[)] {__owned_result} : [(]!ts[.]optional Date: Tue, 24 Nov 2026 17:52:22 +0000 Subject: [PATCH 03/18] rc/own: conditionals and pattern defaults are settled in a module with no function returning a heap value OwnedReturnConsumptionPass returned early when no function was classified as returning owned (no class, no function returning a heap value), running only some of its module-local steps: consumeConditionalResults and settleOwnPatternDefaults were skipped. Under rc `const xs: number[] = c ? [i] : []` (a let, the assignment form, strings, nested arrays) kept the branch's count of the new array beside the local's own and leaked it every evaluation (3M: 110-200 MB, now 5.3 MB). Both paths now run the same tail (settleModuleLocalResults). IR: rc and own in the class-less files with a conditional of a new value (11 rc / 13 own corpus files); gc and none gain the same annotations and retains the class-bearing modules already had there (9 files), which their lowering drops. Co-Authored-By: Claude Opus 5.5 --- .../TypeScript/OwnedReturnConsumptionPass.cpp | 17 +++++++---- tslang/test/tester/CMakeLists.txt | 13 +++++++++ .../tests/00rc_conditional_array_no_class.ts | 28 +++++++++++++++++++ 3 files changed, 53 insertions(+), 5 deletions(-) create mode 100644 tslang/test/tester/tests/00rc_conditional_array_no_class.ts diff --git a/tslang/lib/TypeScript/OwnedReturnConsumptionPass.cpp b/tslang/lib/TypeScript/OwnedReturnConsumptionPass.cpp index 9b519d39e..578c36eb6 100644 --- a/tslang/lib/TypeScript/OwnedReturnConsumptionPass.cpp +++ b/tslang/lib/TypeScript/OwnedReturnConsumptionPass.cpp @@ -169,13 +169,14 @@ class OwnedReturnConsumptionPass } // `new C()` is marked where it is built, so there can be discarded temporaries to give - // back even when no function here is classified as returning owned. + // back even when no function here is classified as returning owned - and conditionals and + // pattern defaults to settle: a module with no such function (no class, no function returning + // a heap value) skipped consumeConditionalResults, and `const xs: number[] = c ? [i] : []` + // under rc kept the branch's count of the new array and the local's own (one leaked every + // evaluation); settleOwnPatternDefaults, under own, never ran there either. if (returnsOwned.empty() && !anyDeclaredRecord) { - ownNewArrayArguments(mth, module); - claimGlobalInitializers(mth, module); - holdReadOnlyNewArrays(mth, module); - releaseDiscardedTemporaries(mth, module); + settleModuleLocalResults(mth, module); return; } @@ -304,6 +305,12 @@ class OwnedReturnConsumptionPass op->erase(); } + settleModuleLocalResults(mth, module); + } + + // What settles results within a function, once calls' results are settled (or none is a call's to settle) + void settleModuleLocalResults(MLIRTypeHelper &mth, mlir::ModuleOp module) + { ownNewArrayArguments(mth, module); settleOwnPatternDefaults(module); diff --git a/tslang/test/tester/CMakeLists.txt b/tslang/test/tester/CMakeLists.txt index 9a74df0d7..9b3a9ac67 100644 --- a/tslang/test/tester/CMakeLists.txt +++ b/tslang/test/tester/CMakeLists.txt @@ -5711,6 +5711,19 @@ add_test(NAME test-own-literal-argument-no-values-ir set_tests_properties(test-own-literal-argument-no-values-ir PROPERTIES PASS_REGULAR_EXPRESSION "\"ts[.]CreateArray\"[(]%[0-9]+[)] {__owned_result} : [(]!ts[.]optional --emit=mlir --no-default-lib -mm=rc + "${PROJECT_SOURCE_DIR}/test/tester/tests/00rc_conditional_array_no_class.ts") +set_tests_properties(test-rc-conditional-array-no-class-ir + PROPERTIES PASS_REGULAR_EXPRESSION "[}][)] {__owned_result, __owned_result_consumed} : [(]!ts[.]boolean[)] -> !ts[.]array" + FAIL_REGULAR_EXPRESSION "error:|Stack dump") # USER RULING 11-24: an element past the end of an array value, without a default, is undefined, as node has it. A # name bound to an element of a reference type (`const [a, b] = [mk(5)] as N[]`, `(N | null)[]`, nested, for-of, a # parameter) is `T | undefined` (it read null); number[]/string[] keep their type's default. The assignment form gives diff --git a/tslang/test/tester/tests/00rc_conditional_array_no_class.ts b/tslang/test/tester/tests/00rc_conditional_array_no_class.ts new file mode 100644 index 000000000..259aebd46 --- /dev/null +++ b/tslang/test/tester/tests/00rc_conditional_array_no_class.ts @@ -0,0 +1,28 @@ +// -mm=rc: a conditional that yields a new array (`const xs: number[] = c ? [i] : []`) in a module with no function +// that returns a heap value - no class, no `new` - leaked the array every evaluation: OwnedReturnConsumptionPass +// skipped consumeConditionalResults there, and the local took a count of its own beside the branch's. A `let`, the +// assignment form, strings and nested arrays too. Every memory model (own and gc were flat already). +function main() { + let total: number = 0; + for (let i = 0; i < 1000; i++) { + const xs: number[] = i % 2 == 0 ? [i] : []; + total += xs.length; + + let ys: number[] = i % 3 == 0 ? [i, i] : []; + total += ys.length; + + let zs: number[] = [i]; + zs = i % 2 == 1 ? [i, i, i] : []; + total += zs.length; + + const ss: string[] = i % 2 == 0 ? ["s" + i] : []; + total += ss.length; + + const nested: number[][] = i % 4 == 0 ? [[i]] : []; + total += nested.length; + } + + print(total); + assert(total == 3418, "total"); + print("done."); +} From 2495d6f837af3237957ec6d44e8e1066f76337fa Mon Sep 17 00:00:00 2001 From: ASDAlexander77 Date: Tue, 24 Nov 2026 18:06:26 +0000 Subject: [PATCH 04/18] `x == null` of a value that may be undefined does not narrow it to null Loose equality with null or undefined is true for both. Of a value whose type may be undefined (an optional, a union with undefined), `c == null` narrowed the equal side to null: in `c == null && c === undefined` the second test was false for undefined and `c === null` true, also in `if (c == null) { ... }` (every memory model; node gives the opposite). Now the equal side keeps its type and the other side is the type without null and undefined (checkSafeCastLooseNullish); strict comparisons and types that cannot be undefined narrow as before. Outputs of the tests whose IR changed (value_missing*, own_value_*, 01arguments) are unchanged. No IR test: a narrowing fix, the RUN test fails on main. Co-Authored-By: Claude Opus 5.5 --- tslang/lib/TypeScript/MLIRGenImpl.h | 95 +++++++++++++++++++ tslang/test/tester/CMakeLists.txt | 6 ++ .../tester/tests/00narrow_loose_nullish.ts | 38 ++++++++ 3 files changed, 139 insertions(+) create mode 100644 tslang/test/tester/tests/00narrow_loose_nullish.ts diff --git a/tslang/lib/TypeScript/MLIRGenImpl.h b/tslang/lib/TypeScript/MLIRGenImpl.h index dd4ed7e10..a3b2fc1bc 100644 --- a/tslang/lib/TypeScript/MLIRGenImpl.h +++ b/tslang/lib/TypeScript/MLIRGenImpl.h @@ -6307,6 +6307,85 @@ class MLIRGenImpl return mlir::failure(); } + // `val == null` / `val == undefined` (loose) of a value whose type may be undefined (an optional, a union with + // undefined): the equal side may be either, and is left as it is; the other side is the type without null and + // undefined. Fails for anything else (the strict forms, a type that cannot be undefined), which the null and + // undefined cases narrow as before. + mlir::LogicalResult checkSafeCastLooseNullish(Expression val, Expression nullishVal, bool inverse, ElseSafeCase *elseSafeCase, + const GenContext &genContext) + { + auto expr = stripParentheses(nullishVal); + auto isNullish = expr == SyntaxKind::NullKeyword || + (expr == SyntaxKind::Identifier && expr.as()->escapedText == S(UNDEFINED_NAME)); + if (!isNullish) + { + return mlir::failure(); + } + + auto type = evaluate(val, genContext); + auto mayBeUndefined = [](mlir::Type type) { + if (isa_and_nonnull(type)) + { + return true; + } + + auto unionType = dyn_cast_or_null(type); + return unionType && llvm::any_of(unionType.getTypes(), [](mlir::Type member) { + return isa(member); + }); + }; + if (!mayBeUndefined(type)) + { + return mlir::failure(); + } + + // neither null nor undefined + auto present = type; + if (auto optionalType = dyn_cast(present)) + { + present = optionalType.getElementType(); + } + + if (auto unionType = dyn_cast(present)) + { + SmallVector members; + for (auto member : unionType.getTypes()) + { + if (auto optionalMember = dyn_cast(member)) + { + member = optionalMember.getElementType(); + } + + if (!isa(member)) + { + members.push_back(member); + } + } + + if (members.empty()) + { + return mlir::failure(); + } + + present = members.size() == 1 ? members.front() : getUnionType(members); + } + + // `!=`: present where true + if (inverse) + { + return addSafeCastStatement(val, present, false, nullptr, genContext); + } + + // `==`: present where false + if (elseSafeCase) + { + elseSafeCase->expr = stripParenthesesAndUntangleEquals(val); + elseSafeCase->safeType = present; + } + + return mlir::success(); + } + mlir::LogicalResult checkSafeCastNull(Expression val, Expression nullVal, bool inverse, ElseSafeCase *elseSafeCase, const GenContext &genContext) { auto expr = stripParentheses(nullVal); @@ -6831,6 +6910,22 @@ class MLIRGenImpl auto left = stripParentheses(binExpr->left); auto right = stripParentheses(binExpr->right); + // `c == null`, `c != undefined` - loose - of a value that may be undefined: equal for null and for + // undefined alike, so the equal side is not narrowed to null (a later `c === undefined` in the same + // `&&` chain was false for undefined, `c === null` true); the other side is neither + if (op == SyntaxKind::EqualsEqualsToken || op == SyntaxKind::ExclamationEqualsToken) + { + if (auto result = checkSafeCastLooseNullish(left, right, inverse, elseSafeCase, genContext); mlir::succeeded(result)) + { + return result; + } + + if (auto result = checkSafeCastLooseNullish(right, left, inverse, elseSafeCase, genContext); mlir::succeeded(result)) + { + return result; + } + } + // TODO: refactor it // typeof if (mlir::failed(checkSafeCastTypeOf(left, right, inverse, elseSafeCase, genContext))) diff --git a/tslang/test/tester/CMakeLists.txt b/tslang/test/tester/CMakeLists.txt index 9b3a9ac67..f27907db4 100644 --- a/tslang/test/tester/CMakeLists.txt +++ b/tslang/test/tester/CMakeLists.txt @@ -5724,6 +5724,12 @@ add_test(NAME test-rc-conditional-array-no-class-ir set_tests_properties(test-rc-conditional-array-no-class-ir PROPERTIES PASS_REGULAR_EXPRESSION "[}][)] {__owned_result, __owned_result_consumed} : [(]!ts[.]boolean[)] -> !ts[.]array" FAIL_REGULAR_EXPRESSION "error:|Stack dump") +# `c == null` / `c == undefined` (loose) of a value that may be undefined leaves the equal side as it is (it was +# narrowed to null: `c == null && c === undefined` false for undefined); results match node, every model. +foreach(loose_nullish_mm gc rc own none) + tslang_add_test(NAME test-jit-${loose_nullish_mm}-narrow-loose-nullish COMMAND test-runner -jit -mm=${loose_nullish_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00narrow_loose_nullish.ts") + tslang_add_test(NAME test-compile-${loose_nullish_mm}-narrow-loose-nullish COMMAND test-runner -mm=${loose_nullish_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00narrow_loose_nullish.ts") +endforeach() # USER RULING 11-24: an element past the end of an array value, without a default, is undefined, as node has it. A # name bound to an element of a reference type (`const [a, b] = [mk(5)] as N[]`, `(N | null)[]`, nested, for-of, a # parameter) is `T | undefined` (it read null); number[]/string[] keep their type's default. The assignment form gives diff --git a/tslang/test/tester/tests/00narrow_loose_nullish.ts b/tslang/test/tester/tests/00narrow_loose_nullish.ts new file mode 100644 index 000000000..57ea94d80 --- /dev/null +++ b/tslang/test/tester/tests/00narrow_loose_nullish.ts @@ -0,0 +1,38 @@ +// `c == null` / `c == undefined` (loose) is true for null and for undefined alike. Of a value that may be undefined, +// the equal side was narrowed to null: in `c == null && c === undefined` the second test was false for undefined +// (and `c === null` true), as in `if (c == null) { c === undefined ... }`. It is left as it is now; the other side is +// the type without null and undefined. Results match node; every memory model. +class C { + constructor(public x: number) {} +} + +function t1(c: C | undefined): boolean { return c == null && c === undefined; } +function t2(c: C | null | undefined): boolean { return c == null && c === undefined; } +function t3(c: C | null | undefined): boolean { return c == null && c === null; } +function t4(c: C | null | undefined): boolean { return c == undefined && c === null; } +function t5(c: number | undefined): boolean { return c == null && c === undefined; } +function t6(c: string | null | undefined): boolean { return c == null && c !== undefined; } + +function a(c: C | undefined): number { if (c == null) return -1; return c.x; } +function b(c: C | null | undefined): number { return c != null ? c.x : -2; } +function d(c: C | undefined): boolean { return c == null || c.x > 0; } +function e(c: number | undefined): number { if (c != undefined) { return c + 1; } return 0; } +function f(c: string | null | undefined): number { return c == undefined ? -3 : c.length; } +function g(c: C | null | undefined): string { if (c == null) { return c === undefined ? "u" : "n"; } return "c" + c.x; } + +function main() { + let out = ""; + out += `${t1(undefined)} ${t1(new C(1))}|`; + out += `${t2(undefined)} ${t2(null)} ${t2(new C(1))}|`; + out += `${t3(undefined)} ${t3(null)} ${t3(new C(1))}|`; + out += `${t4(undefined)} ${t4(null)} ${t4(new C(1))}|`; + out += `${t5(undefined)} ${t5(1)}|`; + out += `${t6(undefined)} ${t6(null)} ${t6("s")}|`; + out += `${a(undefined)} ${a(new C(4))} ${b(null)} ${b(undefined)} ${b(new C(5))}|`; + out += `${d(undefined)} ${d(new C(1))} ${d(new C(-1))}|`; + out += `${e(undefined)} ${e(3)} ${f(null)} ${f(undefined)} ${f("abc")}|`; + out += `${g(undefined)} ${g(null)} ${g(new C(7))}`; + print(out); + assert(out == "true false|true false false|false true false|false true false|true false|false true false|-1 4 -2 -2 5|true true false|0 4 -3 -3 3|u n c7", "as node"); + print("done."); +} From 9dddc3de29c847f8d5601492815bcac6ee2a4e9c Mon Sep 17 00:00:00 2001 From: ASDAlexander77 Date: Tue, 24 Nov 2026 18:20:27 +0000 Subject: [PATCH 05/18] -mm=own: a `let` a pattern binds with a default can be given another value `let { p = mk(1) } = r; p = mk(3)` was refused ("'p' borrows 'r.p' and cannot be assigned", "'p' is merged from several branches"). Its value is a merge of the field's value and of the pattern-default slot's, both borrows, which letBorrows did not see as one (a block argument after lowering). It now does (mergeOfPatternDefault), and the `let` is split like one given a field read (TSLANG 66): what it is given later goes into a holder of its own and the `let` borrows it; no semantic change, the holder mechanism the plain `let p = r.p; p = mk(3)` already uses. `const [a = mk(1), b = mk(2)] = [mk(i)]` (the other shape of the item) was accepted already since the array-default slot (#1022); the test covers it. Co-Authored-By: Claude Opus 5.5 --- .../OwnershipInferenceBorrowers.cpp | 74 +++++++++++++++++++ .../lib/TypeScript/OwnershipInferencePass.h | 1 + tslang/test/tester/CMakeLists.txt | 6 ++ .../own/own_pattern_default_let_assigned.ts | 55 ++++++++++++++ 4 files changed, 136 insertions(+) create mode 100644 tslang/test/tester/own/own_pattern_default_let_assigned.ts diff --git a/tslang/lib/TypeScript/OwnershipInferenceBorrowers.cpp b/tslang/lib/TypeScript/OwnershipInferenceBorrowers.cpp index 089cf6869..4636f8ae6 100644 --- a/tslang/lib/TypeScript/OwnershipInferenceBorrowers.cpp +++ b/tslang/lib/TypeScript/OwnershipInferenceBorrowers.cpp @@ -264,12 +264,86 @@ namespace own_inference { // a read of a place or of a parameter - or of a split `let`'s holder (TSLANG 66) auto root = rootOf(value); + + // ...or a pattern's default over one (`let { p = mk(1) } = r`), lowered to the merge of its two arms: the + // optional's value (a place read) and the read of the pattern-default slot (MLIRGenImpl::optionalValueOrDefault) + if (auto argument = mlir::dyn_cast(root)) + { + return mergeOfPatternDefault(argument, 0); + } + auto rootLoad = root.getDefiningOp(); auto slot = rootLoad ? rootLoad.getReference().getDefiningOp() : mlir_ts::VariableOp(); int index = -1; return placeReadOf(root) || (slot && (isParameterSlot(slot, index) || slot->hasAttr(OWN_LET_HOLDER_ATTR_NAME))); } + // A merge (a block argument) of a pattern's default and what it defaults (`let { p = mk(1) } = r`): each + // incoming value a borrow (letBorrows, through `ts.Value` of an optional) or the read of a pattern-default slot, + // and at least one such read. + bool OwnershipInferencePass::mergeOfPatternDefault(mlir::BlockArgument argument, unsigned depth) + { + auto *block = argument.getOwner(); + if (block->isEntryBlock() || block->hasNoPredecessors() || depth > 4) + { + return false; + } + + auto slotRead = false; + for (auto predecessor = block->pred_begin(); predecessor != block->pred_end(); ++predecessor) + { + auto branchOp = mlir::dyn_cast((*predecessor)->getTerminator()); + if (!branchOp) + { + return false; + } + + auto operands = branchOp.getSuccessorOperands(predecessor.getSuccessorIndex()); + if (argument.getArgNumber() < operands.getProducedOperandCount()) + { + return false; + } + + auto incoming = operands[argument.getArgNumber()]; + if (!incoming) + { + return false; + } + + auto value = rootOf(incoming); + if (auto valueOp = value.getDefiningOp()) + { + value = rootOf(valueOp->getOperand(0)); + } + + auto load = value.getDefiningOp(); + auto slot = load ? load.getReference().getDefiningOp() : mlir_ts::VariableOp(); + if (slot && slot->hasAttr(PATTERN_DEFAULT_SLOT_ATTR_NAME)) + { + slotRead = true; + continue; + } + + if (auto nested = mlir::dyn_cast(value)) + { + if (!mergeOfPatternDefault(nested, depth + 1)) + { + return false; + } + + slotRead = true; + continue; + } + + if (!letBorrows(value)) + { + return false; + } + } + + return slotRead; + } + bool OwnershipInferencePass::borrowsOnly(mlir_ts::VariableOp varOp) { // `let layout = this.computeLayout; if (fp16) layout = this.computeLayoutFP16;` (TSLANG 56): diff --git a/tslang/lib/TypeScript/OwnershipInferencePass.h b/tslang/lib/TypeScript/OwnershipInferencePass.h index a54bff4a0..cc89ebcbd 100644 --- a/tslang/lib/TypeScript/OwnershipInferencePass.h +++ b/tslang/lib/TypeScript/OwnershipInferencePass.h @@ -464,6 +464,7 @@ class OwnershipInferencePass bool borrowsOnly(mlir_ts::VariableOp varOp); // Is `value` a read a `let` given it only borrows (borrowsOnly)? bool letBorrows(mlir::Value value); + bool mergeOfPatternDefault(mlir::BlockArgument argument, unsigned depth); // The `let` (borrowsOnly) that `user` assigns `value` to - the store itself, or rc's retain right // before it - or null. mlir_ts::VariableOp borrowingAssignmentOf(mlir::Operation *user, mlir::Value value); diff --git a/tslang/test/tester/CMakeLists.txt b/tslang/test/tester/CMakeLists.txt index f27907db4..b5d9641a4 100644 --- a/tslang/test/tester/CMakeLists.txt +++ b/tslang/test/tester/CMakeLists.txt @@ -5730,6 +5730,12 @@ foreach(loose_nullish_mm gc rc own none) tslang_add_test(NAME test-jit-${loose_nullish_mm}-narrow-loose-nullish COMMAND test-runner -jit -mm=${loose_nullish_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00narrow_loose_nullish.ts") tslang_add_test(NAME test-compile-${loose_nullish_mm}-narrow-loose-nullish COMMAND test-runner -mm=${loose_nullish_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00narrow_loose_nullish.ts") endforeach() +# -mm=own: a `let` a pattern binds with a default, given another value later (`let { p = mk(1) } = r; p = mk(3)`), is +# split into a holder as a `let` given a field read is (it was refused); the same program under gc and rc. +foreach(let_default_mm gc rc own) + tslang_add_test(NAME test-jit-${let_default_mm}-own-pattern-default-let-assigned COMMAND test-runner -jit -mm=${let_default_mm} "${PROJECT_SOURCE_DIR}/test/tester/own/own_pattern_default_let_assigned.ts") + tslang_add_test(NAME test-compile-${let_default_mm}-own-pattern-default-let-assigned COMMAND test-runner -mm=${let_default_mm} "${PROJECT_SOURCE_DIR}/test/tester/own/own_pattern_default_let_assigned.ts") +endforeach() # USER RULING 11-24: an element past the end of an array value, without a default, is undefined, as node has it. A # name bound to an element of a reference type (`const [a, b] = [mk(5)] as N[]`, `(N | null)[]`, nested, for-of, a # parameter) is `T | undefined` (it read null); number[]/string[] keep their type's default. The assignment form gives diff --git a/tslang/test/tester/own/own_pattern_default_let_assigned.ts b/tslang/test/tester/own/own_pattern_default_let_assigned.ts new file mode 100644 index 000000000..9204bde08 --- /dev/null +++ b/tslang/test/tester/own/own_pattern_default_let_assigned.ts @@ -0,0 +1,55 @@ +// -mm=own: a `let` a pattern binds with a default that makes a new value, then given another value (`let { p = mk(1) } +// = r; p = mk(3)`), was refused ("'p' borrows 'r.p' and cannot be assigned", "merged from several branches"): its +// value is a merge of a borrow of the field and of the pattern-default slot, both borrows, which own did not see +// as one. It is split as a `let` given a field read is: what it is given later goes into a holder of its own, and the +// `let` borrows that. Also `const [a = mk(1), b = mk(2)] = [mk(i)]` (accepted since the array-default slot). The same +// program under gc and rc. +class N { + x: number; + s: string; + constructor(x: number) { + this.x = x; + this.s = "n" + x; + } +} + +class R { + p?: N; +} + +@noinline function mk(i: number): N { + return new N(i); +} + +function f(r: R, i: number): number { + let { p = mk(1) } = r; + let t = p.x + p.s.length; + if (i % 3 == 0) { + p = mk(i + 10); + } + + return t + p.x + p.s.length; +} + +function main() { + let total: number = 0; + for (let i = 0; i < 300; i++) { + const r = new R(); + if (i % 2 == 0) { + r.p = mk(i); + } + + let { p = mk(1) } = r; + total += p.x; + p = mk(3); + total += p.x + p.s.length; + total += f(r, i); + + const [a = mk(1), b = mk(2)] = [mk(i)]; + total += a.x + b.x; + } + + print(total); + assert(total == 124679, "total"); + print("done."); +} From c42b79585ad7e9a14160eefe182b0e40d82ba7da Mon Sep 17 00:00:00 2001 From: ASDAlexander77 Date: Tue, 24 Nov 2026 18:21:15 +0000 Subject: [PATCH 06/18] test: pin that --own-fallback=count reads OwnershipModuleFactsPass's cached analysis An interface-typed parameter given to two `Shape | null` fields is counted only when the module's facts (DescriptorObjectsAnalysis, cached by OwnershipModuleFactsPass) say no class here may hold a closure; without the cache the answer is "may hold" and the program would be refused. own_fallback_cached_analysis (IR: compiles with the warning, 2 counted retains) fails if a pipeline change drops the cache; own_fallback_cached_analysis_held (a class with a closure field) stays an error. The probes of final-rereview m-1 (rr/ip.ts, ip_held.ts). Co-Authored-By: Claude Opus 5.5 --- tslang/test/tester/CMakeLists.txt | 11 +++++++++ .../own/own_fallback_cached_analysis.ts | 23 +++++++++++++++++++ .../own/own_fallback_cached_analysis_held.ts | 21 +++++++++++++++++ 3 files changed, 55 insertions(+) create mode 100644 tslang/test/tester/own/own_fallback_cached_analysis.ts create mode 100644 tslang/test/tester/own/own_fallback_cached_analysis_held.ts diff --git a/tslang/test/tester/CMakeLists.txt b/tslang/test/tester/CMakeLists.txt index b5d9641a4..6ae7a2e86 100644 --- a/tslang/test/tester/CMakeLists.txt +++ b/tslang/test/tester/CMakeLists.txt @@ -6415,6 +6415,17 @@ foreach(fallback_test own/own_fallback_result_borrow_stays_error own/own_err_sha "-DFILE=${PROJECT_SOURCE_DIR}/test/tester/${fallback_test}.ts" -P "${CMAKE_CURRENT_SOURCE_DIR}/own-fallback.cmake") endforeach() +# ...and the fallback reading OwnershipModuleFactsPass's cached analysis (DescriptorObjectsAnalysis): an interface +# parameter given to two fields is counted only when no class here may hold a closure (read without the cache the +# answer is "may hold", and it would be refused), and stays an error when one does +add_test(NAME test-own-fallback-ir-own_fallback_cached_analysis + COMMAND ${CMAKE_COMMAND} -DTSLANG=$ -DMODE=IR -DCOUNTED=2 + "-DFILE=${PROJECT_SOURCE_DIR}/test/tester/own/own_fallback_cached_analysis.ts" + -P "${CMAKE_CURRENT_SOURCE_DIR}/own-fallback.cmake") +add_test(NAME test-own-fallback-ir-own_fallback_cached_analysis_held + COMMAND ${CMAKE_COMMAND} -DTSLANG=$ -DMODE=EXPECT_ERROR + "-DFILE=${PROJECT_SOURCE_DIR}/test/tester/own/own_fallback_cached_analysis_held.ts" + -P "${CMAKE_CURRENT_SOURCE_DIR}/own-fallback.cmake") # ...and a tuple whose kept retains are of a tagged union's type (a `T | null` field): refused at # its place, with own's error add_test(NAME test-own-fallback-ir-own_fallback_tuple_in_union_stays_error diff --git a/tslang/test/tester/own/own_fallback_cached_analysis.ts b/tslang/test/tester/own/own_fallback_cached_analysis.ts new file mode 100644 index 000000000..15279641c --- /dev/null +++ b/tslang/test/tester/own/own_fallback_cached_analysis.ts @@ -0,0 +1,23 @@ +// -mm=own --own-fallback=count: an interface-typed parameter given to two `Shape | null` fields (`h.s = s; k.s = +// s`) is counted only when the module's facts say no class here holds a closure field - a fact +// OwnershipModuleFactsPass caches for the inference (DescriptorObjectsAnalysis). Read without the cache the answer +// is "may hold", and the program is refused instead (own_fallback_cached_analysis_held: the same with a class with a +// closure field, which is refused either way). Pins that the cached analysis is present. +interface Shape { v: number; } +class Node { constructor(public v: number) {} } +class Holder { s: Shape | null = null; } +function link(h: Holder, k: Holder, s: Shape) { + h.s = s; + k.s = s; +} +function main() { + let sum: number = 0; + for (let i = 0; i < 100; i++) { + const h = new Holder(); + const k = new Holder(); + link(h, k, new Node(i)); + sum += h.s!.v + k.s!.v; + } + print(sum); + print("done."); +} diff --git a/tslang/test/tester/own/own_fallback_cached_analysis_held.ts b/tslang/test/tester/own/own_fallback_cached_analysis_held.ts new file mode 100644 index 000000000..15e971476 --- /dev/null +++ b/tslang/test/tester/own/own_fallback_cached_analysis_held.ts @@ -0,0 +1,21 @@ +// -mm=own --own-fallback=count: own_fallback_cached_analysis with a class that has a closure field: the module's +// facts say a class here may hold a closure, so the interface-typed parameter is not counted and stays an error. +interface Shape { v: number; } +class Node { constructor(public v: number) {} } +class Holder { s: Shape | null = null; } +function link(h: Holder, k: Holder, s: Shape) { + h.s = s; + k.s = s; +} +function main() { + let sum: number = 0; + for (let i = 0; i < 100; i++) { + const h = new Holder(); + const k = new Holder(); + link(h, k, new Node(i)); + sum += h.s!.v + k.s!.v; + } + print(sum); + print("done."); +} +class Cl { f: () => number = () => 1; } function useCl() { const c = new Cl(); return c.f(); } From ede5658ac05dbe03ea594a5f442513f57c9122b3 Mon Sep 17 00:00:00 2001 From: ASDAlexander77 Date: Tue, 24 Nov 2026 18:22:32 +0000 Subject: [PATCH 07/18] --own-fallback=count: a function that fails reports no count beside its error With the flag, a function refused for an error that stays could print "-mm=own counts this object here" beside it (own_escaping_capture_used_after_error, own_fallback_uncounted_error_same_place): the user read "counted" about a program that was not built. The counts are reported only when the function does not fail. The fallback test's EXPECT_ERROR mode now also checks that no count is reported (fails with the previous binary on own_escaping_capture_used_after_error). Co-Authored-By: Claude Opus 5.5 --- tslang/lib/TypeScript/OwnershipInferencePass.cpp | 8 ++++++-- tslang/test/tester/own-fallback.cmake | 9 ++++++++- 2 files changed, 14 insertions(+), 3 deletions(-) diff --git a/tslang/lib/TypeScript/OwnershipInferencePass.cpp b/tslang/lib/TypeScript/OwnershipInferencePass.cpp index b907887f8..795e96f2c 100644 --- a/tslang/lib/TypeScript/OwnershipInferencePass.cpp +++ b/tslang/lib/TypeScript/OwnershipInferencePass.cpp @@ -329,12 +329,16 @@ namespace own_inference } markCountedRetains(); - warnCounted(); - // an error nobody counted, or a failure no counted value's error explains + // an error nobody counted, or a failure no counted value's error explains: the function fails, and is not + // built - its counts are not reported (a "counts this object here" beside an error that stays read as if the + // program were built, counting) if (uncountedErrors > 0 || (failureSignalled && countedErrors.empty())) { PassWrapper::signalPassFailure(); + return; } + + warnCounted(); } void OwnershipInferencePass::signalPassFailure() diff --git a/tslang/test/tester/own-fallback.cmake b/tslang/test/tester/own-fallback.cmake index ff9ef96a1..0fae7fb56 100644 --- a/tslang/test/tester/own-fallback.cmake +++ b/tslang/test/tester/own-fallback.cmake @@ -11,7 +11,8 @@ # SHARE, also that its LLVM IR under own has a share routine (`tsshr_`), one for # a closure's capture box (`tsshrbox_`), and an atomic `or` setting the shared # bit: Shared.share is not erased under own -# MODE=EXPECT_ERROR still refused with the flag: `error:` (with ERROR_AT, line:column, one there) +# MODE=EXPECT_ERROR still refused with the flag: `error:` (with ERROR_AT, line:column, one there), and no +# "counts this object here" warning beside it: a function that fails is not built # MODE=SAME the other way round: a file own accepts without the flag is accepted with it # too, with no count and no warning, and run with it (JIT) prints what it prints # under -mm=gc, with no error - the flag only ever turns an error into a count @@ -178,6 +179,12 @@ elseif(MODE STREQUAL "EXPECT_ERROR") if(result EQUAL 0 OR error EQUAL -1) message(FATAL_ERROR "compiled with --own-fallback=count, expected an error (${result}):\n${out}") endif() + # a function that fails is not built: it reports no count beside its error + string(FIND "${out}" "counts this object here" countWarning) + if(NOT countWarning EQUAL -1) + message(FATAL_ERROR "refused with --own-fallback=count, yet reports a count: +${out}") + endif() if(DEFINED ERROR_AT) string(FIND "${out}" ":${ERROR_AT}: error:" errorAt) if(errorAt EQUAL -1) From 4c91b51d43c359d3f32bbda24abf6aa381123694 Mon Sep 17 00:00:00 2001 From: ASDAlexander77 Date: Tue, 24 Nov 2026 18:33:35 +0000 Subject: [PATCH 08/18] test: --own-fallback=count against the default library No ctest used the flag with the default library (final-review M-5). own-defaultlib-facts.cmake takes EXTRA options (compiled each run under the JIT then, and required to count something when it is the flag); test-{jit,compile}-own-fallback-defaultlib run defaultlib/own_fallback_default_lib.ts with --own-fallback=count: a node given two owners by `link` is counted, read through the library's array helpers (map, find, some, indexOf, filter of the mapped values) with its text kept in a Map and a Set, and prints what node prints. (Own's Map and Set hold values, strings, any and Shared, and `filter` of objects is refused by design, so the counted object itself is not put in them.) Skipped when no own default library has been built, like the facts test. Co-Authored-By: Claude Opus 5.5 --- tslang/test/tester/CMakeLists.txt | 21 +++++++++ .../defaultlib/own_fallback_default_lib.ts | 46 +++++++++++++++++++ tslang/test/tester/own-defaultlib-facts.cmake | 19 +++++++- 3 files changed, 84 insertions(+), 2 deletions(-) create mode 100644 tslang/test/tester/defaultlib/own_fallback_default_lib.ts diff --git a/tslang/test/tester/CMakeLists.txt b/tslang/test/tester/CMakeLists.txt index 6ae7a2e86..e6cb4de45 100644 --- a/tslang/test/tester/CMakeLists.txt +++ b/tslang/test/tester/CMakeLists.txt @@ -4185,6 +4185,27 @@ foreach(defaultlib_collector_mode jit compile) set_tests_properties(test-${defaultlib_collector_mode}-gc-defaultlib-collector PROPERTIES SKIP_REGULAR_EXPRESSION "SKIPPED:") endforeach() +# -mm=own --own-fallback=count with the real default library: a counted node held by the library's containers (a +# Map's value, a Set's member, array helpers) beside its two holders prints what gc prints (final-review M-5: no +# test used the flag with the default library). Skipped when no own default library has been built. +foreach(own_defaultlib_mode jit compile) + add_test(NAME test-${own_defaultlib_mode}-own-fallback-defaultlib + COMMAND ${CMAKE_COMMAND} + "-DMODE=${own_defaultlib_mode}" + "-DEXTRA=--own-fallback=count" + "-DTSLANG=$" + "-DTSLANG_BIN=${CMAKE_BINARY_DIR}/bin" + "-DTEST=${CMAKE_CURRENT_SOURCE_DIR}/defaultlib/own_fallback_default_lib.ts" + "-DWORK_DIR=${CMAKE_CURRENT_BINARY_DIR}/own-fallback-defaultlib-${own_defaultlib_mode}" + "-DGC_LIB=${TEST_GC_LIBDIR}" + "-DLLVM_LIB=${defaultlib_collector_llvm_lib}" + "-DTSLANG_LIB=${CMAKE_BINARY_DIR}/lib" + "-DOPT=${defaultlib_collector_opt}" + "-DDEFAULT_LIB_CANDIDATES=${PROJECT_SOURCE_DIR}/../TypeScriptCompilerDefaultLib/__build;${PROJECT_SOURCE_DIR}/../../TypeScriptCompilerDefaultLib/__build" + -P "${CMAKE_CURRENT_SOURCE_DIR}/own-defaultlib-facts.cmake") + set_tests_properties(test-${own_defaultlib_mode}-own-fallback-defaultlib PROPERTIES SKIP_REGULAR_EXPRESSION "SKIPPED:") +endforeach() + # -mm=own with the real default library: its facts reach the program, under the JIT as for an exe # (see own-defaultlib-facts.cmake). Skipped when no own default library has been built. foreach(own_defaultlib_mode jit compile) diff --git a/tslang/test/tester/defaultlib/own_fallback_default_lib.ts b/tslang/test/tester/defaultlib/own_fallback_default_lib.ts new file mode 100644 index 000000000..690a4fd86 --- /dev/null +++ b/tslang/test/tester/defaultlib/own_fallback_default_lib.ts @@ -0,0 +1,46 @@ +// -mm=own --own-fallback=count with the default library (own-defaultlib-facts.cmake, EXTRA): a node own refuses +// to give two owners (`link` stores it in two holders) is counted, and the counted node is then read through the +// library's array helpers (`map`, `find`, `some`, `indexOf`; `filter` of the values it maps to) and its text kept in a Map and a Set (own's +// Map and Set hold values, strings, `any` and Shared), beside its holders. Each owner gives its share back; the +// program prints what gc prints. +class Node { + constructor(public v: number, public s: string) {} +} + +class Holder { + node: Node | null = null; +} + +function link(h: Holder, g: Holder, n: Node) { + h.node = n; + g.node = n; +} + +function main() { + let sum: number = 0; + for (let i = 0; i < 200; i++) { + const h = new Holder(); + const g = new Holder(); + link(h, g, new Node(i, "a" + i)); + + const byName = new Map(); + byName.set(h.node!.s, h.node!.v); + const seen = new Set(); + seen.add(g.node!.s); + const all: Node[] = [new Node(i + 1, "b" + i), new Node(i + 2, "c" + i)]; + const values = all.map((n) => n.v); + const even = values.filter((v) => v % 2 == 0); + const found = all.find((n) => n.v == i + 2); + const any = all.some((n) => n.s == "b" + i); + + sum += byName.get("a" + i)! + (seen.has(h.node!.s) ? 1 : 0) + even.length + values[0] + (found ? found.v : 0) + + (any ? 1 : 0) + all.indexOf(all[1]); + if (h.node!.s != g.node!.s) { + print("bad"); + } + } + + print(sum); + assert(sum == 61100, "sum"); + print("done."); +} diff --git a/tslang/test/tester/own-defaultlib-facts.cmake b/tslang/test/tester/own-defaultlib-facts.cmake index fa8b0e14a..b6998609a 100644 --- a/tslang/test/tester/own-defaultlib-facts.cmake +++ b/tslang/test/tester/own-defaultlib-facts.cmake @@ -5,6 +5,7 @@ # # MODE=jit run it under the JIT # MODE=compile build an exe and run it +# EXTRA more options for tslang (`--own-fallback=count`: the fallback against the library) # # Every test-runner test passes --no-default-lib, so this drives tslang itself. With no default # library built the test prints SKIPPED and CTest reports it skipped. @@ -60,7 +61,7 @@ set(ENV{DEFAULT_LIB_PATH} "") file(REMOVE_RECURSE "${WORK_DIR}") file(MAKE_DIRECTORY "${WORK_DIR}") -set(common ${OPT} -mm=own "--default-lib-path=${default_lib}" "--llvm-lib-path=${LLVM_LIB}" +set(common ${OPT} -mm=own ${EXTRA} "--default-lib-path=${default_lib}" "--llvm-lib-path=${LLVM_LIB}" "--tslang-lib-path=${TSLANG_LIB}" "--gc-lib-path=${GC_LIB}") if(WIN32) @@ -70,13 +71,19 @@ else() endif() if(MODE STREQUAL "jit") - set(command "${TSLANG}" --emit=jit ${common} "--shared-libs=${runtime}" "${TEST}") + # (with EXTRA, compiled each run: a cached object would compile nothing and say nothing) + set(jit_cache) + if(DEFINED EXTRA) + set(jit_cache --jit-cache=false) + endif() + set(command "${TSLANG}" --emit=jit ${jit_cache} ${common} "--shared-libs=${runtime}" "${TEST}") else() execute_process(COMMAND "${TSLANG}" --emit=exe ${common} "${TEST}" -o "${WORK_DIR}/test${exe_suffix}" OUTPUT_VARIABLE out ERROR_VARIABLE err RESULT_VARIABLE status) if(NOT status EQUAL 0) message(FATAL_ERROR "--emit=exe -mm=own: exit ${status}\n${out}\n${err}") endif() + set(build_log "${out}${err}") set(command "${WORK_DIR}/test${exe_suffix}") endif() @@ -88,4 +95,12 @@ if(NOT status EQUAL 0 OR NOT out MATCHES "done\.") message(FATAL_ERROR "${MODE} -mm=own: exit ${status}\n${out}\n${err}") endif() +# with --own-fallback=count, the program exercises it: a value is counted +if(EXTRA MATCHES "own-fallback") + string(FIND "${build_log}${out}${err}" "counts this object here" counted) + if(counted EQUAL -1) + message(FATAL_ERROR "${MODE} -mm=own ${EXTRA}: nothing was counted\n${build_log}${out}${err}") + endif() +endif() + message(STATUS "${MODE} -mm=own: done.") From c7861e9ebf7b4e5925d21aba4fe20ecb9438d258 Mon Sep 17 00:00:00 2001 From: ASDAlexander77 Date: Tue, 24 Nov 2026 18:34:36 +0000 Subject: [PATCH 09/18] -mm=own: a kept parameter is released where an exception leaves through the function's own finally A parameter the function keeps on some paths is released at its exits on the others: the returns and the throws. The end of a cleanup the exception leaves the function from - its own `finally`, an EndCleanup with no landing pad after it - was not one, and the parameter leaked there (final-review M-1: probe s1 +9.9 MB per 400 runs under plain own, r5 the same with --own-fallback=count for a counted kept parameter; both flat now). A parameter kept before something throws past it (`h.node = n; mayThrow()`) stays the holder's (guard-page heap: no fault). Tests: own_kept_param_finally_unwind (gc/rc/own) and own_fallback_kept_param_finally (fallback RUN). Co-Authored-By: Claude Opus 5.5 --- .../OwnershipInferenceKeptParams.cpp | 5 +- tslang/test/tester/CMakeLists.txt | 8 ++- .../own/own_fallback_kept_param_finally.ts | 35 ++++++++++++ .../own/own_kept_param_finally_unwind.ts | 56 +++++++++++++++++++ 4 files changed, 102 insertions(+), 2 deletions(-) create mode 100644 tslang/test/tester/own/own_fallback_kept_param_finally.ts create mode 100644 tslang/test/tester/own/own_kept_param_finally_unwind.ts diff --git a/tslang/lib/TypeScript/OwnershipInferenceKeptParams.cpp b/tslang/lib/TypeScript/OwnershipInferenceKeptParams.cpp index 48ade4726..f4f11484c 100644 --- a/tslang/lib/TypeScript/OwnershipInferenceKeptParams.cpp +++ b/tslang/lib/TypeScript/OwnershipInferenceKeptParams.cpp @@ -95,9 +95,12 @@ namespace own_inference auto *exit = block.empty() ? nullptr : &block.back(); // a thrown value made of the parameter takes it with it: no release there (a leak, // if it does not) + // ...and the end of a cleanup the exception leaves the function from (its own `finally`, no + // landing pad of its own after it): the kept parameter leaked on that way out (final-review M-1) auto leaves = mlir::isa_and_nonnull(exit) || (mlir::isa_and_nonnull(exit) && - !readsSlot(exit->getOperand(0), varOp.getResult())); + !readsSlot(exit->getOperand(0), varOp.getResult())) || + (mlir::isa_and_nonnull(exit) && exit->getNumSuccessors() == 0); if (!leaves) { continue; diff --git a/tslang/test/tester/CMakeLists.txt b/tslang/test/tester/CMakeLists.txt index e6cb4de45..2510027cd 100644 --- a/tslang/test/tester/CMakeLists.txt +++ b/tslang/test/tester/CMakeLists.txt @@ -5757,6 +5757,12 @@ foreach(let_default_mm gc rc own) tslang_add_test(NAME test-jit-${let_default_mm}-own-pattern-default-let-assigned COMMAND test-runner -jit -mm=${let_default_mm} "${PROJECT_SOURCE_DIR}/test/tester/own/own_pattern_default_let_assigned.ts") tslang_add_test(NAME test-compile-${let_default_mm}-own-pattern-default-let-assigned COMMAND test-runner -mm=${let_default_mm} "${PROJECT_SOURCE_DIR}/test/tester/own/own_pattern_default_let_assigned.ts") endforeach() +# -mm=own: a parameter the function keeps on some paths is released at the end of a cleanup the exception leaves +# the function from (its own `finally`), as at its returns and throws (it leaked); the same program under gc and rc. +foreach(kept_finally_mm gc rc own) + tslang_add_test(NAME test-jit-${kept_finally_mm}-own-kept-param-finally-unwind COMMAND test-runner -jit -mm=${kept_finally_mm} "${PROJECT_SOURCE_DIR}/test/tester/own/own_kept_param_finally_unwind.ts") + tslang_add_test(NAME test-compile-${kept_finally_mm}-own-kept-param-finally-unwind COMMAND test-runner -mm=${kept_finally_mm} "${PROJECT_SOURCE_DIR}/test/tester/own/own_kept_param_finally_unwind.ts") +endforeach() # USER RULING 11-24: an element past the end of an array value, without a default, is undefined, as node has it. A # name bound to an element of a reference type (`const [a, b] = [mk(5)] as N[]`, `(N | null)[]`, nested, for-of, a # parameter) is `T | undefined` (it read null); number[]/string[] keep their type's default. The assignment form gives @@ -6479,7 +6485,7 @@ foreach(fallback_test own_fallback_second_owner own_fallback_move_overwrite own_ own_fallback_call_second_owner own_fallback_swap own_fallback_global_lent own_fallback_unwind own_fallback_generator own_fallback_kept_lent own_fallback_kept_call_twice own_fallback_kept_twice_one_call own_fallback_string_second_owner own_fallback_weak_target - own_fallback_unwind_kept_param own_fallback_take_out_of_field own_fallback_take_from_result + own_fallback_unwind_kept_param own_fallback_kept_param_finally own_fallback_take_out_of_field own_fallback_take_from_result own_fallback_take_from_result_iface own_fallback_take_through_id own_fallback_not_promoted own_fallback_keeper own_fallback_fuzz_1122184 own_fallback_fuzz_1122290 own_fallback_fuzz_1122304 own_fallback_let_from_counted_local own_fallback_array_counted diff --git a/tslang/test/tester/own/own_fallback_kept_param_finally.ts b/tslang/test/tester/own/own_fallback_kept_param_finally.ts new file mode 100644 index 000000000..2d9e77681 --- /dev/null +++ b/tslang/test/tester/own/own_fallback_kept_param_finally.ts @@ -0,0 +1,35 @@ +// -mm=own --own-fallback=count: a counted parameter the function keeps, with the exception leaving through the +// function's own `finally` (`try { h.node = n; if (c) throw "x"; return 1 } finally { g.node = n }`): its share was +// given back at the returns and the throws, not at the end of that cleanup, and leaked (+9.9 MB per 400 runs; plain +// own the same, own_kept_param_finally_unwind). Prints what gc prints. +class Node { + constructor(public v: number, public s: string) {} +} +class Holder { + node: Node | null = null; +} +function link(h: Holder, g: Holder, n: Node, c: number): number { + try { + h.node = n; + if (c % 7 == 0) throw "x"; + return 1; + } finally { + g.node = n; + } +} +function main() { + let sum: number = 0; + for (let i = 0; i < 4000; i++) { + const h = new Holder(); + const g = new Holder(); + try { + sum += link(h, g, new Node(i, "a" + i), i); + } catch (e) { + sum += 3; + } + if (h.node) { sum += h.node.v; if (h.node.s != "a" + i) print("bad h"); } + if (g.node) { sum += g.node.v; if (g.node.s != "a" + i) print("bad g"); } + } + print(sum); + print("done."); +} diff --git a/tslang/test/tester/own/own_kept_param_finally_unwind.ts b/tslang/test/tester/own/own_kept_param_finally_unwind.ts new file mode 100644 index 000000000..88011396d --- /dev/null +++ b/tslang/test/tester/own/own_kept_param_finally_unwind.ts @@ -0,0 +1,56 @@ +// -mm=own: a parameter the function keeps on some paths (`if (c % 2 == 0) h.node = n`), with the exception leaving +// through the function's own `finally`: the parameter is released at the function's exits on the paths that did not +// keep it, and the end of that cleanup - where the exception leaves the function - was not one of them: it leaked +// (+9.9 MB per 400 runs, final-review M-1). Kept and then thrown past (`mayThrow` after the store) it stays the +// holder's. The same program under gc and rc. +class Node { + constructor(public v: number, public s: string) {} +} +class Holder { + node: Node | null = null; +} +let trace = 0; +function keep(h: Holder, n: Node, c: number): number { + try { + if (c % 7 == 0) throw "x"; + if (c % 2 == 0) h.node = n; + return 1; + } finally { + trace++; + } +} +@noinline function mayThrow(c: number) { if (c % 5 == 0) throw "y"; } +function keep2(h: Holder, n: Node, c: number): number { + try { + if (c % 2 == 0) h.node = n; + mayThrow(c); + if (c % 7 == 0) throw "x"; + return 1; + } finally { + trace++; + } +} +function main() { + let sum: number = 0; + trace = 0; + for (let i = 0; i < 4000; i++) { + const h = new Holder(); + try { + sum += keep(h, new Node(i, "a" + i), i); + } catch (e) { + sum += 3; + } + const h2 = new Holder(); + try { + sum += keep2(h2, new Node(i, "b" + i), i); + } catch (e) { + sum += 3; + } + if (h.node) { sum += h.node.v; if (h.node.s != "a" + i) print("bad h"); } + if (h2.node) { sum += h2.node.v; if (h2.node.s != "b" + i) print("bad h2"); } + } + print(sum + trace); + assert(sum + trace == 7445088, "total"); + print("done."); +} + From 09c3afffdc3c8271baa2f796678fd7deedbcbf39 Mon Sep 17 00:00:00 2001 From: ASDAlexander77 Date: Tue, 24 Nov 2026 18:54:53 +0000 Subject: [PATCH 10/18] Deterministic IR: landing pad ids per function, stable fields sorted, a weak field named on its view Compiling the same file twice could give different IR (final-review: own and rc, 21 corpus files out of 1896 over three rounds of 8-way parallel compiles): - `__eh_pad_id`: TSContext::nextCatchPadId counted on across the functions a thread's copy of the affine lowering pass had lowered before, so a function's pads were numbered by which thread took it. It starts at 0 for each function (beginRun); the ids only name pads within a function (Win32ExceptionPass). - `ts.own_stable_fields`: built from a map keyed by type pointer; sorted by class name and field position. - a @weak field's `weakField` name on a reread or a write: taken from the checked read found by walking the first operand of what made the view's value, which did not always reach it. weakFieldRead now names the field on the view (`__weak_field_view` = the name), and a reread or a write takes it from there. After: 0 of 1896 files differ across three rounds (own and rc). IR changes: pad id numbers (per function now), the order of ts.own_stable_fields (own_readonly_stable), the weak field names on rereads (own_weak_field_logical). Co-Authored-By: Claude Opus 5.5 --- .../TypeScript/TypeScriptPassContext.h | 7 +++- tslang/lib/TypeScript/MLIRGenClasses.cpp | 41 +++++++++++-------- .../lib/TypeScript/OwnershipSignaturePass.cpp | 11 ++++- 3 files changed, 39 insertions(+), 20 deletions(-) diff --git a/tslang/include/TypeScript/TypeScriptPassContext.h b/tslang/include/TypeScript/TypeScriptPassContext.h index 42814e985..20ffb2280 100644 --- a/tslang/include/TypeScript/TypeScriptPassContext.h +++ b/tslang/include/TypeScript/TypeScriptPassContext.h @@ -135,6 +135,11 @@ struct TSContext catchPadIdOf.beginRun(); finallyPadIdOf.beginRun(); inParentTryFinallyPad.beginRun(); + // numbered from 1 in each function: the pass runs over functions on several threads, each copy with a + // context of its own, so a count carried over from the functions a thread lowered before numbered a + // function's pads differently from one compile to the next (nondeterministic IR); only a function's own pads + // name each other (Win32ExceptionPass) + nextCatchPadId = 0; } // options @@ -165,7 +170,7 @@ struct TSContext OpSideTable catchesLeft{"catchesLeft"}; // Windows: the id a try's catch landing pad goes by, so that the pads of a try inside that // catch clause can name it as the funclet they are nested in - see tagPad in TryOpLowering - // and ts.internal.eh_pad in Win32ExceptionPass. Ids are unique within the module. + // and ts.internal.eh_pad in Win32ExceptionPass. Ids are unique within the function (beginRun). OpSideTable catchPadIdOf{"catchPadIdOf"}; // Windows: the same for the pad a try's finally is entered through on the exceptional path, // and whether a try sits in that copy of its parentTryOp's finally - the one copy that runs diff --git a/tslang/lib/TypeScript/MLIRGenClasses.cpp b/tslang/lib/TypeScript/MLIRGenClasses.cpp index 1336c8098..0858a00f7 100644 --- a/tslang/lib/TypeScript/MLIRGenClasses.cpp +++ b/tslang/lib/TypeScript/MLIRGenClasses.cpp @@ -2911,7 +2911,8 @@ namespace mlirgen } auto viewOp = builder.create(location, declaredType, castValue, loaded); - viewOp->setAttr(WEAK_FIELD_VIEW_ATTR_NAME, builder.getUnitAttr()); + // (naming the field: a reread or a write of the view takes the name from here, weakFieldNameOf) + viewOp->setAttr(WEAK_FIELD_VIEW_ATTR_NAME, builder.getStringAttr(fieldName)); return viewOp; } @@ -2949,21 +2950,24 @@ namespace mlirgen return V(result); } + // The field a @weak field's view reads (weakFieldRead names it on the view): a reread or a write of the view is + // of the same field. It was taken from the checked read found by walking the first operand of what made the + // view's value, which did not always reach it - the field's name was then lost from one compile to the next + // (nondeterministic IR). + static mlir::StringAttr weakFieldNameOf(mlir::Operation *viewOp) + { + return viewOp->getAttrOfType(WEAK_FIELD_VIEW_ATTR_NAME); + } + mlir::Value MLIRGenImpl::weakFieldReread(mlir::Location location, mlir_ts::SafeCastOp viewOp, mlir::Value loaded, const GenContext &genContext) { auto weakRefType = mlir::cast(loaded.getType()); auto derefOp = builder.create(location, weakRefType.getElementType(), loaded); derefOp.setChecked(true); - auto *below = viewOp->getOperand(0).getDefiningOp(); - while (below && !mlir::isa(below)) + if (auto name = weakFieldNameOf(viewOp)) { - below = below->getNumOperands() > 0 ? below->getOperand(0).getDefiningOp() : nullptr; - } - - if (below) - { - derefOp.setWeakFieldAttr(mlir::cast(below).getWeakFieldAttr()); + derefOp.setWeakFieldAttr(name); } auto castValue = weakFieldValue(location, derefOp.getResult(), viewOp.getType(), genContext); @@ -2973,7 +2977,14 @@ namespace mlirgen } auto rereadOp = builder.create(location, viewOp.getType(), castValue, loaded); - rereadOp->setAttr(WEAK_FIELD_VIEW_ATTR_NAME, builder.getUnitAttr()); + if (auto name = weakFieldNameOf(viewOp)) + { + rereadOp->setAttr(WEAK_FIELD_VIEW_ATTR_NAME, name); + } + else + { + rereadOp->setAttr(WEAK_FIELD_VIEW_ATTR_NAME, builder.getUnitAttr()); + } return rereadOp; } @@ -3134,16 +3145,10 @@ namespace mlirgen return mlir::Value(); } - auto derefOp = viewOp->getOperand(0).getDefiningOp(); - while (derefOp && !mlir::isa(derefOp)) - { - derefOp = derefOp->getNumOperands() > 0 ? derefOp->getOperand(0).getDefiningOp() : nullptr; - } - auto weakRef = builder.create(location, weakRefType, target, mlir::StringAttr()); - if (derefOp) + if (auto name = weakFieldNameOf(viewOp)) { - weakRef.setWeakFieldAttr(mlir::cast(derefOp).getWeakFieldAttr()); + weakRef.setWeakFieldAttr(name); } // born with no weak count: the retain the store adds is the first (as `new WeakRef(x)`) diff --git a/tslang/lib/TypeScript/OwnershipSignaturePass.cpp b/tslang/lib/TypeScript/OwnershipSignaturePass.cpp index 2ab3b18ed..208c3970f 100644 --- a/tslang/lib/TypeScript/OwnershipSignaturePass.cpp +++ b/tslang/lib/TypeScript/OwnershipSignaturePass.cpp @@ -200,7 +200,16 @@ namespace own_signature if (!stableFields.empty()) { - module->setAttr(OWN_STABLE_FIELDS_ATTR_NAME, mlir::ArrayAttr::get(&getContext(), stableFields.getArrayRef())); + // in the order of the class names and positions: writtenAfterConstruction is keyed by type pointer, and + // its order changed from one compile to the next (nondeterministic IR) + llvm::SmallVector sorted(stableFields.begin(), stableFields.end()); + auto keyOf = [](mlir::Attribute entry) { + auto pair = mlir::cast(entry); + auto storage = mlir::cast(mlir::cast(pair[0]).getValue()); + return std::make_pair(storage.getName().getAttr().getValue(), mlir::cast(pair[1]).getInt()); + }; + llvm::stable_sort(sorted, [&](mlir::Attribute a, mlir::Attribute b) { return keyOf(a) < keyOf(b); }); + module->setAttr(OWN_STABLE_FIELDS_ATTR_NAME, mlir::ArrayAttr::get(&getContext(), sorted)); } if (auto functionsDropping = module->getAttrOfType(SHARED_LIB_OWN_DROP_FIELDS_ATTR_NAME)) From 330ed799b5b573f93c3a5f03eabc4e69b87fa5e8 Mon Sep 17 00:00:00 2001 From: ASDAlexander77 Date: Tue, 24 Nov 2026 19:18:13 +0000 Subject: [PATCH 11/18] rc/own: a concise arrow gives back what its destructured parameter owns before it returns Item 1 follow-up. A concise arrow body (`({ a, b }) => a + b`) returns without a scope exit, and only a parameter's rc default-value slot was given back there: the names a destructured parameter binds, which own what they read under rc since 119bd340, were never released (the ownership verifier refused 00untyped_binding_params and 01map; rc +7.2 MB per 400 runs), and neither was own's slot for a destructured parameter's default (#1022, +5.4 MB). Both are given back before the return now. Test 00param_pattern_concise_arrow (every model). Co-Authored-By: Claude Opus 5.5 --- tslang/lib/TypeScript/MLIRGenStatements.cpp | 8 ++++++-- tslang/test/tester/CMakeLists.txt | 6 ++++++ .../tests/00param_pattern_concise_arrow.ts | 19 +++++++++++++++++++ 3 files changed, 31 insertions(+), 2 deletions(-) create mode 100644 tslang/test/tester/tests/00param_pattern_concise_arrow.ts diff --git a/tslang/lib/TypeScript/MLIRGenStatements.cpp b/tslang/lib/TypeScript/MLIRGenStatements.cpp index 5f3f3e160..1ffc5a86f 100644 --- a/tslang/lib/TypeScript/MLIRGenStatements.cpp +++ b/tslang/lib/TypeScript/MLIRGenStatements.cpp @@ -92,13 +92,17 @@ namespace mlirgen mlirGenRetainCaptured(loc(body), mlir::ValueRange{resultValue}, /*atLastUse=*/true); // ...but a slot owning a parameter's default value (-mm=rc, processOptionalParam) is given back - // here, as a return statement's scope exit gives it back: what follows the return is not reached + // here, as a return statement's scope exit gives it back: what follows the return is not reached. + // So are a destructured parameter's default slot (-mm=own, ownPatternDefaultSlot) and the names a + // destructured parameter binds (-mm=rc, mlirGenFunctionParamsBindings): `({ a, b }) => a + b` + // never gave them back (the ownership verifier: "some path out of the function never gives back") if (genContext.ownedVars) { for (auto storage : llvm::reverse(*genContext.ownedVars)) { auto varOp = storage.getDefiningOp(); - if (varOp && varOp->hasAttr(DEFAULT_VALUE_SLOT_ATTR_NAME)) + if (varOp && (varOp->hasAttr(DEFAULT_VALUE_SLOT_ATTR_NAME) || varOp->hasAttr(PATTERN_DEFAULT_SLOT_ATTR_NAME) || + (compileOptions.memoryModel == MemoryModelRC && varOp->hasAttr(OWNED_LOCAL_ATTR_NAME)))) { builder.create(loc(body), storage) ->setAttr(SCOPE_EXIT_RELEASE_ATTR_NAME, builder.getUnitAttr()); diff --git a/tslang/test/tester/CMakeLists.txt b/tslang/test/tester/CMakeLists.txt index 2510027cd..06d047673 100644 --- a/tslang/test/tester/CMakeLists.txt +++ b/tslang/test/tester/CMakeLists.txt @@ -5763,6 +5763,12 @@ foreach(kept_finally_mm gc rc own) tslang_add_test(NAME test-jit-${kept_finally_mm}-own-kept-param-finally-unwind COMMAND test-runner -jit -mm=${kept_finally_mm} "${PROJECT_SOURCE_DIR}/test/tester/own/own_kept_param_finally_unwind.ts") tslang_add_test(NAME test-compile-${kept_finally_mm}-own-kept-param-finally-unwind COMMAND test-runner -mm=${kept_finally_mm} "${PROJECT_SOURCE_DIR}/test/tester/own/own_kept_param_finally_unwind.ts") endforeach() +# A concise arrow with a destructured parameter gives back what the parameter's names own (rc) and its default's slot +# (own) before it returns (they leaked; the ownership verifier refused it); every model. +foreach(concise_mm gc rc own none) + tslang_add_test(NAME test-jit-${concise_mm}-param-pattern-concise-arrow COMMAND test-runner -jit -mm=${concise_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00param_pattern_concise_arrow.ts") + tslang_add_test(NAME test-compile-${concise_mm}-param-pattern-concise-arrow COMMAND test-runner -mm=${concise_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00param_pattern_concise_arrow.ts") +endforeach() # USER RULING 11-24: an element past the end of an array value, without a default, is undefined, as node has it. A # name bound to an element of a reference type (`const [a, b] = [mk(5)] as N[]`, `(N | null)[]`, nested, for-of, a # parameter) is `T | undefined` (it read null); number[]/string[] keep their type's default. The assignment form gives diff --git a/tslang/test/tester/tests/00param_pattern_concise_arrow.ts b/tslang/test/tester/tests/00param_pattern_concise_arrow.ts new file mode 100644 index 000000000..a5989c758 --- /dev/null +++ b/tslang/test/tester/tests/00param_pattern_concise_arrow.ts @@ -0,0 +1,19 @@ +// A concise arrow (`([a = mk(i)]: N[]) => a.x`, `({ s }: N) => s.length`) with a destructured parameter returns +// without a scope exit: the names such a parameter binds (-mm=rc: they own what they read) and its default's slot +// (-mm=own) were never given back - rc +7.2 MB, own +5.4 MB per 400 runs, and the ownership verifier refused the +// body ("some path out of the function never gives back"). Given back before the return now; every model prints the +// same. +class N { x: number; s: string; constructor(x: number) { this.x = x; this.s = "n" + x; } } +@noinline function mk(i: number): N { return new N(i); } +function main() { + let t: number = 0; + const none: N[] = []; + for (let i = 0; i < 300; i++) { + const f = ([a = mk(i)]: N[]) => a.x + a.s.length; + const g = ({ s }: N) => s.length; + t += f(none) + g(mk(i)); + } + print(t); + assert(t == 47030, "total"); + print("done."); +} From 6d6297a903e7969f19d0ba11cf64fd2109c4bfd9 Mon Sep 17 00:00:00 2001 From: ASDAlexander77 Date: Tue, 24 Nov 2026 19:46:15 +0000 Subject: [PATCH 12/18] -mm=own: a borrowed `N | null | undefined` narrowed by a loose `!= null` is a view again Review I1 of 2495d6f8. The loose narrowing cast an optional to its type without null and undefined through a ts.SafeCast over the optional, which own took for a store of the borrow: own refused `const c = vs[0]; if (c != null) c.x`, the for-of form, a field `if (h.v != null) h.v.x` and the `&&`/`||`/`?:`/else-if forms, which main accepts. The side that is not null nor undefined now reads an optional as `c !== undefined` does (its value, a ts.Value - a null left in it reads as null). The equal side still keeps its type, so item 5's results stay node's (00narrow_loose_nullish; the reviewer's L01-L14, M01-M11 under gc, rc and own). Test 00narrow_loose_nullish_borrowed (every model). Co-Authored-By: Claude Opus 5.5 --- tslang/lib/TypeScript/MLIRGenImpl.h | 7 ++-- tslang/test/tester/CMakeLists.txt | 6 +++ .../tests/00narrow_loose_nullish_borrowed.ts | 38 +++++++++++++++++++ 3 files changed, 48 insertions(+), 3 deletions(-) create mode 100644 tslang/test/tester/tests/00narrow_loose_nullish_borrowed.ts diff --git a/tslang/lib/TypeScript/MLIRGenImpl.h b/tslang/lib/TypeScript/MLIRGenImpl.h index a3b2fc1bc..c6da1a232 100644 --- a/tslang/lib/TypeScript/MLIRGenImpl.h +++ b/tslang/lib/TypeScript/MLIRGenImpl.h @@ -6339,14 +6339,15 @@ class MLIRGenImpl return mlir::failure(); } - // neither null nor undefined + // not undefined: an optional's value, read as `c !== undefined` reads it (a `ts.Value`, which -mm=own sees as a + // view of a borrow; a cast to the type without null too was taken for a store of it, and own refused a + // borrowed `N | null | undefined` narrowed so). A null left in it reads as null, which is all `c.x` needs. auto present = type; if (auto optionalType = dyn_cast(present)) { present = optionalType.getElementType(); } - - if (auto unionType = dyn_cast(present)) + else if (auto unionType = dyn_cast(present)) { SmallVector members; for (auto member : unionType.getTypes()) diff --git a/tslang/test/tester/CMakeLists.txt b/tslang/test/tester/CMakeLists.txt index 06d047673..b0c276440 100644 --- a/tslang/test/tester/CMakeLists.txt +++ b/tslang/test/tester/CMakeLists.txt @@ -5769,6 +5769,12 @@ foreach(concise_mm gc rc own none) tslang_add_test(NAME test-jit-${concise_mm}-param-pattern-concise-arrow COMMAND test-runner -jit -mm=${concise_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00param_pattern_concise_arrow.ts") tslang_add_test(NAME test-compile-${concise_mm}-param-pattern-concise-arrow COMMAND test-runner -mm=${concise_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00param_pattern_concise_arrow.ts") endforeach() +# ...and a borrowed `N | null | undefined` (an element, a for-of variable, a field) narrowed so is a view of the borrow: +# own accepts it (it refused it after the loose narrowing); every model. +foreach(loose_borrowed_mm gc rc own none) + tslang_add_test(NAME test-jit-${loose_borrowed_mm}-narrow-loose-nullish-borrowed COMMAND test-runner -jit -mm=${loose_borrowed_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00narrow_loose_nullish_borrowed.ts") + tslang_add_test(NAME test-compile-${loose_borrowed_mm}-narrow-loose-nullish-borrowed COMMAND test-runner -mm=${loose_borrowed_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00narrow_loose_nullish_borrowed.ts") +endforeach() # USER RULING 11-24: an element past the end of an array value, without a default, is undefined, as node has it. A # name bound to an element of a reference type (`const [a, b] = [mk(5)] as N[]`, `(N | null)[]`, nested, for-of, a # parameter) is `T | undefined` (it read null); number[]/string[] keep their type's default. The assignment form gives diff --git a/tslang/test/tester/tests/00narrow_loose_nullish_borrowed.ts b/tslang/test/tester/tests/00narrow_loose_nullish_borrowed.ts new file mode 100644 index 000000000..7f12959fd --- /dev/null +++ b/tslang/test/tester/tests/00narrow_loose_nullish_borrowed.ts @@ -0,0 +1,38 @@ +// A borrowed `N | null | undefined` narrowed by a loose `!= null` / `== null` - an element read into a `const`, a +// for-of variable, a field - is read as `c !== undefined` reads it, a view of the borrow: -mm=own accepted these +// before the loose narrowing (00narrow_loose_nullish) and refused them with it ("'c' borrows an element and cannot +// be stored, returned or captured"). Every model; output as node's. +class N { + x: number; + constructor(x: number) { + this.x = x; + } +} + +class H { + v: N | null | undefined = undefined; +} + +function main() { + let total: number = 0; + for (let i = 0; i < 100; i++) { + const vs: (N | null | undefined)[] = [new N(i), null, undefined]; + const c = vs[0]; + if (c != null) total += c.x; + const d = vs[1]; + if (d == null) total += 1; + for (const e of vs) { + if (e != null) total += e.x; + else if (e === undefined) total += 2; + } + + const h = new H(); + h.v = new N(3); + if (h.v != null) total += h.v.x; + total += h.v == null || h.v.x > 2 ? 1 : 0; + } + + print(total); + assert(total == 10600, "total"); + print("done."); +} From 587b2ab479e61c59b31ee2ec3f295c5500fd5f19 Mon Sep 17 00:00:00 2001 From: ASDAlexander77 Date: Tue, 24 Nov 2026 19:47:03 +0000 Subject: [PATCH 13/18] -mm=own: only a pattern default's merge is a borrow of its own; other merges as before Review I2 of 9dddc3de. letBorrows returned mergeOfPatternDefault for every block-argument root, shadowing what it decided before for other merges - the bounds test of an array element (`const [a] = xs; let z = a; z = new N(6)`, refused: "'z' borrows 'xs[]' and cannot be assigned"; main accepts it and prints 6). A merge that is a pattern default's is a borrow; any other falls through to the previous checks. own_pattern_default_let_assigned covers it. Co-Authored-By: Claude Opus 5.5 --- .../lib/TypeScript/OwnershipInferenceBorrowers.cpp | 5 +++-- .../tester/own/own_pattern_default_let_assigned.ts | 12 ++++++++++-- 2 files changed, 13 insertions(+), 4 deletions(-) diff --git a/tslang/lib/TypeScript/OwnershipInferenceBorrowers.cpp b/tslang/lib/TypeScript/OwnershipInferenceBorrowers.cpp index 4636f8ae6..a44147c5c 100644 --- a/tslang/lib/TypeScript/OwnershipInferenceBorrowers.cpp +++ b/tslang/lib/TypeScript/OwnershipInferenceBorrowers.cpp @@ -267,9 +267,10 @@ namespace own_inference // ...or a pattern's default over one (`let { p = mk(1) } = r`), lowered to the merge of its two arms: the // optional's value (a place read) and the read of the pattern-default slot (MLIRGenImpl::optionalValueOrDefault) - if (auto argument = mlir::dyn_cast(root)) + // (any other merge is decided below, as before) + if (auto argument = mlir::dyn_cast(root); argument && mergeOfPatternDefault(argument, 0)) { - return mergeOfPatternDefault(argument, 0); + return true; } auto rootLoad = root.getDefiningOp(); diff --git a/tslang/test/tester/own/own_pattern_default_let_assigned.ts b/tslang/test/tester/own/own_pattern_default_let_assigned.ts index 9204bde08..96cc2b902 100644 --- a/tslang/test/tester/own/own_pattern_default_let_assigned.ts +++ b/tslang/test/tester/own/own_pattern_default_let_assigned.ts @@ -3,7 +3,8 @@ // value is a merge of a borrow of the field and of the pattern-default slot, both borrows, which own did not see // as one. It is split as a `let` given a field read is: what it is given later goes into a holder of its own, and the // `let` borrows that. Also `const [a = mk(1), b = mk(2)] = [mk(i)]` (accepted since the array-default slot). The same -// program under gc and rc. +// program under gc and rc. A `let` given a destructured element (`const [a] = xs; let z = a; z = new N(6)`), a merge +// that is no pattern default, is split as before (it was refused while every merge was taken for one). class N { x: number; s: string; @@ -47,9 +48,16 @@ function main() { const [a = mk(1), b = mk(2)] = [mk(i)]; total += a.x + b.x; + + const xs: N[] = [mk(i), mk(i + 1)]; + const [e] = xs; + let z = e; + total += z.x; + z = new N(6); + total += z.x; } print(total); - assert(total == 124679, "total"); + assert(total == 171329, "total"); print("done."); } From a4ab109815051424676bc2ae241bb37befb4e70e Mon Sep 17 00:00:00 2001 From: ASDAlexander77 Date: Tue, 24 Nov 2026 20:01:47 +0000 Subject: [PATCH 14/18] OwnedReturnConsumptionPass: say that writesPlace is deliberately coarse Review m1 of 119bd340: any store into a field or an element counts, a constructor's too, so nearly every function that makes an object "may write a place"; readsCapturedPlace is what keeps the holds few. A comment only. Co-Authored-By: Claude Opus 5.5 --- tslang/lib/TypeScript/OwnedReturnConsumptionPass.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/tslang/lib/TypeScript/OwnedReturnConsumptionPass.cpp b/tslang/lib/TypeScript/OwnedReturnConsumptionPass.cpp index 578c36eb6..e8833996d 100644 --- a/tslang/lib/TypeScript/OwnedReturnConsumptionPass.cpp +++ b/tslang/lib/TypeScript/OwnedReturnConsumptionPass.cpp @@ -1439,7 +1439,9 @@ class OwnedReturnConsumptionPass llvm::StringSet<> assignsAny; // ...and the functions that may give a field or an element a new value, or take one out of an array // (`pop`, `shift`, `splice`), or give a captured local a new value through its cell: what a place - // in a captured local's object read may be freed by (rc, readsCapturedPlace) + // in a captured local's object read may be freed by (rc, readsCapturedPlace). Deliberately coarse: any + // store into a field or an element counts - a constructor's `this.x = ...` too - so nearly every function that + // makes an object "may write a place"; it is readsCapturedPlace that keeps the holds few llvm::StringSet<> writesPlace; module.walk([&](mlir_ts::FuncOp funcOp) { auto name = funcOp.getSymName(); From 551a11e9d41e036a3de7dbb7b081300695087ce9 Mon Sep 17 00:00:00 2001 From: ASDAlexander77 Date: Tue, 24 Nov 2026 20:25:34 +0000 Subject: [PATCH 15/18] -mm=own: a @value record narrowed by a loose != null is also narrowed off its null niche Follow-up to 6d6297a9. Reading an optional's value left `Hit | null` for a @value record whose null is a niche of its own (`Hit | null` is optional): own_value_record and own_value_loop (`if (h != null) h.thing.id()`) were then refused ("a value that borrows 'this' cannot be stored, returned or captured"; the full ctest caught it). For a @value member the value just read is narrowed again off null, as `c !== null` narrows a union. A class's null stays in it (a second narrowing of a field read, `h.v`, was taken for a store of the borrow). ctest value|narrow|nullish|optional 742/742; reviewer L01-L14, M01-M11 as node. Co-Authored-By: Claude Opus 5.5 --- tslang/lib/TypeScript/MLIRGenImpl.h | 27 +++++++++++++++++++++++++-- 1 file changed, 25 insertions(+), 2 deletions(-) diff --git a/tslang/lib/TypeScript/MLIRGenImpl.h b/tslang/lib/TypeScript/MLIRGenImpl.h index c6da1a232..f9052a3a0 100644 --- a/tslang/lib/TypeScript/MLIRGenImpl.h +++ b/tslang/lib/TypeScript/MLIRGenImpl.h @@ -6371,10 +6371,33 @@ class MLIRGenImpl present = members.size() == 1 ? members.front() : getUnionType(members); } - // `!=`: present where true + // `!=`: present where true - and, for a @value record whose null is a niche of its own (`Hit | null | + // undefined`), not null either, narrowed again from the value just read as `c !== null` narrows a union: its + // fields are read so (own refused a borrow of `this` stored in a `Hit` read as `Hit | null`). A class's null + // stays in it, its reads are the same either way, and a second narrowing of a field read (`h.v`) was taken + // for a store of the borrow if (inverse) { - return addSafeCastStatement(val, present, false, nullptr, genContext); + if (mlir::failed(addSafeCastStatement(val, present, false, nullptr, genContext))) + { + return mlir::failure(); + } + + if (auto unionType = dyn_cast(present); + unionType && llvm::any_of(unionType.getTypes(), [](mlir::Type member) { return isa(member); }) && + llvm::any_of(unionType.getTypes(), [](mlir::Type member) { return isa(member); })) + { + SmallVector members; + llvm::copy_if(unionType.getTypes(), std::back_inserter(members), + [](mlir::Type member) { return !isa(member); }); + if (!members.empty()) + { + return addSafeCastStatement(val, members.size() == 1 ? members.front() : getUnionType(members), false, + nullptr, genContext); + } + } + + return mlir::success(); } // `==`: present where false From a2c6ac0d15412bb79be93b11d35d6af57c7cb037 Mon Sep 17 00:00:00 2001 From: ASDAlexander77 Date: Tue, 24 Nov 2026 21:26:20 +0000 Subject: [PATCH 16/18] -mm=rc: hold an argument whose place another name may reach and the call may write Review I3 of 119bd340, the user's "narrow it first". The caller held an argument read out of a place only when the place's object was a captured local's (or a const captured by value): rc still read freed memory when the object was reachable through another name the callee writes - stored in a global (`G = h; gw2(h.o)`), put in another argument's container (`aw(bx, arr[0])`, `bx = [arr]`), a second const a closure pops, a captured array holding it (main too). readsAliasedPlace holds it when both: - some object on the way to the place may be aliased: it is not one made here that never escapes - a parameter's object, a captured local's, one read out of somewhere else, one stored, captured, passed on or copied to another local; - the call may write a place of a kind on that way: writtenKinds per function, propagated through callees (a call through a value: what the module writes), by a field's name, an element, a captured local's cell. Writes that only make an object - a constructor's into `this`, into an object or box the function just made, into a local record - do not count. Corpus impact (rc only; own, gc and none unchanged): 9 files, 22 retains (00any_keys_write 11) - the unnarrowed rule was 40 files and 77, 7 of them in raytrace's per-light callback; now raytrace and own_raytrace gain none (rc release: main 66-83 ms, branch 66-74 ms). Test 00rc_argument_place_aliased (the reviewer's X01-X21, gc/rc/none) and its IR test. Co-Authored-By: Claude Opus 5.5 --- .../TypeScript/OwnedReturnConsumptionPass.cpp | 348 +++++++++++++++--- tslang/test/tester/CMakeLists.txt | 14 + .../tests/00rc_argument_place_aliased.ts | 233 ++++++++++++ 3 files changed, 550 insertions(+), 45 deletions(-) create mode 100644 tslang/test/tester/tests/00rc_argument_place_aliased.ts diff --git a/tslang/lib/TypeScript/OwnedReturnConsumptionPass.cpp b/tslang/lib/TypeScript/OwnedReturnConsumptionPass.cpp index e8833996d..05548e339 100644 --- a/tslang/lib/TypeScript/OwnedReturnConsumptionPass.cpp +++ b/tslang/lib/TypeScript/OwnedReturnConsumptionPass.cpp @@ -1437,26 +1437,112 @@ class OwnedReturnConsumptionPass llvm::StringMap> assigns; llvm::StringMap> callees; llvm::StringSet<> assignsAny; - // ...and the functions that may give a field or an element a new value, or take one out of an array - // (`pop`, `shift`, `splice`), or give a captured local a new value through its cell: what a place - // in a captured local's object read may be freed by (rc, readsCapturedPlace). Deliberately coarse: any - // store into a field or an element counts - a constructor's `this.x = ...` too - so nearly every function that - // makes an object "may write a place"; it is readsCapturedPlace that keeps the holds few - llvm::StringSet<> writesPlace; + // ...and the places each function gives a new value or takes a value out of (rc, readsAliasedPlace), by kind: + // a field by its name ("F:" + name), an element ("E": a store, `pop`, `shift`, `splice`), a captured local's + // cell ("C"), anything else ("*"). Deliberately coarse - a name stands for that field of every class, an + // element for every array - but not the stores that only make an object: a constructor's into `this`, a + // function's into the object it just made, a local record's into its own slot. A function that calls through + // a value may run any function here: it writes what the module writes (moduleKinds). + llvm::StringMap> writtenKinds; + llvm::StringSet<> moduleKinds; + auto fieldKindOf = [](mlir_ts::PropertyRefOp propertyRefOp) -> std::string { + auto type = propertyRefOp->getOperand(0).getType(); + if (auto refType = mlir::dyn_cast(type)) + { + type = refType.getElementType(); + } + + if (auto classType = mlir::dyn_cast(type)) + { + type = classType.getStorageType(); + } + + mlir::Attribute id; + auto position = propertyRefOp.getPosition(); + if (auto storageType = mlir::dyn_cast(type); + storageType && position >= 0 && static_cast(position) < storageType.getFields().size()) + { + id = storageType.getFields()[position].id; + } + else if (auto tupleType = mlir::dyn_cast(type); + tupleType && position >= 0 && static_cast(position) < tupleType.getFields().size()) + { + id = tupleType.getFields()[position].id; + } + + auto name = mlir::dyn_cast_or_null(id); + return name ? ("F:" + name.getValue()).str() : std::string("*"); + }; + // the object a store makes rather than changes: `this` in a constructor, a new object of this function, a + // local record's slot + auto initializes = [](mlir::Value object, mlir_ts::FuncOp funcOp) { + while (auto castOp = object.getDefiningOp()) + { + object = castOp.getIn(); + } + + if (auto argument = mlir::dyn_cast(object)) + { + return argument.getArgNumber() == 0 && argument.getOwner()->isEntryBlock() && + funcOp.getSymName().ends_with(".constructor"); + } + + if (auto loadOp = object.getDefiningOp()) + { + // `this` read out of a constructor's parameter slot; or a new box's contents + if (loadOp.getReference().getDefiningOp()) + { + return true; + } + + auto *slot = loadOp.getReference().getDefiningOp(); + auto initial = mlir::isa_and_nonnull(slot) && slot->getNumOperands() > 0 + ? slot->getOperand(0) + : mlir::Value(); + auto argument = initial ? mlir::dyn_cast(initial) : mlir::BlockArgument(); + return argument && argument.getArgNumber() == 0 && argument.getOwner()->isEntryBlock() && + funcOp.getSymName().ends_with(".constructor"); + } + + return mlir::isa_and_nonnull(object.getDefiningOp()); + }; module.walk([&](mlir_ts::FuncOp funcOp) { auto name = funcOp.getSymName(); funcOp.walk([&](mlir::Operation *op) { if (mlir::isa(op)) { - writesPlace.insert(name); + writtenKinds[name].insert("E"); } if (auto storeOp = mlir::dyn_cast(op)) { auto reference = storeOp.getReference(); - if (own_facts::isPlace(reference) || reference.getDefiningOp()) + if (auto propertyRefOp = reference.getDefiningOp()) + { + if (!initializes(propertyRefOp->getOperand(0), funcOp)) + { + writtenKinds[name].insert(fieldKindOf(propertyRefOp)); + } + } + else if (auto elementRefOp = reference.getDefiningOp()) + { + if (!initializes(elementRefOp->getOperand(0), funcOp)) + { + writtenKinds[name].insert("E"); + } + } + else if (reference.getDefiningOp()) + { + // a new box's contents (an object literal boxed for an interface): made, not changed + } + else if (own_facts::isPlace(reference)) { - writesPlace.insert(name); + writtenKinds[name].insert("*"); + } + else if (reference.getDefiningOp()) + { + writtenKinds[name].insert("C"); } if (auto global = globalOf(storeOp.getReference(), true); !global.empty()) @@ -1491,10 +1577,6 @@ class OwnedReturnConsumptionPass changed = true; } - if (writesPlace.contains(callee) && writesPlace.insert(caller).second) - { - changed = true; - } if (auto it = assigns.find(callee); it != assigns.end()) { @@ -1514,6 +1596,51 @@ class OwnedReturnConsumptionPass } } + for (auto &entry : writtenKinds) + { + for (auto &kind : entry.getValue()) + { + moduleKinds.insert(kind.getKey()); + } + } + + // a function calling through a value may run any of them + for (auto &entry : assignsAny) + { + for (auto &kind : moduleKinds) + { + writtenKinds[entry.getKey()].insert(kind.getKey()); + } + } + + for (auto changed = true; changed;) + { + changed = false; + for (auto &entry : callees) + { + auto caller = entry.getKey(); + for (auto callee : entry.getValue()) + { + auto it = writtenKinds.find(callee); + if (it == writtenKinds.end()) + { + continue; + } + + llvm::SmallVector kinds; + for (auto &kind : it->getValue()) + { + kinds.push_back(kind.getKey().str()); + } + + for (auto &kind : kinds) + { + changed |= writtenKinds[caller].insert(kind).second; + } + } + } + } + auto mayAssignAnyGlobal = [&](mlir::Operation *op) { auto callee = calleeOf(op); if (callee.empty() || assignsAny.contains(callee)) @@ -1556,27 +1683,142 @@ class OwnedReturnConsumptionPass return false; }; - auto mayWritePlace = [&](mlir::Operation *op) { + // the kinds of places a call may write (writtenKinds; through a value: what any function here writes) + auto mayWriteKind = [&](mlir::Operation *op, llvm::StringRef kind) { auto callee = calleeOf(op); - return callee.empty() || assignsAny.contains(callee) || writesPlace.contains(callee); + const llvm::StringSet<> *kinds = &moduleKinds; + if (!callee.empty() && !assignsAny.contains(callee)) + { + auto it = writtenKinds.find(callee); + if (it == writtenKinds.end()) + { + return false; + } + + kinds = &it->getValue(); + } + + return kinds->contains(kind) || kinds->contains("*"); }; - // Is this a read out of a field or an element of the object a captured local holds (`f(arr[0])`, `arr` - // captured by a closure)? A closure - the callee, or one it calls - may give that place a new value - // (`arr[0] = mk(i)`), take the element out (`arr.pop()`), or give the local a new value, while the - // callee still reads its parameter: the place's release freed the block the argument read. A `const` - // object a closure captures by value (`const h = new H(); () => { h.o = mk(i) }`, then `f(h.o)`) is the - // same object in the closure's box. - auto capturedByValue = [](mlir::Value object) { - std::function captured = [&](mlir::Value value, int depth) { - return depth < 4 && llvm::any_of(value.getUsers(), [&](mlir::Operation *user) { - return mlir::isa(user) || - (mlir::isa(user) && captured(user->getResult(0), depth + 1)); - }); - }; - return captured(object, 0); + // Is this a read out of a field or an element of an object some other name may reach, which the call may give + // a new value? `f(arr[0])` with `arr` captured by a closure that sets `arr[0]`, also stored in a global whose + // element the callee sets, put into another array, copied to another local that `pop`s it; `f(h.o)` with + // `arrh = [h]` and a closure setting `arrh[0].o`. The callee - or what it calls - frees the block the argument + // read while it still reads its parameter. Two facts together, both needed: + // - some object on the way to the place may be reached by another name: it is not one made here that never + // escapes (read only through its places, its length, a comparison or this very call) - a parameter's + // object, a captured local's, one read out of somewhere else, one stored or passed on; + // - the call may write a place of a kind on that way (writtenKinds: the field's name, an element, a captured + // local's cell), a write that makes an object aside. + // A global's object is the global rule's (globalOf, mayAssign), not this one's. + std::function escapes = [&](mlir::Value value, mlir::Operation *call, int depth) { + if (depth > 6) + { + return true; + } + + for (auto &use : value.getUses()) + { + auto *user = use.getOwner(); + if (user == call || mlir::isa(user)) + { + continue; + } + + // a place in it: reading and writing it is not another name for the object + if (mlir::isa(user) && use.getOperandNumber() == 0) + { + continue; + } + + // a store of something else into it + if (auto storeOp = mlir::dyn_cast(user); storeOp && storeOp.getValue() != value) + { + continue; + } + + if (mlir::isa(user)) + { + if (escapes(user->getResult(0), call, depth + 1)) + { + return true; + } + + continue; + } + + return true; + } + + return false; + }; + auto isFresh = [](mlir::Value value) { + auto *def = value.getDefiningOp(); + return mlir::isa_and_nonnull(def) || + (mlir::isa_and_nonnull(def) && mlir::isa(def->getOperand(0).getType())); }; - auto readsCapturedPlace = [&](mlir::Value value) { + // may another name reach the object a value is? Not one made here that never escapes, nor a local's slot given + // only such values, not captured, nothing read out of it escaping. (`captured`: the object is a captured + // local's, whose cell a closure may give a new value) + auto mayBeAliased = [&](mlir::Value object, mlir::Operation *call, bool &captured) { + while (auto castOp = object.getDefiningOp()) + { + object = castOp.getIn(); + } + + if (auto loadOp = object.getDefiningOp()) + { + auto varOp = loadOp.getReference().getDefiningOp(); + if (!varOp) + { + // a global's, or one read out of another place (whose object is looked at in its turn) + return false; + } + + if (varOp.getCaptured().value_or(false)) + { + captured = true; + return true; + } + + if (!varOp.getInitializer() || !isFresh(varOp.getInitializer())) + { + return true; + } + + for (auto *user : varOp->getUsers()) + { + if (auto storeOp = mlir::dyn_cast(user)) + { + if (storeOp.getReference() == varOp.getResult() && !isFresh(storeOp.getValue())) + { + return true; + } + + continue; + } + + if (auto slotRead = mlir::dyn_cast(user); slotRead && escapes(slotRead.getResult(), call, 0)) + { + return true; + } + } + + return false; + } + + // a parameter's object: its caller's, which other names may reach + if (mlir::isa(object)) + { + return true; + } + + return !isFresh(object) || escapes(object, call, 0); + }; + auto readsAliasedPlace = [&](mlir::Value value, mlir::Operation *call) { while (auto castOp = value.getDefiningOp()) { value = castOp.getIn(); @@ -1588,31 +1830,47 @@ class OwnedReturnConsumptionPass return false; } - if (auto varOp = mlir::dyn_cast_or_null(own_facts::slotOfRef(loadOp.getReference()))) + // each place on the way, and the object it is in + auto aliased = false; + auto written = false; + auto ref = loadOp.getReference(); + for (auto depth = 0; depth < 16 && ref && own_facts::isPlace(ref); depth++) { - return varOp.getCaptured().value_or(false); - } + auto *place = ref.getDefiningOp(); + if (auto propertyRefOp = mlir::dyn_cast(place)) + { + written = written || mayWriteKind(call, fieldKindOf(propertyRefOp)); + } + else if (mlir::isa(place)) + { + written = written || mayWriteKind(call, "E"); + } + else + { + written = true; + } - // the object the place is in, through places, when no slot holds it - auto object = loadOp.getReference(); - for (auto depth = 0; depth < 16 && object && own_facts::isPlace(object); depth++) - { - object = object.getDefiningOp()->getOperand(0); + auto object = place->getOperand(0); while (auto castOp = object.getDefiningOp()) { object = castOp.getIn(); } - if (capturedByValue(object)) + // (a field of a local tuple: the place is in the slot itself) + if (mlir::isa_and_nonnull(object.getDefiningOp())) { - return true; + return false; } + auto captured = false; + aliased = mayBeAliased(object, call, captured) || aliased; + written = written || (captured && mayWriteKind(call, "C")); + auto innerLoad = object.getDefiningOp(); - object = innerLoad ? innerLoad.getReference() : mlir::Value(); + ref = innerLoad ? innerLoad.getReference() : mlir::Value(); } - return false; + return aliased && written; }; auto mayAssign = [&](mlir::Operation *op, mlir::StringRef global) { @@ -1765,9 +2023,9 @@ class OwnedReturnConsumptionPass continue; } - // Out of a field or an element of a captured local's object, to a call that may write a place - // (readsCapturedPlace). Under rc the caller holds it. - if (compileOptions.isRefCounted() && readsCapturedPlace(argument) && mayWritePlace(op)) + // Out of a field or an element of an object another name may reach, to a call that may write that + // place (readsAliasedPlace). Under rc the caller holds it. + if (compileOptions.isRefCounted() && readsAliasedPlace(argument, op)) { held.push_back({op, argument}); continue; diff --git a/tslang/test/tester/CMakeLists.txt b/tslang/test/tester/CMakeLists.txt index b0c276440..50c413394 100644 --- a/tslang/test/tester/CMakeLists.txt +++ b/tslang/test/tester/CMakeLists.txt @@ -5775,6 +5775,20 @@ foreach(loose_borrowed_mm gc rc own none) tslang_add_test(NAME test-jit-${loose_borrowed_mm}-narrow-loose-nullish-borrowed COMMAND test-runner -jit -mm=${loose_borrowed_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00narrow_loose_nullish_borrowed.ts") tslang_add_test(NAME test-compile-${loose_borrowed_mm}-narrow-loose-nullish-borrowed COMMAND test-runner -mm=${loose_borrowed_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00narrow_loose_nullish_borrowed.ts") endforeach() +# -mm=rc: an argument read out of a place of an object another name may reach (a global, another argument's container, +# a second const, a captured array, a parameter's object) is held across a call that may write a place of that kind +# (the reviewer's X01-X21; rc read freed memory). gc and none the same. IR: `gw2(h.o)` after `G = h`, with `gw2` setting +# `G.o`, holds the argument. +foreach(arg_aliased_mm gc rc none) + tslang_add_test(NAME test-jit-${arg_aliased_mm}-rc-argument-place-aliased COMMAND test-runner -jit -mm=${arg_aliased_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00rc_argument_place_aliased.ts") + tslang_add_test(NAME test-compile-${arg_aliased_mm}-rc-argument-place-aliased COMMAND test-runner -mm=${arg_aliased_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00rc_argument_place_aliased.ts") +endforeach() +add_test(NAME test-rc-argument-place-aliased-ir + COMMAND $ --emit=mlir --no-default-lib -mm=rc + "${PROJECT_SOURCE_DIR}/test/tester/tests/00rc_argument_place_aliased.ts") +set_tests_properties(test-rc-argument-place-aliased-ir + PROPERTIES PASS_REGULAR_EXPRESSION "identifier = @gw2}>[^\n]*\n[^\n]*\"ts[.]PropertyRef\"[^\n]*\n[^\n]*\"ts[.]Load\"[^\n]*\n *\"ts[.]Retain\"" + FAIL_REGULAR_EXPRESSION "error:|Stack dump") # USER RULING 11-24: an element past the end of an array value, without a default, is undefined, as node has it. A # name bound to an element of a reference type (`const [a, b] = [mk(5)] as N[]`, `(N | null)[]`, nested, for-of, a # parameter) is `T | undefined` (it read null); number[]/string[] keep their type's default. The assignment form gives diff --git a/tslang/test/tester/tests/00rc_argument_place_aliased.ts b/tslang/test/tester/tests/00rc_argument_place_aliased.ts new file mode 100644 index 000000000..0fe10d730 --- /dev/null +++ b/tslang/test/tester/tests/00rc_argument_place_aliased.ts @@ -0,0 +1,233 @@ +// -mm=rc: an argument read out of a field or an element of an object another name may reach, given to a call that +// may write that place through the other name, is held by the caller across the call. The reviewer's X01-X21: the +// object a closure captures (by reference or by value), also stored in a global (`G = h; gw2(h.o)` with `gw2` setting +// `G.o`), in another argument's container (`aw(bx, arr[0])`, `bx = [arr]`), behind a second const a closure pops +// (`const b2 = arr`), reached through a captured array (`arrh = [h]`, a closure setting `arrh[0].o`), a parameter's +// object, a callback. rc read freed memory (main too); each part now prints what gc prints. The hold needs both: an +// object on the way that may be aliased, and a call that may write a place of that kind (a field's name, an element, +// a captured local's cell) - writes that only make an object (a constructor's) do not count. gc and none print the +// same; own refuses these programs. +class N { + x: number; + s: string; + constructor(x: number) { + this.x = x; + this.s = "n" + x; + } +} + +@noinline function mk(i: number): N { + return new N(i); +} + +@noinline function ms(i: number): string { + return "s" + i; +} + +@noinline function take(o: N | null): number { + return o ? o.x + o.s.length : 0; +} + +@noinline function takes(s: string | null): number { + return s ? s.length : 0; +} + +function churn() { + const junk: N[] = []; + for (let i = 0; i < 16; i++) { + junk.push(new N(i)); + } +} +class H { o: N = mk(0); arr: N[] = [mk(0)]; h2: H | null = null; m(p: N): number { this.o = mk(77); this.arr[0] = mk(78); let t: number = 0; churn(); t += p.x + (p.s == "n" + p.x ? 0 : 1000000); return t; } } +let G: H = new H(); +const GA: N[] = [mk(0)]; +function gw(p: N): number { G.o = mk(5); let t: number = 0; churn(); t += p.x + (p.s == "n" + p.x ? 0 : 1000000); return t; } +function gw2(p: N): number { G.o = mk(5); let t: number = 0; churn(); t += p.x + (p.s == "n" + p.x ? 0 : 1000000); return t; } +function hw(b: H, p: N): number { b.h2!.o = mk(5); let t: number = 0; churn(); t += p.x + (p.s == "n" + p.x ? 0 : 1000000); return t; } +function aw(bx: N[][], p: N): number { bx[0][0] = mk(5); let t: number = 0; churn(); t += p.x + (p.s == "n" + p.x ? 0 : 1000000); return t; } +function gaw(p: N): number { GA[0] = mk(5); let t: number = 0; churn(); t += p.x + (p.s == "n" + p.x ? 0 : 1000000); return t; } +function gaw2(p: N): number { GA.pop(); GA.push(mk(5)); let t: number = 0; churn(); t += p.x + (p.s == "n" + p.x ? 0 : 1000000); return t; } +function cw(cb: () => void, p: N): number { cb(); let t: number = 0; churn(); t += p.x + (p.s == "n" + p.x ? 0 : 1000000); return t; } +function pw(h: H): number { return inner(h, h.o); } function inner(h: H, p: N): number { h.o = mk(9); let t: number = 0; churn(); t += p.x + (p.s == "n" + p.x ? 0 : 1000000); return t; } +function x01(): number { + let total: number = 0; + for (let i = 0; i < 300; i++) { + const arr: N[] = [mk(i)]; const f = (p: N) => { arr[0] = mk(i + 1); let t: number = 0; churn(); t += p.x + (p.s == "n" + p.x ? 0 : 1000000); return t; }; total += f(arr[0]); + } + return total; +} +function x02(): number { + let total: number = 0; + for (let i = 0; i < 300; i++) { + const h = new H(); h.o = mk(i); const f = (p: N) => { h.o = mk(i + 1); let t: number = 0; churn(); t += p.x + (p.s == "n" + p.x ? 0 : 1000000); return t; }; total += f(h.o); + } + return total; +} +function x03(): number { + let total: number = 0; + for (let i = 0; i < 300; i++) { + const h = new H(); h.o = mk(i); total += h.m(h.o); + } + return total; +} +function x04(): number { + let total: number = 0; + for (let i = 0; i < 300; i++) { + const h = new H(); h.arr[0] = mk(i); total += h.m(h.arr[0]); + } + return total; +} +function x05(): number { + let total: number = 0; + for (let i = 0; i < 300; i++) { + G.o = mk(i); total += gw(G.o); + } + return total; +} +function x06(): number { + let total: number = 0; + for (let i = 0; i < 300; i++) { + const h = new H(); h.o = mk(i); G = h; total += gw2(h.o); + } + return total; +} +function x07(): number { + let total: number = 0; + for (let i = 0; i < 300; i++) { + const h = new H(); h.o = mk(i); const box = new H(); box.h2 = h; total += hw(box, h.o); + } + return total; +} +function x08(): number { + let total: number = 0; + for (let i = 0; i < 300; i++) { + const arr: N[] = [mk(i)]; const bx: N[][] = [arr]; total += aw(bx, arr[0]); + } + return total; +} +function x09(): number { + let total: number = 0; + for (let i = 0; i < 300; i++) { + const arr: N[] = [mk(i)]; const b2 = arr; const f = (p: N) => { b2.pop(); let t: number = 0; churn(); t += p.x + (p.s == "n" + p.x ? 0 : 1000000); return t; }; total += f(arr[0]); + } + return total; +} +function x10(): number { + let total: number = 0; + for (let i = 0; i < 300; i++) { + const arr: N[] = [mk(i)]; const f = (p: N) => { arr.shift(); let t: number = 0; churn(); t += p.x + (p.s == "n" + p.x ? 0 : 1000000); return t; }; total += f(arr[0]); + } + return total; +} +function x11(): number { + let total: number = 0; + for (let i = 0; i < 300; i++) { + const arr: N[] = [mk(i), mk(1)]; const f = (p: N) => { arr.splice(0, 1); let t: number = 0; churn(); t += p.x + (p.s == "n" + p.x ? 0 : 1000000); return t; }; total += f(arr[0]); + } + return total; +} +function x12(): number { + let total: number = 0; + for (let i = 0; i < 300; i++) { + let arr: N[] = [mk(i)]; const f = (p: N) => { arr = [mk(3)]; let t: number = 0; churn(); t += p.x + (p.s == "n" + p.x ? 0 : 1000000); return t; }; total += f(arr[0]); + } + return total; +} +function x13(): number { + let total: number = 0; + for (let i = 0; i < 300; i++) { + GA[0] = mk(i); total += gaw(GA[0]); + } + return total; +} +function x14(): number { + let total: number = 0; + for (let i = 0; i < 300; i++) { + GA[0] = mk(i); total += gaw2(GA[0]); + } + return total; +} +function x15(): number { + let total: number = 0; + for (let i = 0; i < 300; i++) { + const h = new H(); h.o = mk(i); const w = () => { h.o = mk(i + 2); }; const f = (p: N) => { w(); let t: number = 0; churn(); t += p.x + (p.s == "n" + p.x ? 0 : 1000000); return t; }; total += f(h.o); + } + return total; +} +function x16(): number { + let total: number = 0; + for (let i = 0; i < 300; i++) { + const arr: N[] = [mk(i)]; total += cw(() => { arr[0] = mk(4); }, arr[0]); + } + return total; +} +function x17(): number { + let total: number = 0; + for (let i = 0; i < 300; i++) { + const h = new H(); h.o = mk(i); total += pw(h); + } + return total; +} +function x18(): number { + let total: number = 0; + for (let i = 0; i < 300; i++) { + const h = new H(); h.o = mk(i); const arrh: H[] = [h]; const f = (p: N) => { arrh[0].o = mk(3); let t: number = 0; churn(); t += p.x + (p.s == "n" + p.x ? 0 : 1000000); return t; }; total += f(h.o); + } + return total; +} +function x19(): number { + let total: number = 0; + for (let i = 0; i < 300; i++) { + const h = new H(); h.o = mk(i); const arrh: H[] = [h]; const f = (p: N) => { arrh[0].o = mk(3); let t: number = 0; churn(); t += p.x + (p.s == "n" + p.x ? 0 : 1000000); return t; }; total += f(arrh[0].o); + } + return total; +} +function x20(): number { + let total: number = 0; + for (let i = 0; i < 300; i++) { + const arr: N[] = [mk(i)]; const f = ([p]: N[]) => { arr[0] = mk(i + 1); let t: number = 0; churn(); t += p.x + (p.s == "n" + p.x ? 0 : 1000000); return t; }; total += f(arr); + } + return total; +} +function x21(): number { + let total: number = 0; + for (let i = 0; i < 300; i++) { + const h = new H(); h.o = mk(i); const f = ({ o: p }: H) => { h.o = mk(i + 1); let t: number = 0; churn(); t += p.x + (p.s == "n" + p.x ? 0 : 1000000); return t; }; total += f(h); + } + return total; +} +function main() { + G = new H(); + GA.length = 0; + GA.push(mk(0)); + const totals: number[] = []; + totals.push(x01()); + totals.push(x02()); + totals.push(x03()); + totals.push(x04()); + totals.push(x05()); + totals.push(x06()); + totals.push(x07()); + totals.push(x08()); + totals.push(x09()); + totals.push(x10()); + totals.push(x11()); + totals.push(x12()); + totals.push(x13()); + totals.push(x14()); + totals.push(x15()); + totals.push(x16()); + totals.push(x17()); + totals.push(x18()); + totals.push(x19()); + totals.push(x20()); + totals.push(x21()); + let sum: number = 0; + for (const t of totals) { + sum += t; + } + + print(sum); + assert(sum == 941850, "total"); + print("done."); +} From 4fb0e60dd20a5a127deb5ba92c8ae595b3ee039c Mon Sep 17 00:00:00 2001 From: ASDAlexander77 Date: Tue, 24 Nov 2026 22:01:00 +0000 Subject: [PATCH 17/18] -mm=rc: `a.length = n` and `delete` count as writes for the argument hold Re-review I1 of a2c6ac0d: ts.SetLengthOf (`a.length = n`) gives back the elements it drops but was not an element write in writtenKinds, so `f4(arr[0], al[0])` with `al = [arr]` and `f4` doing `a.length = 0` still read freed memory (rc 3751995, gc 4498500). It is "E" now, beside pop/shift/splice; ts.Delete frees what it deletes with every place in it and is "*". Test 00rc_argument_place_set_length (gc/rc/none; faults under the guard-page heap with the previous binary) and its IR test; the repro is in 00rc_argument_place_aliased too. m1: a comment that a bodiless callee counts as writing nothing because the library's mutating array methods are generic, their bodies analysed here. Co-Authored-By: Claude Opus 5.5 --- .../TypeScript/OwnedReturnConsumptionPass.cpp | 13 +++++- tslang/test/tester/CMakeLists.txt | 12 +++++ .../tests/00rc_argument_place_aliased.ts | 12 ++++- .../tests/00rc_argument_place_set_length.ts | 45 +++++++++++++++++++ 4 files changed, 80 insertions(+), 2 deletions(-) create mode 100644 tslang/test/tester/tests/00rc_argument_place_set_length.ts diff --git a/tslang/lib/TypeScript/OwnedReturnConsumptionPass.cpp b/tslang/lib/TypeScript/OwnedReturnConsumptionPass.cpp index 05548e339..412c37b0d 100644 --- a/tslang/lib/TypeScript/OwnedReturnConsumptionPass.cpp +++ b/tslang/lib/TypeScript/OwnedReturnConsumptionPass.cpp @@ -1510,11 +1510,18 @@ class OwnedReturnConsumptionPass module.walk([&](mlir_ts::FuncOp funcOp) { auto name = funcOp.getSymName(); funcOp.walk([&](mlir::Operation *op) { - if (mlir::isa(op)) + // (`a.length = n` too: a shorter array gives back the elements it drops) + if (mlir::isa(op)) { writtenKinds[name].insert("E"); } + // `delete`: what it frees takes every place in it along + if (mlir::isa(op)) + { + writtenKinds[name].insert("*"); + } + if (auto storeOp = mlir::dyn_cast(op)) { auto reference = storeOp.getReference(); @@ -1689,6 +1696,10 @@ class OwnedReturnConsumptionPass const llvm::StringSet<> *kinds = &moduleKinds; if (!callee.empty() && !assignsAny.contains(callee)) { + // A callee with no body here writes nothing - as for the globals (assigns). That holds because + // the default library's mutating array methods are generic: instantiated in this module, their + // bodies are walked like any function here. A non-generic library function that wrote into an + // array or an object it is given would be missed. auto it = writtenKinds.find(callee); if (it == writtenKinds.end()) { diff --git a/tslang/test/tester/CMakeLists.txt b/tslang/test/tester/CMakeLists.txt index 50c413394..3848d87d6 100644 --- a/tslang/test/tester/CMakeLists.txt +++ b/tslang/test/tester/CMakeLists.txt @@ -5789,6 +5789,18 @@ add_test(NAME test-rc-argument-place-aliased-ir set_tests_properties(test-rc-argument-place-aliased-ir PROPERTIES PASS_REGULAR_EXPRESSION "identifier = @gw2}>[^\n]*\n[^\n]*\"ts[.]PropertyRef\"[^\n]*\n[^\n]*\"ts[.]Load\"[^\n]*\n *\"ts[.]Retain\"" FAIL_REGULAR_EXPRESSION "error:|Stack dump") +# ...and an argument read out of an array a callee shortens through another name (`a.length = 0`): an element write. +# IR: the element read is held. +foreach(arg_set_length_mm gc rc none) + tslang_add_test(NAME test-jit-${arg_set_length_mm}-rc-argument-place-set-length COMMAND test-runner -jit -mm=${arg_set_length_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00rc_argument_place_set_length.ts") + tslang_add_test(NAME test-compile-${arg_set_length_mm}-rc-argument-place-set-length COMMAND test-runner -mm=${arg_set_length_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00rc_argument_place_set_length.ts") +endforeach() +add_test(NAME test-rc-argument-place-set-length-ir + COMMAND $ --emit=mlir --no-default-lib -mm=rc + "${PROJECT_SOURCE_DIR}/test/tester/tests/00rc_argument_place_set_length.ts") +set_tests_properties(test-rc-argument-place-set-length-ir + PROPERTIES PASS_REGULAR_EXPRESSION "\"ts[.]ElementRef\"[^\n]*\n *%[0-9]+ = \"ts[.]Load\"[^\n]*-> !ts[.]class<@N[^\n]*\n *\"ts[.]Retain\"[(]%[0-9]+[)] : [(]!ts[.]class<@N" + FAIL_REGULAR_EXPRESSION "error:|Stack dump") # USER RULING 11-24: an element past the end of an array value, without a default, is undefined, as node has it. A # name bound to an element of a reference type (`const [a, b] = [mk(5)] as N[]`, `(N | null)[]`, nested, for-of, a # parameter) is `T | undefined` (it read null); number[]/string[] keep their type's default. The assignment form gives diff --git a/tslang/test/tester/tests/00rc_argument_place_aliased.ts b/tslang/test/tester/tests/00rc_argument_place_aliased.ts index 0fe10d730..319311eca 100644 --- a/tslang/test/tester/tests/00rc_argument_place_aliased.ts +++ b/tslang/test/tester/tests/00rc_argument_place_aliased.ts @@ -196,6 +196,15 @@ function x21(): number { } return total; } +// an array put into another, given with it to a callee that shortens it (`a.length = 0` drops the element) +function f4(p: N, a: N[]): number { a.length = 0; let t: number = 0; churn(); t += p.x + (p.s == "n" + p.x ? 0 : 1000000); return t; } +function z04(): number { + let total: number = 0; + for (let i = 0; i < 300; i++) { + const arr: N[] = [mk(i)]; const al = [arr]; total += f4(arr[0], al[0]); + } + return total; +} function main() { G = new H(); GA.length = 0; @@ -222,12 +231,13 @@ function main() { totals.push(x19()); totals.push(x20()); totals.push(x21()); + totals.push(z04()); let sum: number = 0; for (const t of totals) { sum += t; } print(sum); - assert(sum == 941850, "total"); + assert(sum == 986700, "total"); print("done."); } diff --git a/tslang/test/tester/tests/00rc_argument_place_set_length.ts b/tslang/test/tester/tests/00rc_argument_place_set_length.ts new file mode 100644 index 000000000..20edf2330 --- /dev/null +++ b/tslang/test/tester/tests/00rc_argument_place_set_length.ts @@ -0,0 +1,45 @@ +// -mm=rc: an argument read out of an array (`f4(arr[0], al[0])`, `al = [arr]`) given to a callee that shortens that +// array through its other name (`a.length = 0` gives back the element it drops) is held by the caller: `a.length = n` +// is an element write (writtenKinds) as `pop`, `shift` and `splice` are. rc read freed memory (3751995 against gc's +// 4498500). Alone in its module, as 00rc_argument_place_aliased's copy of it is held there for another reason. +class N { + x: number; + s: string; + constructor(x: number) { + this.x = x; + this.s = "n" + x; + } +} + +@noinline function mk(i: number): N { + return new N(i); +} + +@noinline function ms(i: number): string { + return "s" + i; +} + +@noinline function take(o: N | null): number { + return o ? o.x + o.s.length : 0; +} + +@noinline function takes(s: string | null): number { + return s ? s.length : 0; +} + +function churn() { + const junk: N[] = []; + for (let i = 0; i < 16; i++) { + junk.push(new N(i)); + } +} +function f4(p: N, a: N[]): number { a.length = 0; let t: number = 0; churn(); t += p.x + (p.s == "n" + p.x ? 0 : 1000000); return t; } +function main() { + let total: number = 0; + for (let i = 0; i < 300; i++) { + const arr: N[] = [mk(i)]; const al = [arr]; total += f4(arr[0], al[0]); + } + print(total); + assert(total == 44850, "total"); + print("done."); +} From 8956cc9aa301aef0a05d8067bbcc098d19bda652 Mon Sep 17 00:00:00 2001 From: ASDAlexander77 Date: Tue, 24 Nov 2026 22:49:15 +0000 Subject: [PATCH 18/18] -mm=own: an empty literal given to a keeping callee is moved, not also given back Fixes the DefaultLib worker_objects failure on wasm32/wasm64 (PR #1027 CI): 3fc0e02a marked the empty constant array cast to an array (`[]`) given to a call an owned result, which the inference gives back after the call - also after a callee that keeps it: `new Order(-1, [])` stores it in a field, so the object freed it again (a free of a freed block, under the guard-page heap natively too). The cast is now replaced by the new empty array it is (ts.NewEmptyArray), which the inference moves into a keeping callee and gives back after one that does not (`ln([])` stays leak-free). Test own_empty_literal_kept_arg (gc/rc/own; faults under the guard-page heap with the previous binary). Co-Authored-By: Claude Opus 5.5 --- .../TypeScript/OwnedReturnConsumptionPass.cpp | 30 +++++++++++++++--- tslang/test/tester/CMakeLists.txt | 7 +++++ .../tester/own/own_empty_literal_kept_arg.ts | 31 +++++++++++++++++++ 3 files changed, 64 insertions(+), 4 deletions(-) create mode 100644 tslang/test/tester/own/own_empty_literal_kept_arg.ts diff --git a/tslang/lib/TypeScript/OwnedReturnConsumptionPass.cpp b/tslang/lib/TypeScript/OwnedReturnConsumptionPass.cpp index 412c37b0d..455625b90 100644 --- a/tslang/lib/TypeScript/OwnedReturnConsumptionPass.cpp +++ b/tslang/lib/TypeScript/OwnedReturnConsumptionPass.cpp @@ -465,11 +465,11 @@ class OwnedReturnConsumptionPass static bool holdsOnlyMovedInElements(MLIRTypeHelper &mth, mlir::Operation *op, bool givenToCall) { - // `f([])`: the empty constant array, copied to the heap where it is cast to an array - it holds nothing - auto castOp = mlir::dyn_cast_or_null(op); - if (auto constArrayType = castOp ? mlir::dyn_cast(castOp.getIn().getType()) : mlir_ts::ConstArrayType()) + // `f([])`: an empty array holds nothing (the empty constant array cast to an array is made one first, + // ownNewArrayArguments) + if (mlir::isa_and_nonnull(op)) { - return constArrayType.getSize() == 0; + return true; } auto arrayOp = mlir::dyn_cast_or_null(op); @@ -681,6 +681,28 @@ class OwnedReturnConsumptionPass } auto *definingOp = argument.getDefiningOp(); + + // `f([])`: the empty constant array cast to an array - a copy made on the heap there - is the new empty + // array it is (ts.NewEmptyArray), which the inference moves into a callee that keeps it (`new + // Order(-1, [])`, the constructor storing it) and gives back after one that does not (`ln([])`, which + // leaked it). Marked owned as the cast it was, it was given back after a keeping callee as well, which + // then freed it again (DefaultLib worker_objects under -mm=own on wasm: "free" of a freed block) + if (auto castOp = mlir::dyn_cast_or_null(definingOp); + castOp && !castOp->hasAttr(OWNED_RESULT_ATTR_NAME) && mlir::isa(argument.getType()) && + arrayMadeFor(argument, op, false)) + { + auto constArrayType = mlir::dyn_cast(castOp.getIn().getType()); + if (constArrayType && constArrayType.getSize() == 0) + { + mlir::OpBuilder builder(castOp); + auto emptyOp = builder.create(castOp->getLoc(), argument.getType()); + castOp->getResult(0).replaceAllUsesWith(emptyOp.getResult()); + castOp->erase(); + argument = emptyOp.getResult(); + definingOp = emptyOp; + } + } + if (!definingOp || !mlir::isa(argument.getType()) || !seen.insert(argument).second || definingOp->hasAttr(OWNED_RESULT_ATTR_NAME) || !ownsWhatItHolds(mth, definingOp, /*givenToCall=*/true) || !(arrayMadeFor(argument, op, false) || isConvertedArrayFor(argument, op))) diff --git a/tslang/test/tester/CMakeLists.txt b/tslang/test/tester/CMakeLists.txt index 3848d87d6..66fa2bc9e 100644 --- a/tslang/test/tester/CMakeLists.txt +++ b/tslang/test/tester/CMakeLists.txt @@ -5732,6 +5732,13 @@ add_test(NAME test-own-literal-argument-no-values-ir set_tests_properties(test-own-literal-argument-no-values-ir PROPERTIES PASS_REGULAR_EXPRESSION "\"ts[.]CreateArray\"[(]%[0-9]+[)] {__owned_result} : [(]!ts[.]optional