diff --git a/docs/own-memory-model.md b/docs/own-memory-model.md index 025fb7345..ae94fa178 100644 --- a/docs/own-memory-model.md +++ b/docs/own-memory-model.md @@ -896,10 +896,15 @@ a reference gives it back on every path out of a function. this.head = n`) or at the tail (`c.next = n`), and `this.head = this.head.next` or `c.next = c.next.next` takes a node out. The node taken out is freed right there, so read what you need of it first: `const h = this.head; const v = h.v; this.head = h.next; return v;`, not `return h.v` - after the assignment. Not accepted yet: a node made with the old head as an argument (`this.head = - new Node(v, this.head)`), a walk that assigns a parameter (`n = n.next`), and an insert that - recurses on a parameter and gives it back (`t.left = insert(t.left, v)`); write the last as a - method that recurses on `this`. + after the assignment. A node can also be made with the old head as an argument (`this.head = new + Node(v, this.head)`), and a tree grown by a function that recurses on a field and gives it back + (`t.left = insert(t.left, v)`): the field is given up to the call, and its result refills it. That + takes a call to a function of the same module that never throws (no `throw` and no `await` in it or + in anything it calls), whose other arguments are values with no heap block or the object `new` made; + anything else is an error. A walk may assign its + parameter (`while (n) { k++; n = n.next; }`) when every value it gives it is read out of the one it + holds: the parameter then borrows the caller's list. A parameter given anything else (`n = new + Node(0)` on some path) is kept, and the caller gives it up. - `Shared` cycles are never freed. - There are no lifetime annotations: a borrow that the compiler cannot follow is an error, even when the program would be correct. The fix is usually a move, a fresh value or `Shared`. diff --git a/docs/own-readiness.md b/docs/own-readiness.md index 006c88e48..113c34170 100644 --- a/docs/own-readiness.md +++ b/docs/own-readiness.md @@ -55,7 +55,10 @@ This is weak evidence, for three reasons. Half of what the fuzzer generates is r 350 programs ran. It was Windows only, and the Windows heap hides double frees that glibc reports. And compiling one real codebase turned up, between 2026-11-13 and 2026-11-15, a read of freed memory (item 50), a double free (item 83), a fix that leaked 2.7 GB and was backed out (item 80), -and a compiler crash in about one run in 500 (#867). All are fixed. The rate says more are there. +and a compiler crash in about one run in 500 (#867). All are fixed. The rate says more are there: +the change that added this page accepted a walk that cut the list ahead of itself (`const nx = +n.next; n.next = null; n = nx`) and read the freed node, found the same day by a probe written for +the next change (spec 83). ## Coverage @@ -96,9 +99,10 @@ Probed one by one under the JIT: | Appending at the tail, cutting the tail: `c.next = n`, `c.next = null` after the walk | Compiles and runs | | List `pop`: `this.head = this.head.next`; unlinking: `c.next = c.next.next` | Compiles and runs | | Using the popped node afterwards: `this.head = h.next; return h.v` | Rejected: the node is freed by the assignment; read it first | -| Push through a constructor: `this.head = new Node(v, this.head)` | Rejected | -| Walking by assigning a parameter: `n = n.next` | Rejected | -| Tree insert by recursion on a parameter: `t.l = ins(t.l, v)` | Rejected | +| Push through a constructor: `this.head = new Node(v, this.head)` | Compiles and runs, when the constructor is in the same module and never throws | +| Walking by assigning a parameter: `n = n.next` | Compiles and runs | +| Tree insert by recursion on a parameter: `t.l = ins(t.l, v)` | Compiles and runs, when the function is in the same module and never throws | +| Cutting while walking: `const nx = n.next; n.next = null; n = nx` | Rejected: the cut frees what `nx` names (accepted by mistake from 2026-11-16 until spec 83) | | Tree insert and sum as methods recursing on `this` | Compiles and runs | | Parent link: `k.parent = this` | Rejected; the answer is `Shared`, whose cycles leak | | `new WeakRef(a)` | Rejected: built on the collector | @@ -146,9 +150,9 @@ assertions-enabled CI leg, and a soak run. The first holds today; the other two 1. **A non-owning back-reference.** `WeakRef` under own, or a declared borrowing field. Without it a tree with parent links either does not compile or leaks. -2. **The rest of linked structures.** A list now works; a node built from the old head, a walk - that assigns a parameter and the recursive tree insert do not. These are what a newcomer writes - first. +2. **The rest of linked structures.** A list, a node built from the old head, a walk that assigns a + parameter and the recursive tree insert work (spec 83). A call that may throw, or one into another + module, still cannot take a field this way, and the popped node cannot be used after the assignment that frees it. 3. **The "not yet" messages.** Second references the compiler cannot classify, values merged from branches, object literals that hold owned values. 4. **Capturing callbacks over `Map` and `Set`**, and a source position for the error they give. diff --git a/tslang/docs/superpowers/specs/2026-09-24-own-memory-model-design.md b/tslang/docs/superpowers/specs/2026-09-24-own-memory-model-design.md index 7ec882617..665ac2f08 100644 --- a/tslang/docs/superpowers/specs/2026-09-24-own-memory-model-design.md +++ b/tslang/docs/superpowers/specs/2026-09-24-own-memory-model-design.md @@ -5850,3 +5850,64 @@ Tests: `00linked_list` and `00linked_list_kept` (own, rc, gc, none; also `-noopt `own_err_list_walk_dropped`, `_walk_call_drops`, `_lookahead_cut`, `_walk_up`, `_pop_used_after`, `_next_kept_twice`, `_refill_from_param`. The corpus, the mm fuzzer (1,000 seeds) and native_ts_graphics' own build are unchanged by it: no file newly refused. + +## 83. A field given to a call and refilled; a parameter that walks; a walk cut ahead of itself, 2026-11-16 + +Three of the shapes section 82 left refused, and a hole it opened. + +**A field given to a call that keeps it, refilled from the call's result (`calledFieldTakeOf`).** +`this.head = new Node(v, this.head)` and `t.left = insert(t.left, v)`: the read of the field goes to a +call that keeps that argument (`__own_params`), and the store right after it puts the call's result (a +constructor's: the object `new` made) back into the same field of the same object. Section 82's moves +out of a field all have nothing but reads between the read and the refill; here the callee runs, and +it may reach the field another way (`insert` carries `__own_drop_fields` for the very field it is +given). So the field is given up before the call (`ts.TakeOutOfField`, as for a splice: emptied in a +mortal object; kept, with its value made immortal, in one an append-only global keeps), and the +refill's release stays: it frees what the field holds then, nothing unless the callee put something +there. The match: a class field holding a class object or null (not a string, a handle, a +back-reference or a borrowing field); the read given once, to that call only, in its block; between +the read and the call only reads, constants and views; between the call and the refill only views of +the result and rc's retain of them. The call's other arguments hold no heap block, or are the object +`new` made: not the object the field is in (`this.wrap(this.head)`, `own_err_list_push_through_this`) +nor the field again (`f(t.l, t.l)`, `own_err_tree_field_given_twice`). + +The call must never throw (`__own_no_throw`, below). A throw caught by any caller would find the field +given up where gc and rc keep the old value: `this.head = new Node(v, this.head)` with a constructor +that throws would empty the list (`own_err_list_push_ctor_throws`). Not an invoke either, whose normal +path goes on in another block. + +**`__own_no_throw` (`OwnershipSignaturePass::computeNoThrow`).** A greatest fixpoint over the module: a +function never throws while its body holds no `ts.Throw`, `ts.ThrowCall` or `ts.ThrowUnwind` (a failed +cast is a `ts.Throw` MLIRGen writes into the body) and no op of the `async` dialect (an await rethrows), +and every call in it is resolved to functions of this module that never throw. An imported, unresolved +or `instanceof` call may throw, so a constructor of another module's class cannot take a field. The fact is put on +each call, since inference reads no other function's body (#867). + +**A parameter that only walks down borrows (`walksDownOnly`).** Section 81 made an assigned parameter a +kept one: its local owns what it holds. A local whose every assignment stores a value read out of what +it holds, through fields of class objects (`n = n.next`, `n = n.left.right`; not through a handle), +owns none of it: it walks down from what it was given. Any other use of the local but reads, rc's counts +and the debugger's record (a swap, its address given away) keeps the old rule. `keeps` no longer counts such a local as the +parameter's taker, so the parameter stays a borrow, and inference treats the local as section 82's +`let` given only borrows. One assignment of anything else (`n = new Node(9)` on some path) keeps the +old rule (`own_err_param_walk_mixed`). The same holds for `let n = m` of a parameter `m`. + +**A walk cut ahead of itself (the hole).** Section 82's `frees` let a release of a field of what the +walking `let` holds go when the `let` only walks down, reading "what the `let` holds" as the value read +or one under it. That is true only once the `let` has been given the value read. `const nx = n.next; +n.next = null; n = nx` reads `n` for the cut while it still holds the node above: the release frees the +node `nx` names, and the walk goes on into it. Section 82 accepted it, and the program crashed +(`own_err_list_unlink_walk`, refused before section 82). Now the read of the `let` that the released +place hangs from must come after the assignment: every way from the read to it runs the assignment, +and no way from it reaches the drop through the read again. `c.next = (c = c.next, null)` reads `c` +for the place before the step and stores after it: section 82 accepted it and the program crashed +(`own_err_list_cut_in_step`). The cut after the walk (`if (c) c.next = null`) and a +cut of the node just stepped to (`c = c.next; if (c && c.v == 2) c.next = null`) still compile. + +Still refused: a field given to a call that may throw, a node used after the assignment that frees +it, and a walk that keeps or returns the parameter it walks (`last(n)` returning `n`: the local borrows, +and a borrow is not returned from a parameter's local). + +Tests: `00linked_list_build` (own, rc, gc, none; also `-noopt` under own), and +`own_err_list_unlink_walk`, `_cut_in_step`, `_cut_through_alias`, `_push_ctor_throws`, `_push_through_this`, +`own_err_tree_field_given_twice`, `own_err_param_walk_mixed`. diff --git a/tslang/lib/TypeScript/OwnershipFacts.h b/tslang/lib/TypeScript/OwnershipFacts.h index eb0b4a0d5..be02b592f 100644 --- a/tslang/lib/TypeScript/OwnershipFacts.h +++ b/tslang/lib/TypeScript/OwnershipFacts.h @@ -65,6 +65,9 @@ namespace mlir_ts = mlir::typescript; // The callee destroys nothing its caller can reach: no overwrite of a place it did not make, no // assignment of a global, no call that may. #define OWN_NO_DROPS_ATTR_NAME "__own_no_drops" +// The callee never throws: no `throw` in its body or in any function it calls, every call it makes +// resolved to functions of this module (OwnershipSignaturePass::computeNoThrow). +#define OWN_NO_THROW_ATTR_NAME "__own_no_throw" // The callee destroys nothing its caller can reach but the old values of the places it overwrites: // [position, slot type] pairs - a field's position (OWN_INTERFACE_FIELD_POSITION for a field reached // through an interface), -1 for an element - judged as those stores would be if they were the @@ -204,6 +207,11 @@ inline bool callNoDrops(mlir::Operation *op) return op->hasAttr(OWN_NO_DROPS_ATTR_NAME); } +inline bool callNoThrow(mlir::Operation *op) +{ + return op->hasAttr(OWN_NO_THROW_ATTR_NAME); +} + // The places a call's callees may overwrite (OWN_DROP_FIELDS_ATTR_NAME), when that is all they // destroy; none when they may destroy anything. inline std::optional>> callDropFields(mlir::Operation *op) diff --git a/tslang/lib/TypeScript/OwnershipInferencePass.h b/tslang/lib/TypeScript/OwnershipInferencePass.h index ef4550a77..b537ab558 100644 --- a/tslang/lib/TypeScript/OwnershipInferencePass.h +++ b/tslang/lib/TypeScript/OwnershipInferencePass.h @@ -909,6 +909,15 @@ class OwnershipInferencePass // the field is emptied right before the release, and its value is the place's. `take.release` is // that release. bool splicedFieldTakeOf(mlir::Operation *read, FieldTake &take); + // ...or is `kept` a call that keeps `read`, a read of a field of a class object, whose result is + // stored into that same field right after it: `this.head = new Node(v, this.head)`, `t.left = + // insert(t.left, v)`. The field is given up right before the call (ts.TakeOutOfField), so that + // nothing the callee does through another way to the object sees the value twice, and the refill's + // release frees what the field holds then. `take.release` is that release. + bool calledFieldTakeOf(mlir::Operation *read, mlir::Operation *kept, FieldTake &take); + // Are `object` and `other` the same object: sameObject, or two reads of one local in a block + // with no assignment of it and nothing that runs other code between them? + static bool sameObjectInBlock(mlir::Value object, mlir::Value other); // Can `call` be given a copy of `value`, a string read out of a place, in its place (callCopies)? static bool copiesInto(mlir::Operation *call, mlir::Value value); // Does `store` put `value`, a string read out of a place, into another place with no retain of diff --git a/tslang/lib/TypeScript/OwnershipInferencePlaceReads.cpp b/tslang/lib/TypeScript/OwnershipInferencePlaceReads.cpp index 24aa098c9..ea1e500f9 100644 --- a/tslang/lib/TypeScript/OwnershipInferencePlaceReads.cpp +++ b/tslang/lib/TypeScript/OwnershipInferencePlaceReads.cpp @@ -1066,6 +1066,35 @@ namespace own_inference } } + // ...or given to a call that keeps it, whose result refills the field right after (`this.head = + // new Node(v, this.head)`, `t.left = insert(t.left, v)`): the field is given up before the call, + // and the refill's release frees what it holds then - nothing, unless the callee put something + // there through another way to the object. + if (FieldTake called; !take.taker && kept && !letKept && !countedHandle && !backReference && + calledFieldTakeOf(read, kept, called)) + { + takenOps.insert(called.taker); + auto *stillKept = walk(); + takenOps.clear(); + auto usedAfter = llvm::any_of(uses, [&](auto &use) { + return use.op != called.taker && reachableAfter(called.taker, use.op, use.kills); + }); + if (!stillKept && !letKept && !usedAfter) + { + if (!dryRun) + { + mlir::OpBuilder builder(called.taker); + auto object = called.field.getDefiningOp().getObjectRef(); + builder.create(called.taker->getLoc(), object, called.field); + } + + toErase.insert(bookkeeping.begin(), bookkeeping.end()); + return true; + } + + kept = walk(); + } + if (take.taker) { bookkeeping.push_back(take.retain); @@ -1167,8 +1196,8 @@ namespace own_inference !isBackReferenceField(propertyRefOp.getResult()) && !isBorrowingField(propertyRefOp.getResult()); }; // is `value` the value read (or, with `underLet`, what the local holds), or read out of it - // through such places - auto readUnder = [&](mlir::Value value, bool underLet) { + // through such places; `letRead` is then that read of the local + auto readUnder = [&](mlir::Value value, bool underLet, mlir::Operation **letRead = nullptr) { for (auto root = rootOf(value); root;) { if (!underLet && root == result) @@ -1184,6 +1213,11 @@ namespace own_inference if (underLet && loadOp.getReference() == assignedLet.getResult()) { + if (letRead) + { + *letRead = loadOp; + } + return true; } @@ -1230,7 +1264,19 @@ namespace own_inference return false; } - if (!assignedLet || !readUnder(object, true)) + mlir::Operation *letRead = nullptr; + if (!assignedLet || !readUnder(object, true, &letRead)) + { + return true; + } + + // ...when the local is read for it after it is given the value read: every way from the + // read to that read of the local runs the assignment, and none from there reaches the + // drop through the read again. `const nx = n.next; n.next = null; n = nx` reads `n` + // while it still holds the object above, and frees what `nx` borrows. + if (!letRead || reachableAfter(read, letRead, llvm::ArrayRef{assignment}) || + (reachableAfter(letRead, read, llvm::ArrayRef()) && + reachableAfter(read, drop, llvm::ArrayRef{letRead}))) { return true; } @@ -1760,62 +1806,171 @@ namespace own_inference // (the borrow check of that read sees to it that the place still holds it here) auto held = rootOf(field.getObjectRef()).getDefiningOp(); auto heldPlace = held ? held.getReference().getDefiningOp() : mlir_ts::PropertyRefOp(); - auto sameObjectHere = [&](mlir::Value object, mlir::Value other) { - if (sameObject(object, other)) + if (!heldPlace || isHandle(held.getResult()) || heldPlace.getPosition() != place.getPosition() || + heldPlace.getType() != place.getType() || + !sameObjectInBlock(rootOf(heldPlace.getObjectRef()), rootOf(place.getObjectRef()))) + { + return false; + } + + // from the read to the store: reads, rc's retain and the release, nothing that runs other code + for (auto *op = read->getNextNode(); op && op != storeOp.getOperation(); op = op->getNextNode()) + { + if (op != release.getOperation() && + !mlir::isa(op) && !isView(op)) { - return true; + return false; + } + } + + take.retain = retainOp; + take.taker = storeOp; + take.field = field.getResult(); + take.release = release; + return true; + } + + bool OwnershipInferencePass::sameObjectInBlock(mlir::Value object, mlir::Value other) + { + if (sameObject(object, other)) + { + return true; + } + + // two reads of one local in a block, with no assignment of it between + auto first = object.getDefiningOp(); + auto second = other.getDefiningOp(); + if (!first || !second || first.getReference() != second.getReference() || + !first.getReference().getDefiningOp() || first->getBlock() != second->getBlock()) + { + return false; + } + + if (!first->isBeforeInBlock(second)) + { + std::swap(first, second); + } + + for (auto *op = first->getNextNode(); op && op != second.getOperation(); op = op->getNextNode()) + { + if (auto assigned = mlir::dyn_cast(op); assigned && assigned.getReference() == first.getReference()) + { + return false; } - // two reads of one local in a block, with no assignment of it between - auto first = object.getDefiningOp(); - auto second = other.getDefiningOp(); - if (!first || !second || first.getReference() != second.getReference() || - !first.getReference().getDefiningOp() || first->getBlock() != second->getBlock()) + if (op->getNumRegions() > 0 || isCall(op)) { return false; } + } + + return true; + } + + bool OwnershipInferencePass::calledFieldTakeOf(mlir::Operation *read, mlir::Operation *kept, FieldTake &take) + { + // a field of a class object that owns what it holds: not a string, which is copied where it is + // kept (spec 22), nor a handle, which is counted, nor a field a back-reference or a borrow is + // stored into + auto loadOp = mlir::dyn_cast(read); + auto field = loadOp ? loadOp.getReference().getDefiningOp() : mlir_ts::PropertyRefOp(); + if (!field || !mlir::isa(field.getObjectRef().getType()) || isBackReferenceField(field.getResult()) || + isBorrowingField(field.getResult()) || isCopyableValueAt(read, loadOp.getType()) || isHandle(loadOp.getResult())) + { + return false; + } + + // ...that holds a class object or null: one pointer, which ts.TakeOutOfField empties + auto holdsObjectOrNull = mlir::isa(loadOp.getType()); + if (auto unionType = mlir::dyn_cast(loadOp.getType())) + { + auto types = unionType.getTypes(); + holdsObjectOrNull = llvm::all_of(types, [](mlir::Type type) { return mlir::isa(type); }) && + llvm::count_if(types, [](mlir::Type type) { return mlir::isa(type); }) == 1; + } + + if (!holdsObjectOrNull) + { + return false; + } + + // The call keeps the read, given it once and nothing else uses it. One that never throws: a + // throw caught anywhere would find the field given up, where the other models keep it. + if (!kept || !isCall(kept) || !callNoThrow(kept) || mlir::isa(kept) || + kept->getBlock() != read->getBlock() || !read->isBeforeInBlock(kept) || !loadOp->hasOneUse() || + *loadOp->user_begin() != kept || !isKeptArgument(kept, loadOp.getResult())) + { + return false; + } - if (!first->isBeforeInBlock(second)) + // Its other arguments hold nothing the callee could reach the value by: values with no block, + // and the object a `new` made for a constructor. Not the object the field is in (`this.wrap( + // this.head)`), nor another read of the field (`f(t.l, t.l.r)`). + for (auto arg : callArgs(kept)) + { + if (arg == loadOp.getResult() || holdsNoBlock(arg) || isCopyableValueAt(kept, arg.getType())) { - std::swap(first, second); + continue; } - for (auto *op = first->getNextNode(); op && op != second.getOperation(); op = op->getNextNode()) + auto *def = rootOf(arg).getDefiningOp(); + if (!mlir::isa_and_nonnull(def)) { - if (auto assigned = mlir::dyn_cast(op); assigned && assigned.getReference() == first.getReference()) - { - return false; - } + return false; + } + } - if (op->getNumRegions() > 0 || isCall(op)) - { - return false; - } + // From the read to the call: reads, constants and views of the arguments - nothing that writes + // or runs other code. + for (auto *op = read->getNextNode(); op && op != kept; op = op->getNextNode()) + { + if (!mlir::isa(op) && !isView(op)) + { + return false; } + } - return true; - }; - if (!heldPlace || isHandle(held.getResult()) || heldPlace.getPosition() != place.getPosition() || - heldPlace.getType() != place.getType() || !sameObjectHere(rootOf(heldPlace.getObjectRef()), rootOf(place.getObjectRef()))) + // From the call to the refill: views of its result and rc's retain of them, then the release + // of the same field of the same object right before the store of the result into it. A + // constructor's result is the object `new` made, its first argument. + auto args = callArgs(kept); + auto callResult = kept->getNumResults() == 1 ? kept->getResult(0) + : kept->getNumResults() == 0 && !args.empty() && + mlir::isa_and_nonnull(args.front().getDefiningOp()) ? args.front() + : mlir::Value(); + if (!callResult) { return false; } - // from the read to the store: reads, rc's retain and the release, nothing that runs other code - for (auto *op = read->getNextNode(); op && op != storeOp.getOperation(); op = op->getNextNode()) + for (auto *op = kept->getNextNode(); op; op = op->getNextNode()) { - if (op != release.getOperation() && - !mlir::isa(op) && !isView(op)) + if (auto releaseSlotOp = mlir::dyn_cast(op)) + { + auto place = releaseSlotOp.getSlot().getDefiningOp(); + auto storeOp = mlir::dyn_cast_or_null(op->getNextNode()); + if (!place || !storeOp || storeOp.getReference() != releaseSlotOp.getSlot() || + rootOf(storeOp.getValue()) != callResult || place.getPosition() != field.getPosition() || + place.getType() != field.getType() || !sameObjectInBlock(rootOf(place.getObjectRef()), rootOf(field.getObjectRef()))) + { + return false; + } + + take.taker = kept; + take.field = field.getResult(); + take.release = op; + return true; + } + + auto viewOfResult = isView(op) && rootOf(op->getResult(0)) == callResult; + auto retainOfResult = mlir::isa(op) && rootOf(op->getOperand(0)) == callResult; + if (!viewOfResult && !retainOfResult) { return false; } } - take.retain = retainOp; - take.taker = storeOp; - take.field = field.getResult(); - take.release = release; - return true; + return false; } bool OwnershipInferencePass::namedFieldTakeOf(mlir::Operation *read, mlir::Operation *retain, diff --git a/tslang/lib/TypeScript/OwnershipSignaturePass.cpp b/tslang/lib/TypeScript/OwnershipSignaturePass.cpp index a71110e7a..ceba99796 100644 --- a/tslang/lib/TypeScript/OwnershipSignaturePass.cpp +++ b/tslang/lib/TypeScript/OwnershipSignaturePass.cpp @@ -254,6 +254,7 @@ namespace own_signature findBorrowingStates(module); computeFacts(); computeDrops(); + computeNoThrow(); pinAssignedGlobals(); rejectGlobalArgumentsDropped(); findBoundedForwarders(); @@ -1205,11 +1206,12 @@ namespace own_signature // `let r = init; ... r = f(r, v)`: a local that owns what it is declared from and is given // another value is no borrow of the parameter - the assignment releases what it holds - so // the parameter moves into it (spec 33: `___array_reduce`'s accumulator). Not a string: the - // local copies it (spec 22) + // local copies it (spec 22). Nor a local that only walks down from it (`n = n.next`, spec 83): + // what it is given is read out of what it holds, and it borrows all of it. if (auto varOp = mlir::dyn_cast(user)) { return varOp.getInitializer() == used && isOwningVariable(varOp) && !varOp.getCaptured().value_or(false) && - isAssigned(varOp) && !isCopyableString(used.getType()); + isAssigned(varOp) && !isCopyableString(used.getType()) && !walksDownOnly(varOp); } return false; @@ -1708,6 +1710,71 @@ namespace own_signature computeDropsRound(true); } + void OwnershipSignaturePass::computeNoThrow() + { + llvm::DenseMap> callsIn; + for (auto &call : calls) + { + callsIn[call.op->getParentOfType()].push_back(&call); + } + + // the bodies first: no `throw` anywhere in them (a failed cast is one, made in the body), and + // no async code, whose await rethrows what the awaited body threw + noThrow.clear(); + for (auto &entry : functions) + { + auto funcOp = entry.second; + if (funcOp.isDeclaration()) + { + continue; + } + + auto throws = funcOp->walk([](mlir::Operation *op) { + auto *dialect = op->getDialect(); + return mlir::isa(op) || + (dialect && dialect->getNamespace() == "async") + ? mlir::WalkResult::interrupt() + : mlir::WalkResult::advance(); + }).wasInterrupted(); + if (!throws) + { + noThrow.insert(funcOp); + } + } + + // ...then the calls they make: to functions of this module, every one of which never throws + auto callNeverThrows = [&](const Callees &callees) { + return callees.known && !callees.imported && !callees.instanceOf && !callees.funcs.empty() && + llvm::all_of(callees.funcs, [&](mlir_ts::FuncOp callee) { return noThrow.contains(callee); }); + }; + for (auto changed = true; changed;) + { + changed = false; + for (auto &entry : functions) + { + auto funcOp = entry.second; + if (noThrow.contains(funcOp) && + llvm::any_of(callsIn[funcOp], [&](Call *call) { return !callNeverThrows(call->callees); })) + { + noThrow.erase(funcOp); + changed = true; + } + } + } + + for (auto &call : calls) + { + if (callNeverThrows(call.callees)) + { + call.op->setAttr(OWN_NO_THROW_ATTR_NAME, mlir::UnitAttr::get(&getContext())); + } + else + { + call.op->removeAttr(OWN_NO_THROW_ATTR_NAME); + } + } + } + bool OwnershipSignaturePass::familyResultsFresh(int64_t index, mlir::StringAttr identifier) { for (auto member : familyOf(index, identifier)) @@ -2471,6 +2538,62 @@ namespace own_signature }); } + bool OwnershipSignaturePass::walksDownOnly(mlir_ts::VariableOp varOp) + { + auto assigned = false; + for (auto *user : varOp.getResult().getUsers()) + { + // reads, rc's counts and the debugger's record of it; anything else (a swap, its address + // given away) may give it a value no store here shows + auto storeOp = mlir::dyn_cast(user); + if (!storeOp || storeOp.getReference() != varOp.getResult()) + { + if (!mlir::isa(user)) + { + return false; + } + + continue; + } + + // the value, read out of a field of a class object, that read out of another... down to a + // read of the local itself. Not through a handle, whose payload others hold too. + auto value = storeOp.getValue(); + auto throughField = false; + for (;;) + { + auto loadOp = rootOf(value).getDefiningOp(); + if (!loadOp || isHandle(loadOp.getResult())) + { + return false; + } + + if (loadOp.getReference() == varOp.getResult()) + { + break; + } + + auto field = loadOp.getReference().getDefiningOp(); + if (!field || !mlir::isa(field.getObjectRef().getType())) + { + return false; + } + + throughField = true; + value = field.getObjectRef(); + } + + if (!throughField) + { + return false; + } + + assigned = true; + } + + return assigned; + } + bool OwnershipSignaturePass::holdsOnlyFresh(mlir_ts::VariableOp varOp) { if (!isOwningVariable(varOp) || varOp.getCaptured().value_or(false)) diff --git a/tslang/lib/TypeScript/OwnershipSignaturePass.h b/tslang/lib/TypeScript/OwnershipSignaturePass.h index d9d5ba92d..e78df9506 100644 --- a/tslang/lib/TypeScript/OwnershipSignaturePass.h +++ b/tslang/lib/TypeScript/OwnershipSignaturePass.h @@ -1154,6 +1154,13 @@ class OwnershipSignaturePass : public mlir::PassWrapper noThrow; + bool callMayDrop(const Callees &callees); // ---- Globals a call may assign ---- @@ -1226,6 +1233,9 @@ class OwnershipSignaturePass : public mlir::PassWrapper r ? l : r); +} + +// walks that assign their parameter +function len(n: Node | null) { + let k = 0; + while (n) { + k++; + n = n.next; + } + + return k; +} + +function total(n: Node | null) { + let s = 0.0; + while (n) { + s += n.v; + n = n.next; + } + + return s; +} + +// drops every node after the first that holds `v` +function cutAfter(n: Node | null, v: number) { + while (n) { + if (n.v == v) { + n.next = null; + return; + } + + n = n.next; + } +} + +function make(count: number) { + const s = new Stack(); + for (let i = 1; i <= count; i++) s.push(i); + return s; +} + +// a node an append-only global keeps: the node made in front of what it holds keeps that too +let KEEP: Node[] = []; + +function prepend(n: Node, v: number) { + n.next = new Node(v, n.next); +} + +function main() { + let checks = 0.0; + for (let i = 0; i < 2000; i++) { + const s = make(5); // 5 4 3 2 1 + assert(s.sum() == 15 && len(s.head) == 5 && total(s.head) == 15, "push"); + assert(s.pop() == 5 && s.sum() == 10, "pop"); + + cutAfter(s.head, 3); // 4 3 + assert(len(s.head) == 2 && total(s.head) == 7, "cut"); + assert(len(make(3).head) == 3, "walk a temporary"); + + let root: Tree | null = null; + for (const v of [50, 30, 70, 20, 40, 60, 80, 35]) root = insert(root, v); + assert(treeSum(root) == 385 && depth(root) == 4, "tree"); + + // nodes of the same size made anew: a freed node read by mistake would show here + const fresh = new Node(1000, null); + checks += s.sum() + treeSum(root) + fresh.v; + } + + let kept = 0.0; + for (let i = 0; i < 300; i++) { + KEEP.push(new Node(i, null)); + const k = KEEP[i]; + prepend(k, 1); + prepend(k, 2); // i 2 1 + const fresh = new Node(1000, null); + kept += total(k) + fresh.v; + } + + assert(checks == 2000 * (7 + 385 + 1000), "checks"); + assert(kept == 300 * 1003 + 299 * 150, "kept"); + print("done."); +}