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
34 changes: 34 additions & 0 deletions TSLANG_ISSUES.md
Original file line number Diff line number Diff line change
Expand Up @@ -289,6 +289,40 @@ own now (`bokeh`, `calibrated_timestamps`, `shader_debugprintf`, `simple_compute
`simple_pbr`), 143 of the 276 sources still fail. Regression tests `tslang/test/tester/tests/00tslang_issue_53.ts`
(every model) and `own/own_err_kept_by_constructor_reset.ts`.

54 (a value merged from a `?:` whose branches each bring a fresh value or null: `const pipeline =
loaded ? device.createPipelineFromDesc(layout, desc) : null; ... this.blitPipelines.push(pipeline)` in
`core/nri_donut_textures.ts`, refused "is merged from several branches; -mm=own cannot prove which one
owns it yet") is fixed. Such a merge is the function's own when every way into it brings a fresh value
that nothing else uses (a call's result, a `new`, another such merge) or null or undefined: rc gave it the
one reference it holds. It moves like the call's result itself, and 50, 52 and 53 follow it after the
move. In a loop's body each iteration's merge is a value of its own. Two checks took a block argument,
which has no defining op, for a value made before the loop: the release at the end of one iteration
looked like a second release of the next iteration's value, and a move in the body looked like a move
of a value made outside the loop. They now take the argument as made where its block starts. A merge at
a loop's head (a value carried from one iteration into the next) is not covered. A merge that takes a
local (`c ? local : null`), a merge moved twice, and one made before a loop and moved in it are still
refused. `nri_donut_textures.ts` is left with one error, which is its own: `new MipBlit(texture, ...)`
keeps `this.textures[t]` in a second object, a second owner (an index would do). Merge errors left in
the sweep: 3. Regression tests `tslang/test/tester/tests/00tslang_issue_54.ts` (every model) and
`own/own_err_merge_moved_twice.ts`.

55 (an array literal of fields: `const directions = [this.dir, this.dir, this.right, this.right, this.up,
this.up]` in `core/donut_first_person_camera.ts`, `const pipelines = [this.a, this.b, this.c]` and
`for (const p of [this.a, this.b])` in the examples, refused "borrows a field and cannot be stored") is
fixed. An array literal that is only read (its length and its elements), held in a local or used as it
is, and whose elements are each a read out of a field or an element or a parameter, borrows its
elements while it is used, as the array a rest parameter is given already did (spec 49). Its release
gives back the array and not the elements, so the same field twice is fine. Every use of the array,
and of what is read out of it, is a use of each element: a field written, or a call that may write
it, before such a use is still refused, "borrows a field but is used here after it may be released
or overwritten". So is an array written, stored, returned, captured or given to a call, one with a
fresh element, or an element read out of it and stored. Spec section 80 has the rules. In the sweep,
array literals of fields refused went from 18 to 1 (`this.options = [...]` stores it: refused, rightly),
and `donut_first_person_camera.ts` is left with the two errors of a `let` that borrows a field and is
given a new array (`let dir = this.dir; ... dir = rotateAround(...)`). Regression tests
`tslang/test/tester/tests/00tslang_issue_55.ts` (every model, and as an exe) and
`own/own_err_borrowing_array_field_reset.ts`.

For native_ts_graphics, from the same sweep (its code, not the compiler):
- `examples/dynamic_primitive_clipping.ts:223`, `desc.setDepthClip(clip)` with `clip` the loop's `int`,
fails under every model since #846 (a number is not a `boolean` argument, TS2345). alpha127 still
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5723,3 +5723,31 @@ and its declared `@keeps` and `@lends` apply, as to `obj.set(key, value)`.
Found with it, under every model: the call lowered for an indexer's `set` had no result, also when
`set` returns one (`set(key, value): this`), so the call disagreed with the function it calls and the
lowering to LLVM crashed now and then. It has the setter's results now, unused.

## 80. An array literal that borrows its elements, 2026-11-14

TSLANG_ISSUES 55. `const pipelines = [this.a, this.b, this.c]` and `for (const p of [this.a, this.b])`
were refused, "borrows a field and cannot be stored": an element of an array literal moved into the
array, and a field read cannot move. §49 had the borrowing array a rest parameter is given; this is
the same array held in a local or used as it is.

`classifyLocalBorrowingArrays` takes a `ts.CreateArray` that is only read, and whose block-holding
elements are each a read out of a place (a field, an element) or of a parameter's slot, with no fresh
value among them:
- held in a local (`ts.Variable` initialized with it, not captured), the local is only read (its
`ts.RetainSlot` and `ts.ReleaseSlot`s aside), or used as it is with a `ts.Release` of its own;
- each read of it is a `ts.LengthOf`, or a `ts.ElementRef` that is only read;
- `walkRecord` of it finds nothing that keeps it and no return.

Such an array is marked `OWN_BORROWING_ARRAY_ATTR_NAME`, rc's references for its elements go
(`fieldBorrowRetains`), and its releases are marked `OWN_SHALLOW_RELEASE_ATTR_NAME`: a `ts.Release`
or a `ts.ReleaseSlot` (lowered with `emitReleaseArrayShallow`) frees the array and not its elements,
so the same field twice is fine. Every use `walkRecord` found - of the array and of what is read out
of it - is a use of each element (`arrayElementUses`, read by `walkBorrowed`), so an element's source
written or released before any of them is the error it is for a field read held in a local; the
array's own release is not one. The array is one borrow: a use of it bounds every element, also one
it does not read.

Not here: an array written (`push`, an element stored), stored, returned, captured or given to a
call (the call's array of §49 aside); a literal with a fresh element beside borrowed ones; a local's
value as an element (`[background, tile]`), whose bound is the local's own ends.
13 changes: 12 additions & 1 deletion tslang/lib/TypeScript/LowerToLLVM.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -786,7 +786,18 @@ class ReleaseSlotOpLowering : public TsLlvmPattern<mlir_ts::ReleaseSlotOp>
{
OwnershipRoutineLogic orl(op, rewriter, getTypeConverter(), tsLlvmContext->compileOptions);
auto releaseSlot = [&]() {
orl.emitReleaseSlot(cast<mlir_ts::RefType>(op.getSlot().getType()).getElementType(), transformed.getSlot());
auto elementType = cast<mlir_ts::RefType>(op.getSlot().getType()).getElementType();
// a local array literal that only borrowed its elements (-mm=own's
// classifyLocalBorrowingArrays): the array goes, its elements stay with their owners
if (auto arrayType = dyn_cast<mlir_ts::ArrayType>(elementType); arrayType && op->hasAttr(OWN_SHALLOW_RELEASE_ATTR_NAME))
{
TypeHelper th(rewriter);
auto header = rewriter.create<LLVM::LoadOp>(op->getLoc(), th.getPtrType(), transformed.getSlot());
orl.emitReleaseArrayShallow(arrayType, header);
return;
}

orl.emitReleaseSlot(elementType, transformed.getSlot());
};

// an interface's field filled by a setter has no slot: the setter lets go of what it held
Expand Down
99 changes: 99 additions & 0 deletions tslang/lib/TypeScript/OwnershipFacts.h
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
#include "TypeScript/MLIRLogic/MLIRTypeHelper.h"

#include "mlir/Dialect/ControlFlow/IR/ControlFlowOps.h"
#include "mlir/IR/Dominance.h"
#include "mlir/Interfaces/ControlFlowInterfaces.h"

#include "llvm/ADT/DenseMap.h"
Expand Down Expand Up @@ -576,8 +577,106 @@ inline bool takenOutOfBorrowedRest(mlir::Operation *def)
return rest && !llvm::is_contained(ownedParams(rest.getOwner()->getParentOp()), static_cast<int32_t>(rest.getArgNumber()));
}

inline bool isFresh(mlir::Value value);

// A value merged from branches (TSLANG 54): `const p = loaded ? device.create() : null`. It is the
// function's own when every way into the merge brings a fresh value that nothing else uses, or null
// or undefined, which holds no block - rc gave it the one reference the merge holds. Not across a
// loop: a block that reaches one of its own predecessors carries a value from one iteration into the
// next, which is not decided here.
inline bool isFreshMerge(mlir::BlockArgument argument, unsigned depth = 0)
{
auto *block = argument.getOwner();
if (block->isEntryBlock() || block->hasNoPredecessors() || depth > 8)
{
return false;
}

// a loop header: a predecessor it dominates comes back to it (a merge inside a loop's body is
// fine - each iteration makes its own values)
mlir::DominanceInfo dominance(block->getParentOp());
for (auto predecessor = block->pred_begin(); predecessor != block->pred_end(); ++predecessor)
{
if (dominance.dominates(block, *predecessor))
{
return false;
}

auto branchOp = mlir::dyn_cast<mlir::BranchOpInterface>((*predecessor)->getTerminator());
if (!branchOp)
{
return false;
}

auto operands = branchOp.getSuccessorOperands(predecessor.getSuccessorIndex());
if (argument.getArgNumber() < operands.getProducedOperandCount())
{
return false;
}

auto incoming = operands[argument.getArgNumber()];
if (!incoming)
{
return false;
}

// null or undefined, seen through its casts
auto constant = incoming;
while (auto castOp = constant.getDefiningOp<mlir_ts::CastOp>())
{
constant = castOp.getIn();
}

if (constant.getDefiningOp<mlir_ts::NullOp>() || constant.getDefiningOp<mlir_ts::UndefOp>() ||
constant.getDefiningOp<mlir_ts::OptionalUndefOp>())
{
continue;
}

if (auto nested = mlir::dyn_cast<mlir::BlockArgument>(incoming))
{
if (!nested.hasOneUse() || !isFreshMerge(nested, depth + 1))
{
return false;
}

continue;
}

// the fresh value and the views it reaches the branch through, used by nothing else
for (auto value = incoming;;)
{
if (!value.hasOneUse())
{
return false;
}

auto *def = value.getDefiningOp();
if (def && isView(def) && def->getNumOperands() == 1)
{
value = def->getOperand(0);
continue;
}

if (!isFresh(value))
{
return false;
}

break;
}
}

return true;
}

inline bool isFresh(mlir::Value value)
{
if (auto argument = mlir::dyn_cast<mlir::BlockArgument>(value))
{
return isFreshMerge(argument);
}

auto *def = value.getDefiningOp();
if (!def || resultBorrows(def) >= 0 || takenOutOfBorrowedRest(def))
{
Expand Down
12 changes: 12 additions & 0 deletions tslang/lib/TypeScript/OwnershipInferenceBorrowers.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -425,6 +425,18 @@ namespace own_inference
}
}

// an element of an array literal that only borrows (TSLANG 55): whatever uses the
// array reads it - and nothing else: its release leaves the element to its owner
if (auto found = arrayElementUses.find(user); found != arrayElementUses.end())
{
for (auto &arrayUse : found->second)
{
uses.push_back({arrayUse.op, pending.kills, arrayUse.callee});
}

continue;
}

if (pending.borrowed && keeping.returns && mlir::isa<mlir_ts::ReturnInternalOp>(user))
{
continue;
Expand Down
118 changes: 118 additions & 0 deletions tslang/lib/TypeScript/OwnershipInferenceClosures.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -558,6 +558,124 @@ namespace own_inference
});
}

void OwnershipInferencePass::classifyLocalBorrowingArrays()
{
getFunction().walk([&](mlir_ts::CreateArrayOp arrayOp) {
// `const pipelines = [this.a, this.b]` (TSLANG 55): an array literal in a local, made only
// of what it does not own - each a read out of a place (a field, an element) or a
// parameter - and only read: its length and its elements. It borrows its elements as the
// array a rest parameter is given does (spec 49), for as long as it is used.
auto result = arrayOp.getResult();
if (arrayOp->getNumOperands() == 0 || arrayOp->hasAttr(OWN_BORROWING_ARRAY_ATTR_NAME) || result.use_empty())
{
return;
}

// held in a local, or used as it is (`for (const p of [this.a, this.b])`)
auto slot = result.hasOneUse() ? mlir::dyn_cast<mlir_ts::VariableOp>(*result.getUsers().begin()) : mlir_ts::VariableOp();
if (slot && (slot.getInitializer() != result || slot.getCaptured().value_or(false)))
{
return;
}

llvm::SmallVector<mlir::Operation *> retains;
for (auto element : arrayOp->getOperands())
{
if (holdsNoBlock(element))
{
continue;
}

auto root = rootOf(element);
auto rootLoad = root.getDefiningOp<mlir_ts::LoadOp>();
auto paramSlot = rootLoad ? rootLoad.getReference().getDefiningOp<mlir_ts::VariableOp>() : mlir_ts::VariableOp();
int index = -1;
auto isParameter = paramSlot && isParameterSlot(paramSlot, index);
auto *retain = retainBefore(element, arrayOp);
if (!retain || (!placeReadOf(root) && !isParameter))
{
return;
}

retains.push_back(retain);
}

if (retains.empty())
{
return;
}

// the local: read, and given back - never written, never passed on
llvm::SmallVector<mlir::Operation *> releases;
llvm::SmallVector<mlir::Value> reads;
if (slot)
{
for (auto *user : slot->getUsers())
{
if (auto loadOp = mlir::dyn_cast<mlir_ts::LoadOp>(user))
{
reads.push_back(loadOp.getResult());
}
else if (mlir::isa<mlir_ts::ReleaseSlotOp>(user))
{
releases.push_back(user);
}
else if (!mlir::isa<mlir_ts::RetainSlotOp, mlir_ts::DebugVariableOp>(user))
{
return;
}
}
}
else
{
reads.push_back(result);
}

// each read: its length, or an element read out of it (and not written); the array used
// as it is is given back by a `ts.Release` of its own
for (auto read : reads)
{
for (auto *user : read.getUsers())
{
if (mlir::isa<mlir_ts::LengthOfOp, mlir_ts::DebugVariableOp>(user))
{
continue;
}

if (!slot && mlir::isa<mlir_ts::ReleaseOp>(user))
{
releases.push_back(user);
continue;
}

auto elementRefOp = mlir::dyn_cast<mlir_ts::ElementRefOp>(user);
if (!elementRefOp || elementRefOp.getArray() != read ||
llvm::any_of(elementRefOp->getUsers(), [](mlir::Operation *refUser) { return !mlir::isa<mlir_ts::LoadOp>(refUser); }))
{
return;
}
}
}

// what reads the array reads what it borrows: each use bounds every element (walkBorrowed)
RecordWalk walk;
walkRecord({result}, {}, walk);
if (walk.kept || !walk.returns.empty())
{
return;
}

setAttrTracked(arrayOp, OWN_BORROWING_ARRAY_ATTR_NAME);
fieldBorrowRetains.insert(retains.begin(), retains.end());
arrayElementUses[arrayOp.getOperation()] = walk.uses;
// its releases give back the array, without what it holds
for (auto *release : releases)
{
setAttrTracked(release, OWN_SHALLOW_RELEASE_ATTR_NAME);
}
});
}

bool OwnershipInferencePass::isBorrowingCell(mlir::Value ref)
{
auto cellLoad = ref.getDefiningOp<mlir_ts::LoadOp>();
Expand Down
13 changes: 13 additions & 0 deletions tslang/lib/TypeScript/OwnershipInferenceMoves.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -708,7 +708,14 @@ namespace own_inference
}
});

// a block's argument (a merge, TSLANG 54) is made again each time its block is entered: in a
// loop, the release at the end of one iteration and the one of the next are of two values
auto *definition = value.getDefiningOp();
if (auto argument = mlir::dyn_cast<mlir::BlockArgument>(value); argument && !argument.getOwner()->empty())
{
definition = &argument.getOwner()->front();
}

for (auto *first : releases)
{
for (auto *second : releases)
Expand Down Expand Up @@ -924,7 +931,13 @@ namespace own_inference
}
});

// a block's argument (a merge, TSLANG 54) is made where its block starts, each time it is
// entered: a move of it in that loop's body is of that iteration's value
auto *definition = value.getDefiningOp();
if (auto argument = mlir::dyn_cast<mlir::BlockArgument>(value); argument && !argument.getOwner()->empty())
{
definition = &argument.getOwner()->front();
}

// `c ? h : h2` that is only read borrows `h` and `h2`, and in a loop moves neither. What
// reads the merged value reads this one, so each such read can be a use after a move of
Expand Down
3 changes: 3 additions & 0 deletions tslang/lib/TypeScript/OwnershipInferencePass.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -307,6 +307,8 @@ namespace own_inference
classifyRecords();
// ...and whether an array given to a rest parameter takes its elements (spec 49)
classifyArgumentArrays();
// ...and whether an array literal in a local only borrows its elements (TSLANG 55)
classifyLocalBorrowingArrays();
// a kept parameter the body may not move on every path is released at its exits (spec 33)
releaseKeptParamsAtExits();
auto exitReleasesGone = llvm::make_scope_exit([&]() {
Expand Down Expand Up @@ -399,6 +401,7 @@ namespace own_inference
returnsRecordOf = isRecordResult(f) ? resultBorrowsAll(f) : llvm::SmallVector<int>();
records.clear();
recordStoreUses.clear();
arrayElementUses.clear();
}

// A store of a value that owns a block into a parameter's own slot: the function's argument, which no local
Expand Down
Loading
Loading