From 14c508890a353f29714ad2823f91c2daa37ced3e Mon Sep 17 00:00:00 2001 From: ASDAlexander77 Date: Sun, 25 Oct 2026 11:23:35 +0000 Subject: [PATCH] -mm=own: what an append-only global keeps is immortal (keepers, @immortalizes) - A keeper is a non-exported array global only ever pushed onto: what it holds lives to the end of the program. A value pushed into one is made immortal (ts.MakeImmortal, ts.MarkImmortalCell) where its origin is known: a bound method's object, a closure's box, cells and copies, a fresh value. - A function that pushes a parameter keeps it for good; its callers mark the argument (a fixpoint over calls). One another module may call says so with @immortalizes("p"), checked against the body and carried in declarations. - Inference treats such values as immortal; stack promotion as escaping. - Tests: own_immortal_keepers (all models), own-keepers-objects.cmake, own_err_keeper_*. Closure-escape error tests now empty their global so it is no keeper. Spec: docs/superpowers/specs/2026-10-25-own-immortal-keepers-design.md Co-Authored-By: Claude Opus 5.5 --- .../2026-10-25-own-immortal-keepers-design.md | 156 +++++ tslang/include/TypeScript/Defines.h | 6 + .../LowerToLLVM/OwnershipRoutineLogic.h | 30 + .../MLIRLogic/MLIRDeclarationPrinter.h | 5 +- .../TypeScript/MLIRLogic/MLIRGenStore.h | 4 + tslang/include/TypeScript/TypeScriptOps.td | 27 + tslang/lib/TypeScript/CMakeLists.txt | 1 + tslang/lib/TypeScript/DeclarationPrinter.cpp | 19 +- tslang/lib/TypeScript/LowerToLLVM.cpp | 63 +- tslang/lib/TypeScript/MLIRGenFunctions.cpp | 3 +- tslang/lib/TypeScript/MLIRGenImpl.h | 29 +- tslang/lib/TypeScript/OwnershipFacts.h | 20 + .../TypeScript/OwnershipInferenceClosures.cpp | 9 + .../OwnershipInferenceGlobalReads.cpp | 4 +- .../TypeScript/OwnershipInferenceMoves.cpp | 10 +- .../lib/TypeScript/OwnershipInferencePass.cpp | 10 +- .../TypeScript/OwnershipSignatureKeepers.cpp | 549 ++++++++++++++++++ .../lib/TypeScript/OwnershipSignaturePass.cpp | 3 + .../lib/TypeScript/OwnershipSignaturePass.h | 39 ++ tslang/lib/TypeScript/StackEscapeFacts.h | 2 + tslang/test/tester/CMakeLists.txt | 31 +- tslang/test/tester/own-keepers-objects.cmake | 54 ++ .../tester/own/own_err_closure_escape_loop.ts | 5 + .../own/own_err_closure_escape_some_paths.ts | 5 + .../own/own_err_closure_escape_twice.ts | 5 + .../own_err_keeper_called_through_value.ts | 16 + .../tester/own/own_err_keeper_declared.ts | 12 + .../tester/own/own_err_keeper_exported.ts | 10 + .../test/tester/own/own_err_keeper_popped.ts | 23 + .../own/own_err_keeper_unknown_value.ts | 16 + .../test/tester/own/own_immortal_keepers.ts | 108 ++++ tslang/test/tester/tests/own_keepers_lib.ts | 17 + tslang/test/tester/tests/own_keepers_main.ts | 50 ++ 33 files changed, 1313 insertions(+), 28 deletions(-) create mode 100644 tslang/docs/superpowers/specs/2026-10-25-own-immortal-keepers-design.md create mode 100644 tslang/lib/TypeScript/OwnershipSignatureKeepers.cpp create mode 100644 tslang/test/tester/own-keepers-objects.cmake create mode 100644 tslang/test/tester/own/own_err_keeper_called_through_value.ts create mode 100644 tslang/test/tester/own/own_err_keeper_declared.ts create mode 100644 tslang/test/tester/own/own_err_keeper_exported.ts create mode 100644 tslang/test/tester/own/own_err_keeper_popped.ts create mode 100644 tslang/test/tester/own/own_err_keeper_unknown_value.ts create mode 100644 tslang/test/tester/own/own_immortal_keepers.ts create mode 100644 tslang/test/tester/tests/own_keepers_lib.ts create mode 100644 tslang/test/tester/tests/own_keepers_main.ts diff --git a/tslang/docs/superpowers/specs/2026-10-25-own-immortal-keepers-design.md b/tslang/docs/superpowers/specs/2026-10-25-own-immortal-keepers-design.md new file mode 100644 index 000000000..0579e72cc --- /dev/null +++ b/tslang/docs/superpowers/specs/2026-10-25-own-immortal-keepers-design.md @@ -0,0 +1,156 @@ +# -mm=own: what an append-only global keeps is immortal + +## 1. Why + +A callback a C library calls later has to stay alive after the call that registered it. Under gc a +TypeScript wrapper keeps it in a module-level array that is only ever pushed to, so Boehm sees it: + +```ts +let retained: Callback[] = []; +setRenderCallback(handler: Callback) { retained.push(handler); Donut_SetRenderCallback(this.handle, handler); } +``` + +Under own that push is a move: the wrapper keeps `handler`, so its caller must give it up, and a +bound method `this.onRender` cannot be given up (its object is the caller's `this`, owned by +`main`). A closure that captures a local fails the same way ("captured by a closure that escapes, +and is still used here"). Since `__MEMORY_MODEL__` the generated wrappers skip the push under own, +and the lifetime is the C++ one: the pass objects outlive `App.run()`. This design lets own prove it +instead: what such an array keeps lives to the end of the program, so it is made immortal where it +is kept, as an immortal global is (spec 25). + +## 2. Keepers + +A **keeper** is a `ts.Global` that: + +- is not exported or imported (no `export`, `import`, `dllexport`, `dllimport`), and is not reached + through a vtable; +- is an array whose element type is a class, a bound function, a function value (`hybrid_func`), a + string or an array; +- is given its value only by its region, which yields a new array (`[]`, `ts.Constant` of an array, + `ts.CreateArray`, `ts.NewArray`); +- is used only by `ts.AddressOf`s whose users are a `ts.ArrayPush` (the array operand), and + `ts.Load`s whose users read it: `ts.LengthOf`, and `ts.ElementRef`s that are only loaded. + +Nothing ever takes an element out of a keeper or overwrites one (no `pop`, `shift`, `splice`, +`length =`, element store, nor the array given to anything), and nothing releases a global. So +what it holds is never released: it lives to the end of the program. + +`findKeepers` (OwnershipSignaturePass) marks each `ts.AddressOf` of a keeper +`__own_keeper_global`, and each `ts.Load` of one of its elements `__own_keeper_read`. + +## 3. Immortal at the push + +A value pushed into a keeper is made immortal there: its block's header becomes +`HEAP_BLOCK_IMMORTAL`, so every release skips it, its fields included (a release of an immortal +block runs no destroy body). Writing the header only leaks; it frees nothing. So it is sound wherever +the block is a heap block with a header, and every block the value relies on is made immortal too. +Two blocks need more than the value's own: + +- **A bound method** (`this.onRender`) holds its `this` without owning it, so the object is + marked. +- **A closure that does not escape** borrows its cells and the values it captured by value from the + frame that built it, which releases them. Its box, each cell and each value captured by value + are marked. + +Only the function that builds a value knows these blocks: a callee given a `hybrid_func` does not +know whether its context is an object, a box (whose layout it does not know) or a C++ object with +no header at all. So the mark is made by the function that knows the value's origin, and a function +that pushes a parameter passes the duty to its callers: + +- **The value is a parameter** (a load of the parameter's slot, through casts): the function + **immortalizes** that parameter (`__own_immortalizes`, argument indices). Nothing is marked + there; every call of it marks its argument, by these same rules. +- **The value is built here, or read out of an owning local whose initializer it is**: a bound + method (`ts.ThisSymbolRef`, `ts.ThisVirtualSymbolRef` of a class that owns its block, not + `@cpp`), a closure (`ts.CreateBoundFunction` of a capture box), an allocation (`ts.New`, + `ts.CreateArray`, `ts.NewArray`), or a string. It is marked here. +- **It is immortal already**: a literal, an immortal global's read, a keeper's element. +- **Anything else** (a field's value, a call's result, a merge): an error at the push, "-mm=own + cannot make the value kept in 'retained' immortal here". + +A call passes an argument to a parameter its callee immortalizes. That argument is decided by the +same rules: a parameter of the caller propagates (a fixpoint over the calls, as `@keeps` facts +are), and anything else is marked at the call. + +## 4. In the IR + +- `%i = ts.MakeImmortal(%v)`: the same value, now immortal. Inserted right after `%v`'s definition + (the root, before casts); every other use of `%v` is given `%i`. With `assumed` it marks nothing: + it wraps a parameter its callers made immortal. +- `ts.MarkImmortalCell(%cell)`: marks a captured variable's cell. + +To inference, `ts.MakeImmortal`'s result is immortal (`isImmortalLiteral`): its retains go, and it +may be pushed, stored, returned or given to a call that keeps it, as a string literal may. Its +operand is only borrowed, so the frame still owns what it built and releases it at the end, which +the header makes a no-op. A keeper's element read is immortal too, and is no place read. A keeper's +`ts.AddressOf` is no global read either: the array is never replaced, only appended to. A push of +an immortal value keeps nothing, so a parameter pushed through `ts.MakeImmortal` is not +`__own_params`. That is why the caller's `this` can go to `setRenderCallback`. + +The lowering, under own only: + +- a class or object instance, a string: the block, when not null and not already immortal (a stack + object and a literal have immortal headers, and a literal's may be read-only); +- an array: its header block, when there is one; +- a bound function: its `this`, an object or a capture box; +- `assumed`: nothing. + +## 5. Across modules: `@immortalizes` + +A function another module may call (open: exported, or its address taken) cannot tell callers it +does not see to mark their arguments. Like `@keeps`, an open function that immortalizes a parameter +must say so: `@immortalizes("handler")`. It is checked against the body (`checkDeclared`): a +parameter it names that the body does not immortalize, or one the body immortalizes that it does +not name, is an error. A bodyless declaration's `@immortalizes` is trusted, as `@nodrops` is: a C +function that keeps a callback for good. The decorator is carried in an importer's re-parsed +declaration and in a shared library's declarations, so every caller marks its arguments. + +A call through a class family or an interface immortalizes a parameter only when every callee does. +When the callees disagree, the function that immortalizes is an error: some calls of it would not +mark. + +## 6. Not here + +- A keeper of optionals, unions or tuples: their payloads would need marking through the tag. +- A function value of unknown origin (a field's `hybrid_func`): its context may be a bound method's + object, which only its type tells. +- Removing elements from a keeper: that is an ordinary array, and the push is the move it is + today. + +## 7. As built + +- `OwnershipSignatureKeepers.cpp`: `findKeepers`, `classifyKept`, `decideKeptForGood` (runs after + `findOpen`, before `computeFacts`: an immortal value keeps nothing, so a parameter pushed through + `ts.MakeImmortal` is not `__own_params`), `makeImmortal`. A call's callees are its resolved + functions, or, for a call the pass knows nothing else of (another module's function with no + facts), the declarations of the symbols it names, whose `@immortalizes` is read. +- Inference: `isImmortalLiteral` and the retain decision accept `isKeptForGood`; a keeper's element + read is neither a place read nor a global read; `ts.MakeImmortal` and `ts.MarkImmortalCell` are + borrows; `followClosure` takes `ts.MakeImmortal` as a use and follows it no further, so a closure + kept for good borrows its cells from the frame (which then may still use the captured variables), + and whatever is done with the immortal value afterwards bounds nothing. +- Stack promotion (`StackEscapeFacts`): `ts.MakeImmortal` and `ts.MarkImmortalCell` are an escape, + reason "kept for good", so nothing kept is ever a stack object. +- The decorator is carried like `@keeps`: `processOwnParamMarkers`, the global a declaration's calls + go through, a shared library's printed declarations (a 32-bit mask in a class's method info, which + fits where a 64-bit one would grow the vtable's `SmallVector` past its inline limit). + +Existing programs change only where an array was a keeper: `own_err_closure_escape_twice`, `_loop` +and `_some_paths` pushed closures into a global that is now one, so they were accepted (soundly); +they now empty it once (`handlers.length = 0`), which keeps their errors. `own_closure_escape` and +the stack-promotion test `pass_to_keeper` push into keepers and pass, the latter with the reason +"kept for good" under own. + +## 8. Tests + +- `own_immortal_keepers` (own, gc, rc, none; compile and JIT): a registry pushing a parameter into + a keeper and using it after; a constructor registering `this.onTick` from a function that returns; + a closure over a local the frame still uses; a forwarding function, and an exported one that says + `@immortalizes`; objects pushed directly, fresh and from a local; a keeper's element stored into a + field; churn between, so a freed block would be handed out again. +- `test-own-keepers-objects` (own-keepers-objects.cmake): the keeper in a library object, an + importer registering a bound method and a closure from functions that return; `2 102 2`. +- `own_err_keeper_*`: a value of unknown origin pushed (`unknown_value`), an exported function + without `@immortalizes` (`exported`), an `@immortalizes` the body disagrees with (`declared`), a + function that keeps for good passed on as a value (`called_through_value`), and an array that is + also popped, which is no keeper, so the move error stays (`popped`). diff --git a/tslang/include/TypeScript/Defines.h b/tslang/include/TypeScript/Defines.h index 6b948ba93..0ab1aa3ca 100644 --- a/tslang/include/TypeScript/Defines.h +++ b/tslang/include/TypeScript/Defines.h @@ -331,6 +331,12 @@ // that returns such a record has to say it. A unit attribute on the FuncOp. #define RECORD_DECORATOR "record" #define OWN_DECLARED_RECORD_ATTR_NAME "ts.own_declared_record" +// `@immortalizes` names the parameters the function keeps for good, in an append-only global (a +// keeper, docs/superpowers/specs/2026-10-25-own-immortal-keepers-design.md): its callers make each +// argument immortal. Checked against a body; trusted on a declaration, a C function that keeps a +// callback for good. A FuncOp attribute of argument indices. +#define IMMORTALIZES_DECORATOR "immortalizes" +#define OWN_DECLARED_IMMORTALIZES_ATTR_NAME "ts.own_declared_immortalizes" // the names of the arguments of a function that says any, for -mm=own's errors about it #define OWN_DECLARED_PARAM_NAMES_ATTR_NAME "ts.own_declared_param_names" diff --git a/tslang/include/TypeScript/LowerToLLVM/OwnershipRoutineLogic.h b/tslang/include/TypeScript/LowerToLLVM/OwnershipRoutineLogic.h index 8eeb1410e..3cb447026 100644 --- a/tslang/include/TypeScript/LowerToLLVM/OwnershipRoutineLogic.h +++ b/tslang/include/TypeScript/LowerToLLVM/OwnershipRoutineLogic.h @@ -479,6 +479,36 @@ class OwnershipRoutineLogic }); } + // The same for a block that may be immortal already (ts.MakeImmortal, own's keepers): a stack + // object's header is, and a literal's, which may be read-only, so the header is written only + // when it is mortal. + void emitMarkImmortalIfMortal(mlir::Value payloadPtr) + { + emitIfNonNull(payloadPtr, [&]() { + TypeConverterHelper tch(typeConverter); + TypeHelper th(rewriter); + LLVMCodeHelperBase ch(op, rewriter, typeConverter, compileOptions); + auto loc = op->getLoc(); + + auto isMortal = emitIsMortal(payloadPtr); + auto *currentBlock = rewriter.getInsertionBlock(); + auto *continuationBlock = rewriter.splitBlock(currentBlock, rewriter.getInsertionPoint()); + auto *markBlock = rewriter.createBlock(continuationBlock); + + rewriter.setInsertionPointToEnd(markBlock); + auto llvmIndexType = tch.convertType(th.getIndexType()); + auto blockPtr = ch.getBlockPtrFromPayloadPtr(loc, payloadPtr, llvmIndexType); + rewriter.create( + loc, rewriter.create(loc, llvmIndexType, rewriter.getIntegerAttr(llvmIndexType, HEAP_BLOCK_IMMORTAL)), + blockPtr); + rewriter.create(loc, ValueRange{}, continuationBlock); + + rewriter.setInsertionPointToEnd(currentBlock); + rewriter.create(loc, isMortal, markBlock, continuationBlock); + rewriter.setInsertionPointToStart(continuationBlock); + }); + } + private: // Field types of a record-shaped type, empty for anything else. llvm::SmallVector getFieldTypes(mlir::Type type) diff --git a/tslang/include/TypeScript/MLIRLogic/MLIRDeclarationPrinter.h b/tslang/include/TypeScript/MLIRLogic/MLIRDeclarationPrinter.h index 3b9e139ff..20951056b 100644 --- a/tslang/include/TypeScript/MLIRLogic/MLIRDeclarationPrinter.h +++ b/tslang/include/TypeScript/MLIRLogic/MLIRDeclarationPrinter.h @@ -25,7 +25,7 @@ namespace typescript void printVariableDeclaration(StringRef, NamespaceInfo::TypePtr, mlir::Type, bool, StringRef = StringRef()); void print(StringRef, NamespaceInfo::TypePtr, mlir_ts::FunctionType, StringRef = StringRef(), ArrayRef ownKeeps = {}, ArrayRef ownBorrows = {}, ArrayRef ownLends = {}, - bool ownRecord = false); + bool ownRecord = false, ArrayRef ownImmortalizes = {}); void print(ClassInfo::TypePtr); void print(InterfaceInfo::TypePtr); void printGenericClass(NamespaceInfo::TypePtr, StringRef); @@ -41,7 +41,8 @@ namespace typescript bool filterName(StringRef); bool filterField(mlir::Attribute); void printParams(ArrayRef, mlir::Type); - void printOwnMarkers(ArrayRef, ArrayRef, ArrayRef, bool, bool, unsigned); + void printOwnMarkers(ArrayRef, ArrayRef, ArrayRef, bool, bool, unsigned, + ArrayRef = {}); void printFunction(StringRef, ArrayRef, mlir::Type); void printMethod(bool, StringRef, ArrayRef, mlir::Type, mlir::Type); void printAccessor(bool, StringRef, StringRef, mlir_ts::AccessLevel, ArrayRef, mlir::Type, mlir::Type, StringRef); diff --git a/tslang/include/TypeScript/MLIRLogic/MLIRGenStore.h b/tslang/include/TypeScript/MLIRLogic/MLIRGenStore.h index a39b54b53..d596a652b 100644 --- a/tslang/include/TypeScript/MLIRLogic/MLIRGenStore.h +++ b/tslang/include/TypeScript/MLIRLogic/MLIRGenStore.h @@ -172,6 +172,10 @@ struct MethodInfo uint64_t ownLendsMask = 0; // `@record` (OWN_DECLARED_RECORD_ATTR_NAME): what `@lends` names, the result is a record of bool ownRecord = false; + // `@immortalizes` (OWN_DECLARED_IMMORTALIZES_ATTR_NAME), as a mask like `@lends`'s, of 32 bits: + // it fits beside `ownRecord`, where a 64-bit one would grow the vtable's SmallVector past its + // inline-size limit + uint32_t ownImmortalizesMask = 0; }; struct GenericMethodInfo diff --git a/tslang/include/TypeScript/TypeScriptOps.td b/tslang/include/TypeScript/TypeScriptOps.td index 543032808..5168f5176 100644 --- a/tslang/include/TypeScript/TypeScriptOps.td +++ b/tslang/include/TypeScript/TypeScriptOps.td @@ -625,6 +625,33 @@ def TypeScript_ReleaseContentsOp : TypeScript_Op<"ReleaseContents"> { let arguments = (ins AnyType:$instance, UnitAttr:$reset); } +def TypeScript_MakeImmortalOp : TypeScript_Op<"MakeImmortal", [AllTypesMatch<["value", "result"]>]> { + let summary = "the same value, its block marked immortal"; + let description = [{ + -mm=own (docs/superpowers/specs/2026-10-25-own-immortal-keepers-design.md): a value an + append-only global keeps for good. Its block - an object's, a string's, an array's header, a + bound function's `this` - is marked HEAP_BLOCK_IMMORTAL, unless it is null or immortal already, + so every release skips it. The result is that value, immortal: owned by no one. With `assumed` + nothing is marked: the value is a parameter its callers made immortal. + + Only OwnershipSignaturePass makes it; under the other models it is never there. + }]; + + let arguments = (ins AnyType:$value, UnitAttr:$assumed); + let results = (outs AnyType:$result); +} + +def TypeScript_MarkImmortalCellOp : TypeScript_Op<"MarkImmortalCell"> { + let summary = "mark a captured variable's cell immortal"; + let description = [{ + The cell of a variable a closure captures, when that closure is kept for good and borrows the + cell from the frame that declared it (-mm=own, MakeImmortal): the frame's release of the cell + then skips it. + }]; + + let arguments = (ins TypeScript_Ref:$slot); +} + def TypeScript_SizeOfOp : TypeScript_Op<"SizeOf", [Pure]> { let summary = "size of type"; let description = [{ diff --git a/tslang/lib/TypeScript/CMakeLists.txt b/tslang/lib/TypeScript/CMakeLists.txt index bdac9b1c7..69c6de3b7 100644 --- a/tslang/lib/TypeScript/CMakeLists.txt +++ b/tslang/lib/TypeScript/CMakeLists.txt @@ -49,6 +49,7 @@ add_mlir_dialect_library(MLIRTypeScript OwnershipSignatureGenerators.cpp OwnershipSignatureGlobals.cpp OwnershipSignatureInterfaces.cpp + OwnershipSignatureKeepers.cpp OwnershipSignatureRecords.cpp OwnershipSignatureResolve.cpp OwnedReturnConsumptionPass.cpp diff --git a/tslang/lib/TypeScript/DeclarationPrinter.cpp b/tslang/lib/TypeScript/DeclarationPrinter.cpp index 9f25ef38e..d07b178e9 100644 --- a/tslang/lib/TypeScript/DeclarationPrinter.cpp +++ b/tslang/lib/TypeScript/DeclarationPrinter.cpp @@ -232,7 +232,7 @@ namespace typescript // the receiver of a method, so the importer reads the same argument indices back. `@record` after // `@lends`: the importer's only way to know the result is a record it owns (own spec 32). void MLIRDeclarationPrinter::printOwnMarkers(ArrayRef keeps, ArrayRef borrows, ArrayRef lends, - bool record, bool hasThis, unsigned indent) + bool record, bool hasThis, unsigned indent, ArrayRef immortalizes) { auto printMarker = [&](StringRef name, ArrayRef indices) { if (indices.empty()) @@ -262,6 +262,7 @@ namespace typescript }; printMarker(KEEPS_DECORATOR, keeps); + printMarker(IMMORTALIZES_DECORATOR, immortalizes); printMarker(BORROWS_DECORATOR, borrows); printMarker(LENDS_DECORATOR, lends); if (record && !lends.empty()) @@ -448,7 +449,7 @@ namespace typescript void MLIRDeclarationPrinter::print(StringRef name, NamespaceInfo::TypePtr elementNamespace, mlir_ts::FunctionType funcType, StringRef dllName, ArrayRef ownKeeps, ArrayRef ownBorrows, ArrayRef ownLends, - bool ownRecord) + bool ownRecord, ArrayRef ownImmortalizes) { printNamespaceBegin(elementNamespace); @@ -460,7 +461,7 @@ namespace typescript newline(); } - printOwnMarkers(ownKeeps, ownBorrows, ownLends, ownRecord, /*hasThis=*/false, 0); + printOwnMarkers(ownKeeps, ownBorrows, ownLends, ownRecord, /*hasThis=*/false, 0, ownImmortalizes); printFunction( name, @@ -731,17 +732,25 @@ namespace typescript newline(); } - // every index `@lends` names: MLIRGen refuses one past 63, which the mask cannot hold + // every index `@lends` and `@immortalizes` name: MLIRGen refuses one past 63, which the + // masks cannot hold SmallVector lends; + SmallVector immortalizes; for (int32_t index = 0; index < 64; ++index) { if (method.ownLendsMask & (uint64_t(1) << index)) { lends.push_back(index); } + + if (index < 32 && (method.ownImmortalizesMask & (uint32_t(1) << index))) + { + immortalizes.push_back(index); + } } - printOwnMarkers(method.ownKeeps, method.ownBorrows, lends, method.ownRecord, /*hasThis=*/!method.isStatic, 4); + printOwnMarkers(method.ownKeeps, method.ownBorrows, lends, method.ownRecord, /*hasThis=*/!method.isStatic, 4, + immortalizes); // the slot of a @cpp class's virtual method: without it the importer takes the method // for a non-virtual one diff --git a/tslang/lib/TypeScript/LowerToLLVM.cpp b/tslang/lib/TypeScript/LowerToLLVM.cpp index d4ad0060c..3a6182d8f 100644 --- a/tslang/lib/TypeScript/LowerToLLVM.cpp +++ b/tslang/lib/TypeScript/LowerToLLVM.cpp @@ -651,6 +651,64 @@ class ReleaseCellOpLowering : public TsLlvmPattern } }; +// -mm=own's keepers (docs/superpowers/specs/2026-10-25-own-immortal-keepers-design.md): the block a +// value kept for good relies on is marked immortal, so every release skips it. +class MakeImmortalOpLowering : public TsLlvmPattern +{ + public: + using TsLlvmPattern::TsLlvmPattern; + + LogicalResult matchAndRewrite(mlir_ts::MakeImmortalOp op, Adaptor transformed, + ConversionPatternRewriter &rewriter) const final + { + auto value = transformed.getValue(); + if (tsLlvmContext->compileOptions.memoryModel == MemoryModelOwn && !op.getAssumed()) + { + OwnershipRoutineLogic orl(op, rewriter, getTypeConverter(), tsLlvmContext->compileOptions); + auto type = op.getValue().getType(); + if (auto boundFuncType = dyn_cast(type)) + { + // a bound method's object, which it does not own, or a closure's box + TypeHelper th(rewriter); + auto thisValue = rewriter.create(op->getLoc(), th.getPtrType(), value, + ArrayRef{THIS_VALUE_INDEX}); + orl.emitMarkImmortalIfMortal(thisValue); + } + else if (isa(type)) + { + // the instance, the string, the array's header + orl.emitMarkImmortalIfMortal(value); + } + else + { + return op.emitError("-mm=own cannot make a value of this type immortal"); + } + } + + rewriter.replaceOp(op, value); + return mlir::success(); + } +}; + +class MarkImmortalCellOpLowering : public TsLlvmPattern +{ + public: + using TsLlvmPattern::TsLlvmPattern; + + LogicalResult matchAndRewrite(mlir_ts::MarkImmortalCellOp op, Adaptor transformed, + ConversionPatternRewriter &rewriter) const final + { + if (tsLlvmContext->compileOptions.memoryModel == MemoryModelOwn) + { + OwnershipRoutineLogic orl(op, rewriter, getTypeConverter(), tsLlvmContext->compileOptions); + orl.emitMarkImmortalIfMortal(transformed.getSlot()); + } + + rewriter.eraseOp(op); + return mlir::success(); + } +}; + class SizeOfOpLowering : public TsLlvmPattern { public: @@ -2072,7 +2130,8 @@ struct FuncOpLowering : public TsLlvmPattern // read by -mm=own only if (name == OWN_DECLARED_NO_DROPS_ATTR_NAME || name == OWN_DECLARED_KEEPS_ATTR_NAME || name == OWN_DECLARED_BORROWS_ATTR_NAME || name == OWN_DECLARED_LENDS_ATTR_NAME || - name == OWN_DECLARED_RECORD_ATTR_NAME || name == OWN_DECLARED_PARAM_NAMES_ATTR_NAME) { + name == OWN_DECLARED_RECORD_ATTR_NAME || name == OWN_DECLARED_PARAM_NAMES_ATTR_NAME || + name == OWN_DECLARED_IMMORTALIZES_ATTR_NAME) { continue; } @@ -9092,7 +9151,7 @@ void TypeScriptToLLVMLoweringPass::runOnOperation() PointerOffsetRefOpLowering, LogicalBinaryOpLowering, NullOpLowering, NewOpLowering, CreateTupleOpLowering, DeconstructTupleOpLowering, CreateArrayOpLowering, NewEmptyArrayOpLowering, NewArrayOpLowering, ArrayPushOpLowering, ArrayPopOpLowering, ArrayUnshiftOpLowering, ArrayShiftOpLowering, ArraySpliceOpLowering, ArrayViewOpLowering, DeleteOpLowering, - ParseFloatOpLowering, ParseIntOpLowering, IsNaNOpLowering, PrintOpLowering, ConvertFOpLowering, StoreOpLowering, SizeOfOpLowering, TypeDescriptorOpLowering, RetainOpLowering, ReleaseOpLowering, RetainSlotOpLowering, ReleaseSlotOpLowering, RetainCellOpLowering, ReleaseCellOpLowering, ReleaseContentsOpLowering, + ParseFloatOpLowering, ParseIntOpLowering, IsNaNOpLowering, PrintOpLowering, ConvertFOpLowering, StoreOpLowering, SizeOfOpLowering, TypeDescriptorOpLowering, RetainOpLowering, ReleaseOpLowering, RetainSlotOpLowering, ReleaseSlotOpLowering, RetainCellOpLowering, ReleaseCellOpLowering, ReleaseContentsOpLowering, MakeImmortalOpLowering, MarkImmortalCellOpLowering, InsertPropertyOpLowering, LengthOfOpLowering, SetLengthOfOpLowering, StringLengthOpLowering, StringResizeOpLowering, StringConcatOpLowering, StringCopyOpLowering, SharedNewOpLowering, SharedValueRefOpLowering, SharedCountOpLowering, StringCompareOpLowering, AnyCompareOpLowering, CharToStringOpLowering, UndefOpLowering, CopyStructOpLowering, MemoryCopyOpLowering, MemoryMoveOpLowering, diff --git a/tslang/lib/TypeScript/MLIRGenFunctions.cpp b/tslang/lib/TypeScript/MLIRGenFunctions.cpp index b9bc5466b..ffefa4e96 100644 --- a/tslang/lib/TypeScript/MLIRGenFunctions.cpp +++ b/tslang/lib/TypeScript/MLIRGenFunctions.cpp @@ -1288,7 +1288,8 @@ namespace mlirgen if (auto globalOp = theModule.lookupSymbol(globalName)) { for (auto *name : {OWN_DECLARED_KEEPS_ATTR_NAME, OWN_DECLARED_BORROWS_ATTR_NAME, OWN_DECLARED_LENDS_ATTR_NAME, - OWN_DECLARED_RECORD_ATTR_NAME, OWN_DECLARED_PARAM_NAMES_ATTR_NAME}) + OWN_DECLARED_RECORD_ATTR_NAME, OWN_DECLARED_IMMORTALIZES_ATTR_NAME, + OWN_DECLARED_PARAM_NAMES_ATTR_NAME}) { if (auto attr = declared->getAttr(name)) { diff --git a/tslang/lib/TypeScript/MLIRGenImpl.h b/tslang/lib/TypeScript/MLIRGenImpl.h index 3b145323c..d15a4bb01 100644 --- a/tslang/lib/TypeScript/MLIRGenImpl.h +++ b/tslang/lib/TypeScript/MLIRGenImpl.h @@ -3415,14 +3415,16 @@ class MLIRGenImpl return; } - if (name != KEEPS_DECORATOR && name != BORROWS_DECORATOR && name != LENDS_DECORATOR) + if (name != KEEPS_DECORATOR && name != BORROWS_DECORATOR && name != LENDS_DECORATOR && + name != IMMORTALIZES_DECORATOR) { return; } - auto attrName = name == KEEPS_DECORATOR ? OWN_DECLARED_KEEPS_ATTR_NAME - : name == BORROWS_DECORATOR ? OWN_DECLARED_BORROWS_ATTR_NAME - : OWN_DECLARED_LENDS_ATTR_NAME; + auto attrName = name == KEEPS_DECORATOR ? OWN_DECLARED_KEEPS_ATTR_NAME + : name == BORROWS_DECORATOR ? OWN_DECLARED_BORROWS_ATTR_NAME + : name == IMMORTALIZES_DECORATOR ? OWN_DECLARED_IMMORTALIZES_ATTR_NAME + : OWN_DECLARED_LENDS_ATTR_NAME; if (llvm::any_of(attrs, [&](mlir::NamedAttribute &attr) { return attr.getName() == attrName; })) { emitError(location) << "'@" << name << "' is given twice"; @@ -13144,6 +13146,23 @@ class MLIRGenImpl } methodInfo.ownRecord = funcOp->hasAttr(OWN_DECLARED_RECORD_ATTR_NAME); + + methodInfo.ownImmortalizesMask = 0; + if (auto immortalizes = funcOp->getAttrOfType(OWN_DECLARED_IMMORTALIZES_ATTR_NAME)) + { + for (auto index : immortalizes.asArrayRef()) + { + // the class's declaration is printed from a 32-bit mask + if (index >= 32) + { + emitError(location) << "'@" IMMORTALIZES_DECORATOR "' of '" << funcOp.getSymName() + << "' names an argument past the 32nd"; + return false; + } + + methodInfo.ownImmortalizesMask |= uint32_t(1) << index; + } + } } if (propertyName.size() > 0) @@ -14732,7 +14751,7 @@ class MLIRGenImpl }; dp.print(funcProto->getNameWithoutNamespace(), elementNamespace, funcProto->getFuncType(), dllName, marker(OWN_DECLARED_KEEPS_ATTR_NAME), marker(OWN_DECLARED_BORROWS_ATTR_NAME), marker(OWN_DECLARED_LENDS_ATTR_NAME), - funcOp && funcOp->hasAttr(OWN_DECLARED_RECORD_ATTR_NAME)); + funcOp && funcOp->hasAttr(OWN_DECLARED_RECORD_ATTR_NAME), marker(OWN_DECLARED_IMMORTALIZES_ATTR_NAME)); declExports << ss.str().str(); } diff --git a/tslang/lib/TypeScript/OwnershipFacts.h b/tslang/lib/TypeScript/OwnershipFacts.h index b92804106..647a2fa0c 100644 --- a/tslang/lib/TypeScript/OwnershipFacts.h +++ b/tslang/lib/TypeScript/OwnershipFacts.h @@ -97,6 +97,17 @@ constexpr int64_t OWN_INTERFACE_FIELD_POSITION = -3; // every `ts.AddressOf` of it (isImmortalGlobalRead), and on the `ts.Store` that initializes it, // whose lowering writes the header word. #define OWN_IMMORTAL_GLOBAL_ATTR_NAME "__own_immortal" +// A keeper (docs/superpowers/specs/2026-10-25-own-immortal-keepers-design.md): an append-only array +// global of this module, never given another value, whose elements nothing takes out or overwrites. +// What it holds lives to the end of the program, so each value pushed into it is made immortal +// (ts.MakeImmortal). On every `ts.AddressOf` of it, which no global read is (the array is never +// replaced), and on every `ts.Load` of one of its elements (OWN_KEEPER_READ_ATTR_NAME), which is +// immortal and no place read. +#define OWN_KEEPER_GLOBAL_ATTR_NAME "__own_keeper_global" +#define OWN_KEEPER_READ_ATTR_NAME "__own_keeper_read" +// On a function: the parameters it keeps for good, in a keeper or through a callee that does +// (argument indices). Its callers make each argument immortal. +#define OWN_IMMORTALIZES_ATTR_NAME "__own_immortalizes" // A call inside a try body is a `ts.Invoke` (`ts.InvokeHybrid` through a hybrid function): a // terminator whose normal and unwind edges are its successors. It names its callee as a symbol, or @@ -401,6 +412,15 @@ inline mlir_ts::AddressOfOp globalReadOf(mlir::Value value) // A read of an immortal global (OWN_IMMORTAL_GLOBAL_ATTR_NAME), seen through its views: the // global's own block, which no release frees. Its fields are not immortal: a read out of one is a // place read like any other. +// A value made immortal where a keeper keeps it (ts.MakeImmortal), or a keeper's element, seen +// through its views: owned by no one, and no release frees it. +inline bool isKeptForGood(mlir::Value value) +{ + auto *def = rootOf(value).getDefiningOp(); + return def && (mlir::isa(def) || + (mlir::isa(def) && def->hasAttr(OWN_KEEPER_READ_ATTR_NAME))); +} + inline bool isImmortalGlobalRead(mlir::Value value) { auto addressOfOp = globalReadOf(value); diff --git a/tslang/lib/TypeScript/OwnershipInferenceClosures.cpp b/tslang/lib/TypeScript/OwnershipInferenceClosures.cpp index 33a6a9004..ceafb0c07 100644 --- a/tslang/lib/TypeScript/OwnershipInferenceClosures.cpp +++ b/tslang/lib/TypeScript/OwnershipInferenceClosures.cpp @@ -746,6 +746,15 @@ namespace own_inference return; } + // kept for good (a keeper's): the box, its cells and its copies are immortal from + // here, so the frame's releases of them free nothing, and whatever is done with the + // immortal value - pushed, stored, run later - outlives nothing it relies on + if (mlir::isa(user)) + { + uses.push_back(user); + return; + } + if (isCall(user)) { if (isKeptArgument(user, used)) diff --git a/tslang/lib/TypeScript/OwnershipInferenceGlobalReads.cpp b/tslang/lib/TypeScript/OwnershipInferenceGlobalReads.cpp index bcbbcee57..01e64c017 100644 --- a/tslang/lib/TypeScript/OwnershipInferenceGlobalReads.cpp +++ b/tslang/lib/TypeScript/OwnershipInferenceGlobalReads.cpp @@ -77,7 +77,9 @@ namespace own_inference { auto addressOfOp = loadOp.getReference().getDefiningOp(); auto result = loadOp.getResult(); - return addressOfOp && !addressOfOp->hasAttr(OWN_IMMORTAL_GLOBAL_ATTR_NAME) && ownsHeap(result) && !isHandle(result); + // a keeper is never given another array, only appended to (OWN_KEEPER_GLOBAL_ATTR_NAME) + return addressOfOp && !addressOfOp->hasAttr(OWN_IMMORTAL_GLOBAL_ATTR_NAME) && + !addressOfOp->hasAttr(OWN_KEEPER_GLOBAL_ATTR_NAME) && ownsHeap(result) && !isHandle(result); } void OwnershipInferencePass::checkGlobalRead(mlir_ts::LoadOp read) diff --git a/tslang/lib/TypeScript/OwnershipInferenceMoves.cpp b/tslang/lib/TypeScript/OwnershipInferenceMoves.cpp index 58ef47d38..e0f5ae309 100644 --- a/tslang/lib/TypeScript/OwnershipInferenceMoves.cpp +++ b/tslang/lib/TypeScript/OwnershipInferenceMoves.cpp @@ -329,7 +329,9 @@ namespace own_inference bool OwnershipInferencePass::isImmortalLiteral(mlir::Value value) { - if (isImmortalGlobalRead(value)) + // ...or a value a keeper keeps for good, which is made immortal (ts.MakeImmortal), and a + // keeper's element + if (isImmortalGlobalRead(value) || isKeptForGood(value)) { return true; } @@ -341,6 +343,12 @@ namespace own_inference bool OwnershipInferencePass::isBorrow(mlir::Operation *user, mlir::Value value) { + // marking a value immortal (a keeper's) reads it; the result is another value, owned by none + if (mlir::isa(user)) + { + return true; + } + if (mlir::isahasAttr(OWN_FRESH_RESULT_ATTR_NAME)) + // nor is a keeper's element, which no release frees (OWN_KEEPER_READ_ATTR_NAME) + if (placeReadOf(loadOp.getResult()) && !loadOp->hasAttr(OWN_FRESH_RESULT_ATTR_NAME) && + !loadOp->hasAttr(OWN_KEEPER_READ_ATTR_NAME)) { ops.placeReads.push_back(loadOp); } @@ -362,7 +364,8 @@ namespace own_inference continue; } - if (value && placeReadOf(value)) + // (not a keeper's element, which is no place read: immortal, decided below) + if (value && placeReadOf(value) && !isKeptForGood(value)) { continue; // a read out of a container: checkPlaceRead decided it } @@ -414,7 +417,8 @@ namespace own_inference // an immortal global's value (spec 25): owned by no one, so returned, stored or kept // as often as it is read, and its releases skip it - if (value && isImmortalGlobalRead(value) && (mlir::isa(op) || slotHoldsInitializerAt(op))) + if (value && (isImmortalGlobalRead(value) || isKeptForGood(value)) && + (mlir::isa(op) || slotHoldsInitializerAt(op))) { toErase.insert(op); continue; diff --git a/tslang/lib/TypeScript/OwnershipSignatureKeepers.cpp b/tslang/lib/TypeScript/OwnershipSignatureKeepers.cpp new file mode 100644 index 000000000..90821a709 --- /dev/null +++ b/tslang/lib/TypeScript/OwnershipSignatureKeepers.cpp @@ -0,0 +1,549 @@ +// OwnershipSignaturePass (see OwnershipSignaturePass.h): keepers - append-only array globals whose +// elements live to the end of the program - and the values they keep, made immortal where it is +// known what they rely on (docs/superpowers/specs/2026-10-25-own-immortal-keepers-design.md). + +#include "OwnershipSignaturePass.h" + +#include + +#define DEBUG_TYPE "own" + +namespace own_signature +{ + + // The value a chain of casts starts from: `this.onTick` cast to the array's function type + static mlir::Value castRoot(mlir::Value value) + { + while (auto castOp = value.getDefiningOp()) + { + value = castOp.getIn(); + } + + return value; + } + + // Does a global's initializer region give it a new array - `[]`, an array literal - and nothing + // else? + static bool regionYieldsNewArray(mlir_ts::GlobalOp globalOp) + { + if (!globalOp.getInitializerRegion().hasOneBlock()) + { + return false; + } + + auto resultOp = mlir::dyn_cast(globalOp.getInitializerBlock()->getTerminator()); + if (!resultOp || resultOp->getNumOperands() != 1) + { + return false; + } + + auto *def = castRoot(resultOp->getOperand(0)).getDefiningOp(); + return mlir::isa_and_nonnull(def); + } + + void OwnershipSignaturePass::findKeepers(mlir::ModuleOp module) + { + auto uses = mlir::SymbolTable::getSymbolUses(&module.getBodyRegion()); + if (!uses) + { + return; // an op this pass cannot read symbols through: nothing is known append-only + } + + llvm::StringMap> usesOf; + for (auto &use : *uses) + { + usesOf[use.getSymbolRef().getRootReference().getValue()].push_back(use.getUser()); + } + + auto mth = typeHelper(&getContext()); + module.walk([&](mlir_ts::GlobalOp globalOp) { + auto arrayType = mlir::dyn_cast(globalOp.getType()); + if (!arrayType || globalOp->hasAttr("export") || globalOp->hasAttr("import") || globalOp->hasAttr(DLL_EXPORT) || + globalOp->hasAttr(DLL_IMPORT) || !regionYieldsNewArray(globalOp)) + { + return; + } + + // an element ts.MakeImmortal can mark, that owns a block (not a @cpp object) + auto elementType = arrayType.getElementType(); + if (!mlir::isa(elementType) || + !mth.ownsHeapMemory(globalOp.getLoc(), elementType)) + { + return; + } + + // pushed onto, its length read, its elements loaded: nothing else + llvm::SmallVector addresses; + llvm::SmallVector elementReads; + for (auto *user : usesOf.lookup(globalOp.getSymName())) + { + auto addressOfOp = mlir::dyn_cast(user); + if (!addressOfOp) + { + return; + } + + for (auto *addressUser : addressOfOp->getUsers()) + { + // in a function, which decideKeptForGood looks at: not a global's region + if (auto pushOp = mlir::dyn_cast(addressUser); + pushOp && pushOp.getOp() == addressOfOp.getResult() && + !llvm::is_contained(pushOp.getItems(), addressOfOp.getResult()) && + pushOp->getParentOfType()) + { + continue; + } + + auto loadOp = mlir::dyn_cast(addressUser); + if (!loadOp) + { + return; + } + + for (auto *arrayUser : loadOp->getUsers()) + { + if (mlir::isa(arrayUser)) + { + continue; + } + + auto elementRefOp = mlir::dyn_cast(arrayUser); + if (!elementRefOp || elementRefOp->getOperand(0) != loadOp.getResult()) + { + return; + } + + for (auto *elementUser : elementRefOp->getUsers()) + { + auto elementLoad = mlir::dyn_cast(elementUser); + if (!elementLoad) + { + return; + } + + elementReads.push_back(elementLoad); + } + } + } + + addresses.push_back(addressOfOp); + } + + keepers.insert(globalOp.getSymName()); + for (auto addressOfOp : addresses) + { + addressOfOp->setAttr(OWN_KEEPER_GLOBAL_ATTR_NAME, mlir::UnitAttr::get(&getContext())); + } + + for (auto elementLoad : elementReads) + { + elementLoad->setAttr(OWN_KEEPER_READ_ATTR_NAME, mlir::UnitAttr::get(&getContext())); + } + }); + } + + OwnershipSignaturePass::Kept OwnershipSignaturePass::classifyKept(mlir::Value value, mlir_ts::FuncOp funcOp) + { + auto root = castRoot(value); + if (holdsNoBlock(root) || isConstantData(root) || isKeptForGood(root) || isImmortalGlobalRead(root)) + { + return {KeptKind::Immortal}; + } + + int32_t index = -1; + if (readsParameterSlot(root, funcOp, index)) + { + return {KeptKind::Param, index, root}; + } + + auto *def = root.getDefiningOp(); + if (!def) + { + return {KeptKind::Unknown}; + } + + // read out of an owning local declared from it and never assigned: what it was declared from, + // the block the read is + if (auto loadOp = mlir::dyn_cast(def)) + { + auto varOp = loadOp.getReference().getDefiningOp(); + if (varOp && isOwningVariable(varOp) && !varOp.getCaptured().value_or(false) && varOp.getInitializer() && + !isAssigned(varOp)) + { + auto declared = classifyKept(varOp.getInitializer(), funcOp); + if (declared.kind == KeptKind::Mark) + { + declared.root = root; + } + + if (declared.kind == KeptKind::Mark || declared.kind == KeptKind::Immortal) + { + return declared; + } + } + + return {KeptKind::Unknown}; + } + + // a closure: its box, and the cells and values the box borrows from this frame + if (auto boundOp = mlir::dyn_cast(def)) + { + auto boxOp = boundOp.getThisVal().getDefiningOp(); + if (boxOp && boxOp->hasAttr(CAPTURE_BOX_ATTR_NAME)) + { + return {KeptKind::Mark, -1, root, boxOp.getResult()}; + } + + return {KeptKind::Unknown}; + } + + // a bound method: the object, which it holds without owning + if (mlir::isa(def) && + mlir::isa(root.getType())) + { + auto object = def->getOperand(0); + if (mlir::isa(object.getType()) && own_facts::ownsHeap(object)) + { + return {KeptKind::Mark, -1, root}; + } + + return {KeptKind::Unknown}; + } + + // made here: an object, an array, a string + if (mlir::isa(root.getType()) && + own_facts::ownsHeap(root) && isFresh(root)) + { + return {KeptKind::Mark, -1, root}; + } + + return {KeptKind::Unknown}; + } + + llvm::SmallVector OwnershipSignaturePass::calleesImmortalize(const Callees &callees, bool &disagree) + { + disagree = false; + if (callees.viaCallback) + { + return {}; + } + + // the functions it may reach; a call this pass knows nothing else of - another module's + // function, which says what it keeps for good in its declaration - by the symbols it names + llvm::SmallVector funcs(callees.funcs.begin(), callees.funcs.end()); + if (funcs.empty()) + { + for (auto name : callees.named) + { + if (auto funcOp = functions.lookup(name.getValue())) + { + funcs.push_back(funcOp); + } + else + { + return {}; + } + } + } + + std::optional> common; + for (auto callee : funcs) + { + auto found = immortalizes.find(callee); + llvm::SmallVector those; + if (found != immortalizes.end()) + { + those = found->second; + } + + if (!common) + { + common = those; + } + else if (*common != those) + { + disagree = true; + return {}; + } + } + + return common ? *common : llvm::SmallVector(); + } + + bool OwnershipSignaturePass::takesAddress(mlir_ts::FuncOp funcOp, mlir::ModuleOp module) + { + auto uses = mlir::SymbolTable::getSymbolUses(funcOp.getSymNameAttr(), &module.getBodyRegion()); + if (!uses) + { + return true; + } + + for (auto &use : *uses) + { + auto *user = use.getUser(); + // a direct call, or a virtual one, whose family is resolved; the class vtable's entry + if (mlir::isa(user) || + (mlir::isa(user) && isClassVTableEntry(user))) + { + continue; + } + + return true; + } + + return false; + } + + void OwnershipSignaturePass::makeImmortal(const Kept &kept, bool assumed) + { + auto root = kept.root; + mlir::OpBuilder builder(&getContext()); + builder.setInsertionPointAfterValue(root); + auto makeOp = builder.create(root.getLoc(), root.getType(), root, + assumed ? builder.getUnitAttr() : mlir::UnitAttr()); + root.replaceAllUsesExcept(makeOp.getResult(), makeOp); + if (!kept.box) + { + return; + } + + // what the box holds and borrows from this frame, which releases it: each captured cell, and + // each value captured by value that owns a block + for (auto *boxUser : kept.box.getUsers()) + { + auto propertyRefOp = mlir::dyn_cast(boxUser); + if (!propertyRefOp) + { + continue; + } + + for (auto *fieldUser : propertyRefOp->getUsers()) + { + auto storeOp = mlir::dyn_cast(fieldUser); + if (!storeOp || storeOp.getReference() != propertyRefOp.getResult()) + { + continue; + } + + auto captured = storeOp.getValue(); + if (mlir::isa(captured.getType())) + { + builder.create(captured.getLoc(), captured); + } + else if (own_facts::ownsHeap(captured) && !holdsNoBlock(captured)) + { + builder.create(captured.getLoc(), captured.getType(), captured, mlir::UnitAttr()); + } + } + } + } + + void OwnershipSignaturePass::decideKeptForGood(mlir::ModuleOp module) + { + // a value kept for good: a keeper's push of it, or a call's argument its callee keeps so + struct Site + { + mlir::Operation *op; + unsigned operand; + }; + + llvm::MapVector> pushes; + module.walk([&](mlir_ts::ArrayPushOp pushOp) { + auto addressOfOp = pushOp.getOp().getDefiningOp(); + auto funcOp = pushOp->getParentOfType(); + if (!addressOfOp || !addressOfOp->hasAttr(OWN_KEEPER_GLOBAL_ATTR_NAME) || !funcOp) + { + return; + } + + for (auto index : llvm::seq(1, pushOp->getNumOperands())) + { + pushes[funcOp].push_back({pushOp, index}); + } + }); + + // what declarations say: a C function that keeps a callback for good + immortalizes.clear(); + for (auto &entry : functions) + { + auto funcOp = entry.second; + if (auto declared = funcOp->getAttrOfType(OWN_DECLARED_IMMORTALIZES_ATTR_NAME); + declared && funcOp.isDeclaration()) + { + immortalizes[funcOp].assign(declared.asArrayRef().begin(), declared.asArrayRef().end()); + } + } + + auto addParam = [&](mlir_ts::FuncOp funcOp, int32_t param) { + auto ¶ms = immortalizes[funcOp]; + if (llvm::is_contained(params, param)) + { + return false; + } + + params.insert(llvm::upper_bound(params, param), param); + return true; + }; + + // a parameter pushed, or given to a callee's parameter kept for good, is kept for good + for (auto changed = true; changed;) + { + changed = false; + for (auto &[op, sites] : pushes) + { + auto funcOp = mlir::cast(op); + for (auto site : sites) + { + auto kept = classifyKept(site.op->getOperand(site.operand), funcOp); + if (kept.kind == KeptKind::Param) + { + changed |= addParam(funcOp, kept.param); + } + } + } + + for (auto &call : calls) + { + auto funcOp = call.op->getParentOfType(); + bool disagree = false; + auto args = callArgs(call.op); + for (auto index : calleesImmortalize(call.callees, disagree)) + { + if (funcOp && static_cast(index) < args.size()) + { + auto kept = classifyKept(args[index], funcOp); + if (kept.kind == KeptKind::Param) + { + changed |= addParam(funcOp, kept.param); + } + } + } + } + } + + auto failed = false; + auto describe = [](mlir_ts::FuncOp funcOp, llvm::ArrayRef params) { return describeParams(funcOp, params); }; + + // a function's callers must all know to make what they give it immortal + for (auto &entry : functions) + { + auto funcOp = entry.second; + if (funcOp.isDeclaration()) + { + continue; + } + + auto found = immortalizes.find(funcOp); + llvm::SmallVector computed; + if (found != immortalizes.end()) + { + computed = found->second; + } + + auto declared = funcOp->getAttrOfType(OWN_DECLARED_IMMORTALIZES_ATTR_NAME); + if (declared && llvm::ArrayRef(computed) != declared.asArrayRef()) + { + funcOp.emitError("'@" IMMORTALIZES_DECORATOR "' of '") + << funcOp.getSymName() << "' names " << describe(funcOp, declared.asArrayRef()) + << ", but its body keeps for good " << describe(funcOp, computed); + failed = true; + continue; + } + + if (computed.empty()) + { + continue; + } + + if (takesAddress(funcOp, module)) + { + funcOp.emitError("'") << funcOp.getSymName() << "' keeps " << describe(funcOp, computed) + << " for good, but -mm=own cannot make every caller make it immortal: the function is " + "called through a value"; + failed = true; + } + else if (!declared && open.contains(funcOp)) + { + funcOp.emitError("'") << funcOp.getSymName() << "' keeps " << describe(funcOp, computed) + << " for good, but -mm=own cannot tell its callers in other modules; '@" IMMORTALIZES_DECORATOR + "' would say it in its signature"; + failed = true; + } + } + + // a family whose members disagree: some calls of the one that keeps would not mark + for (auto &call : calls) + { + bool disagree = false; + calleesImmortalize(call.callees, disagree); + if (disagree) + { + call.op->emitError("the functions this call may reach do not all keep the same arguments for good; -mm=own " + "cannot make what it passes immortal"); + failed = true; + } + } + + if (failed) + { + signalPassFailure(); + return; + } + + // every value kept for good: immortal from where it is made, or where it is a parameter + auto decide = [&](mlir::Operation *site, mlir::Value value, mlir_ts::FuncOp funcOp, llvm::StringRef where) { + auto kept = classifyKept(value, funcOp); + switch (kept.kind) + { + case KeptKind::Immortal: + return; + case KeptKind::Param: + makeImmortal(kept, /*assumed=*/true); + return; + case KeptKind::Mark: + makeImmortal(kept, /*assumed=*/false); + return; + case KeptKind::Unknown: + site->emitError("-mm=own cannot make the value ") << where << " immortal here: it is not made here, nor a parameter"; + failed = true; + return; + } + }; + + for (auto &[op, sites] : pushes) + { + for (auto site : sites) + { + auto pushOp = mlir::cast(site.op); + auto addressOfOp = pushOp.getOp().getDefiningOp(); + decide(site.op, site.op->getOperand(site.operand), mlir::cast(op), + ("kept in '" + addressOfOp.getGlobalName() + "'").str()); + } + } + + for (auto &call : calls) + { + auto funcOp = call.op->getParentOfType(); + bool disagree = false; + auto params = calleesImmortalize(call.callees, disagree); + for (auto index : params) + { + auto args = callArgs(call.op); + if (funcOp && static_cast(index) < args.size()) + { + decide(call.op, args[index], funcOp, "given to a parameter its callee keeps for good"); + } + } + } + + if (failed) + { + signalPassFailure(); + } + } + +} // namespace own_signature + +#undef DEBUG_TYPE diff --git a/tslang/lib/TypeScript/OwnershipSignaturePass.cpp b/tslang/lib/TypeScript/OwnershipSignaturePass.cpp index 920646184..9dbe1f307 100644 --- a/tslang/lib/TypeScript/OwnershipSignaturePass.cpp +++ b/tslang/lib/TypeScript/OwnershipSignaturePass.cpp @@ -71,6 +71,9 @@ namespace own_signature }); findOpen(module); + // before the facts: a value kept for good is immortal, which keeps nothing of its owner + findKeepers(module); + decideKeptForGood(module); computeFacts(); computeDrops(); pinAssignedGlobals(); diff --git a/tslang/lib/TypeScript/OwnershipSignaturePass.h b/tslang/lib/TypeScript/OwnershipSignaturePass.h index d1220dc1e..395ebec68 100644 --- a/tslang/lib/TypeScript/OwnershipSignaturePass.h +++ b/tslang/lib/TypeScript/OwnershipSignaturePass.h @@ -108,6 +108,41 @@ class OwnershipSignaturePass : public mlir::PassWrapper keepers; + void findKeepers(mlir::ModuleOp module); + + // What a value kept for good - pushed into a keeper, or given to a parameter its callee keeps + // so - relies on, and who makes it immortal: nobody (it is already), the callers (a parameter), + // or the function that knows how it was made, which marks `root` (and a closure's `box`). + enum class KeptKind + { + Immortal, + Param, + Mark, + Unknown + }; + + struct Kept + { + KeptKind kind = KeptKind::Unknown; + int32_t param = -1; + mlir::Value root; + mlir::Value box; + }; + + Kept classifyKept(mlir::Value value, mlir_ts::FuncOp funcOp); + + // The parameters each function keeps for good (OWN_IMMORTALIZES_ATTR_NAME): a fixpoint over the + // keepers' pushes and the calls; then every value kept is made immortal (ts.MakeImmortal). + llvm::DenseMap> immortalizes; + void decideKeptForGood(mlir::ModuleOp module); + void makeImmortal(const Kept &kept, bool assumed); + // a reference to the function that is not a call, or a class vtable's entry: a caller that + // would not know to mark what it passes + bool takesAddress(mlir_ts::FuncOp funcOp, mlir::ModuleOp module); + void moveIntoGlobals(mlir::ModuleOp module); void runOnOperation() override; @@ -167,6 +202,10 @@ class OwnershipSignaturePass : public mlir::PassWrapper writtenGlobals; llvm::SmallVector calls; + // the parameters every callee of a call keeps for good (immortalizes); `disagree` when some do + // and some not + llvm::SmallVector calleesImmortalize(const Callees &callees, bool &disagree); + // Functions of imported libraries that destroy nothing a caller can reach, by the name they // are exported under (SHARED_LIB_OWN_NO_DROPS_ATTR_NAME). llvm::StringSet<> importedNoDrops; diff --git a/tslang/lib/TypeScript/StackEscapeFacts.h b/tslang/lib/TypeScript/StackEscapeFacts.h index f081378e2..9df58e127 100644 --- a/tslang/lib/TypeScript/StackEscapeFacts.h +++ b/tslang/lib/TypeScript/StackEscapeFacts.h @@ -656,6 +656,8 @@ class StackEscapeFacts return argumentEscapes(candidates, use.getOperandNumber() - 1); }) .Case([&](auto) { return "returned"; }) + // -mm=own's keepers: kept for good, it outlives every frame + .Case([&](auto) { return "kept for good"; }) .Case([&](auto) { return "thrown"; }) .Default([&](auto) { return "unclassified"; }); } diff --git a/tslang/test/tester/CMakeLists.txt b/tslang/test/tester/CMakeLists.txt index 295b8bd17..7ee8c3649 100644 --- a/tslang/test/tester/CMakeLists.txt +++ b/tslang/test/tester/CMakeLists.txt @@ -1675,8 +1675,18 @@ if (WIN32) "-DLLVM_LIB=${LLVM_LIBRARY_DIR}" "-DTSLANG_LIB=${CMAKE_BINARY_DIR}/lib" -P "${CMAKE_CURRENT_SOURCE_DIR}/own-facts-objects.cmake") + # ...and a library's keeper: the importer makes what it gives `@immortalizes` immortal + add_test(NAME test-own-keepers-objects + COMMAND ${CMAKE_COMMAND} + "-DTSLANG=$" + "-DSOURCE_DIR=${PROJECT_SOURCE_DIR}/test/tester/tests" + "-DWORK_DIR=${CMAKE_CURRENT_BINARY_DIR}/own-keepers-objects" + "-DLLVM_LIB=${LLVM_LIBRARY_DIR}" + "-DTSLANG_LIB=${CMAKE_BINARY_DIR}/lib" + -P "${CMAKE_CURRENT_SOURCE_DIR}/own-keepers-objects.cmake") endif() -# __MEMORY_MODEL__: the branch for another model is not generated (a GC_ call outside gc is an error) +# __MEMORY_MODEL__: the branch not taken is not generated (a call of a function defined nowhere there +# would not link) foreach(model_mm gc rc own none) tslang_add_test(NAME test-jit-${model_mm}-memory-model-constant COMMAND test-runner -jit -mm=${model_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00memory_model_constant.ts") tslang_add_test(NAME test-compile-${model_mm}-memory-model-constant COMMAND test-runner -mm=${model_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00memory_model_constant.ts") @@ -3867,7 +3877,7 @@ foreach(own_test own_fresh_string own_fresh_array own_return_new own_try_local o own_borrowing_record own_borrowing_record_arg own_reduce own_fresh_call_result own_ternary_outer_loop own_destructure_elements own_tuple_record_values own_value_record own_value_loop own_value_temporaries - own_call_field_drops) + own_call_field_drops own_immortal_keepers) tslang_add_test(NAME test-jit-own-${own_test} COMMAND test-runner -jit -mm=own "${PROJECT_SOURCE_DIR}/test/tester/own/${own_test}.ts") tslang_add_test(NAME test-compile-own-${own_test} COMMAND test-runner -mm=own "${PROJECT_SOURCE_DIR}/test/tester/own/${own_test}.ts") # The promise: no counting at all in what own emits. @@ -3881,7 +3891,7 @@ endforeach() # A global never reassigned is immortal under own (spec 25); the same program under every other model. foreach(immortal_mm rc gc none) - foreach(immortal_test own_immortal_global own_immortal_global_region own_global_loop_store) + foreach(immortal_test own_immortal_global own_immortal_global_region own_global_loop_store own_immortal_keepers) tslang_add_test(NAME test-jit-${immortal_mm}-${immortal_test} COMMAND test-runner -jit -mm=${immortal_mm} "${PROJECT_SOURCE_DIR}/test/tester/own/${immortal_test}.ts") tslang_add_test(NAME test-compile-${immortal_mm}-${immortal_test} COMMAND test-runner -mm=${immortal_mm} "${PROJECT_SOURCE_DIR}/test/tester/own/${immortal_test}.ts") endforeach() @@ -4291,11 +4301,11 @@ set(own_error_cases "own_err_field_alias|:9:11: error: '[^']*' is used here after its value was moved" "own_err_call_in_try_drops|:30:11: error: '[^']*' borrows a field but is used here after it may be released or overwritten" "own_err_closure_escape_used|:9:11: error: '[^']*' is captured by a closure that escapes, and is still used here" - "own_err_closure_escape_twice|:7:19: error: '[^']*' is captured by a closure that escapes, and is still used here" + "own_err_closure_escape_twice|:12:19: error: '[^']*' is captured by a closure that escapes, and is still used here" "own_err_closure_escape_param|:7:12: error: a closure that escapes owns what it captures, but -mm=own cannot move this variable into it: its value is the caller's" "own_err_closure_escape_inherited|:9:21: error: a closure that escapes owns what it captures, but -mm=own cannot move this variable into it: it is captured from an enclosing function" - "own_err_closure_escape_loop|:11:23: error: '[^']*' is moved inside a loop but was made outside it" - "own_err_closure_escape_some_paths|:12:23: error: '[^']*' is moved here on some paths only" + "own_err_closure_escape_loop|:16:23: error: '[^']*' is moved inside a loop but was made outside it" + "own_err_closure_escape_some_paths|:17:23: error: '[^']*' is moved here on some paths only" "own_err_closure_outlives_cell|:13:11: error: '[^']*' borrows '[^']*', which it captures, but runs here after '[^']*' is released" "own_err_closure_copy_moved|:13:11: error: '[^']*' borrows '[^']*', which it captures, but runs here after '[^']*' is released" "own_err_closure_param_assigned|:9:5: error: '[^']*' is a captured parameter and cannot be assigned under -mm=own: its value is the caller's" @@ -4539,7 +4549,12 @@ set(own_error_cases "own_err_record_without_lends|:11:1: error: '@record' of 'pairOf' says its result is a borrowing record, but no '@lends' names what it borrows" "own_err_record_not_record|:7:1: error: '@record' of 'first' says its result is a record that borrows 'a', but its body returns a borrow of it as it is" "own_err_record_exported_unsaid|:12:1: error: 'pairOf' returns a record that borrows 'a', 'b', which another module can learn only from '@record' beside its '@lends'" - "own_err_value_export_borrowing|:13:1: error: 'wrap' returns a tuple that borrows 'n' and owns nothing, which -mm=own cannot tell another module yet") + "own_err_value_export_borrowing|:13:1: error: 'wrap' returns a tuple that borrows 'n' and owns nothing, which -mm=own cannot tell another module yet" + "own_err_keeper_unknown_value|:11:5: error: -mm=own cannot make the value kept in 'retained' immortal here: it is not made here, nor a parameter" + "own_err_keeper_exported|:7:5: error: 'Registry[.]register' keeps '#1' for good, but -mm=own cannot tell its callers in other modules. '@immortalizes' would say it in its signature" + "own_err_keeper_declared|:5:1: error: '@immortalizes' of 'keep' names 'a', but its body keeps for good 'b'" + "own_err_keeper_called_through_value|:6:1: error: 'keep' keeps '#0' for good, but -mm=own cannot make every caller make it immortal: the function is called through a value" + "own_err_keeper_popped|:14:9: error: argument '[^']*' is given to 'Registry[.]register', which keeps it, but -mm=own cannot move it here") foreach(own_error_case ${own_error_cases}) string(FIND "${own_error_case}" "|" own_error_sep) string(SUBSTRING "${own_error_case}" 0 ${own_error_sep} own_error_name) @@ -5264,7 +5279,7 @@ set(stack_promotion_decision_tests "ctor_local|ctor_local\.ts:14:19: remark: stack-promotion: stack" "borrow_uses|borrow_uses\.ts:17:15: remark: stack-promotion: stack.*borrow_uses\.ts:18:15: remark: stack-promotion: stack" "pass_to_reader|pass_to_reader\.ts:18:19: remark: stack-promotion: stack" - "pass_to_keeper|pass_to_keeper\.ts:16:15: remark: stack-promotion: heap: argument" + "pass_to_keeper|pass_to_keeper\.ts:16:15: remark: stack-promotion: heap: (argument|kept for good)" "method_keeps_this|method_keeps_this\.ts:15:15: remark: stack-promotion: heap: argument" "virtual_one_keeps|virtual_one_keeps\.ts:26:18: remark: stack-promotion: heap: argument" "ctor_keeps_this|ctor_keeps_this\.ts:13:15: remark: stack-promotion: heap: argument" diff --git a/tslang/test/tester/own-keepers-objects.cmake b/tslang/test/tester/own-keepers-objects.cmake new file mode 100644 index 000000000..e048bddf3 --- /dev/null +++ b/tslang/test/tester/own-keepers-objects.cmake @@ -0,0 +1,54 @@ +# -mm=own's keepers across two modules compiled into objects of their own and linked into one program +# (docs/superpowers/specs/2026-10-25-own-immortal-keepers-design.md): own_keepers_lib.ts keeps the +# callbacks it is given for good, and says so with `@immortalizes`; own_keepers_main.ts registers a +# bound method and a closure from functions that return before the callbacks run. The importer reads +# the marker from the library's declaration and makes what it passes immortal, so the program runs +# with the right numbers after the memory its locals released is handed out again. + +cmake_minimum_required(VERSION 3.17.3) + +foreach(var TSLANG SOURCE_DIR WORK_DIR LLVM_LIB TSLANG_LIB) + if(NOT DEFINED ${var}) + message(FATAL_ERROR "${var} is required") + endif() +endforeach() + +set(ENV{GC_LIB_PATH} "") +set(ENV{TSLANG_LIB_PATH} "") + +file(REMOVE_RECURSE "${WORK_DIR}") +file(MAKE_DIRECTORY "${WORK_DIR}") +# the importer finds `./own_keepers_lib` beside it, as a source to read declarations from +foreach(file own_keepers_lib.ts own_keepers_main.ts) + file(COPY "${SOURCE_DIR}/${file}" DESTINATION "${WORK_DIR}") +endforeach() + +function(tslang_run what) + execute_process(COMMAND "${TSLANG}" ${ARGN} + WORKING_DIRECTORY "${WORK_DIR}" + OUTPUT_VARIABLE out + ERROR_VARIABLE err + RESULT_VARIABLE status) + set(status "${status}" PARENT_SCOPE) + set(output "${out}${err}" PARENT_SCOPE) +endfunction() + +tslang_run(lib --emit=obj -mm=own own_keepers_lib.ts -o own_keepers_lib.obj) +if(NOT status EQUAL 0 OR output MATCHES "error:|Stack dump") + message(FATAL_ERROR "own_keepers_lib: exit ${status}\n${output}") +endif() + +tslang_run(link --emit=exe -mm=own "--llvm-lib-path=${LLVM_LIB}" "--tslang-lib-path=${TSLANG_LIB}" + --own-facts=own_keepers_lib.obj --obj=own_keepers_lib.obj own_keepers_main.ts -o own_keepers.exe) +if(NOT status EQUAL 0 OR output MATCHES "error:|Stack dump") + message(FATAL_ERROR "linking own_keepers: exit ${status}\n${output}") +endif() + +execute_process(COMMAND "${WORK_DIR}/own_keepers.exe" + WORKING_DIRECTORY "${WORK_DIR}" + OUTPUT_VARIABLE out + ERROR_VARIABLE err + RESULT_VARIABLE status) +if(NOT status EQUAL 0 OR NOT "${out}" MATCHES "^2 102 2[\r\n]+done[.]") + message(FATAL_ERROR "own_keepers.exe: exit ${status}\n${out}${err}") +endif() diff --git a/tslang/test/tester/own/own_err_closure_escape_loop.ts b/tslang/test/tester/own/own_err_closure_escape_loop.ts index 063a72905..e30b573d5 100644 --- a/tslang/test/tester/own/own_err_closure_escape_loop.ts +++ b/tslang/test/tester/own/own_err_closure_escape_loop.ts @@ -5,6 +5,11 @@ class C { let handlers: (() => number)[] = []; +// emptied, so no keeper: what it holds may be released (a keeper's would be immortal) +function reset() { + handlers.length = 0; +} + function register() { let a = new C(1); for (let i = 0; i < 3; i++) { diff --git a/tslang/test/tester/own/own_err_closure_escape_some_paths.ts b/tslang/test/tester/own/own_err_closure_escape_some_paths.ts index ecacec09c..7e64e4d19 100644 --- a/tslang/test/tester/own/own_err_closure_escape_some_paths.ts +++ b/tslang/test/tester/own/own_err_closure_escape_some_paths.ts @@ -6,6 +6,11 @@ class C { let handlers: (() => number)[] = []; +// emptied, so no keeper: what it holds may be released (a keeper's would be immortal) +function reset() { + handlers.length = 0; +} + function register(keep: boolean) { let a = new C(1); if (keep) { diff --git a/tslang/test/tester/own/own_err_closure_escape_twice.ts b/tslang/test/tester/own/own_err_closure_escape_twice.ts index fb0175a2d..b6f44f248 100644 --- a/tslang/test/tester/own/own_err_closure_escape_twice.ts +++ b/tslang/test/tester/own/own_err_closure_escape_twice.ts @@ -1,6 +1,11 @@ // -mm=own, phase 5b rejects: two closures that escape cannot both own `n`. let handlers: (() => number)[] = []; +// emptied, so no keeper: what it holds may be released (a keeper's would be immortal) +function reset() { + handlers.length = 0; +} + function register() { let n: number = 0; handlers.push(() => ++n); diff --git a/tslang/test/tester/own/own_err_keeper_called_through_value.ts b/tslang/test/tester/own/own_err_keeper_called_through_value.ts new file mode 100644 index 000000000..b28fd78f3 --- /dev/null +++ b/tslang/test/tester/own/own_err_keeper_called_through_value.ts @@ -0,0 +1,16 @@ +// A function that keeps a parameter for good, passed on as a function value: whoever calls it +// through that value would not know to make the argument immortal. +type Callback = (n: number) => void; +let retained: Callback[] = []; + +function keep(h: Callback) { + retained.push(h); +} + +function apply(f: (h: Callback) => void) { + f((n: number) => {}); +} + +function main() { + apply(keep); +} diff --git a/tslang/test/tester/own/own_err_keeper_declared.ts b/tslang/test/tester/own/own_err_keeper_declared.ts new file mode 100644 index 000000000..f3e18da9d --- /dev/null +++ b/tslang/test/tester/own/own_err_keeper_declared.ts @@ -0,0 +1,12 @@ +// `@immortalizes` is checked against the body: it names 'a', but the body keeps 'b' for good. +type Callback = (n: number) => void; +let retained: Callback[] = []; + +@immortalizes("a") +function keep(a: Callback, b: Callback) { + retained.push(b); +} + +function main() { + keep((n: number) => {}, (n: number) => {}); +} diff --git a/tslang/test/tester/own/own_err_keeper_exported.ts b/tslang/test/tester/own/own_err_keeper_exported.ts new file mode 100644 index 000000000..74f9cdfe4 --- /dev/null +++ b/tslang/test/tester/own/own_err_keeper_exported.ts @@ -0,0 +1,10 @@ +// A function another module may call that keeps a parameter for good has to say so: its callers in +// other modules make the argument immortal only if they know. +type Callback = (n: number) => void; +let retained: Callback[] = []; + +export class Registry { + register(handler: Callback): void { + retained.push(handler); + } +} diff --git a/tslang/test/tester/own/own_err_keeper_popped.ts b/tslang/test/tester/own/own_err_keeper_popped.ts new file mode 100644 index 000000000..30fa5c68e --- /dev/null +++ b/tslang/test/tester/own/own_err_keeper_popped.ts @@ -0,0 +1,23 @@ +// An array an element is taken out of is no keeper: what it holds may be released, so the push is +// the move it always was, and a bound method of the caller's object cannot be given up. +type Callback = (n: number) => void; +let retained: Callback[] = []; + +class Registry { + register(handler: Callback): void { + retained.push(handler); + } +} + +class Counter { + constructor(registry: Registry) { + registry.register(this.onTick); + } + + onTick(n: number): void {} +} + +function main() { + const c = new Counter(new Registry()); + retained.pop(); +} diff --git a/tslang/test/tester/own/own_err_keeper_unknown_value.ts b/tslang/test/tester/own/own_err_keeper_unknown_value.ts new file mode 100644 index 000000000..223010024 --- /dev/null +++ b/tslang/test/tester/own/own_err_keeper_unknown_value.ts @@ -0,0 +1,16 @@ +// A keeper's push of a value this function did not make and is no parameter of it - a field's +// function value - cannot be made immortal: only its maker knows what it relies on. +type Callback = (n: number) => void; +let retained: Callback[] = []; + +class H { + cb: Callback = (n: number) => {}; +} + +function keep(h: H) { + retained.push(h.cb); +} + +function main() { + keep(new H()); +} diff --git a/tslang/test/tester/own/own_immortal_keepers.ts b/tslang/test/tester/own/own_immortal_keepers.ts new file mode 100644 index 000000000..d894ffc39 --- /dev/null +++ b/tslang/test/tester/own/own_immortal_keepers.ts @@ -0,0 +1,108 @@ +// A module-level array that is only ever pushed onto - a keeper - keeps what it holds to the end of +// the program, so under -mm=own a value pushed into it is made immortal where it is known what it +// relies on (docs/superpowers/specs/2026-10-25-own-immortal-keepers-design.md): a bound method's +// object, a closure's box and the cells it borrows, an object pushed directly. The owners' releases +// then free nothing, and the callbacks still run after the functions that registered them return +// and the memory they released is handed out again. +type Callback = (n: number) => void; +let retained: Callback[] = []; + +class Registry { + register(handler: Callback): void { + retained.push(handler); + handler(0); // still the caller's to use after the push + } +} + +class Counter { + count: number[] = [0.0]; + constructor(registry: Registry) { + registry.register(this.onTick); // the object is main's, and kept for good + } + onTick(n: number): void { + this.count[0] += n; + } +} + +// a parameter passed on: the caller makes it immortal +function forward(r: Registry, h: Callback): void { + r.register(h); +} + +// said, as a function another module may call has to +@immortalizes("h") +export function forwardExported(h: Callback): void { + new Registry().register(h); +} + +class Node { + constructor(public v: number) {} +} + +let nodes: Node[] = []; + +let sums: number[] = [0.0, 0.0, 0.0, 0.0]; + +function setupBound(): Counter { + return new Counter(new Registry()); +} + +function setupClosure(): void { + const total = [100.0]; + new Registry().register((n: number) => { total[0] += n; sums[0] = total[0]; }); + total[0] += 1.0; // the frame still uses what the closure captured +} + +function setupForward(): void { + const box = [7.0]; + forward(new Registry(), (n: number) => { box[0] += n; sums[1] = box[0]; }); +} + +function setupExported(): void { + const box = [20.0]; + forwardExported((n: number) => { box[0] += n; sums[2] = box[0]; }); +} + +function setupNodes(): void { + nodes.push(new Node(5)); + const local = new Node(6); + nodes.push(local); // and still the local's + sums[3] = local.v; +} + +class Holder { + first: Callback; + constructor() { this.first = retained[0]; } // a keeper's element goes anywhere +} + +function churn(): number { + let sum = 0.0; + for (let i = 0; i < 20000; i++) { + const a = [i * 1.0, 2.0, 3.0]; + sum += a[0]; + } + return sum; +} + +function main() { + const counter = setupBound(); + setupClosure(); + setupForward(); + setupExported(); + setupNodes(); + churn(); + for (let k = 0; k < 3; k++) { + for (const cb of retained) { + cb(1); + } + + churn(); + } + + const holder = new Holder(); + holder.first(10); + print(counter.count[0], sums[0], sums[1], sums[2], nodes[0].v + nodes[1].v, retained.length); + assert(counter.count[0] == 13 && sums[0] == 104 && sums[1] == 10 && sums[2] == 23); + assert(nodes[0].v + nodes[1].v == 11 && sums[3] == 6 && retained.length == 4); + print("done."); +} diff --git a/tslang/test/tester/tests/own_keepers_lib.ts b/tslang/test/tester/tests/own_keepers_lib.ts new file mode 100644 index 000000000..d43619b2d --- /dev/null +++ b/tslang/test/tester/tests/own_keepers_lib.ts @@ -0,0 +1,17 @@ +// The library half of own-keepers-objects.cmake: a keeper - an array only ever pushed onto - and the +// function that keeps a callback in it for good. Another module calls it, so it says so with +// `@immortalizes`, and each caller makes what it passes immortal. +let retained: ((n: number) => void)[] = []; + +@immortalizes("handler") +export function register(handler: (n: number) => void): void { + retained.push(handler); +} + +export function runAll(n: number): number { + for (const cb of retained) { + cb(n); + } + + return retained.length; +} diff --git a/tslang/test/tester/tests/own_keepers_main.ts b/tslang/test/tester/tests/own_keepers_main.ts new file mode 100644 index 000000000..150686bb8 --- /dev/null +++ b/tslang/test/tester/tests/own_keepers_main.ts @@ -0,0 +1,50 @@ +// The program half of own-keepers-objects.cmake: it registers a bound method of an object and a +// closure over a local with another module's `register`, which keeps them for good, from functions +// that return before they run. Reading the declaration's `@immortalizes`, -mm=own makes the object, +// the box and the cell immortal here, so they outlive their owners' releases. +import { register, runAll } from "./own_keepers_lib"; + +let results: number[] = [0.0, 0.0]; + +class Counter { + count: number[] = [0.0]; + + constructor() { + register(this.onTick); + } + + onTick(n: number): void { + this.count[0] += n; + results[0] = this.count[0]; + } +} + +function setupBound(): void { + const c = new Counter(); +} + +function setupClosure(): void { + const total = [100.0]; + register((n: number) => { total[0] += n; results[1] = total[0]; }); +} + +function churn(): number { + let sum = 0.0; + for (let i = 0; i < 20000; i++) { + const a = [i * 1.0, 2.0]; + sum += a[0]; + } + + return sum; +} + +function main() { + setupBound(); + setupClosure(); + churn(); + runAll(1); + churn(); + const kept = runAll(1); + print(results[0], results[1], kept); // 2 102 2 + print("done."); +}