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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -5352,3 +5352,29 @@ from a `let` declared in it and from one given anew in it, churning between step
none; the ownership verifier is silent on it. `own_err_let_field_{global,read_again,loop,captured}` stay
borrows; so do a parameter or a mix of a parameter and a fresh object given to the local, and a `let h =
r` read after.

## 66. An object literal whose arrows capture, given later to an object type, 2026-10-29

`const k = 2; const o = { w: (x: number) => x * k }; apply(o)` for `apply(o: { w: (x: number) =>
number })` was `'this value' borrows a field and cannot be stored, returned or captured` (spec 62 left
an arrow that names a local around it a method bound to the literal). The cast to the parameter's object
type reads each member out of the literal (`ts.Cast` of the object to its storage, a `ts.PropertyRef`
and a `Load` of each field: a method bound to the literal) and makes the parameter's tuple of them
(`ts.CreateTuple`). The members stay methods; the call borrows them.

- **The tuple passes the borrow on** (`passesOn`): what the tuple is given to has the bound method, and
is walked as it. A store, a return or a call that keeps the tuple still keeps the borrow.
- **The object is the chain's root** (`chainOf`): a field read through the object seen as its storage
has the object above it, owned when this function made it. Before, the cast was the root, owned by no
one, and so any call - the very call given the tuple - might drop it.
- **Neither moves the object** (`isBorrow`): the cast to its storage when only its fields are reached
through it (each read is a place read, as `o.w` straight off the object is), and a tuple made of a
value only to be given to calls that keep none of it, released by nothing.

`own_literal_captures` gives such literals (a number captured, a string captured by two members) to an
object-type parameter, calls a member after, gives the literal again and to an interface, churning
between steps, under own, rc, gc and none.

