From 48daae3774297d72a9971d2a896482f618848851 Mon Sep 17 00:00:00 2001 From: ASDAlexander77 Date: Tue, 24 Nov 2026 12:21:31 +0000 Subject: [PATCH 1/8] Array destructuring applies an element's default where the element is missing `const [a = mk(1), b = mk(2)] = [mk(i)]` crashed the compiler in every memory model (also a typed tuple, a nested pattern, a for...of pattern, a parameter pattern), and `const [a = 1, b = 2] = [5]` gave b the default of its type (0; a string null) instead of 2: array binding elements ignored their defaults - an element past the end of a literal or tuple was undefined, which the compiler then read as an object. The default is now the element's value past the end of a literal, tuple or constant array, in the bounds test's else branch for an array (the element then of both types when the default is of another), and where the element read is undefined or optional; as in TypeScript. An element a literal is known to have (also an inner literal read out of an outer one) is read without a bounds test, so its default never applies there. An element past the end without a default stays undefined, as #964 made it (tsc reports TS2493 for a tuple there). IR changes in every model on two existing tests, both this shape: tests/00destructuring_redeclare_defaults.ts (`var [x, , y = 5] = [1, 2]`: y is now 5, the assert was against the second declaration) and own/rc_destructuring_literal.ts (in-bounds literal elements with defaults: read directly). Co-Authored-By: Claude Opus 5.5 --- tslang/lib/TypeScript/MLIRGenImpl.h | 3 +- tslang/lib/TypeScript/MLIRGenVariables.cpp | 138 +++++++++++++++++- tslang/test/tester/CMakeLists.txt | 11 ++ .../tests/00destructuring_default_past_end.ts | 39 +++++ ...0destructuring_default_past_end_objects.ts | 48 ++++++ 5 files changed, 231 insertions(+), 8 deletions(-) create mode 100644 tslang/test/tester/tests/00destructuring_default_past_end.ts create mode 100644 tslang/test/tester/tests/00destructuring_default_past_end_objects.ts diff --git a/tslang/lib/TypeScript/MLIRGenImpl.h b/tslang/lib/TypeScript/MLIRGenImpl.h index d5c9ab1d7..104aaebbe 100644 --- a/tslang/lib/TypeScript/MLIRGenImpl.h +++ b/tslang/lib/TypeScript/MLIRGenImpl.h @@ -3507,7 +3507,8 @@ class MLIRGenImpl // TODO: to support '...' u need to use 'processOperandSpreadElement' and instead of "index" param use "next" logic ValueOrLogicalResult processDeclarationArrayBindingPatternSubPath( mlir::Location location, int index, mlir::Type type, mlir::Value init, - bool isDotDotDot, bool isIterator, bool isArrayLike, mlir::Value arrayLikeLengthValue, mlir::Type arrayLikeElementType, const GenContext &genContext); + bool isDotDotDot, bool isIterator, bool isArrayLike, mlir::Value arrayLikeLengthValue, mlir::Type arrayLikeElementType, + Expression defaultValue, const GenContext &genContext); mlir::LogicalResult processDeclarationArrayBindingPattern(mlir::Location location, ArrayBindingPattern arrayBindingPattern, VariableClass varClass, diff --git a/tslang/lib/TypeScript/MLIRGenVariables.cpp b/tslang/lib/TypeScript/MLIRGenVariables.cpp index b41f2d83a..bae717fbb 100644 --- a/tslang/lib/TypeScript/MLIRGenVariables.cpp +++ b/tslang/lib/TypeScript/MLIRGenVariables.cpp @@ -507,8 +507,35 @@ namespace mlirgen ValueOrLogicalResult MLIRGenImpl::processDeclarationArrayBindingPatternSubPath( mlir::Location location, int index, mlir::Type type, mlir::Value init, - bool isDotDotDot, bool isIterator, bool isArrayLike, mlir::Value arrayLikeLengthValue, mlir::Type arrayLikeElementType, const GenContext &genContext) + bool isDotDotDot, bool isIterator, bool isArrayLike, mlir::Value arrayLikeLengthValue, mlir::Type arrayLikeElementType, + Expression defaultValue, const GenContext &genContext) { + // An element's default (`const [a = mk(1), b = mk(2)] = [mk(i)]`) is its value where the element is missing - past + // the end of the source, or undefined there - as in TypeScript. It was not applied: an element past the end of a + // literal was undefined (the compiler crashed reading it) or the default of its type (`[a = 1, b = 2] = [5]` gave + // b 0). `castTo`: the element type the value must have, where the other way gives one of that type. + auto makeDefault = [&](mlir::Type castTo) -> mlir::Value { + auto result = mlirGen(defaultValue, genContext); + if (result.failed_or_no_value()) + { + return mlir::Value(); + } + + auto value = V(result); + if (castTo && value.getType() != castTo) + { + auto castResult = cast(location, castTo, value, genContext); + if (castResult.failed_or_no_value()) + { + return mlir::Value(); + } + + value = V(castResult); + } + + return value; + }; + MLIRPropertyAccessCodeLogic cl(compileOptions, builder, location, init, builder.getI32IntegerAttr(index)); mlir::Value subInit = mlir::TypeSwitch(type) @@ -545,7 +572,7 @@ namespace mlirgen // as the element of an array is; read, it was no value and the statement failed with nothing said if (index >= (int)constTupleType.size()) { - return V(builder.create(location, getUndefinedType())); + return defaultValue ? makeDefault(mlir::Type()) : V(builder.create(location, getUndefinedType())); } return cl.Tuple(constTupleType, true); @@ -583,7 +610,7 @@ namespace mlirgen // as the element of an array is; read, it was no value and the statement failed with nothing said if (index >= (int)tupleType.size()) { - return V(builder.create(location, getUndefinedType())); + return defaultValue ? makeDefault(mlir::Type()) : V(builder.create(location, getUndefinedType())); } return cl.Tuple(tupleType, true); @@ -605,7 +632,8 @@ namespace mlirgen // past the end: the default of the element type, null for a reference (see below) if (static_cast(index) >= constArrayType.getSize()) { - return V(builder.create(location, constArrayType.getElementType())); + return defaultValue ? makeDefault(mlir::Type()) + : V(builder.create(location, constArrayType.getElementType())); } // TODO: unify it with ElementAccess @@ -632,6 +660,72 @@ namespace mlirgen auto inBoundsValue = V(builder.create(location, getBooleanType(), builder.getI32IntegerAttr((int)SyntaxKind::GreaterThanToken), lengthValue, indexValue)); + // (a literal that has the element - `[[k = mk(1)] = []] = [[mk(i)]]` - always gives it: the default + // never applies, as for a constant array) + // (unless the element may be undefined: `[u = 3] = [undefined]`) + auto elementMayBeUndefined = [&](mlir::Type elementType) { + if (isa(elementType)) + { + return true; + } + + auto unionType = dyn_cast(elementType); + return unionType && llvm::any_of(unionType.getTypes(), [](mlir::Type type) { + return isa(type); + }); + }; + // (also an inner literal read out of an outer one: `[[b = mk(1)] = [mk(2)]] = [[mk(i)]]`) + auto literalOf = [](mlir::Value value) { + while (auto loadOp = value.getDefiningOp()) + { + auto elementRefOp = loadOp.getReference().getDefiningOp(); + auto outer = elementRefOp ? elementRefOp->getOperand(0).getDefiningOp() + : mlir_ts::CreateArrayOp(); + auto indexOp = elementRefOp ? elementRefOp->getOperand(1).getDefiningOp() + : mlir_ts::ConstantOp(); + auto indexAttr = indexOp ? dyn_cast(indexOp.getValue()) : mlir::IntegerAttr(); + if (!outer || !indexAttr || indexAttr.getInt() < 0 || + indexAttr.getInt() >= (int64_t)outer->getNumOperands()) + { + break; + } + + value = outer->getOperand(indexAttr.getInt()); + } + + return value.getDefiningOp(); + }; + if (auto createArrayOp = literalOf(init); + defaultValue && createArrayOp && static_cast(index) < createArrayOp->getNumOperands() && + !elementMayBeUndefined(arrayType.getElementType())) + { + // the element, read as out of a constant array: no bounds test (an inner pattern reads it on) + auto constIndex = builder.create(location, builder.getI32Type(), + builder.getI32IntegerAttr(index)); + auto elemRef = builder.create( + location, mlir_ts::RefType::get(arrayType.getElementType()), init, constIndex); + return V(builder.create(location, arrayType.getElementType(), elemRef)); + } + + // (with a default of another type, `const [a, b = "q"] = numbers`, the element is of both) + mlir::Type valueType = arrayType.getElementType(); + if (defaultValue) + { + if (auto defaultType = evaluate(defaultValue, genContext)) + { + defaultType = mth.wideStorageType(defaultType); + llvm::StringMap> typeParamsWithArgs; + // (an array default of an array element - `[[k = mk(1)] = []]` - is of the element's type) + auto bothArrays = isa(defaultType) && + isa(valueType); + if (defaultType != valueType && !bothArrays && + mth.extendsType(location, defaultType, valueType, typeParamsWithArgs) != ExtendsResult::True) + { + valueType = getUnionType(location, valueType, defaultType); + } + } + } + auto result = conditionalValue(location, inBoundsValue, [&]() { // TODO: unify it with ElementAccess @@ -639,10 +733,23 @@ namespace mlirgen builder.getI32IntegerAttr(index)); auto elemRef = builder.create( location, mlir_ts::RefType::get(arrayType.getElementType()), init, constIndex); - return ValueOrLogicalResult( - V(builder.create(location, arrayType.getElementType(), elemRef))); + mlir::Value element = V(builder.create(location, arrayType.getElementType(), elemRef)); + if (element.getType() != valueType) + { + auto castResult = cast(location, valueType, element, genContext); + EXIT_IF_FAILED_OR_NO_VALUE(castResult) + element = V(castResult); + } + + return ValueOrLogicalResult(element); }, [&](mlir::Type elementType) { + if (defaultValue) + { + auto value = makeDefault(elementType); + return value ? ValueOrLogicalResult(value) : ValueOrLogicalResult(mlir::failure()); + } + return ValueOrLogicalResult(V(builder.create(location, elementType))); }); return result.failed_or_no_value() ? mlir::Value() : V(result); @@ -699,6 +806,22 @@ namespace mlirgen return mlir::failure(); } + // ...and where the element read is undefined, or may be (`[a = 1] = [undefined]`, an optional element) + if (defaultValue && !isDotDotDot) + { + if (isa(subInit.getType())) + { + return makeDefault(mlir::Type()); + } + + if (auto optionalType = dyn_cast(subInit.getType())) + { + auto result = optionalValueOrDefault(location, optionalType.getElementType(), subInit, defaultValue, genContext); + EXIT_IF_FAILED_OR_NO_VALUE(result) + return V(result); + } + } + return subInit; } @@ -792,7 +915,8 @@ namespace mlirgen auto subValueFunc = [&](mlir::Location location, const GenContext &genContext) { auto result = processDeclarationArrayBindingPatternSubPath( - location, index, type, init, !!arrayBindingElement->dotDotDotToken, isIterator, isSourceArrayLike, arrayLikeLengthValue, arrayLikeElementType, genContext); + location, index, type, init, !!arrayBindingElement->dotDotDotToken, isIterator, isSourceArrayLike, arrayLikeLengthValue, arrayLikeElementType, + arrayBindingElement->initializer, genContext); if (result.failed_or_no_value()) { return std::make_tuple(mlir::Type(), mlir::Value(), TypeProvided::No); diff --git a/tslang/test/tester/CMakeLists.txt b/tslang/test/tester/CMakeLists.txt index 31a55db36..429a76adf 100644 --- a/tslang/test/tester/CMakeLists.txt +++ b/tslang/test/tester/CMakeLists.txt @@ -5586,6 +5586,17 @@ foreach(getter_mm rc gc none) tslang_add_test(NAME test-jit-${getter_mm}-getter-temporary COMMAND test-runner -jit -mm=${getter_mm} "${PROJECT_SOURCE_DIR}/test/tester/own/rc_getter_temporary.ts") tslang_add_test(NAME test-compile-${getter_mm}-getter-temporary COMMAND test-runner -mm=${getter_mm} "${PROJECT_SOURCE_DIR}/test/tester/own/rc_getter_temporary.ts") endforeach() +# Array destructuring past the end of its source applies the element's default (`const [a = 1, b = 2] = [5]`, b was +# 0; with objects the compiler crashed): numbers and strings under every model, objects under gc and rc (own refuses a +# borrow of the literal's element beside a new default). +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() +foreach(past_end_mm gc rc) + tslang_add_test(NAME test-jit-${past_end_mm}-destructuring-default-past-end-objects COMMAND test-runner -jit -mm=${past_end_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00destructuring_default_past_end_objects.ts") + tslang_add_test(NAME test-compile-${past_end_mm}-destructuring-default-past-end-objects COMMAND test-runner -mm=${past_end_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00destructuring_default_past_end_objects.ts") +endforeach() # A conditional's branch yielding an element of an array literal nested in another (`c ? [[mk(i)]][0][0] : # null`), a field read out of an element (`c ? [{ v: mk(i) }][0].v : null`), also past a cast that only narrows # (`!`, `as N`, ``), an optional chain out of a literal (`c ? [[mk(i)]][0]?.[0] : null`), or an element of a diff --git a/tslang/test/tester/tests/00destructuring_default_past_end.ts b/tslang/test/tester/tests/00destructuring_default_past_end.ts new file mode 100644 index 000000000..645ab13e4 --- /dev/null +++ b/tslang/test/tester/tests/00destructuring_default_past_end.ts @@ -0,0 +1,39 @@ +// Array destructuring past the end of its source: an element's default is its value where the element is missing +// (`const [a = 1, b = 2] = [5]`: b is 2, as in TypeScript). It was not applied: the default of the element type was +// used (b was 0, a string null), and with objects (`const [a = mk(1), b = mk(2)] = [mk(5)]`, a typed tuple, a nested +// pattern, a for...of pattern) the compiler crashed. Numbers, strings, a typed array, an undefined element, a +// parameter pattern of numbers; every memory model. (Objects: 00destructuring_default_past_end_objects.ts.) +function sum([a = 1, b = 2]: number[]): number { + return a + b; +} + +function main() { + let total: number = 0; + for (let i = 0; i < 100; i++) { + const [a = 1, b = 2] = [i]; + total += a + b; + + const [s = "x", t = "y"] = ["s" + i]; + total += s.length + t.length; + + const xs: number[] = []; + if (i % 2 == 0) { + xs.push(i); + } + + const [p = 1, q = 2] = xs; + total += p + q; + + const [u = 3] = [undefined]; + total += u; + + const [v, w = "q"] = [i]; + total += v + w.length; + + total += sum([i]) + sum([]); + } + + print(total); + assert(total == 19040, "total"); + print("done."); +} diff --git a/tslang/test/tester/tests/00destructuring_default_past_end_objects.ts b/tslang/test/tester/tests/00destructuring_default_past_end_objects.ts new file mode 100644 index 000000000..088035337 --- /dev/null +++ b/tslang/test/tester/tests/00destructuring_default_past_end_objects.ts @@ -0,0 +1,48 @@ +// Array destructuring past the end of its source, with objects: an element's default is its value where the element +// is missing (`const [a = mk(1), b = mk(2)] = [mk(i)]`: b is mk(2)). The compiler crashed on these (the element read +// past the end of the literal was an undefined value read as an object): a literal, a typed tuple, a nested pattern, +// a for...of pattern, a parameter pattern, an assignment. Under gc and rc (own refuses a borrow of the literal's +// element beside a new default). +class N { + x: number; + constructor(x: number) { + this.x = x; + } +} + +function mk(i: number): N { + return new N(i); +} + +function pick([a = mk(1), b = mk(2)]: N[]): number { + return a.x + b.x; +} + +function main() { + let total: number = 0; + for (let i = 0; i < 100; i++) { + const [a = mk(1), b = mk(2)] = [mk(i)]; + total += a.x + b.x; + + const t: [N] = [mk(i)]; + const [e, f = mk(3)] = t; + total += e.x + f.x; + + const [[g, h = mk(4)]] = [[mk(i)]]; + total += g.x + h.x; + + for (const [p, q = mk(10)] of [[mk(i)]]) { + total += p.x + q.x; + } + + let k: N, m: N; + [k, m = mk(8)] = [mk(i)]; + total += k.x + m.x; + + total += pick([mk(i)]) + pick([]); + } + + print(total); + assert(total == 32900, "total"); + print("done."); +} From d97b8e57a4fb02f2ce1651eccbb6ac5e4cf0e70e Mon Sep 17 00:00:00 2001 From: ASDAlexander77 Date: Tue, 24 Nov 2026 12:54:48 +0000 Subject: [PATCH 2/8] -mm=rc/own: a pattern default that is a local gives the local back `const e = mk(i + 1); const { p = e } = r`, from a record literal, and the assignment form `({ p: p2 = e ?? mk(1) } = ...)` leaked `e` every evaluation under rc (main too; own too for a named record): the default region yields the local as the value-or-default's result, and handedOnByConditional knew only an IfOp branch handing a value on, so the local's release took the default's ts.Result for an escape. A ts.OptValueOrDefault's default is now handed on the same way, under rc and own (set per module; gc and none keep their IR). Co-Authored-By: Claude Opus 5.5 --- .../TypeScript/OwnedReturnConsumptionPass.cpp | 14 ++++- tslang/test/tester/CMakeLists.txt | 11 ++++ .../own/rc_destructuring_default_local.ts | 55 +++++++++++++++++++ .../rc_destructuring_default_local_literal.ts | 52 ++++++++++++++++++ 4 files changed, 129 insertions(+), 3 deletions(-) create mode 100644 tslang/test/tester/own/rc_destructuring_default_local.ts create mode 100644 tslang/test/tester/own/rc_destructuring_default_local_literal.ts diff --git a/tslang/lib/TypeScript/OwnedReturnConsumptionPass.cpp b/tslang/lib/TypeScript/OwnedReturnConsumptionPass.cpp index 75baafcc1..84c3d27e1 100644 --- a/tslang/lib/TypeScript/OwnedReturnConsumptionPass.cpp +++ b/tslang/lib/TypeScript/OwnedReturnConsumptionPass.cpp @@ -67,6 +67,7 @@ class OwnedReturnConsumptionPass { auto module = getOperation(); MLIRTypeHelper mth(module->getContext(), compileOptions); + handsOnThroughDefaults = compileOptions.tracksOwnership(); copyEscapingStringViews(module); @@ -3571,11 +3572,18 @@ class OwnedReturnConsumptionPass // What a branch of a conditional expression hands `value` on as: the result of the `ts.If` whose branch this // `ts.Result` ends, at each position the branch yields `value` in - a conditional may yield more than one value // (holdPastConditional adds the literal its branch holds). None for any other user. + // (under rc and own also the default of a value-or-default - `const { p = e } = r` hands `e` on as the op's result - + // set for the module being run: gc and none keep their IR) + static inline thread_local bool handsOnThroughDefaults = false; + static llvm::SmallVector handedOnByConditional(mlir::Operation *user, mlir::Value value) { llvm::SmallVector handedOn; - auto ifOp = mlir::isa(user) ? mlir::dyn_cast_or_null(user->getParentOp()) : mlir_ts::IfOp(); - if (!ifOp || ifOp.getNumResults() != user->getNumOperands()) + auto *conditional = mlir::isa(user) ? user->getParentOp() : nullptr; + if (!conditional || + !(mlir::isa(conditional) || + (handsOnThroughDefaults && mlir::isa(conditional))) || + conditional->getNumResults() != user->getNumOperands()) { return handedOn; } @@ -3584,7 +3592,7 @@ class OwnedReturnConsumptionPass { if (operand.get() == value) { - handedOn.push_back(ifOp.getResult(operand.getOperandNumber())); + handedOn.push_back(conditional->getResult(operand.getOperandNumber())); } } diff --git a/tslang/test/tester/CMakeLists.txt b/tslang/test/tester/CMakeLists.txt index 429a76adf..1466754ad 100644 --- a/tslang/test/tester/CMakeLists.txt +++ b/tslang/test/tester/CMakeLists.txt @@ -5586,6 +5586,17 @@ foreach(getter_mm rc gc none) tslang_add_test(NAME test-jit-${getter_mm}-getter-temporary COMMAND test-runner -jit -mm=${getter_mm} "${PROJECT_SOURCE_DIR}/test/tester/own/rc_getter_temporary.ts") tslang_add_test(NAME test-compile-${getter_mm}-getter-temporary COMMAND test-runner -mm=${getter_mm} "${PROJECT_SOURCE_DIR}/test/tester/own/rc_getter_temporary.ts") endforeach() +# A pattern's default that is a local (`const e = mk(i + 1); const { p = e } = r`) gives the local back at the end of +# its block under rc and own (it leaked): the default hands it on as the value-or-default's result. A named record, +# a `let`, an array pattern under every model; a record literal source and the assignment form under gc and rc. +foreach(default_local_mm gc rc own) + tslang_add_test(NAME test-jit-${default_local_mm}-destructuring-default-local COMMAND test-runner -jit -mm=${default_local_mm} "${PROJECT_SOURCE_DIR}/test/tester/own/rc_destructuring_default_local.ts") + tslang_add_test(NAME test-compile-${default_local_mm}-destructuring-default-local COMMAND test-runner -mm=${default_local_mm} "${PROJECT_SOURCE_DIR}/test/tester/own/rc_destructuring_default_local.ts") +endforeach() +foreach(default_local_mm gc rc) + tslang_add_test(NAME test-jit-${default_local_mm}-destructuring-default-local-literal COMMAND test-runner -jit -mm=${default_local_mm} "${PROJECT_SOURCE_DIR}/test/tester/own/rc_destructuring_default_local_literal.ts") + tslang_add_test(NAME test-compile-${default_local_mm}-destructuring-default-local-literal COMMAND test-runner -mm=${default_local_mm} "${PROJECT_SOURCE_DIR}/test/tester/own/rc_destructuring_default_local_literal.ts") +endforeach() # Array destructuring past the end of its source applies the element's default (`const [a = 1, b = 2] = [5]`, b was # 0; with objects the compiler crashed): numbers and strings under every model, objects under gc and rc (own refuses a # borrow of the literal's element beside a new default). diff --git a/tslang/test/tester/own/rc_destructuring_default_local.ts b/tslang/test/tester/own/rc_destructuring_default_local.ts new file mode 100644 index 000000000..ef438058d --- /dev/null +++ b/tslang/test/tester/own/rc_destructuring_default_local.ts @@ -0,0 +1,55 @@ +// -mm=rc, -mm=own: a pattern's default that is a local (`const e = mk(i + 1); const { p = e } = r`): the default hands +// the local on as the value-or-default's result, which only a conditional's branch was known to do, so the local's +// release took that for an escape and the local leaked every evaluation (+17.5 MB per 400 runs of this loop's shape, +// main too; own too). The local is now given back at the end of its block. A named record, a `let` local, an array +// pattern; the same program under gc. (A record literal source and the assignment form, which own refuses, are in +// rc_destructuring_default_local_literal.) +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); +} + +interface R { + p?: N; +} + +function churn() { + const junk: N[] = []; + for (let i = 0; i < 16; i++) { + junk.push(new N(i)); + } +} + +function main() { + let total: number = 0; + for (let i = 0; i < 400; i++) { + const c = i % 2 == 0; + const r: R = c ? { p: mk(i) } : {}; + + const e = mk(i + 1); + const { p = e } = r; + total += p.x + p.s.length; + + let f = mk(i + 2); + const { p: q = f } = r; + total += q.x; + + const g = mk(i + 3); + const [a = g] = c ? [mk(i)] : []; + total += a.x; + + churn(); + } + + print(total); + assert(total == 242092, "total"); + print("done."); +} diff --git a/tslang/test/tester/own/rc_destructuring_default_local_literal.ts b/tslang/test/tester/own/rc_destructuring_default_local_literal.ts new file mode 100644 index 000000000..6268bfc2d --- /dev/null +++ b/tslang/test/tester/own/rc_destructuring_default_local_literal.ts @@ -0,0 +1,52 @@ +// -mm=rc: a pattern's default that is a local, from a record literal (`const { p = e } = { p: c ? mk(i) : undefined +// }`) and in the assignment form (`({ p: p2 = e ?? mk(1) } = ...)`, `({ p: p3 = e } = r)`): the local is given back +// at the end of its block (it leaked every evaluation, main too). The same program under gc (own refuses these). +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); +} + +interface R { + p?: N; +} + +function churn() { + const junk: N[] = []; + for (let i = 0; i < 16; i++) { + junk.push(new N(i)); + } +} + +function main() { + let total: number = 0; + for (let i = 0; i < 400; i++) { + const c = i % 2 == 0; + const r: R = c ? { p: mk(i) } : {}; + + const e = mk(i + 1); + const { p = e } = { p: c ? mk(i) : undefined }; + total += p.x + p.s.length; + + let p2: N = mk(0); + ({ p: p2 = e ?? mk(1) } = { p: c ? mk(i) : undefined }); + total += p2.x; + + let p3: N = mk(0); + ({ p: p3 = e } = r); + total += p3.x; + + churn(); + } + + print(total); + assert(total == 241492, "total"); + print("done."); +} From 0cde20d29573eb2bd5947ca9d13fcdf694c32589 Mon Sep 17 00:00:00 2001 From: ASDAlexander77 Date: Tue, 24 Nov 2026 13:16:37 +0000 Subject: [PATCH 3/8] -mm=own: a pattern default that makes a new value is held by a slot of the scope `const { p = mk(1) } = r`, `p = e ?? mk(1)`, `p = [mk(1)][0]`, `p = "q" + i` leaked the new value under own every evaluation that ran the default (main too): the pattern's value borrows the field or the default, and nothing owned the default's value (own does not share rc's settling of ts.OptValueOrDefault). Under own, optionalValueOrDefault now gives the default a slot of the scope (an owned local, empty unless the default runs, released when the scope ends) and the region yields a read of it. Once calls are settled, settleOwnPatternDefaults keeps the store only for a new value - at the region's yield, or in the branch of a conditional there that makes it; the one element of a literal made only to read it is that element - and drops it for a borrowed default (`p = e`), which yields its borrow as before. Own acceptance unchanged (corpus, plain and --own-fallback=count, which compiles these programs identically); rc, gc and none IR unchanged. Co-Authored-By: Claude Opus 5.5 --- tslang/include/TypeScript/Defines.h | 1 + tslang/lib/TypeScript/MLIRGenImpl.h | 27 ++++ .../TypeScript/OwnedReturnConsumptionPass.cpp | 115 ++++++++++++++++++ tslang/test/tester/CMakeLists.txt | 13 ++ .../own/own_pattern_default_new_value.ts | 64 ++++++++++ 5 files changed, 220 insertions(+) create mode 100644 tslang/test/tester/own/own_pattern_default_new_value.ts diff --git a/tslang/include/TypeScript/Defines.h b/tslang/include/TypeScript/Defines.h index 7744952bb..7abfaa675 100644 --- a/tslang/include/TypeScript/Defines.h +++ b/tslang/include/TypeScript/Defines.h @@ -79,6 +79,7 @@ #define OWNED_LOCAL_CONSUMED_ATTR_NAME "__owned_consumed" // -mm=rc: the slot of the frame that owns a parameter's default value while it is taken (processOptionalParam) #define DEFAULT_VALUE_SLOT_ATTR_NAME "__default_value_slot" +#define PATTERN_DEFAULT_SLOT_ATTR_NAME "__pattern_default_slot" // the owning slot that holds the fresh values a `let` borrowing a field is given (TSLANG 66) #define OWN_LET_HOLDER_ATTR_NAME "__own_let_holder" diff --git a/tslang/lib/TypeScript/MLIRGenImpl.h b/tslang/lib/TypeScript/MLIRGenImpl.h index 104aaebbe..4d8c7b575 100644 --- a/tslang/lib/TypeScript/MLIRGenImpl.h +++ b/tslang/lib/TypeScript/MLIRGenImpl.h @@ -4916,6 +4916,25 @@ class MLIRGenImpl ValueOrLogicalResult optionalValueOrDefault(mlir::Location location, mlir::Type dataType, mlir::Value value, Expression defaultExpr, const GenContext &genContext) { + // -mm=own: a default that makes a new value (`const { p = mk(1) } = r`, `"q" + i`) is held by a slot of the scope, + // empty unless the default is taken, given back when the scope ends, as a local is; the value read borrows it, as + // it borrows the field otherwise. Nothing owned the new value: every evaluation that ran the default leaked it. + // A borrowed default (`p = e`) is not stored (settleOwnPatternDefaults). + // (rc settles the op in OwnedReturnConsumptionPass, consumeValueOrDefaultResults.) + mlir::Value defaultSlot; + if (compileOptions.memoryModel == MemoryModelOwn && genContext.ownedVars && mth.ownsHeapMemory(location, dataType)) + { + defaultSlot = builder.create(location, mlir_ts::RefType::get(dataType), mlir::Value(), + builder.getBoolAttr(false), builder.getIndexAttr(0)); + auto empty = builder.create(location, dataType); + builder.create(location, empty, defaultSlot); + auto varOp = defaultSlot.getDefiningOp(); + varOp->setAttr(OWNED_LOCAL_ATTR_NAME, builder.getUnitAttr()); + varOp->setAttr(OWNED_LOCAL_CONSUMED_ATTR_NAME, builder.getUnitAttr()); + varOp->setAttr(PATTERN_DEFAULT_SLOT_ATTR_NAME, builder.getUnitAttr()); + genContext.ownedVars->push_back(defaultSlot); + } + auto optionalValueOrDefaultOp = builder.create( location, dataType, value); @@ -4938,6 +4957,14 @@ class MLIRGenImpl CAST(defaultValue, location, dataType, defaultValue, genContext); } + // (whether the default is a new value is known once calls are settled: OwnedReturnConsumptionPass, + // settleOwnPatternDefaults, keeps the store of one and drops it for a borrowed default) + if (defaultSlot) + { + builder.create(location, defaultValue, defaultSlot); + defaultValue = builder.create(location, dataType, defaultSlot); + } + builder.create(location, defaultValue); builder.setInsertionPointAfter(optionalValueOrDefaultOp); diff --git a/tslang/lib/TypeScript/OwnedReturnConsumptionPass.cpp b/tslang/lib/TypeScript/OwnedReturnConsumptionPass.cpp index 84c3d27e1..1245830c8 100644 --- a/tslang/lib/TypeScript/OwnedReturnConsumptionPass.cpp +++ b/tslang/lib/TypeScript/OwnedReturnConsumptionPass.cpp @@ -307,6 +307,8 @@ class OwnedReturnConsumptionPass ownNewArrayArguments(mth, module); + settleOwnPatternDefaults(module); + consumeConditionalResults(mth, module); claimGlobalInitializers(mth, module); @@ -2820,6 +2822,119 @@ class OwnedReturnConsumptionPass consumeValueOrDefaultResults(mth, module); } + // -mm=own: a pattern's default stores what it yields into a slot of the scope (MLIRGenImpl::optionalValueOrDefault), + // which owns it and gives it back when the scope ends; the pattern's value borrows the slot. Only a new value is the + // slot's to own - a call's result, a new object, a fresh string, as settled here, once calls are marked: it moves in. + // A default that borrows (`p = e`, a field, a literal's element) is not stored: what the region yields is that + // value, as before, and the slot stays empty. + void settleOwnPatternDefaults(mlir::ModuleOp module) + { + if (compileOptions.memoryModel != MemoryModelOwn) + { + return; + } + + llvm::SmallVector stores; + module.walk([&](mlir_ts::StoreOp storeOp) { + auto varOp = storeOp.getReference().getDefiningOp(); + if (varOp && varOp->hasAttr(PATTERN_DEFAULT_SLOT_ATTR_NAME) && + mlir::isa_and_nonnull(storeOp->getParentOp())) + { + stores.push_back(storeOp); + } + }); + + // the new value a region yields, where it is made: at its own `ts.Result`, or in a branch of a conditional + // there (`p = e ?? mk(1)`: only the branch that makes one stores it, the other yields its borrow) + std::function storeNewValue = [&](mlir::Operation *resultOp, unsigned index, + mlir::Value slot) { + auto yielded = resultOp->getOperand(index); + auto slotType = mlir::cast(slot.getType()).getElementType(); + auto produced = yielded; + while (auto castOp = produced.getDefiningOp()) + { + if (!mlir::isa(castOp.getType())) + { + break; + } + + produced = castOp.getIn(); + } + + auto *producer = produced.getDefiningOp(); + if (producer && ::typescript::mayTakeOverReference(produced) && yielded.getType() == slotType) + { + producer->setAttr(OWNED_RESULT_CONSUMED_ATTR_NAME, mlir::UnitAttr::get(&getContext())); + mlir::OpBuilder builder(resultOp); + builder.create(resultOp->getLoc(), yielded, slot); + auto loadOp = builder.create(resultOp->getLoc(), slotType, slot); + resultOp->setOperand(index, loadOp.getResult()); + return; + } + + // (the one element of a literal made there only to read it, `p = [mk(1)][0]`: that element is the value; the + // literal is not made - it held the element and was never given back) + if (auto loadOp = mlir::dyn_cast_or_null(producer); loadOp && produced == yielded) + { + auto elementRefOp = loadOp.getReference().getDefiningOp(); + auto literal = elementRefOp ? elementRefOp->getOperand(0).getDefiningOp() + : mlir_ts::CreateArrayOp(); + if (literal && literal->getNumOperands() == 1 && literal->getParentRegion() == resultOp->getParentRegion() && + literal->getResult(0).hasOneUse() && elementRefOp->getResult(0).hasOneUse() && loadOp->getResult(0).hasOneUse() && + literal->getOperand(0).getType() == yielded.getType() && literal->getOperand(0).getDefiningOp() && + literal->getOperand(0).getDefiningOp()->hasAttr(OWNED_RESULT_ATTR_NAME) && + !literal->getOperand(0).getDefiningOp()->hasAttr(OWNED_RESULT_NAMED_ATTR_NAME)) + { + auto element = literal->getOperand(0); + resultOp->setOperand(index, element); + loadOp->erase(); + elementRefOp->erase(); + literal->erase(); + if (auto *elementProducer = element.getDefiningOp()) + { + elementProducer->removeAttr(OWNED_RESULT_CONSUMED_ATTR_NAME); + } + + storeNewValue(resultOp, index, slot); + return; + } + } + + if (auto ifOp = mlir::dyn_cast_or_null(producer); + ifOp && produced == yielded && resultOp->getParentRegion()->isAncestor(ifOp->getParentRegion())) + { + auto resultIndex = mlir::cast(produced).getResultNumber(); + for (auto ®ion : ifOp->getRegions()) + { + auto innerResult = region.empty() ? nullptr : region.back().getTerminator(); + if (mlir::isa_and_nonnull(innerResult) && innerResult->getNumOperands() > resultIndex) + { + storeNewValue(innerResult, resultIndex, slot); + } + } + } + }; + + for (auto storeOp : stores) + { + // the store MLIRGen made at the region's end, and the read that follows it: put back to what the region + // yields, then stored where a new value is made + auto loadOp = mlir::dyn_cast_or_null(storeOp->getNextNode()); + auto resultOp = loadOp ? mlir::dyn_cast_or_null(loadOp->getNextNode()) : mlir_ts::ResultOp(); + if (!loadOp || loadOp.getReference() != storeOp.getReference() || !resultOp || + resultOp->getNumOperands() != 1 || resultOp->getOperand(0) != loadOp.getResult()) + { + continue; + } + + auto slot = storeOp.getReference(); + resultOp->setOperand(0, storeOp.getValue()); + loadOp->erase(); + storeOp->erase(); + storeNewValue(resultOp, 0, slot); + } + } + // The same disagreement in a default of a destructuring pattern (`const { p = mk(1) } = { p: c ? mk(i) : // undefined }`): `ts.OptValueOrDefault` hands back the value the optional holds - a borrow of the field - or // what its default region makes - a +1 nobody took, so every evaluation that ran the default leaked it. Under rc diff --git a/tslang/test/tester/CMakeLists.txt b/tslang/test/tester/CMakeLists.txt index 1466754ad..8042e5a76 100644 --- a/tslang/test/tester/CMakeLists.txt +++ b/tslang/test/tester/CMakeLists.txt @@ -5586,6 +5586,19 @@ foreach(getter_mm rc gc none) tslang_add_test(NAME test-jit-${getter_mm}-getter-temporary COMMAND test-runner -jit -mm=${getter_mm} "${PROJECT_SOURCE_DIR}/test/tester/own/rc_getter_temporary.ts") tslang_add_test(NAME test-compile-${getter_mm}-getter-temporary COMMAND test-runner -mm=${getter_mm} "${PROJECT_SOURCE_DIR}/test/tester/own/rc_getter_temporary.ts") endforeach() +# -mm=own: a pattern's default that makes a new value (`const { p = mk(1) } = r`, `e ?? mk(1)`, `[mk(1)][0]`, +# `"q" + i`) is held by a slot of the scope and given back when the scope ends (it leaked); the same program under +# rc and gc. IR: the default stores the new value into the slot and yields a read of it (none before). +foreach(pattern_default_mm gc rc own) + tslang_add_test(NAME test-jit-${pattern_default_mm}-own-pattern-default-new-value COMMAND test-runner -jit -mm=${pattern_default_mm} "${PROJECT_SOURCE_DIR}/test/tester/own/own_pattern_default_new_value.ts") + tslang_add_test(NAME test-compile-${pattern_default_mm}-own-pattern-default-new-value COMMAND test-runner -mm=${pattern_default_mm} "${PROJECT_SOURCE_DIR}/test/tester/own/own_pattern_default_new_value.ts") +endforeach() +add_test(NAME test-own-pattern-default-slot + COMMAND $ --emit=mlir --no-default-lib -mm=own + "${PROJECT_SOURCE_DIR}/test/tester/own/own_pattern_default_new_value.ts") +set_tests_properties(test-own-pattern-default-slot + PROPERTIES PASS_REGULAR_EXPRESSION "\"ts[.]Store\"[(]%[0-9]+, %[0-9]+[)] : [(]!ts[.]class<@N[^\n]*\n *%[0-9]+ = \"ts[.]Load\"[(]%[0-9]+[)] : [(]!ts[.]ref Date: Tue, 24 Nov 2026 14:06:16 +0000 Subject: [PATCH 4/8] -mm=own: a parameter default that makes a new value is owned by the frame's slot `function f(p: N = mk(1))`, a method's, a constructor's, an arrow's, a closure's and a default reading another parameter leaked the default under own every call that took it (main too; #1015 fixed rc with a frame slot). processOptionalParam now creates #1015's slot under own too, without its retain: the default is stored and read back, and settleOwnPatternDefaults (now also for a ts.ParamOpt region) keeps the store only for a new value; a borrowed default (a global, another parameter) yields its borrow. A parameter that may be kept - stored, returned, given to a call or a literal (`constructor(public a = new C())`) - is left as before: own keeps it with its default (own_param_default_kept). Own's field-locals rewrite read a parameter's field again where the result is stored, after the slot's release at the return; a release of a default slot now counts as a write of fields there (OwnershipFacts mayWriteField). rc, gc and none IR unchanged; own acceptance unchanged (corpus, plain and with --own-fallback=count). Co-Authored-By: Claude Opus 5.5 --- tslang/lib/TypeScript/MLIRGenImpl.h | 16 +++- .../TypeScript/OwnedReturnConsumptionPass.cpp | 40 +++++++++- tslang/lib/TypeScript/OwnershipFacts.h | 5 +- tslang/test/tester/CMakeLists.txt | 13 ++++ .../tester/own/own_param_default_new_value.ts | 73 +++++++++++++++++++ 5 files changed, 140 insertions(+), 7 deletions(-) create mode 100644 tslang/test/tester/own/own_param_default_new_value.ts diff --git a/tslang/lib/TypeScript/MLIRGenImpl.h b/tslang/lib/TypeScript/MLIRGenImpl.h index 4d8c7b575..d839b51c8 100644 --- a/tslang/lib/TypeScript/MLIRGenImpl.h +++ b/tslang/lib/TypeScript/MLIRGenImpl.h @@ -4979,8 +4979,11 @@ class MLIRGenImpl // printed 0). A function gives back none of its parameters (the caller owns what it passes), so the value is // owned by a slot of the frame, empty unless the default is taken, given back at the function's exit // (mlirGenFunctionBody lists it with the parameters' storage); the parameter borrows it. + // -mm=own the same: the slot owns a new default value, moved in (settleOwnPatternDefaults keeps the store of one + // and drops it for a borrowed default, which the parameter then borrows as before) + auto ownSlot = compileOptions.memoryModel == MemoryModelOwn; mlir::Value defaultSlot; - if (compileOptions.isRefCounted() && mth.ownsHeapMemory(location, dataType)) + if ((compileOptions.isRefCounted() || ownSlot) && mth.ownsHeapMemory(location, dataType)) { defaultSlot = builder.create(location, mlir_ts::RefType::get(dataType), mlir::Value(), builder.getBoolAttr(false), builder.getIndexAttr(0)); @@ -4990,6 +4993,10 @@ class MLIRGenImpl varOp->setAttr(OWNED_LOCAL_ATTR_NAME, builder.getUnitAttr()); varOp->setAttr(OWNED_LOCAL_CONSUMED_ATTR_NAME, builder.getUnitAttr()); varOp->setAttr(DEFAULT_VALUE_SLOT_ATTR_NAME, builder.getUnitAttr()); + if (ownSlot) + { + varOp->setAttr(PATTERN_DEFAULT_SLOT_ATTR_NAME, builder.getUnitAttr()); + } } auto paramOptionalOp = builder.create( @@ -5017,8 +5024,11 @@ class MLIRGenImpl if (defaultSlot) { // as an awaited result's slot takes it (mlirGen(AwaitExpression)): a value that carries a reference - // hands it over, anything else is retained - if (producesOwnedReference(defaultValue)) + // hands it over, anything else is retained (own: settled later, no retain) + if (ownSlot) + { + } + else if (producesOwnedReference(defaultValue)) { consumeOwnedReference(defaultValue); } diff --git a/tslang/lib/TypeScript/OwnedReturnConsumptionPass.cpp b/tslang/lib/TypeScript/OwnedReturnConsumptionPass.cpp index 1245830c8..bad6679ad 100644 --- a/tslang/lib/TypeScript/OwnedReturnConsumptionPass.cpp +++ b/tslang/lib/TypeScript/OwnedReturnConsumptionPass.cpp @@ -2838,7 +2838,7 @@ class OwnedReturnConsumptionPass module.walk([&](mlir_ts::StoreOp storeOp) { auto varOp = storeOp.getReference().getDefiningOp(); if (varOp && varOp->hasAttr(PATTERN_DEFAULT_SLOT_ATTR_NAME) && - mlir::isa_and_nonnull(storeOp->getParentOp())) + mlir::isa_and_nonnull(storeOp->getParentOp())) { stores.push_back(storeOp); } @@ -2919,9 +2919,11 @@ class OwnedReturnConsumptionPass { // the store MLIRGen made at the region's end, and the read that follows it: put back to what the region // yields, then stored where a new value is made + // (a parameter's default ends with `ts.ParamDefaultValue`, processOptionalParam) auto loadOp = mlir::dyn_cast_or_null(storeOp->getNextNode()); - auto resultOp = loadOp ? mlir::dyn_cast_or_null(loadOp->getNextNode()) : mlir_ts::ResultOp(); - if (!loadOp || loadOp.getReference() != storeOp.getReference() || !resultOp || + auto *resultOp = loadOp ? loadOp->getNextNode() : nullptr; + if (!loadOp || loadOp.getReference() != storeOp.getReference() || + !mlir::isa_and_nonnull(resultOp) || resultOp->getNumOperands() != 1 || resultOp->getOperand(0) != loadOp.getResult()) { continue; @@ -2931,6 +2933,38 @@ class OwnedReturnConsumptionPass resultOp->setOperand(0, storeOp.getValue()); loadOp->erase(); storeOp->erase(); + + // A parameter that may be kept - stored, returned, given to a call or a new literal (`constructor(public + // a = new C())`) - holds its default as it holds an argument: own keeps it, the default moving out with + // it (own_param_default_kept). Only a parameter that is only read borrows the slot. + if (auto paramOptionalOp = mlir::dyn_cast(resultOp->getParentOp())) + { + auto mayKeep = llvm::any_of(paramOptionalOp->getResult(0).getUsers(), [&](mlir::Operation *user) { + auto readOp = mlir::dyn_cast(user); + if (!readOp) + { + return !mlir::isa(user); + } + + std::function handedOn = [&](mlir::Value value) { + return llvm::any_of(value.getUsers(), [&](mlir::Operation *reader) { + if (mlir::isa(reader)) + { + return handedOn(reader->getResult(0)); + } + + return !mlir::isa(reader); + }); + }; + return handedOn(readOp.getResult()); + }); + if (mayKeep) + { + continue; + } + } + storeNewValue(resultOp, 0, slot); } } diff --git a/tslang/lib/TypeScript/OwnershipFacts.h b/tslang/lib/TypeScript/OwnershipFacts.h index 1ff0ba24b..62d104acf 100644 --- a/tslang/lib/TypeScript/OwnershipFacts.h +++ b/tslang/lib/TypeScript/OwnershipFacts.h @@ -1525,7 +1525,10 @@ inline bool mayWriteField(mlir::Operation *op, mlir_ts::PropertyRefOp field, mli } else if (auto releaseSlotOp = mlir::dyn_cast(inner)) { - writes = writesPlace(releaseSlotOp.getSlot()); + // (a slot owning a default value - a parameter's or a pattern's - frees what a parameter or local + // reading its field may be: `m(p = mk(1)) { return p.x; }` read it after the release) + auto slotOp = releaseSlotOp.getSlot().getDefiningOp(); + writes = writesPlace(releaseSlotOp.getSlot()) || (slotOp && slotOp->hasAttr(PATTERN_DEFAULT_SLOT_ATTR_NAME)); } else if (auto swapOp = mlir::dyn_cast(inner)) { diff --git a/tslang/test/tester/CMakeLists.txt b/tslang/test/tester/CMakeLists.txt index 8042e5a76..09ec4f23b 100644 --- a/tslang/test/tester/CMakeLists.txt +++ b/tslang/test/tester/CMakeLists.txt @@ -5586,6 +5586,19 @@ foreach(getter_mm rc gc none) tslang_add_test(NAME test-jit-${getter_mm}-getter-temporary COMMAND test-runner -jit -mm=${getter_mm} "${PROJECT_SOURCE_DIR}/test/tester/own/rc_getter_temporary.ts") tslang_add_test(NAME test-compile-${getter_mm}-getter-temporary COMMAND test-runner -mm=${getter_mm} "${PROJECT_SOURCE_DIR}/test/tester/own/rc_getter_temporary.ts") endforeach() +# -mm=own: a parameter's default that makes a new value (a function's, a method's, a constructor's, an arrow's, a +# closure's) is owned by the frame's slot (#1015's, for rc) and given back at exit (it leaked); the same program under +# rc and gc. IR: the default stores the new value into the slot and gives a read of it (none before). +foreach(param_default_mm gc rc own) + tslang_add_test(NAME test-jit-${param_default_mm}-own-param-default-new-value COMMAND test-runner -jit -mm=${param_default_mm} "${PROJECT_SOURCE_DIR}/test/tester/own/own_param_default_new_value.ts") + tslang_add_test(NAME test-compile-${param_default_mm}-own-param-default-new-value COMMAND test-runner -mm=${param_default_mm} "${PROJECT_SOURCE_DIR}/test/tester/own/own_param_default_new_value.ts") +endforeach() +add_test(NAME test-own-param-default-slot + COMMAND $ --emit=mlir --no-default-lib -mm=own + "${PROJECT_SOURCE_DIR}/test/tester/own/own_param_default_new_value.ts") +set_tests_properties(test-own-param-default-slot + PROPERTIES PASS_REGULAR_EXPRESSION "\"ts[.]Store\"[(]%[0-9]+, %[0-9]+[)] : [(]!ts[.]class<@N[^\n]*\n *%[0-9]+ = \"ts[.]Load\"[(]%[0-9]+[)] : [(]!ts[.]ref p.x; + let total: number = 0; + for (let i = 0; i < 400; i++) { + const c = i % 2 == 0; + const base = i; + const closure = (p: N = mk(base)): number => { + return p.x; + }; + + total += f(c ? mk(i) : undefined); + total += fromParam(mk(i), c ? mk(i) : undefined); + total += borrows(mk(i), c ? mk(i) : undefined, c ? mk(i) : undefined); + total += new K(c ? mk(i) : undefined).v + new K().m(c ? mk(i) : undefined); + total += arrow(c ? mk(i) : undefined) + closure(c ? mk(i) : undefined); + + churn(); + } + + print(total); + assert(total == 541545, "total"); + print("done."); +} From 7c5e22fb5137dfb9b4fa12d420094649b541a88d Mon Sep 17 00:00:00 2001 From: ASDAlexander77 Date: Tue, 24 Nov 2026 15:18:23 +0000 Subject: [PATCH 5/8] -mm=own: a pattern default's slot in a try body or a switch case is made in front of the TryOp/SwitchOp The slot holding a pattern default that makes a new value (0cde20d2) was made where the default is, inside the TryOp's or SwitchOp's region, and released where that region does not reach: own failed with "operand #0 does not dominate this use" (`try { const { p = mk(9) } = r; }`, `case 1: { ... }`, a case without a block, in a loop). It is now made where an owned local of that scope is hoisted to. A generator keeps the default as before (its locals are fields of the generator object). A slot made inside an expression (a destructuring assignment in `?:`) reaches no scope exit: it is not released there, and settleOwnPatternDefaults takes it out again, so own refuses that program with the ownership error, as main does, not the internal one. Co-Authored-By: Claude Opus 5.5 --- tslang/lib/TypeScript/MLIRGenImpl.h | 64 ++++++++--- .../TypeScript/OwnedReturnConsumptionPass.cpp | 29 +++++ tslang/test/tester/CMakeLists.txt | 11 ++ .../own/own_pattern_default_try_switch.ts | 105 ++++++++++++++++++ ...own_pattern_default_in_expression_error.ts | 28 +++++ 5 files changed, 224 insertions(+), 13 deletions(-) create mode 100644 tslang/test/tester/own/own_pattern_default_try_switch.ts create mode 100644 tslang/test/tester/tests/00own_pattern_default_in_expression_error.ts diff --git a/tslang/lib/TypeScript/MLIRGenImpl.h b/tslang/lib/TypeScript/MLIRGenImpl.h index d839b51c8..fd81de6c2 100644 --- a/tslang/lib/TypeScript/MLIRGenImpl.h +++ b/tslang/lib/TypeScript/MLIRGenImpl.h @@ -1061,6 +1061,13 @@ class MLIRGenImpl // `onlyOnAttr` names the copies of a hand-written finally the releases are kept in - // UNWIND_ONLY_ATTR_NAME or RETURN_ONLY_ATTR_NAME - or is empty for an ordinary release + bool isPatternDefaultSlotOutOfReach(mlir::Value storage) + { + auto varOp = storage.getDefiningOp(); + return varOp && varOp->hasAttr(PATTERN_DEFAULT_SLOT_ATTR_NAME) && + !varOp->getParentRegion()->isAncestor(builder.getInsertionBlock()->getParent()); + } + void releaseScopeOwnedVars(mlir::Location location, const SmallVector &ownedVars, StringRef onlyOnAttr = {}) { @@ -1079,6 +1086,14 @@ class MLIRGenImpl } else if (isOwnedLocalSlot(storage)) { + // (a pattern default's slot made inside an expression does not reach the scope's end: + // ownPatternDefaultSlot) + if (isPatternDefaultSlotOutOfReach(storage)) + { + continue; + } + + releaseOp = builder.create(location, storage); // a closure written further on may still capture it (releaseCapturedSlotsAsCells) releaseOp->setAttr(SCOPE_EXIT_RELEASE_ATTR_NAME, builder.getUnitAttr()); @@ -4914,6 +4929,41 @@ class MLIRGenImpl return mclh.conditionalValue(condValue, trueValue, falseValue); } + // -mm=own: the slot a pattern's default that makes a new value is held by (optionalValueOrDefault), a slot of the + // scope, released when the scope ends. Made where the scope's owned locals are: in a `try` body or a `switch` case, + // in front of the TryOp/SwitchOp, as an owned local is hoisted (mlirGen(VariableDeclaration)) - made in the region, + // it did not dominate the release on the unwind leg or at the switch's end ("operand #0 does not dominate this + // use"). None in a generator, whose locals are fields of the generator object kept between turns: the default is + // what it was before, refused where it was refused. A slot made inside an expression (a destructuring assignment in + // `?:`) does not dominate the scope's end either: it is not released there (releaseScopeOwnedVars), and + // settleOwnPatternDefaults takes such a slot out again. + mlir::Value ownPatternDefaultSlot(mlir::Location location, mlir::Type dataType, const GenContext &genContext) + { + if (compileOptions.memoryModel != MemoryModelOwn || !genContext.ownedVars || genContext.generatorSwitchOperation || + !mth.ownsHeapMemory(location, dataType)) + { + return mlir::Value(); + } + + mlir::OpBuilder::InsertionGuard insertGuard(builder); + if ((genContext.allocateScopeOwnedVarsOutsideOfOperation || genContext.allocateVarsOutsideOfOperation) && + genContext.currentOperation) + { + builder.setInsertionPoint(genContext.currentOperation); + } + + mlir::Value defaultSlot = builder.create(location, mlir_ts::RefType::get(dataType), mlir::Value(), + builder.getBoolAttr(false), builder.getIndexAttr(0)); + auto empty = builder.create(location, dataType); + builder.create(location, empty, defaultSlot); + auto varOp = defaultSlot.getDefiningOp(); + varOp->setAttr(OWNED_LOCAL_ATTR_NAME, builder.getUnitAttr()); + varOp->setAttr(OWNED_LOCAL_CONSUMED_ATTR_NAME, builder.getUnitAttr()); + varOp->setAttr(PATTERN_DEFAULT_SLOT_ATTR_NAME, builder.getUnitAttr()); + genContext.ownedVars->push_back(defaultSlot); + return defaultSlot; + } + ValueOrLogicalResult optionalValueOrDefault(mlir::Location location, mlir::Type dataType, mlir::Value value, Expression defaultExpr, const GenContext &genContext) { // -mm=own: a default that makes a new value (`const { p = mk(1) } = r`, `"q" + i`) is held by a slot of the scope, @@ -4921,19 +4971,7 @@ class MLIRGenImpl // it borrows the field otherwise. Nothing owned the new value: every evaluation that ran the default leaked it. // A borrowed default (`p = e`) is not stored (settleOwnPatternDefaults). // (rc settles the op in OwnedReturnConsumptionPass, consumeValueOrDefaultResults.) - mlir::Value defaultSlot; - if (compileOptions.memoryModel == MemoryModelOwn && genContext.ownedVars && mth.ownsHeapMemory(location, dataType)) - { - defaultSlot = builder.create(location, mlir_ts::RefType::get(dataType), mlir::Value(), - builder.getBoolAttr(false), builder.getIndexAttr(0)); - auto empty = builder.create(location, dataType); - builder.create(location, empty, defaultSlot); - auto varOp = defaultSlot.getDefiningOp(); - varOp->setAttr(OWNED_LOCAL_ATTR_NAME, builder.getUnitAttr()); - varOp->setAttr(OWNED_LOCAL_CONSUMED_ATTR_NAME, builder.getUnitAttr()); - varOp->setAttr(PATTERN_DEFAULT_SLOT_ATTR_NAME, builder.getUnitAttr()); - genContext.ownedVars->push_back(defaultSlot); - } + auto defaultSlot = ownPatternDefaultSlot(location, dataType, genContext); auto optionalValueOrDefaultOp = builder.create( location, dataType, value); diff --git a/tslang/lib/TypeScript/OwnedReturnConsumptionPass.cpp b/tslang/lib/TypeScript/OwnedReturnConsumptionPass.cpp index bad6679ad..3c8dbc2ab 100644 --- a/tslang/lib/TypeScript/OwnedReturnConsumptionPass.cpp +++ b/tslang/lib/TypeScript/OwnedReturnConsumptionPass.cpp @@ -2934,6 +2934,35 @@ class OwnedReturnConsumptionPass loadOp->erase(); storeOp->erase(); + // a slot no scope exit releases - made inside an expression (a destructuring assignment in `?:`), which + // does not reach the scope's end (MLIRGenImpl::releaseScopeOwnedVars): taken out, the default is what it + // was without one + if (llvm::none_of(slot.getUsers(), [](mlir::Operation *user) { return mlir::isa(user); })) + { + for (auto *user : llvm::make_early_inc_range(slot.getUsers())) + { + auto emptyStore = mlir::dyn_cast(user); + if (!emptyStore) + { + continue; + } + + auto *emptyValue = emptyStore.getValue().getDefiningOp(); + emptyStore->erase(); + if (mlir::isa_and_nonnull(emptyValue) && emptyValue->use_empty()) + { + emptyValue->erase(); + } + } + + if (slot.use_empty()) + { + slot.getDefiningOp()->erase(); + } + + continue; + } + // A parameter that may be kept - stored, returned, given to a call or a new literal (`constructor(public // a = new C())`) - holds its default as it holds an argument: own keeps it, the default moving out with // it (own_param_default_kept). Only a parameter that is only read borrows the slot. diff --git a/tslang/test/tester/CMakeLists.txt b/tslang/test/tester/CMakeLists.txt index 09ec4f23b..740b2d03f 100644 --- a/tslang/test/tester/CMakeLists.txt +++ b/tslang/test/tester/CMakeLists.txt @@ -5612,6 +5612,17 @@ add_test(NAME test-own-pattern-default-slot set_tests_properties(test-own-pattern-default-slot PROPERTIES PASS_REGULAR_EXPRESSION "\"ts[.]Store\"[(]%[0-9]+, %[0-9]+[)] : [(]!ts[.]class<@N[^\n]*\n *%[0-9]+ = \"ts[.]Load\"[(]%[0-9]+[)] : [(]!ts[.]ref Date: Tue, 24 Nov 2026 15:19:41 +0000 Subject: [PATCH 6/8] -mm=own: an array pattern's element default that makes a new value is held by the pattern-default slot Once 48daae37 applied an array element's default, own refused array patterns with an object default that main accepted (`const [a = mk(1)] = xs`, `(N | null)[]`, `(N | undefined)[]`, a destructured parameter `([a = mk(1)]: N[])`, `{ arr: [a = mk(1)] } = o`): the bounds test's ts.If merged a borrow of the element with a new value nobody owned. The default branch now stores into the same slot an object pattern's default uses, and settleOwnPatternDefaults settles it there too (also through the ts.OptionalValue an element of `T | undefined` wraps it in). A destructured parameter's slot is the frame's, listed with the parameters' storage and given back at exit. Co-Authored-By: Claude Opus 5.5 --- .../TypeScript/MLIRLogic/MLIRGenContext.h | 5 ++ tslang/lib/TypeScript/MLIRGenFunctions.cpp | 12 ++- tslang/lib/TypeScript/MLIRGenImpl.h | 11 ++- tslang/lib/TypeScript/MLIRGenVariables.cpp | 19 ++++- .../TypeScript/OwnedReturnConsumptionPass.cpp | 18 ++++- tslang/test/tester/CMakeLists.txt | 7 ++ .../own_array_pattern_default_new_value.ts | 81 +++++++++++++++++++ 7 files changed, 141 insertions(+), 12 deletions(-) create mode 100644 tslang/test/tester/own/own_array_pattern_default_new_value.ts diff --git a/tslang/include/TypeScript/MLIRLogic/MLIRGenContext.h b/tslang/include/TypeScript/MLIRLogic/MLIRGenContext.h index 23fce1978..b18076e21 100644 --- a/tslang/include/TypeScript/MLIRLogic/MLIRGenContext.h +++ b/tslang/include/TypeScript/MLIRLogic/MLIRGenContext.h @@ -136,6 +136,7 @@ struct GenContext generatorSwitchOperation = nullptr; allocateVarsOutsideOfOperation = false; allocateScopeOwnedVarsOutsideOfOperation = false; + bindingParamPatterns = false; } void clearReceiverTypes() @@ -219,6 +220,10 @@ struct GenContext // a catch clause's variable is being declared: the landing pad writes it, not an initializer, so it // starts with nothing in it (MLIRGenImpl::adjustLocalVariableType) bool declaringCatchVariable = false; + // a function's prologue is destructuring a parameter (`function f([a = mk(1)]: N[])`): no scope owns anything yet + // (ownedVars is null), and -mm=own's slot for a pattern default that makes a new value is the frame's, given back + // at the function's exit (MLIRGenImpl::ownPatternDefaultSlot, mlirGenFunctionBody) + bool bindingParamPatterns = false; bool forceDiscover = false; bool discoverParamsOnly = false; bool insertIntoParentScope = false; diff --git a/tslang/lib/TypeScript/MLIRGenFunctions.cpp b/tslang/lib/TypeScript/MLIRGenFunctions.cpp index 9d556a9d3..9a6a087dd 100644 --- a/tslang/lib/TypeScript/MLIRGenFunctions.cpp +++ b/tslang/lib/TypeScript/MLIRGenFunctions.cpp @@ -2623,11 +2623,13 @@ namespace mlirgen assert(val); auto initFunc = [&](mlir::Location, const GenContext &) { return std::make_tuple(val.getType(), val, TypeProvided::No); }; + GenContext bindingGenContext(genContext); + bindingGenContext.bindingParamPatterns = true; if (bindingPattern == SyntaxKind::ArrayBindingPattern) { auto arrayBindingPattern = bindingPattern.as(); if (mlir::failed(processDeclarationArrayBindingPattern(location, arrayBindingPattern, VariableType::Let, - initFunc, genContext))) + initFunc, bindingGenContext))) { return mlir::failure(); } @@ -2636,7 +2638,7 @@ namespace mlirgen { auto objectBindingPattern = bindingPattern.as(); if (mlir::failed(processDeclarationObjectBindingPattern(location, objectBindingPattern, VariableType::Let, - initFunc, genContext))) + initFunc, bindingGenContext))) { return mlir::failure(); } @@ -2898,8 +2900,10 @@ namespace mlirgen { paramCells->push_back(prologueOp.getResult(0)); } - // ...and the slot owning a parameter's default value (processOptionalParam), given back at exit - else if (isa(prologueOp) && prologueOp.hasAttr(DEFAULT_VALUE_SLOT_ATTR_NAME)) + // ...and the slot owning a parameter's default value (processOptionalParam), or, under own, a default in a + // destructured parameter (ownPatternDefaultSlot), given back at exit + else if (isa(prologueOp) && + (prologueOp.hasAttr(DEFAULT_VALUE_SLOT_ATTR_NAME) || prologueOp.hasAttr(PATTERN_DEFAULT_SLOT_ATTR_NAME))) { paramCells->push_back(prologueOp.getResult(0)); } diff --git a/tslang/lib/TypeScript/MLIRGenImpl.h b/tslang/lib/TypeScript/MLIRGenImpl.h index fd81de6c2..44b2dbbab 100644 --- a/tslang/lib/TypeScript/MLIRGenImpl.h +++ b/tslang/lib/TypeScript/MLIRGenImpl.h @@ -4939,8 +4939,9 @@ class MLIRGenImpl // settleOwnPatternDefaults takes such a slot out again. mlir::Value ownPatternDefaultSlot(mlir::Location location, mlir::Type dataType, const GenContext &genContext) { - if (compileOptions.memoryModel != MemoryModelOwn || !genContext.ownedVars || genContext.generatorSwitchOperation || - !mth.ownsHeapMemory(location, dataType)) + // (a destructured parameter's default: the frame's, listed when the prologue is done, mlirGenFunctionBody) + if (compileOptions.memoryModel != MemoryModelOwn || !(genContext.ownedVars || genContext.bindingParamPatterns) || + genContext.generatorSwitchOperation || !mth.ownsHeapMemory(location, dataType)) { return mlir::Value(); } @@ -4960,7 +4961,11 @@ class MLIRGenImpl varOp->setAttr(OWNED_LOCAL_ATTR_NAME, builder.getUnitAttr()); varOp->setAttr(OWNED_LOCAL_CONSUMED_ATTR_NAME, builder.getUnitAttr()); varOp->setAttr(PATTERN_DEFAULT_SLOT_ATTR_NAME, builder.getUnitAttr()); - genContext.ownedVars->push_back(defaultSlot); + if (genContext.ownedVars) + { + genContext.ownedVars->push_back(defaultSlot); + } + return defaultSlot; } diff --git a/tslang/lib/TypeScript/MLIRGenVariables.cpp b/tslang/lib/TypeScript/MLIRGenVariables.cpp index bae717fbb..b689c0882 100644 --- a/tslang/lib/TypeScript/MLIRGenVariables.cpp +++ b/tslang/lib/TypeScript/MLIRGenVariables.cpp @@ -726,6 +726,11 @@ namespace mlirgen } } + // -mm=own: a default that makes a new value is held by a slot of the scope, as an object pattern's is + // (optionalValueOrDefault); the element read borrows the slot or the source's element. A new value + // merged with a borrow of the element had no owner: own refused the pattern. + auto defaultSlot = defaultValue ? ownPatternDefaultSlot(location, valueType, genContext) : mlir::Value(); + auto result = conditionalValue(location, inBoundsValue, [&]() { // TODO: unify it with ElementAccess @@ -747,7 +752,19 @@ namespace mlirgen if (defaultValue) { auto value = makeDefault(elementType); - return value ? ValueOrLogicalResult(value) : ValueOrLogicalResult(mlir::failure()); + if (!value) + { + return ValueOrLogicalResult(mlir::failure()); + } + + // (kept only for a new value: settleOwnPatternDefaults) + if (defaultSlot && value.getType() == valueType) + { + builder.create(location, value, defaultSlot); + value = builder.create(location, valueType, defaultSlot); + } + + return ValueOrLogicalResult(value); } return ValueOrLogicalResult(V(builder.create(location, elementType))); diff --git a/tslang/lib/TypeScript/OwnedReturnConsumptionPass.cpp b/tslang/lib/TypeScript/OwnedReturnConsumptionPass.cpp index 3c8dbc2ab..24cb9411e 100644 --- a/tslang/lib/TypeScript/OwnedReturnConsumptionPass.cpp +++ b/tslang/lib/TypeScript/OwnedReturnConsumptionPass.cpp @@ -2826,7 +2826,8 @@ class OwnedReturnConsumptionPass // which owns it and gives it back when the scope ends; the pattern's value borrows the slot. Only a new value is the // slot's to own - a call's result, a new object, a fresh string, as settled here, once calls are marked: it moves in. // A default that borrows (`p = e`, a field, a literal's element) is not stored: what the region yields is that - // value, as before, and the slot stays empty. + // value, as before, and the slot stays empty. (An array pattern's element default is the else branch of the bounds + // test, a `ts.If`: MLIRGenImpl::processDeclarationArrayBindingPatternSubPath.) void settleOwnPatternDefaults(mlir::ModuleOp module) { if (compileOptions.memoryModel != MemoryModelOwn) @@ -2838,7 +2839,8 @@ class OwnedReturnConsumptionPass module.walk([&](mlir_ts::StoreOp storeOp) { auto varOp = storeOp.getReference().getDefiningOp(); if (varOp && varOp->hasAttr(PATTERN_DEFAULT_SLOT_ATTR_NAME) && - mlir::isa_and_nonnull(storeOp->getParentOp())) + mlir::isa_and_nonnull( + storeOp->getParentOp())) { stores.push_back(storeOp); } @@ -2851,9 +2853,17 @@ class OwnedReturnConsumptionPass auto yielded = resultOp->getOperand(index); auto slotType = mlir::cast(slot.getType()).getElementType(); auto produced = yielded; - while (auto castOp = produced.getDefiningOp()) + while (true) { - if (!mlir::isa(castOp.getType())) + // (an element of an array of `T | undefined`: the default wrapped as an optional, `ts.OptionalValue`) + if (auto optionalValueOp = produced.getDefiningOp()) + { + produced = optionalValueOp.getIn(); + continue; + } + + auto castOp = produced.getDefiningOp(); + if (!castOp || !mlir::isa(castOp.getType())) { break; } diff --git a/tslang/test/tester/CMakeLists.txt b/tslang/test/tester/CMakeLists.txt index 740b2d03f..52d869d23 100644 --- a/tslang/test/tester/CMakeLists.txt +++ b/tslang/test/tester/CMakeLists.txt @@ -5623,6 +5623,13 @@ endforeach() add_test(NAME test-compile-own-pattern-default-in-expression-error COMMAND test-runner -mm=own "${PROJECT_SOURCE_DIR}/test/tester/tests/00own_pattern_default_in_expression_error.ts") set_tests_properties(test-compile-own-pattern-default-in-expression-error PROPERTIES PASS_REGULAR_EXPRESSION "a value that borrows 'r.p' cannot be stored, returned or captured" FAIL_REGULAR_EXPRESSION "does not dominate|Stack dump|Assertion failed") +# -mm=own: an array pattern's element default that makes a new value (`const [a = mk(1)] = xs`; `(N | null)[]`, +# `(N | undefined)[]`, in a `try`, a nested pattern of a field, a destructured parameter) is held by a slot, as an +# object pattern's is (own refused these once the default was applied); the same program under rc and gc. +foreach(array_default_mm gc rc own) + tslang_add_test(NAME test-jit-${array_default_mm}-own-array-pattern-default-new-value COMMAND test-runner -jit -mm=${array_default_mm} "${PROJECT_SOURCE_DIR}/test/tester/own/own_array_pattern_default_new_value.ts") + tslang_add_test(NAME test-compile-${array_default_mm}-own-array-pattern-default-new-value COMMAND test-runner -mm=${array_default_mm} "${PROJECT_SOURCE_DIR}/test/tester/own/own_array_pattern_default_new_value.ts") +endforeach() # A pattern's default that is a local (`const e = mk(i + 1); const { p = e } = r`) gives the local back at the end of # its block under rc and own (it leaked): the default hands it on as the value-or-default's result. A named record, # a `let`, an array pattern under every model; a record literal source and the assignment form under gc and rc. diff --git a/tslang/test/tester/own/own_array_pattern_default_new_value.ts b/tslang/test/tester/own/own_array_pattern_default_new_value.ts new file mode 100644 index 000000000..3f27283a8 --- /dev/null +++ b/tslang/test/tester/own/own_array_pattern_default_new_value.ts @@ -0,0 +1,81 @@ +// -mm=own: an array pattern's element default that makes a new value (`const [a = mk(1)] = xs`) is held by a slot of +// the scope, as an object pattern's default is, and the element read borrows that slot or the source's element. Own +// refused these patterns once the default was applied (a new value merged with a borrow of the element had no owner): +// an array source, an array of `T | null` and of `T | undefined`, in a `try` body, a nested pattern of a field, a +// destructured parameter of a function (whose slot is the frame's, given back at exit). The same program under rc +// and gc. +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); +} + +class R { + p?: N; +} + +function v(o: N | undefined | null): number { + return o === undefined ? 1 : o === null ? 2 : o.x + o.s.length; +} + +function param([a = mk(1), b = mk(2)]: N[]): number { + return v(a) + v(b); +} + +function paramOptional([a = mk(3)]: (N | undefined)[], i: number): number { + return v(a) + i; +} + +function paramObject({ p = mk(4) }: R): number { + return v(p); +} + +function main() { + let total: number = 0; + for (let i = 0; i < 300; i++) { + const xs: N[] = i % 3 == 0 ? [] : i % 3 == 1 ? [mk(i)] : [mk(i), mk(i + 1)]; + const [a = mk(1), b = mk(2)] = xs; + total += v(a) + v(b); + + const ns: (N | null)[] = i % 2 == 0 ? [null] : []; + const [c = mk(5)] = ns; + total += v(c); + + const us: (N | undefined)[] = i % 2 == 0 ? [undefined, mk(i)] : [mk(i)]; + const [d = mk(6), e = mk(7)] = us; + total += v(d) + v(e); + + try { + const [f = mk(8)] = i % 4 == 0 ? [] : [mk(i)]; + if (i % 5 == 4) throw "x"; + total += v(f); + } catch (err) { + total += 3; + } + + const o = { arr: [mk(i)] }; + const { arr: [g = mk(9), h = mk(10)] } = o; + total += v(g) + v(h); + + const none: N[] = []; + total += param(xs) + param(none); + const noneOptional: (N | undefined)[] = []; + const undefinedOnly: (N | undefined)[] = [undefined]; + total += paramOptional(noneOptional, i) + paramOptional([mk(i)], i) + paramOptional(undefinedOnly, i); + + const r = new R(); + if (i % 2 == 0) r.p = mk(i); + total += paramObject(r); + } + + print(total); + assert(total == 432003, "total"); + print("done."); +} From c2cc234a4128412eedb3ec624989c23c51466cc5 Mon Sep 17 00:00:00 2001 From: ASDAlexander77 Date: Tue, 24 Nov 2026 15:19:51 +0000 Subject: [PATCH 7/8] OwnedReturnConsumptionPass: whether a value-or-default hands its default on is read from the pass's options The static thread_local flag set in runOnOperation (handsOnThroughDefaults) is gone: handedOnByConditional reads compileOptions.tracksOwnership() itself, and it and the helpers that call it (leavesBlockBy, yieldedByBranch, storedIntoUnownedLocalOutside, lastUseInBlock, escapesThroughStore) are members now, all called from members already. No change in what the pass emits. Co-Authored-By: Claude Opus 5.5 --- .../TypeScript/OwnedReturnConsumptionPass.cpp | 23 ++++++++----------- 1 file changed, 10 insertions(+), 13 deletions(-) diff --git a/tslang/lib/TypeScript/OwnedReturnConsumptionPass.cpp b/tslang/lib/TypeScript/OwnedReturnConsumptionPass.cpp index 24cb9411e..3c2445e86 100644 --- a/tslang/lib/TypeScript/OwnedReturnConsumptionPass.cpp +++ b/tslang/lib/TypeScript/OwnedReturnConsumptionPass.cpp @@ -67,7 +67,6 @@ class OwnedReturnConsumptionPass { auto module = getOperation(); MLIRTypeHelper mth(module->getContext(), compileOptions); - handsOnThroughDefaults = compileOptions.tracksOwnership(); copyEscapingStringViews(module); @@ -997,7 +996,7 @@ class OwnedReturnConsumptionPass // Does `value` stay in `block` but for its terminator? Seen through the casts that only widen it, and through a // conditional expression in `block` (or in a statement of it) whose branch yields it: that conditional's result // is the value then. `leaves` is set when `block`'s terminator takes it; false for any other terminator. - static bool leavesBlockBy(mlir::Value value, mlir::Block *block, bool &leaves, int depth = 0) + bool leavesBlockBy(mlir::Value value, mlir::Block *block, bool &leaves, int depth = 0) { if (depth > 64) { @@ -1080,7 +1079,7 @@ class OwnedReturnConsumptionPass // through the casts that only widen it). The conditional's result may be yielded on by a branch of another // (`c ? (d ? [mk(i)][0] : null) : null`), and so on: `levels` is how many conditionals the literal is held past, // to the end of the block the outermost one is in. - static bool yieldedByBranch(mlir::Operation *op, const std::function &leavesUncounted, int &levels) + bool yieldedByBranch(mlir::Operation *op, const std::function &leavesUncounted, int &levels) { auto ifOp = conditionalOf(op->getBlock()); if (!ifOp || !op->getParentOfType()) @@ -3562,7 +3561,7 @@ class OwnedReturnConsumptionPass // at the end of the `if`, and `finally { let n = mk(); for (..) { use(n); n = mk(); } }` at the // end of the loop body; the local then read a freed block. Such a value is left with no one to // give it back - a leak - which is the side the whole arc keeps the uncertain case on. - static bool storedIntoUnownedLocalOutside(mlir::Operation *op) + bool storedIntoUnownedLocalOutside(mlir::Operation *op) { llvm::SmallVector values{op->getResult(0)}; while (!values.empty()) @@ -3621,7 +3620,7 @@ class OwnedReturnConsumptionPass // - what is loaded from a local of the block it is stored into: every use of that local is a load or a // store, or the local is one it can't follow. // A store anywhere else, or a terminator handing it on otherwise (a loop's), is a use it can't follow. - static mlir::Operation *lastUseInBlock(mlir::Operation *op) + mlir::Operation *lastUseInBlock(mlir::Operation *op) { auto *block = op->getBlock(); mlir::Operation *last = op; @@ -3760,17 +3759,15 @@ class OwnedReturnConsumptionPass // What a branch of a conditional expression hands `value` on as: the result of the `ts.If` whose branch this // `ts.Result` ends, at each position the branch yields `value` in - a conditional may yield more than one value // (holdPastConditional adds the literal its branch holds). None for any other user. - // (under rc and own also the default of a value-or-default - `const { p = e } = r` hands `e` on as the op's result - - // set for the module being run: gc and none keep their IR) - static inline thread_local bool handsOnThroughDefaults = false; - - static llvm::SmallVector handedOnByConditional(mlir::Operation *user, mlir::Value value) + // (under rc and own also the default of a value-or-default - `const { p = e } = r` hands `e` on as the op's result; + // gc and none keep their IR) + llvm::SmallVector handedOnByConditional(mlir::Operation *user, mlir::Value value) { llvm::SmallVector handedOn; auto *conditional = mlir::isa(user) ? user->getParentOp() : nullptr; if (!conditional || !(mlir::isa(conditional) || - (handsOnThroughDefaults && mlir::isa(conditional))) || + (compileOptions.tracksOwnership() && mlir::isa(conditional))) || conditional->getNumResults() != user->getNumOperands()) { return handedOn; @@ -3899,7 +3896,7 @@ class OwnedReturnConsumptionPass // was born with, and a release before the yield would free what the caller reads. Any store // is treated that way, rather than telling the record apart from a place that does count. // Under rc the record takes a reference of its own (retainYieldedRecords). - static bool escapesThroughStore(mlir::Value value) + bool escapesThroughStore(mlir::Value value) { for (auto *user : value.getUsers()) { @@ -3920,7 +3917,7 @@ class OwnedReturnConsumptionPass } // `yield b ? h : h2` stores what the branch hands on - if (llvm::any_of(handedOnByConditional(user, value), [](mlir::Value handedOn) { return escapesThroughStore(handedOn); })) + if (llvm::any_of(handedOnByConditional(user, value), [&](mlir::Value handedOn) { return escapesThroughStore(handedOn); })) { return true; } From d73778659164c3ff695f5dbe1958980fe6ca8a94 Mon Sep 17 00:00:00 2001 From: ASDAlexander77 Date: Tue, 24 Nov 2026 16:28:25 +0000 Subject: [PATCH 8/8] An element past the end of an array value, without a default, reads as undefined As node has it (`const [a, b] = [mk(5)] as N[]`: b is undefined). A name bound to an element of a reference type (a class, an interface, an object, an array, a tuple, a union with one of those or null) is `T | undefined` behind the bounds test, and the past-end branch yields undefined; it read null. That covers nested patterns, for-of, and destructured parameters, in every memory model. Not where a literal source has the element, nor for an inner pattern, which reads the element on. A primitive element (number[], string[], unions of those) keeps its type, which cannot hold undefined, and reads as the type's default as before. The assignment form gives undefined to a target that can hold it (`let t: N | undefined; [s, t] = xs`); it read whatever followed the array's data. A `const` read of an element through that optional wrapper is held like a plain element read (readsElement looks through ts.OptionalValue): under rc the overwrite of the element freed what the const still read (00const_element_read under the guard-page heap). Co-Authored-By: Claude Opus 5.5 --- tslang/lib/TypeScript/MLIRGenImpl.h | 83 ++++++++++++++++++- tslang/lib/TypeScript/MLIRGenVariables.cpp | 19 ++++- tslang/test/tester/CMakeLists.txt | 19 +++++ .../test/tester/tests/00const_element_read.ts | 6 +- .../00destructuring_past_end_undefined.ts | 57 +++++++++++++ ...destructuring_past_end_undefined_assign.ts | 34 ++++++++ 6 files changed, 209 insertions(+), 9 deletions(-) create mode 100644 tslang/test/tester/tests/00destructuring_past_end_undefined.ts create mode 100644 tslang/test/tester/tests/00destructuring_past_end_undefined_assign.ts diff --git a/tslang/lib/TypeScript/MLIRGenImpl.h b/tslang/lib/TypeScript/MLIRGenImpl.h index 44b2dbbab..8276147c8 100644 --- a/tslang/lib/TypeScript/MLIRGenImpl.h +++ b/tslang/lib/TypeScript/MLIRGenImpl.h @@ -2202,12 +2202,25 @@ class MLIRGenImpl } // A value read out of an element, through any casts: what `a[0]` is in `const c = a[0]`, and - // what `b` is in `const [b] = a`, read there only when `a` is long enough (the `then` of an if). + // what `b` is in `const [b] = a`, read there only when `a` is long enough (the `then` of an if; of a reference + // type, `T | undefined`, the element wrapped as an optional: readsUndefinedPastEnd). static bool readsElement(mlir::Value value) { - while (auto castOp = value ? value.getDefiningOp() : mlir_ts::CastOp()) + while (value) { - value = castOp.getIn(); + if (auto castOp = value.getDefiningOp()) + { + value = castOp.getIn(); + continue; + } + + if (auto optionalValueOp = value.getDefiningOp()) + { + value = optionalValueOp.getIn(); + continue; + } + + break; } if (auto ifOp = value ? value.getDefiningOp() : mlir_ts::IfOp()) @@ -3523,7 +3536,24 @@ class MLIRGenImpl ValueOrLogicalResult processDeclarationArrayBindingPatternSubPath( mlir::Location location, int index, mlir::Type type, mlir::Value init, bool isDotDotDot, bool isIterator, bool isArrayLike, mlir::Value arrayLikeLengthValue, mlir::Type arrayLikeElementType, - Expression defaultValue, const GenContext &genContext); + Expression defaultValue, bool bindsName, const GenContext &genContext); + + // An element of an array value past its end is undefined (`const [a, b] = [mk(5)] as N[]`: b, as node has it). + // A reference element type (a class, an interface, an object, an array, a tuple, a union with one of those or + // null) is read as `T | undefined` then - its own type has only null for "nothing", and the element read as null. + // A primitive one (number, boolean, string, a union of those) keeps its type and reads as its type's default: the + // variable could not hold undefined. + static bool readsUndefinedPastEnd(mlir::Type elementType) + { + if (isa(elementType)) + { + return true; + } + + auto unionType = dyn_cast(elementType); + return unionType && llvm::any_of(unionType.getTypes(), [](mlir::Type type) { return readsUndefinedPastEnd(type); }); + } mlir::LogicalResult processDeclarationArrayBindingPattern(mlir::Location location, ArrayBindingPattern arrayBindingPattern, VariableClass varClass, @@ -10152,6 +10182,51 @@ class MLIRGenImpl continue; } + // An element past the end is undefined (as node has it): a target that can hold undefined (`let b: N | + // undefined; [a, b] = xs`) is given undefined there, not null - the element is read as `T | undefined` + // behind a bounds test (readsUndefinedPastEnd). A target that cannot hold it keeps the read below. + auto targetHoldsUndefined = [&]() { + if (!leftExpressionValue || !readsUndefinedPastEnd(elementType)) + { + return false; + } + + auto targetType = leftExpressionValue.getType(); + if (isa(targetType)) + { + return true; + } + + auto unionType = dyn_cast(targetType); + return unionType && llvm::any_of(unionType.getTypes(), [](mlir::Type type) { + return isa(type); + }); + }; + if (!defaultValue && targetHoldsUndefined()) + { + auto lengthValue = builder.create(location, builder.getIndexType(), rightExpressionValue); + auto boundValue = builder.create(location, mth.getIndexType(), mth.getIndexAttrValue(index)); + auto inBounds = V(builder.create(location, getBooleanType(), + builder.getI32IntegerAttr((int)SyntaxKind::GreaterThanToken), lengthValue, boundValue)); + auto optionalType = mlir_ts::OptionalType::get(elementType); + auto conditional = conditionalValue(location, inBounds, + [&]() -> ValueOrLogicalResult { + auto element = readElement(); + CAST_A(optionalElement, location, optionalType, element, genContext); + return ValueOrLogicalResult(optionalElement); + }, + [&](mlir::Type trueValueType) { + return ValueOrLogicalResult(V(builder.create(location, trueValueType))); + }); + EXIT_IF_FAILED_OR_NO_VALUE(conditional) + if (mlir::failed(saveTo(V(conditional)))) + { + return mlir::failure(); + } + + continue; + } + // without a default the element is read as it was (an owned element moved out of a fresh array literal // under -mm=own is that read) if (!defaultValue) diff --git a/tslang/lib/TypeScript/MLIRGenVariables.cpp b/tslang/lib/TypeScript/MLIRGenVariables.cpp index b689c0882..2b1a336f9 100644 --- a/tslang/lib/TypeScript/MLIRGenVariables.cpp +++ b/tslang/lib/TypeScript/MLIRGenVariables.cpp @@ -508,7 +508,7 @@ namespace mlirgen ValueOrLogicalResult MLIRGenImpl::processDeclarationArrayBindingPatternSubPath( mlir::Location location, int index, mlir::Type type, mlir::Value init, bool isDotDotDot, bool isIterator, bool isArrayLike, mlir::Value arrayLikeLengthValue, mlir::Type arrayLikeElementType, - Expression defaultValue, const GenContext &genContext) + Expression defaultValue, bool bindsName, const GenContext &genContext) { // An element's default (`const [a = mk(1), b = mk(2)] = [mk(i)]`) is its value where the element is missing - past // the end of the source, or undefined there - as in TypeScript. It was not applied: an element past the end of a @@ -726,6 +726,16 @@ namespace mlirgen } } + // (without a default, an element past the end is undefined: a name bound to an element of a reference + // type is `T | undefined` - readsUndefinedPastEnd; it read as null. Not where a literal has the element, + // nor for an inner pattern, which reads the element on) + auto createArrayOfInit = literalOf(init); + if (!defaultValue && !isDotDotDot && bindsName && readsUndefinedPastEnd(valueType) && + !(createArrayOfInit && static_cast(index) < createArrayOfInit->getNumOperands())) + { + valueType = mlir_ts::OptionalType::get(valueType); + } + // -mm=own: a default that makes a new value is held by a slot of the scope, as an object pattern's is // (optionalValueOrDefault); the element read borrows the slot or the source's element. A new value // merged with a borrow of the element had no owner: own refused the pattern. @@ -767,6 +777,11 @@ namespace mlirgen return ValueOrLogicalResult(value); } + if (isa(elementType)) + { + return ValueOrLogicalResult(V(builder.create(location, elementType))); + } + return ValueOrLogicalResult(V(builder.create(location, elementType))); }); return result.failed_or_no_value() ? mlir::Value() : V(result); @@ -933,7 +948,7 @@ namespace mlirgen auto subValueFunc = [&](mlir::Location location, const GenContext &genContext) { auto result = processDeclarationArrayBindingPatternSubPath( location, index, type, init, !!arrayBindingElement->dotDotDotToken, isIterator, isSourceArrayLike, arrayLikeLengthValue, arrayLikeElementType, - arrayBindingElement->initializer, genContext); + arrayBindingElement->initializer, arrayBindingElement->name == SyntaxKind::Identifier, genContext); if (result.failed_or_no_value()) { return std::make_tuple(mlir::Type(), mlir::Value(), TypeProvided::No); diff --git a/tslang/test/tester/CMakeLists.txt b/tslang/test/tester/CMakeLists.txt index 52d869d23..fd7530842 100644 --- a/tslang/test/tester/CMakeLists.txt +++ b/tslang/test/tester/CMakeLists.txt @@ -5648,6 +5648,25 @@ 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() +# 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 +# undefined to a target that can hold it (own refuses that shape, as before). IR: the past-end branch yields an +# undefined `N | undefined`. +foreach(past_end_undefined_mm gc rc own none) + tslang_add_test(NAME test-jit-${past_end_undefined_mm}-destructuring-past-end-undefined COMMAND test-runner -jit -mm=${past_end_undefined_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00destructuring_past_end_undefined.ts") + tslang_add_test(NAME test-compile-${past_end_undefined_mm}-destructuring-past-end-undefined COMMAND test-runner -mm=${past_end_undefined_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00destructuring_past_end_undefined.ts") +endforeach() +foreach(past_end_undefined_mm gc rc none) + tslang_add_test(NAME test-jit-${past_end_undefined_mm}-destructuring-past-end-undefined-assign COMMAND test-runner -jit -mm=${past_end_undefined_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00destructuring_past_end_undefined_assign.ts") + tslang_add_test(NAME test-compile-${past_end_undefined_mm}-destructuring-past-end-undefined-assign COMMAND test-runner -mm=${past_end_undefined_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00destructuring_past_end_undefined_assign.ts") +endforeach() +add_test(NAME test-destructuring-past-end-undefined-ir + COMMAND $ --emit=mlir --no-default-lib -mm=gc + "${PROJECT_SOURCE_DIR}/test/tester/tests/00destructuring_past_end_undefined.ts") +set_tests_properties(test-destructuring-past-end-undefined-ir + PROPERTIES PASS_REGULAR_EXPRESSION "\"ts[.]OptionalUndef\"[(][)] : [(][)] -> !ts[.]optional