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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -5453,3 +5453,72 @@ that escapes owns what it captures ... its value is the caller's`. Two shapes, t
`own_literal_let_captures` captures `let`s - inline in a call, in a `const` literal called and given on,
given to an interface - assigns them after, and captures parameters in literals given to an object-type
and an interface parameter, churning between steps, under own, rc, gc and none.

## 70. A field that refers back to its own object, 2026-10-29

`class A { n = 1; fn = () => this.n; }` was `a closure that escapes owns what it captures, but -mm=own
cannot move this variable into it: its value is the caller's`, and `fn = this.get` was `'this value'
takes a second reference`. Both are a **back-reference**: a value stored into a field of an object that
holds the object itself. Own had no such value. An escaping closure owns what it captures (§17), so the
object would own the field, the field the closure's box, and the box the object. gc and rc compiled
both. rc's counts make the cycle a leak, which this section does not change.

Such a value now **borrows** its object (USER decisions, 2026-10-29: Q1 every model, Q2 an error, Q3
only a field of `this` itself). The field owns the closure, as it owns any value, and the box's release
frees the box, not the object. What the field holds is only ever reached through the object, so the
object bounds it: a read of the field is §14's borrow, and nothing takes it out.

- **`this` is captured by copy** (MLIRGen, every model). An arrow reading a variable captured it by
reference, through a cell (`ts.Param {captured}`), so that an assignment after reaches the closure.
`this` is never assigned, so a copy is the same value, and a member of any class now gives
`setCaptureByValue` to its `this`, as a `@value` class's did. There is no cell, so the box holds the
object itself, which also saves a heap cell per closure. gc and rc box the copy as any copy, and rc
retains it as the cell held it before: the same cycle.
- **A back-reference's box** (`isBackReferenceBox`, `OwnershipFacts.h`) holds the member's `this`
(`isMemberThis`: the first parameter, of a class type, or a read of its slot) and nothing else that
owns a block. The closure over it is stored once, into a field of that `this` (`isFieldOfMemberThis`:
of its object, or of a base class's storage in it, §57). Anything else done with the closure is a
call through it, a view of it, or a count of it. Inference (`classifyClosures`) marks the copies
borrowed (`OWN_CAPTURE_BORROW_ATTR_NAME`) and the closure `__own_borrows_captures`, so its routine
frees the box alone (`tsfrecb_`). rc's retain of the copy goes (`fieldBorrowRetains`).
- **`this` in any box keeps nothing** (the signature pass's `keeps`): the object is the caller's, which
no box can own, so a member storing it into a capture box does not keep its `this`. Inference decides
the closure: one that does not escape borrows it, as it borrowed the cell before. A closure with cells
borrows every copy already (§16); one with copies only borrows them when it holds `this` and none of
them was made for it (`borrowsCopies`; `own_closure_borrow`'s `() => this.c.x`, `own_raytrace`'s
`addLight`). A back-reference borrows it as above. Any other escaping closure over `this`
(`return () => this.n`) stays an error, now `'this value' is a parameter, kept here, but -mm=own cannot
make the callers of ... give it up`.
- **A bound method of `this`** (`ThisSymbolRef`/`ThisVirtualSymbolRef` of the member's `this`,
`isBoundMethodOfMemberThis`) stored into a field of `this` already borrows: the closure's tag is null
for a bound method, and its release frees nothing of the object. `keeps` takes the store for no
keeping, and inference drops rc's retain for it.
- **The fields** (`OWN_BACK_REFERENCE_FIELDS_ATTR_NAME`, `ts.own_back_reference_fields`): the signature
pass lists each class storage and position a back-reference is stored into (`isBackReferenceStore`).
`checkPlaceRead` takes nothing out of such a field (`isBackReferenceField`): neither specs 48/65's
`fieldTakeOf` nor spec 63/64's `temporaryFieldTakeOf`. So `return a.fn`, `h.call = a.fn` and the
like stay borrows of the object, and are `borrows a field and cannot be stored, returned or
captured`, the error any other borrowed field gives (Q2), rather than a new message.
- **Calling it** (`a.fn()`) needs nothing new. A body that writes the field it is called through
(`fn = () => { this.fn = g; return this.n; }`) frees its own box during the call, and that is safe:
a closure body reads each value captured by copy out of its box once, at its entry, so the box is not
read after. The code is static. The negative the proposal named, `own_err_back_reference_rewrites`,
is not one.
- **Moving the object** (`let b = a`, `return a`, an array that holds it) moves the field with it. The
box still points at the same object, which the new owner keeps.

A closure that captures anything besides `this` that owns a block (a parameter, a local, another
object) is no back-reference and keeps §17's rules. So does a back-reference stored anywhere but a
field of that `this`, and one in an array the object holds or in a nested object's field (Q3).

`own_back_reference` stores arrow fields reading `this` (one with a parameter, one calling another and
a method), a bound method field, a field a method assigns and one main assigns, a derived class's field
and one its constructor stores, and calls them after the object moved and in objects an array holds.
It churns between steps, under own, rc, gc and none, and own emits no counting. Negatives:
`own_err_back_reference_taken` (`return c.get`), `own_err_back_reference_stored` (`h.call = c.get`) and
`own_err_back_reference_captures` (a closure capturing `this` and a parameter, §17's error). Two million
objects with an arrow field each run in a flat 49 MB under own.

Not here: an arrow field reading a getter (`fn = () => this.prop` with `get prop()`) fails in every model,
because its arrow is kept as returning void (PR #744). A call through a field returning a string, under
`--no-default-lib`, is `borrows a field but is used here after ...` whatever the field holds, as before.
2 changes: 2 additions & 0 deletions tslang/include/TypeScript/Defines.h
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,8 @@
// Its release routine skips them, and a borrowing `.captured` box frees its cells but not what
// they hold.
#define OWN_BORROWING_FIELDS_ATTR_NAME "ts.own_borrowing_fields"
// [class storage type, field position] of each field a back-reference is stored into (own spec 70)
#define OWN_BACK_REFERENCE_FIELDS_ATTR_NAME "ts.own_back_reference_fields"
// -mm=own only, set by OwnershipSignaturePass on the module, in the same shape: the fields of a
// generator's state object - its locals - read only to be yielded (`const groups = [...r]; yield
// groups`). A yield moves what such a field holds to the caller, so the field never owns it: an
Expand Down
7 changes: 5 additions & 2 deletions tslang/lib/TypeScript/MLIRGenFunctions.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1626,8 +1626,11 @@ namespace mlirgen
param->setReadWriteAccess();
// `this` of a @value class's method is the value, which nothing assigns: a closure
// takes a copy of it, not its cell (so a `ref` named `this` in a capture is the
// constructor's slot alone)
if (param->getName() == THIS_NAME && index == firstIndex && getValueClassInfo(param->getType()))
// constructor's slot alone). So does `this` of any class's member: the copy is the
// same object, with no cell for it (own spec 70: a field's closure over `this`
// borrows the object, which a cell moved into the box could not)
if (param->getName() == THIS_NAME && index == firstIndex &&
(getValueClassInfo(param->getType()) || isa<mlir_ts::ClassType>(param->getType())))
{
param->setCaptureByValue();
}
Expand Down
200 changes: 200 additions & 0 deletions tslang/lib/TypeScript/OwnershipFacts.h
Original file line number Diff line number Diff line change
Expand Up @@ -1343,6 +1343,206 @@ inline mlir_ts::CreateBoundFunctionOp closureOfBox(mlir::Value box)
return {};
}

// `this` of the class member a function is: its first parameter, of a class type, or a read of the
// parameter's slot, seen through views (spec 70)
inline bool isMemberThis(mlir::Value value)
{
value = rootOf(value);
// the parameter's slot: `ts.Param` in MLIRGen, `ts.Variable` initialized from it by the time the
// own passes run
if (auto loadOp = value.getDefiningOp<mlir_ts::LoadOp>())
{
auto *slot = loadOp.getReference().getDefiningOp();
if (auto varOp = mlir::dyn_cast_or_null<mlir_ts::VariableOp>(slot); varOp && varOp.getInitializer())
{
value = varOp.getInitializer();
}
else if (auto paramOp = mlir::dyn_cast_or_null<mlir_ts::ParamOp>(slot))
{
value = paramOp->getOperand(0);
}
else
{
return false;
}
}

auto argument = mlir::dyn_cast<mlir::BlockArgument>(value);
return argument && argument.getArgNumber() == 0 && argument.getOwner()->isEntryBlock() &&
mlir::isa<mlir_ts::FuncOp>(argument.getOwner()->getParentOp()) &&
mlir::isa<mlir_ts::ClassType>(argument.getType());
}

// A field of the member's `this`: of its object, or of a base class's storage in it (spec 57)
inline bool isFieldOfMemberThis(mlir::Value ref)
{
auto propertyRefOp = ref.getDefiningOp<mlir_ts::PropertyRefOp>();
if (!propertyRefOp)
{
return false;
}

auto object = propertyRefOp->getOperand(0);
while (auto baseRefOp = object.getDefiningOp<mlir_ts::PropertyRefOp>())
{
auto refType = mlir::dyn_cast<mlir_ts::RefType>(baseRefOp.getType());
if (!refType || !mlir::isa<mlir_ts::ClassStorageType>(refType.getElementType()))
{
return false;
}

object = baseRefOp->getOperand(0);
}

return isMemberThis(object);
}

// A back-reference's box (spec 70): it holds the member's `this` and nothing else that owns a block,
// and the closure over it is stored once, into a field of that `this`; anything else done with the
// closure is a call through it, a view of it, or a count of it. The box borrows the object: the
// field owns the closure, and the object bounds it.
inline bool isBackReferenceBox(mlir::Value box)
{
auto boundOp = closureOfBox(box);
if (!boundOp)
{
return false;
}

auto holdsThis = false;
for (auto *user : box.getUsers())
{
if (user == boundOp.getOperation() || mlir::isa<mlir_ts::RetainCellOp, mlir_ts::ReleaseCellOp>(user))
{
continue;
}

auto propertyRefOp = mlir::dyn_cast<mlir_ts::PropertyRefOp>(user);
if (!propertyRefOp)
{
return false;
}

for (auto *fieldUser : propertyRefOp->getUsers())
{
auto storeOp = mlir::dyn_cast<mlir_ts::StoreOp>(fieldUser);
if (!storeOp || storeOp.getReference() != propertyRefOp.getResult())
{
return false;
}

if (isMemberThis(storeOp.getValue()))
{
holdsThis = true;
}
else if (!holdsNoBlock(storeOp.getValue()))
{
return false;
}
}
}

if (!holdsThis)
{
return false;
}

auto stores = 0;
llvm::SmallVector<mlir::Value> pending{boundOp.getResult()};
while (!pending.empty())
{
auto value = pending.pop_back_val();
for (auto *user : value.getUsers())
{
if (mlir::isa<mlir_ts::RetainOp, mlir_ts::ReleaseOp, mlir_ts::GetThisOp, mlir_ts::GetMethodOp>(user))
{
continue;
}

if (auto storeOp = mlir::dyn_cast<mlir_ts::StoreOp>(user);
storeOp && storeOp.getValue() == value && isFieldOfMemberThis(storeOp.getReference()))
{
++stores;
continue;
}

if (isView(user))
{
pending.push_back(user->getResult(0));
continue;
}

return false;
}
}

return stores == 1;
}

// The class storage a field is in: of a class object, or of a base class's storage in one; null for
// any other field
inline mlir_ts::ClassStorageType fieldOwnerStorage(mlir_ts::PropertyRefOp propertyRefOp)
{
auto type = propertyRefOp->getOperand(0).getType();
if (auto refType = mlir::dyn_cast<mlir_ts::RefType>(type))
{
type = refType.getElementType();
}

if (auto classType = mlir::dyn_cast<mlir_ts::ClassType>(type))
{
return mlir::dyn_cast<mlir_ts::ClassStorageType>(classType.getStorageType());
}

return mlir::dyn_cast<mlir_ts::ClassStorageType>(type);
}

// Is `ref` a field some back-reference is stored into (OWN_BACK_REFERENCE_FIELDS_ATTR_NAME, the
// signature pass's)? What it holds may borrow the object it is in, so it is never taken out of it
inline bool isBackReferenceField(mlir::Value ref)
{
auto propertyRefOp = ref.getDefiningOp<mlir_ts::PropertyRefOp>();
auto storage = propertyRefOp ? fieldOwnerStorage(propertyRefOp) : mlir_ts::ClassStorageType();
auto module = propertyRefOp ? propertyRefOp->getParentOfType<mlir::ModuleOp>() : mlir::ModuleOp();
auto entries = module ? module->getAttrOfType<mlir::ArrayAttr>(OWN_BACK_REFERENCE_FIELDS_ATTR_NAME) : mlir::ArrayAttr();
if (!storage || !entries)
{
return false;
}

return llvm::any_of(entries.getAsRange<mlir::ArrayAttr>(), [&](mlir::ArrayAttr entry) {
return mlir::cast<mlir::TypeAttr>(entry[0]).getValue() == storage &&
mlir::cast<mlir::IntegerAttr>(entry[1]).getInt() == propertyRefOp.getPosition();
});
}

// A method of the member's `this` bound to it (`this.m`), seen through views (spec 70). Its release
// frees nothing of the object (the closure's tag is null for a bound method): it borrows it
inline bool isBoundMethodOfMemberThis(mlir::Value value)
{
auto *def = rootOf(value).getDefiningOp();
return def && mlir::isa<mlir_ts::ThisSymbolRefOp, mlir_ts::ThisVirtualSymbolRefOp>(def) &&
isMemberThis(def->getOperand(0));
}

// A store of a back-reference into a field of the member's `this` (spec 70): a closure over a
// back-reference's box, or a bound method of that `this`
inline bool isBackReferenceStore(mlir_ts::StoreOp storeOp)
{
if (!isFieldOfMemberThis(storeOp.getReference()))
{
return false;
}

if (isBoundMethodOfMemberThis(storeOp.getValue()))
{
return true;
}

auto boundOp = rootOf(storeOp.getValue()).getDefiningOp<mlir_ts::CreateBoundFunctionOp>();
return boundOp && isBackReferenceBox(boundOp.getThisVal());
}

// Is this the slot of parameter `argument` - a local declared from it that owns nothing, is not
// captured, and is never assigned, so every read of it is the argument?
inline bool isParameterSlot(mlir_ts::VariableOp varOp, int &index)
Expand Down
55 changes: 48 additions & 7 deletions tslang/lib/TypeScript/OwnershipInferenceClosures.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,26 @@
namespace own_inference
{

// A closure stored into a field of the object it captures (spec 70; isBackReferenceBox)
bool OwnershipInferencePass::isBackReference(Closure &closure)
{
return !closure.hasCells && isBackReferenceBox(closure.box);
}

void OwnershipInferencePass::classifyClosures()
{
// a bound method of `this` stored into a field of `this` (spec 70): it borrows the object, so
// rc's reference for it goes, as a borrowing field's does
getFunction().walk([&](mlir_ts::StoreOp storeOp) {
if (isFieldOfMemberThis(storeOp.getReference()) && isBoundMethodOfMemberThis(storeOp.getValue()))
{
if (auto *retain = retainBefore(storeOp.getValue(), storeOp))
{
fieldBorrowRetains.insert(retain);
}
}
});

getFunction().walk([&](mlir_ts::CreateBoundFunctionOp boundOp) {
if (!boundOp->hasAttr(OWNS_CAPTURE_ATTR_NAME) || closureOfBox(boundOp.getThisVal()) != boundOp)
{
Expand Down Expand Up @@ -60,21 +78,44 @@ namespace own_inference
closure->escape = escape;
}

// a back-reference (spec 70): the field owns the closure, and its box borrows the object -
// its routine frees the box alone (`__own_borrows_captures`), and rc's reference for the
// copy goes, as a borrowing field's does
if (isBackReference(*closure))
{
for (auto &fill : closure->fills)
{
if (auto *retain = retainBefore(fill.second.getValue(), fill.second))
{
fieldBorrowRetains.insert(retain);
}

setAttrTracked(fill.second, OWN_CAPTURE_BORROW_ATTR_NAME);
}

setAttrTracked(boundOp, OWN_BORROWS_CAPTURES_ATTR_NAME);
return;
}

// copies only: the box owns them (phase 4); only an alias needs deciding - unless the box
// is given to a generator's maker whose result borrows from it
if (!closure->hasCells)
{
// ...and only when every copy has an owner of its own: the box frees itself alone, so a
// value made for it (a callback that captures, `a.filter((x) => x > n)`) would be
// nobody's
// ...or when it holds the member's `this` (a copy, spec 70), the caller's, as a closure
// that does not escape borrowed the cell it held before
auto noneFresh = llvm::none_of(closure->fills, [&](auto &fill) {
auto value = fill.second.getValue();
return !holdsNoBlock(value) && isFresh(rootOf(value));
});
auto holdsThis = llvm::any_of(closure->fills, [&](auto &fill) { return isMemberThis(fill.second.getValue()); });
closure->borrowsCopies =
!closure->escape &&
llvm::any_of(closure->boxUses,
[](mlir::Operation *use) { return use->hasAttr(OWN_RESULT_BOUNDED_ATTR_NAME); }) &&
llvm::none_of(closure->fills, [&](auto &fill) {
auto value = fill.second.getValue();
return !holdsNoBlock(value) && isFresh(rootOf(value));
});
!closure->escape && noneFresh &&
(holdsThis || llvm::any_of(closure->boxUses, [](mlir::Operation *use) {
return use->hasAttr(OWN_RESULT_BOUNDED_ATTR_NAME);
}));
if (!closure->borrowsCopies)
{
if (!closure->escape && closure->aliased)
Expand Down
1 change: 1 addition & 0 deletions tslang/lib/TypeScript/OwnershipInferencePass.h
Original file line number Diff line number Diff line change
Expand Up @@ -253,6 +253,7 @@ class OwnershipInferencePass
// stores are reads or takers depends on it. A closure with copies only keeps what phase 4 does
// with it - its box owns them, and each copy moves in.
void classifyClosures();
bool isBackReference(Closure &closure);
// An object literal's `.captured` box (its arrows' captures, spec 67): when the literal stays in
// this function, the box borrows the copies it holds, as a closure that does not escape does
void classifyLiteralCaptures();
Expand Down
Loading
Loading