Not here: a literal whose arrow captures an object (`const b = new Box(5); const q = { w: (x: number) =>
x * b.n }`) moves the object into the literal's `.captured`, so `b` cannot be used after it under own,
where a closure capturing it only borrows it (§16).
7 changes: 6 additions & 1 deletion tslang/include/TypeScript/Defines.h
Original file line number Diff line number Diff line change
Expand Up @@ -488,7 +488,12 @@
// Fields may be added, but never reordered or resized, and a new one goes immediately before
// the block header, which has to stay last - see TYPE_DESCR_BLOCK_HEADER.
#define TYPE_DESCR_KIND 0
#define TYPE_DESCR_RESERVED 1
// For a tuple, an id of its layout - its fields' names and types (TypeOfOpHelper::layoutIdOf) -
// and 0 for anything else. A cast from `any` to an object type compares it with the type's own
// (ts.IsTupleOfLayout): the box says only "tuple", and a tuple of other fields read as the type's
// was garbage (`{ n: 5 }` holds an s32, read as a number). Computed from the type's text, so a
// tuple boxed by one module matches the same type in another.
#define TYPE_DESCR_LAYOUT 1
// Address of the type's release routine, or null when the type owns no heap memory - null
// says "nothing to release", not "unknown". Generated by OwnershipRoutineLogic.
#define TYPE_DESCR_RELEASE 2
Expand Down
7 changes: 4 additions & 3 deletions tslang/include/TypeScript/LowerToLLVM/LLVMCodeHelper.h
Original file line number Diff line number Diff line change
Expand Up @@ -354,7 +354,7 @@ class LLVMCodeHelper : public LLVMCodeHelperBase
// capture box); it is not part of the name the record carries.
mlir::Value getOrCreateTypeDescriptorName(mlir::Type type, std::string name, int kind,
StringRef releaseRoutineName, StringRef retainRoutineName,
StringRef variant = "")
StringRef variant = "", uint32_t layout = 0)
{
auto loc = op->getLoc();
auto parentModule = op->getParentOfType<ModuleOp>();
Expand Down Expand Up @@ -390,8 +390,9 @@ class LLVMCodeHelper : public LLVMCodeHelperBase
mlir::Value recordValue = rewriter.create<LLVM::UndefOp>(loc, recordType);
setStructValue(loc, recordValue, rewriter.create<LLVM::ConstantOp>(loc, i32Ty, rewriter.getI32IntegerAttr(kind)),
TYPE_DESCR_KIND);
setStructValue(loc, recordValue, rewriter.create<LLVM::ConstantOp>(loc, i32Ty, rewriter.getI32IntegerAttr(0)),
TYPE_DESCR_RESERVED);
setStructValue(loc, recordValue,
rewriter.create<LLVM::ConstantOp>(loc, i32Ty, rewriter.getI32IntegerAttr((int32_t)layout)),
TYPE_DESCR_LAYOUT);
// empty when the type owns no heap memory, which a null slot states positively:
// "nothing to release", rather than leaving it unknown
mlir::Value releaseValue =
Expand Down
11 changes: 10 additions & 1 deletion tslang/include/TypeScript/LowerToLLVM/TypeDescriptorLogic.h
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ class TypeDescriptorLogic
{
}

// { i32 kind, i32 reserved, ptr release, index blockHeader }
// { i32 kind, i32 layout, ptr release, ptr retain, index blockHeader }
static LLVM::LLVMStructType getRecordType(mlir::OpBuilder &builder, mlir::Type llvmIndexType)
{
auto i32Ty = builder.getI32Type();
Expand Down Expand Up @@ -78,6 +78,15 @@ class TypeDescriptorLogic
return rewriter.create<LLVM::LoadOp>(loc, th.getI32Type(), kindPtr);
}

// TYPE_DESCR_LAYOUT of the type this tag names
mlir::Value getLayoutFromTag(mlir::Value tagValue)
{
auto recordPtr = getRecordPtrFromTag(tagValue);
auto layoutPtr = rewriter.create<LLVM::GEPOp>(loc, th.getPtrType(), getRecordType(), recordPtr,
ArrayRef<LLVM::GEPArg>{0, TYPE_DESCR_LAYOUT});
return rewriter.create<LLVM::LoadOp>(loc, th.getI32Type(), layoutPtr);
}

mlir::Value isKind(mlir::Value tagValue, int kind)
{
auto kindValue = getKindFromTag(tagValue);
Expand Down
60 changes: 60 additions & 0 deletions tslang/include/TypeScript/MLIRLogic/TypeOfOpHelper.h
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
#include "TypeScript/TypeScriptOps.h"

#include "llvm/ADT/StringSwitch.h"
#include "llvm/Support/xxhash.h"

#define DEBUG_TYPE "mlir"

Expand Down Expand Up @@ -99,6 +100,65 @@ class TypeOfOpHelper
.Default(TYPE_KIND_UNKNOWN);
}

// A tuple's layout as text: its fields' names and types, with a literal field as its type
// (`{ n: 5 }` holds an s32) and a const tuple as the tuple it is, so a literal and the object
// type that names the same fields read alike.
static void layoutText(mlir::Type type, llvm::raw_ostream &os)
{
if (auto literalType = dyn_cast<mlir_ts::LiteralType>(type))
{
layoutText(literalType.getElementType(), os);
return;
}

llvm::ArrayRef<mlir_ts::FieldInfo> fields;
if (auto tupleType = dyn_cast<mlir_ts::TupleType>(type))
{
fields = tupleType.getFields();
}
else if (auto constTupleType = dyn_cast<mlir_ts::ConstTupleType>(type))
{
fields = constTupleType.getFields();
}
else
{
type.print(os);
return;
}

os << "{";
for (auto &field : fields)
{
if (field.id)
{
field.id.print(os);
}

os << ":";
layoutText(field.type, os);
os << ",";
}

os << "}";
}

// TYPE_DESCR_LAYOUT of a type's descriptor: an id of a tuple's layout text (never 0), and 0 for
// anything else. A hash of the text, not of the type: the type's own hash differs between
// modules, which a tuple boxed in one and cast in another must not.
static uint32_t layoutIdOf(mlir::Type type)
{
if (!isa<mlir_ts::TupleType, mlir_ts::ConstTupleType>(type))
{
return 0;
}

std::string text;
llvm::raw_string_ostream os(text);
layoutText(type, os);
auto id = (uint32_t)llvm::xxh3_64bits(os.str());
return id ? id : 1;
}

std::string typeOfAsString(mlir::Type type)
{
if (type.isIntOrIndex() && !type.isIndex())
Expand Down
12 changes: 12 additions & 0 deletions tslang/include/TypeScript/TypeScriptOps.td
Original file line number Diff line number Diff line change
Expand Up @@ -501,6 +501,18 @@ def TypeScript_TypeOfAnyOp : TypeScript_Op<"TypeOfAny", [Pure]> {
let results = (outs TypeScript_String:$typeOf);
}

def TypeScript_IsTupleOfLayoutOp : TypeScript_Op<"IsTupleOfLayout", [Pure]> {
let summary = "whether an any holds a tuple of a type's layout";
let description = [{
True when the box $value holds a tuple whose fields have the names and types of $layoutType's:
the TYPE_DESCR_LAYOUT of the box's tag is $layoutType's. A cast from `any` to an object type
reads the box as that type's layout, which another tuple's is not (`{ n: 5 }` holds an s32).
}];

let arguments = (ins TypeScript_Any:$value, TypeAttr:$layoutType);
let results = (outs TypeScript_Boolean:$res);
}

def TypeScript_TypeDescriptorOp : TypeScript_Op<"TypeDescriptor", [Pure]> {
let summary = "type name from the static descriptor of a type";
let description = [{
Expand Down
2 changes: 1 addition & 1 deletion tslang/lib/TypeScript/LowerToAffineLoops.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2946,7 +2946,7 @@ void AddTsAffineLegalOps(ConversionTarget &target)
mlir_ts::EndCatchOp, mlir_ts::BeginCleanupOp, mlir_ts::EndCleanupOp, mlir_ts::ThrowUnwindOp,
mlir_ts::ThrowCallOp, mlir_ts::SymbolCallInternalOp, mlir_ts::CallInternalOp, mlir_ts::ReturnInternalOp,
mlir_ts::NoOp, mlir_ts::SwitchStateInternalOp, mlir_ts::UnreachableOp, mlir_ts::GlobalConstructorOp, mlir_ts::AppendToUsedOp,
mlir_ts::CreateBoundFunctionOp, mlir_ts::TypeOfAnyOp, mlir_ts::BoxOp, mlir_ts::UnboxOp,
mlir_ts::CreateBoundFunctionOp, mlir_ts::TypeOfAnyOp, mlir_ts::IsTupleOfLayoutOp, mlir_ts::BoxOp, mlir_ts::UnboxOp,
mlir_ts::CreateUnionInstanceOp, mlir_ts::GetValueFromUnionOp, mlir_ts::GetTypeInfoFromUnionOp,
mlir_ts::OptionalOp, mlir_ts::OptionalValueOp, mlir_ts::OptionalUndefOp,
mlir_ts::LoadLibraryPermanentlyOp, mlir_ts::SearchForAddressOfSymbolOp,
Expand Down
27 changes: 25 additions & 2 deletions tslang/lib/TypeScript/LowerToLLVM.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -480,7 +480,8 @@ class TypeDescriptorOpLowering : public TsLlvmPattern<mlir_ts::TypeDescriptorOp>

rewriter.replaceOp(op, ch.getOrCreateTypeDescriptorName(descriptorType, name,
TypeOfOpHelper::typeKindFromName(name),
releaseRoutineName, retainRoutineName, variant));
releaseRoutineName, retainRoutineName, variant,
TypeOfOpHelper::layoutIdOf(descriptorType)));

return success();
}
Expand Down Expand Up @@ -7829,6 +7830,28 @@ struct TypeOfOpLowering : public TsLlvmPattern<mlir_ts::TypeOfOp>
}
};

