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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions TSLANG_ISSUES.md
Original file line number Diff line number Diff line change
Expand Up @@ -4385,3 +4385,35 @@ Test `00tslang_issue_224.ts` (all models); `own_counted_let_without_value`, `own
field's type (one only), so the object is counted with both owners, as rc counts it.

Tests `own_counted_global_read_overwritten`, `own_fallback_constructor_kept_second_owner`.

226. The Debug-compiler suite, and a double free under -mm=own (2026-11-29).
- **-mm=own: one string put into a tuple twice was freed twice.** `<[V, V]>[value, value]` yielded by a generator
(it reads its state's slot twice) and `const p = <[string, string]>[s, s]` gave the tuple two owners of one string,
and its release gave it back twice: the program hung or crashed at exit (a Set's entries() made so). After the
analysis each repeat of a string in a tuple - the same value, or a read of the same place - is a copy of its own
(an object given twice is still refused as a use after its move).
- **The Debug-compiler suite on the rebuilt Debug LLVM: 153 of 10,139 failed.** Fixed here:
- a generator's return() result literal had no source span, and its storage name came from an empty span: about
80 generator tests (and callee_non_null, iterable_string_for_of, 217) stopped on `loc_->pos != loc_->_end`. It
takes the body's span (the generator object has the function's);
- a cast of an interface, or of `null | V` of a @value V, to `null` reached castLLVMTypes' "review usage" stop
(class_to_interface_null, value_missing_niche): a value seen as `null` is the null pointer;
- a closure's function type compared with a function type had its captures compared with the first parameter
(generic_arrow_any): they are skipped, as a receiver is;
- `const { 0: a } = t` read its key with IntegerAttr::getInt() on an `si32` (declarationsAndAssignments);
- `resolveModuleFile` assigned a path its own parent, a view into itself (ambient_module_import; undefined
behaviour in Release too);
- `x.w ??= v` of a @weak field read its view after storing the right side had erased it (own_weak_field_logical).
- `tsbindgen -o -` closed stdout, which its stream does not own (LLVM's `ShouldClose` assert): it is flushed.
Rerun by name on the Debug compiler, 139 of the 153 pass. Still open: under a Debug compiler's JIT
own_counted_list_cut_in_step crashes before it prints (its exe, and the Release compiler's JIT, print 2; the
IR the two compilers make is the same); crash-errors huge-object-type-from-any times out (300 s) in a Debug
compiler; and in a Debug build tree the tests that build an optimized exe link the tree's debug-CRT runtime
(`_CrtDbgReport` unresolved, LNK2038: gc-opt-uncaught-throw_*, atomic-rc, foreign-thread-gc,
borrow-facts-defaultlib), as on 11-13. The Debug tree's CMake cache also named MSVC 14.51's lib.exe and link.exe
(borrow-facts-*): cleared and reconfigured locally.
- `Map.entries()` yields `[k, v]` tuples and `Set.entries()` `[v, v]`, as in JavaScript (DefaultLib #125).
- Re-checked, not a leak: an rc async function with a catch and a finally that awaits. Its peak grows in 32 MB steps
of the allocator and falls back while it runs (34-98 MB over 2M-6M calls), with or without the catch.

Test `00tuple_repeated_string` (all models).
1 change: 1 addition & 0 deletions docs/whats-new.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
# What's new

- `Map.entries()` gives `[key, value]` tuples and `Set.entries()` `[value, value]`, as in JavaScript (`JSON.stringify` writes them as arrays); under -mm=own a string put into one tuple twice is no longer freed twice; a debug compiler no longer stops on generators, a cast of an interface to `null`, or a closure given where a function of `any` is expected
- -mm=own: a local holding a global's value can be used after the global is given another one (`const n = G; G = mk(); print(n.x)`, or after a call that assigns `G`): it takes a reference of its own where own can't prove the borrow; the debug compiler no longer asserts on `<f32>"2.5"` or `<bigint>"7"`
- -mm=own: `c ? e : new B(1)` of a borrow `e` compiles (the merge takes a reference of its own to the borrow), and so does `let x: C;` declared without a value and given one later, a field's or a global's value too (it owns what it is given, counted where own can't prove the move)
- `{ ...src, k: 3 }` has the `k` written after the spread (it kept src's); under -mm=own a spread of a literal holding a new string no longer leaks it, and `<{ code: number }>a` of an `any` can be cast more than once, and of a box holding `{ code: 7 }`
Expand Down
8 changes: 8 additions & 0 deletions tslang/include/TypeScript/LowerToLLVM/CastLogicHelper.h
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,14 @@ class CastLogicHelper
return in;
}

// A value seen as `null` (a narrowing to the null side: an interface, `null | V` of a @value V) is the null
// pointer, whatever it was. Not a cast of its bytes: an interface's two words or a union's tag and payload
// reached castLLVMTypes as a struct to a pointer, its "review usage" stop in a debug compiler
if (isa<mlir_ts::NullType>(resType) && isa<LLVM::LLVMPointerType>(resLLVMType))
{
return rewriter.create<LLVM::ZeroOp>(loc, resLLVMType);
}

// `unknown` is the box `any` is (MLIRGenImpl::cast boxes into it and unboxes out of it)
if ((isa<mlir_ts::AnyType>(inType) && isa<mlir_ts::UnknownType>(resType))
|| (isa<mlir_ts::UnknownType>(inType) && isa<mlir_ts::AnyType>(resType)))
Expand Down
13 changes: 10 additions & 3 deletions tslang/include/TypeScript/MLIRLogic/MLIRTypeHelper.h
Original file line number Diff line number Diff line change
Expand Up @@ -1543,9 +1543,16 @@ class MLIRTypeHelper
LLVM_DEBUG(llvm::dbgs() << "\n!!"
<< "@ TestFunctionTypesMatchWithObjectMethods:" << inFuncType << " -> " << resFuncType << "\n";);

// TODO: seems capture function with wrong function type
assert(startParamIn > 0 || inFuncType.getNumInputs() == 0
|| startParamIn == 0 && inFuncType.getNumInputs() > 0 && !isRefTuple(inFuncType.getInput(0)));
// A function of a closure takes its captures first, a reference to their tuple (`ref<tuple<...>>`): no parameter
// a caller gives, so it is skipped as a receiver is below (generic_arrow_any: an arrow given where a function of
// `any` is expected, asserted in a debug compiler and compared the captures with the first parameter)
// (the same captures on both sides are compared as they are, as any parameters)
auto inCaptures = startParamIn == 0 && inFuncType.getNumInputs() > 0 && isRefTuple(inFuncType.getInput(0));
auto resCaptures = startParamRes == 0 && resFuncType.getNumInputs() > 0 && isRefTuple(resFuncType.getInput(0));
if (inCaptures && !resCaptures)
{
startParamIn = 1;
}

// 1 we need to skip opaque and objects
// TODO: we need to refactor func types the way that we can understand if this is func with "captured var", bound to object etc
Expand Down
12 changes: 6 additions & 6 deletions tslang/lib/TypeScript/MLIRGenClasses.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -3092,25 +3092,25 @@ namespace mlirgen
return viewOp->getAttrOfType<mlir::StringAttr>(WEAK_FIELD_VIEW_ATTR_NAME);
}

mlir::Value MLIRGenImpl::weakFieldReread(mlir::Location location, mlir_ts::SafeCastOp viewOp, mlir::Value loaded,
const GenContext &genContext)
mlir::Value MLIRGenImpl::weakFieldReread(mlir::Location location, mlir::Type viewType, mlir::StringAttr name,
mlir::Value loaded, const GenContext &genContext)
{
auto weakRefType = mlir::cast<mlir_ts::WeakRefType>(loaded.getType());
auto derefOp = builder.create<mlir_ts::WeakRefDerefOp>(location, weakRefType.getElementType(), loaded);
derefOp.setChecked(true);
if (auto name = weakFieldNameOf(viewOp))
if (name)
{
derefOp.setWeakFieldAttr(name);
}

auto castValue = weakFieldValue(location, derefOp.getResult(), viewOp.getType(), genContext);
auto castValue = weakFieldValue(location, derefOp.getResult(), viewType, genContext);
if (!castValue)
{
return mlir::Value();
}

auto rereadOp = builder.create<mlir_ts::SafeCastOp>(location, viewOp.getType(), castValue, loaded);
if (auto name = weakFieldNameOf(viewOp))
auto rereadOp = builder.create<mlir_ts::SafeCastOp>(location, viewType, castValue, loaded);
if (name)
{
rereadOp->setAttr(WEAK_FIELD_VIEW_ATTR_NAME, name);
}
Expand Down
10 changes: 9 additions & 1 deletion tslang/lib/TypeScript/MLIRGenFunctions.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1515,7 +1515,15 @@ namespace mlirgen
NodeArray<Statement> statements;
statements.push_back(nf.createIfStatement(paused(), nf.createBlock(resume, false), undefined));
statements.push_back(finished());
statements.push_back(nf.createReturnStatement(nf.createObjectLiteralExpression(resultProperties, false)));
// (its storage is named after its location: the body's span, which no other literal of the generator has - the
// generator object takes the function's. With none, the name came from an empty span, which a debug
// compiler stopped on, and two generators at one position would have shared it)
auto result = nf.createObjectLiteralExpression(resultProperties, false);
auto spanOf = functionLikeDeclarationBaseAST->body ? static_cast<Node>(functionLikeDeclarationBaseAST->body)
: static_cast<Node>(functionLikeDeclarationBaseAST);
result->pos = spanOf->pos;
result->_end = spanOf->_end;
statements.push_back(nf.createReturnStatement(result));
addMethod("return", parameters, statements);
}

Expand Down
21 changes: 16 additions & 5 deletions tslang/lib/TypeScript/MLIRGenImpl.h
Original file line number Diff line number Diff line change
Expand Up @@ -8575,6 +8575,15 @@ class MLIRGenImpl
auto result = mlirGen(leftExpression, genContext);
EXIT_IF_FAILED_OR_NO_VALUE(result)
auto leftExpressionValue = V(result);
// a @weak field's view (own spec 93), taken now: storing the right side drops the view once nothing uses
// it (dropWeakFieldView), and asking it afterwards read the erased op
mlir::Type weakViewType;
mlir::StringAttr weakViewName;
if (auto viewOp = weakFieldView(leftExpressionValue))
{
weakViewType = viewOp.getType();
weakViewName = viewOp->getAttrOfType<mlir::StringAttr>(WEAK_FIELD_VIEW_ATTR_NAME);
}

// only a place read by a load is read again (through a test's narrowing of it); an accessor's
// getter is not run twice: it is stored the merge, as before
Expand Down Expand Up @@ -8651,9 +8660,9 @@ class MLIRGenImpl

auto reloaded = builder.create<mlir_ts::LoadOp>(location, leftLoad.getType(), reference);
// a @weak field (own spec 93): read again as its declared type, checked
if (auto viewOp = weakFieldView(leftExpressionValue))
if (weakViewType)
{
return V(weakFieldReread(location, viewOp, reloaded, genContext));
return V(weakFieldReread(location, weakViewType, weakViewName, reloaded, genContext));
}

return V(reloaded);
Expand Down Expand Up @@ -21331,8 +21340,9 @@ class MLIRGenImpl
mlir::Value loaded, const GenContext &genContext);
mlir::Value weakFieldValue(mlir::Location location, mlir::Value pointer, mlir::Type declaredType,
const GenContext &genContext);
// own spec 93: `loaded`, the slot read again, as the checked read `viewOp` is
mlir::Value weakFieldReread(mlir::Location location, mlir_ts::SafeCastOp viewOp, mlir::Value loaded,
// own spec 93: `loaded`, the slot read again, as the checked read of the view of type `viewType` (naming the
// field `name`, when it has one) is. The view's type and name, not the view: it may be gone by then
mlir::Value weakFieldReread(mlir::Location location, mlir::Type viewType, mlir::StringAttr name, mlir::Value loaded,
const GenContext &genContext);
// own spec 93: the view weakFieldRead made, if `value` is one (or a test's narrowing of one)
mlir_ts::SafeCastOp weakFieldView(mlir::Value value);
Expand Down Expand Up @@ -23400,7 +23410,8 @@ class MLIRGenImpl
break;
}

folder = parent;
// (`parent` points into `folder`, a prefix of it: assigning it read the buffer being written)
folder.resize(parent.size());
}

return std::nullopt;
Expand Down
3 changes: 2 additions & 1 deletion tslang/lib/TypeScript/MLIRGenVariables.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1099,7 +1099,8 @@ namespace mlirgen
// an index past a tuple's elements (`const { 3: d } = t` of a `[boolean, string, number]`) failed without
// an error
auto checkIndex = [&](auto tupleType) {
auto index = mlir::cast<mlir::IntegerAttr>(fieldName).getInt();
// (a literal key is an `si32` constant: getInt() asserts on a signed type, getValue() reads any)
auto index = mlir::cast<mlir::IntegerAttr>(fieldName).getValue().getSExtValue();
if (tupleType.getIndex(fieldName) < 0 && (index < 0 || static_cast<size_t>(index) >= tupleType.size()))
{
emitError(location) << "a tuple of type '" << to_print(type) << "' has no element at index "
Expand Down
51 changes: 51 additions & 0 deletions tslang/lib/TypeScript/OwnershipInferencePass.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -198,8 +198,59 @@ namespace own_inference
}
}

// A string put into one tuple twice (`<[V, V]>[value, value]`, a generator's `yield [v, v]` reading its state's slot
// twice): the tuple owns each of its fields, and its release gave the one string back twice - a double free (a
// set's entries() under -mm=own, TSLANG 225). Each repeat is a copy of its own, as a string given a second owner
// is. A repeat is the same value, or a read of the same place (two loads through one reference, nothing stored in
// between). An object given twice is refused by the move checks (a use after its move) and stays so.
static void copyRepeatedTupleStrings(mlir::Operation *function)
{
llvm::SmallVector<mlir_ts::CreateTupleOp> tuples;
function->walk([&](mlir_ts::CreateTupleOp createTupleOp) { tuples.push_back(createTupleOp); });
for (auto createTupleOp : tuples)
{
llvm::SmallDenseMap<mlir::Value, unsigned, 4> seen;
for (auto &operand : createTupleOp->getOpOperands())
{
auto value = operand.get();
if (!isCopyableString(value.getType()))
{
continue;
}

auto key = value;
if (auto loadOp = value.getDefiningOp<mlir_ts::LoadOp>(); loadOp && loadOp->getBlock() == createTupleOp->getBlock())
{
// (a store through the same reference between the two reads gives the second a value of its own)
auto storedBetween = false;
for (auto *op = loadOp->getNextNode(); op && op != createTupleOp.getOperation(); op = op->getNextNode())
{
if (auto storeOp = mlir::dyn_cast<mlir_ts::StoreOp>(op); storeOp && storeOp.getReference() == loadOp.getReference())
{
storedBetween = true;
}
}

key = storedBetween ? value : loadOp.getReference();
}

if (seen.try_emplace(key, operand.getOperandNumber()).second)
{
continue;
}

mlir::OpBuilder builder(createTupleOp);
auto copy = builder.create<mlir_ts::StringCopyOp>(createTupleOp->getLoc(), value.getType(), value);
operand.set(copy);
}
}
}

void OwnershipInferencePass::runOnFunction()
{
// (after the analysis has decided rc's ops: the copy is then the repeat's own reference, which nothing else gives it)
auto copyRepeats = llvm::make_scope_exit([&]() { copyRepeatedTupleStrings(getFunction()); });

// what the real run may do that the dry run did not: only where the dry run failed, so a
// function today's analysis accepts is decided as it was
localLetCandidates.clear();
Expand Down
6 changes: 6 additions & 0 deletions tslang/test/tester/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -2678,6 +2678,12 @@ foreach(issue224_mm gc rc none own)
tslang_add_test(NAME test-jit-00tslang_issue_224-${issue224_mm} COMMAND test-runner -jit -mm=${issue224_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00tslang_issue_224.ts")
tslang_add_test(NAME test-compile-00tslang_issue_224-${issue224_mm} COMMAND test-runner -mm=${issue224_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00tslang_issue_224.ts")
endforeach()
# TSLANG 225: a string put into one tuple twice (a generator's `yield [v, v]`, a Set's entries()) - under -mm=own its
# release gave it back twice
foreach(tuple_repeat_mm gc rc none own)
tslang_add_test(NAME test-jit-00tuple_repeated_string-${tuple_repeat_mm} COMMAND test-runner -jit -mm=${tuple_repeat_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00tuple_repeated_string.ts")
tslang_add_test(NAME test-compile-00tuple_repeated_string-${tuple_repeat_mm} COMMAND test-runner -mm=${tuple_repeat_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/00tuple_repeated_string.ts")
endforeach()
# ...and what was refused for it, accepted since TSLANG 219 (USER RULING 11-27): an argument and a borrow neither of
# which this function owns (two parameters, `this` and a parameter), the array a loop reads emptied by the call, a
# field given a value it does not make - the borrowing local takes a reference of its own
Expand Down
56 changes: 56 additions & 0 deletions tslang/test/tester/tests/00tuple_repeated_string.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
// TSLANG 225: one string put into a tuple twice, in every memory model. Under -mm=own the tuple owns each of its fields,
// and its release gave the one string back twice - a double free: a generator yielding `<[V, V]>[value, value]` (a
// Set's entries()) hung or crashed at exit, and `const p = <[string, string]>[s, s]` freed `s` twice. Each repeat is
// a copy of its own now.
class Bag {
items: string[] = [];

@borrows("this")
*pairs() {
for (let i = 0; i < this.items.length; i++) {
const value = this.items[i];
yield <[string, string]>[value, value];
}
}
}

class Junk {
constructor(public s: string) {}
}

function churn() {
const junk: Junk[] = [];
for (let i = 0; i < 64; i++) {
junk.push(new Junk("j" + i));
}
}

function twice(k: number): number {
const s = "s" + k;
const p = <[string, string]>[s, s];
churn();
return p[0].length + p[1].length;
}

function main() {
let total: number = 0;
for (let k = 0; k < 100; k++) {
const b = new Bag();
b.items.push("a" + k);
b.items.push("b" + k);
for (const [x, y] of b.pairs()) {
assert(x == y, "the same value");
total += x.length + y.length;
}

for (const e of b.pairs()) {
total += e[0].length + e[1].length;
}

total += twice(k);
}

print(total);
assert(total == 2900, "the total");
print("done.");
}
11 changes: 10 additions & 1 deletion tslang/tsbindgen/tsbindgen.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -261,7 +261,16 @@ int main(int argc, char **argv)
}

out << printed->text;
out.close();
// (`-o -` is stdout, which the stream does not own: close() asserts there, so it is flushed instead)
if (outputFile.getValue() == "-")
{
out.flush();
}
else
{
out.close();
}

if (out.has_error())
{
llvm::WithColor::error(llvm::errs(), "tsbindgen") << "cannot write '" << outputFile << "'\n";
Expand Down
Loading