struct IsTupleOfLayoutOpLowering : public TsLlvmPattern<mlir_ts::IsTupleOfLayoutOp>
{
using TsLlvmPattern<mlir_ts::IsTupleOfLayoutOp>::TsLlvmPattern;

LogicalResult matchAndRewrite(mlir_ts::IsTupleOfLayoutOp op, Adaptor transformed,
ConversionPatternRewriter &rewriter) const final
{
auto loc = op.getLoc();

TypeHelper th(rewriter);
TypeConverterHelper tch(getTypeConverter());

AnyLogic al(op, rewriter, tch, loc, tsLlvmContext->compileOptions);
TypeDescriptorLogic tdl(rewriter, tch, loc);
auto layout = tdl.getLayoutFromTag(al.getTypeOfAny(transformed.getValue()));
auto expected = rewriter.create<LLVM::ConstantOp>(
loc, th.getI32Type(), rewriter.getI32IntegerAttr((int32_t)TypeOfOpHelper::layoutIdOf(op.getLayoutType())));
rewriter.replaceOpWithNewOp<LLVM::ICmpOp>(op, LLVM::ICmpPredicate::eq, layout, expected);
return success();
}
};

struct TypeOfAnyOpLowering : public TsLlvmPattern<mlir_ts::TypeOfAnyOp>
{
using TsLlvmPattern<mlir_ts::TypeOfAnyOp>::TsLlvmPattern;
Expand Down Expand Up @@ -9494,7 +9517,7 @@ void TypeScriptToLLVMLoweringPass::runOnOperation()
LoadSaveValueLowering, ThrowUnwindOpLowering, ThrowCallOpLowering, VariableOpLowering, DebugVariableOpLowering, AllocaOpLowering, InvokeOpLowering, AccessorUnwindEdgeOpLowering,
InvokeHybridOpLowering, VirtualSymbolRefOpLowering, ThisVirtualSymbolRefOpLowering, ThisSymbolRefOpLowering, InterfaceSymbolRefOpLowering,
NewInterfaceOpLowering, VTableOffsetRefOpLowering, LoadBoundRefOpLowering, StoreBoundRefOpLowering, CreateBoundRefOpLowering,
CreateBoundFunctionOpLowering, GetThisOpLowering, GetMethodOpLowering, TypeOfOpLowering, TypeOfAnyOpLowering, DebuggerOpLowering,
CreateBoundFunctionOpLowering, GetThisOpLowering, GetMethodOpLowering, TypeOfOpLowering, TypeOfAnyOpLowering, IsTupleOfLayoutOpLowering, DebuggerOpLowering,
UnreachableOpLowering, SymbolCallInternalOpLowering, CallInternalOpLowering, CallHybridInternalOpLowering,
ReturnInternalOpLowering, NoOpLowering, GlobalConstructorOpLowering, AppendToUsedOpLowering, ExtractInterfaceThisOpLowering,
ExtractInterfaceVTableOpLowering, BoxOpLowering, UnboxOpLowering, DialectCastOpLowering, CreateUnionInstanceOpLowering,
Expand Down
10 changes: 7 additions & 3 deletions tslang/lib/TypeScript/MLIRGenCast.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2744,8 +2744,8 @@ namespace mlirgen
// read out of it, and anything else - a class object, a number - throws. It was read as the tuple's
// layout whatever it held (`(<{ f: F }>x).f = g` with a class object in `x` wrote over its vtable).
// `___check_tuple` only asks the box (it keeps nothing of it); the read after it is the raw one it
// was. A tuple of another layout passes the check: the box names no tuple's fields (`{ n: 5 }`
// holds an s32, read as a number).
// was. A tuple of other fields throws too: its descriptor's layout id is not the type's
// (ts.IsTupleOfLayout) - `{ n: 5 }` holds an s32, which was read as a number.
ValueOrLogicalResult MLIRGenImpl::castAnyToTuple(mlir::Location location, mlir::Type type, mlir::Value value,
const GenContext &genContext)
{
Expand All @@ -2756,8 +2756,10 @@ namespace mlirgen
removeGenericFunctionMap(funcName);

stringstream ss;
ss << S("function __check_tuple<T>(a: any) {\n");
ss << S("function __check_tuple<T>(a: any, sameLayout: boolean) {\n");
ss << S("if (typeof a != 'tuple') throw \"Can't cast from any: the value is not an object of type '")
<< stows(to_print(type)) << S("'\";\n");
ss << S("if (!sameLayout) throw \"Can't cast from any: the object's fields are not those of type '")
<< stows(to_print(type)) << S("'\";\n}\n");

auto src = ss.str();
Expand All @@ -2780,8 +2782,10 @@ namespace mlirgen
GenContext funcCallGenContext(genContext);
funcCallGenContext.typeAliasMap.insert({".TYPE_ALIAS_T", type});

// asked before the call: every box's tag has a descriptor, a tuple's or not
SmallVector<mlir::Value, 4> operands;
operands.push_back(value);
operands.push_back(builder.create<mlir_ts::IsTupleOfLayoutOp>(location, getBooleanType(), value, mlir::TypeAttr::get(type)));

NodeFactory nf(NodeFactoryFlags::None);
auto checked = mlirGenCallExpression(
Expand Down
9 changes: 9 additions & 0 deletions tslang/lib/TypeScript/OwnershipInferenceBorrowers.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -273,6 +273,15 @@ namespace own_inference
return true;
}

// a tuple made of it only to be given to calls that keep none of it (isBorrow): the calls have
// it (an object literal's method, bound to the literal, read into the object type a parameter
// is - `applyT(p)` of a literal whose arrows capture, spec 66). Any other tuple keeps it.
if (mlir::isa<mlir_ts::CreateTupleOp>(user) && isBorrow(user, use.get()))
{
values.push_back(user->getResult(0));
return true;
}

// one of the values a select chooses between, not its condition
if (auto selectOp = mlir::dyn_cast<mlir::arith::SelectOp>(user); selectOp && use.get() != selectOp.getCondition())
{
Expand Down
25 changes: 24 additions & 1 deletion tslang/lib/TypeScript/OwnershipInferenceMoves.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -428,7 +428,7 @@ namespace own_inference

// a test - `if (d)`, `d?.x`, `typeof u` - asks about the value, and keeps nothing
if (mlir::isa<mlir_ts::HasValueOp, mlir_ts::GetTypeInfoFromUnionOp, mlir_ts::TypeOfOp,
mlir_ts::TypeOfAnyOp>(user))
mlir_ts::TypeOfAnyOp, mlir_ts::IsTupleOfLayoutOp>(user))
{
return true;
}
Expand Down Expand Up @@ -481,6 +481,18 @@ namespace own_inference
}
}

// ...and so does an object seen as the storage it points at, when only its fields are reached
// through it: each read of one is a place read (checkPlaceRead), as `o.w` straight off the
// object is. A cast to an object type reads an object literal's fields so (spec 66).
if (auto castOp = mlir::dyn_cast<mlir_ts::CastOp>(user);
castOp && mlir::isa<mlir_ts::ObjectType>(castOp.getIn().getType()) && mlir::isa<mlir_ts::RefType>(castOp.getType()))
{
auto storage = castOp.getResult();
return !storage.use_empty() && llvm::all_of(storage.getUsers(), [](mlir::Operation *storageUser) {
return mlir::isa<mlir_ts::PropertyRefOp>(storageUser);
});
}

// ...and so does a cast to `null` or `undefined`, which holds no block: `--di` records the
// `r` that `if (r == null)` narrows as one
if (auto castOp = mlir::dyn_cast<mlir_ts::CastOp>(user))
Expand All @@ -501,6 +513,17 @@ namespace own_inference
return !isKeptArgument(user, value);
}

// ...and so is a tuple made of it only to be given to calls that keep none of it, and that
// nothing releases: an object literal's method bound to it, read into the object type a
// parameter is (`applyT(p)`, spec 66)
if (auto createTupleOp = mlir::dyn_cast<mlir_ts::CreateTupleOp>(user))
{
auto tuple = createTupleOp.getResult();
return !tuple.use_empty() && llvm::all_of(tuple.getUses(), [&](mlir::OpOperand &use) {
return isCall(use.getOwner()) && !isCalleeOperand(use) && !isKeptArgument(use.getOwner(), tuple);
});
}

// the array being pushed onto is written, not taken; what is inserted is taken
if (auto pushOp = mlir::dyn_cast<mlir_ts::ArrayPushOp>(user))
{
Expand Down
11 changes: 11 additions & 0 deletions tslang/lib/TypeScript/OwnershipInferencePlaceReads.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -389,6 +389,17 @@ namespace own_inference
continue;
}

// an object seen as the storage it points at, its fields read through it: the object
// (an object literal this function made is its own, `applyT(p)` of one whose arrows
// capture reads a method bound to it into the parameter's object type)
if (auto castOp = base.getDefiningOp<mlir_ts::CastOp>();
castOp && mlir::isa<mlir_ts::ObjectType>(castOp.getIn().getType()) &&
mlir::isa<mlir_ts::RefType>(castOp.getType()))
{
bases.push_back(rootOf(castOp.getIn()));
continue;
}

// a result that borrows an argument is somewhere under the argument
if (auto *call = borrowingCall(base))
{
Expand Down
Loading
Loading