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
12 changes: 12 additions & 0 deletions tslang/include/TypeScript/TypeScriptOps.td
Original file line number Diff line number Diff line change
Expand Up @@ -942,6 +942,18 @@ def TypeScript_InvokeOp : TypeScript_Op<"Invoke", [
let hasVerifier = 1;
}

// Ends the block of a load or a store through an interface's field inside a `try` (mayCallInterfaceAccessor):
// the slot may name a cell, whose getter or setter the access calls once lowered to LLVM, where it is an invoke
// unwinding to `unwindDest`. Until then this edge keeps the landing block, which may have no other predecessor,
// and shows the analyses that the access may leave for it. Lowered to a branch to `normalDest`.
def TypeScript_AccessorUnwindEdgeOp : TypeScript_Op<"AccessorUnwindEdge", [
DeclareOpInterfaceMethods<BranchOpInterface>,
Terminator
]> {
let successors = (successor AnySuccessor:$normalDest,
AnySuccessor:$unwindDest);
}

def TypeScript_InvokeHybridOp : TypeScript_Op<"InvokeHybrid", [
AttrSizedOperandSegments,
DeclareOpInterfaceMethods<BranchOpInterface>,
Expand Down
37 changes: 37 additions & 0 deletions tslang/include/TypeScript/TypeScriptPassContext.h
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
#include "TypeScript/Defines.h"
#include "TypeScript/TypeScriptDialect.h"
#include "TypeScript/TypeScriptOps.h"
#include "TypeScript/DataStructs.h"
Expand Down Expand Up @@ -180,8 +181,44 @@ struct TSFunctionContext
TSFunctionContext() = default;

mlir::SmallVector<mlir::Block *> stateLabels;

// the loads and stores through an interface's field inside a `try`, and the blocks their accessor calls unwind
// to (the innermost try's, which comes last): AccessorUnwindEdgeOps once the function is lowered
mlir::SmallVector<std::pair<Operation *, mlir::Block *>> accessorUnwinds;
};

// A reference through an interface's field whose slot may name a cell of accessors (INTERFACE_ACCESSOR_CELL_TAG)
// instead of an offset: a field not optional, not function-typed, not a write of either kind.
inline bool isInterfaceAccessorCellRef(mlir::Value reference)
{
auto interfaceSymbolRefOp = reference.getDefiningOp<mlir_ts::InterfaceSymbolRefOp>();
if (!interfaceSymbolRefOp || interfaceSymbolRefOp.getOptional().value_or(false)
|| interfaceSymbolRefOp->hasAttr(INTERFACE_FUNCTION_FIELD_WRITE_ATTR)
|| interfaceSymbolRefOp->hasAttr(INTERFACE_OPTIONAL_WRITE_ATTR))
{
return false;
}

auto refType = dyn_cast<mlir_ts::RefType>(interfaceSymbolRefOp.getType());
return refType && !isa<mlir_ts::FunctionType>(refType.getElementType());
}

// a load or a store that may call an interface field's getter or setter
inline bool mayCallInterfaceAccessor(Operation *op)
{
if (auto loadOp = dyn_cast<mlir_ts::LoadOp>(op))
{
return isInterfaceAccessorCellRef(loadOp.getReference());
}

if (auto storeOp = dyn_cast<mlir_ts::StoreOp>(op))
{
return isInterfaceAccessorCellRef(storeOp.getReference());
}

return false;
}

template <typename OpTy> class TsPattern : public OpRewritePattern<OpTy>
{
public:
Expand Down
41 changes: 40 additions & 1 deletion tslang/lib/TypeScript/LowerToAffineLoops.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1889,6 +1889,7 @@ struct TryOpLowering : public TsPattern<mlir_ts::TryOp>
auto exitBlock = finallyHasOps ? exitBlockLast : continuation;
auto landingBlock = cleanupHasOps ? cleanupBlock : catchHasOps ? catchesBlock : finallyBlock;
tsContext->landingBlockOf[tryOp.getOperation()] = landingBlock;

if (landingBlock)
{
// TODO: check for nested ops for example in if block
Expand All @@ -1902,6 +1903,10 @@ struct TryOpLowering : public TsPattern<mlir_ts::TryOp>
{
tsContext->unwind[op] = landingBlock;
}
else if (mayCallInterfaceAccessor(op))
{
tsFuncContext->accessorUnwinds.push_back({op, landingBlock});
}
};
auto it = bodyBlock;
do
Expand Down Expand Up @@ -2101,6 +2106,10 @@ struct TryOpLowering : public TsPattern<mlir_ts::TryOp>
{
tsContext->unwind[op] = finallyBlock;
}
else if (mayCallInterfaceAccessor(op))
{
tsFuncContext->accessorUnwinds.push_back({op, finallyBlock});
}
};

if (catchesBlock)
Expand Down Expand Up @@ -2929,7 +2938,7 @@ void AddTsAffineLegalOps(ConversionTarget &target)
mlir_ts::LoadOp, mlir_ts::LoadSaveOp, mlir_ts::NewOp, mlir_ts::CreateTupleOp, mlir_ts::DeconstructTupleOp, mlir_ts::CreateArrayOp,
mlir_ts::NewEmptyArrayOp, mlir_ts::NewArrayOp, mlir_ts::DeleteOp, mlir_ts::PropertyRefOp, mlir_ts::InsertPropertyOp,
mlir_ts::ExtractPropertyOp, mlir_ts::LogicalBinaryOp, mlir_ts::UndefOp, mlir_ts::VariableOp, mlir_ts::DebugVariableOp, mlir_ts::AllocaOp,
mlir_ts::InvokeOp, /*mlir_ts::ResultOp,*/ mlir_ts::VirtualSymbolRefOp, mlir_ts::ThisVirtualSymbolRefOp, mlir_ts::ThisSymbolRefOp, mlir_ts::InterfaceSymbolRefOp,
mlir_ts::InvokeOp, mlir_ts::AccessorUnwindEdgeOp, /*mlir_ts::ResultOp,*/ mlir_ts::VirtualSymbolRefOp, mlir_ts::ThisVirtualSymbolRefOp, mlir_ts::ThisSymbolRefOp, mlir_ts::InterfaceSymbolRefOp,
mlir_ts::ExtractInterfaceThisOp, mlir_ts::ExtractInterfaceVTableOp, mlir_ts::ArrayPushOp, mlir_ts::ArrayPopOp,
mlir_ts::ArrayUnshiftOp, mlir_ts::ArrayShiftOp, mlir_ts::ArraySpliceOp, mlir_ts::ArrayViewOp,
mlir_ts::NewInterfaceOp, mlir_ts::VTableOffsetRefOp, mlir_ts::GetThisOp, mlir_ts::GetMethodOp, mlir_ts::DebuggerOp,
Expand Down Expand Up @@ -2968,6 +2977,8 @@ void AddTsAffinePatterns(MLIRContext &context, ConversionTarget &target, Rewrite
&context, &tsContext, &tsFuncContext);
}

static void addAccessorUnwindEdges(TSFunctionContext &tsFuncContext);

void TypeScriptToAffineLoweringTSFuncPass::runOnFunction()
{
auto function = getFunction();
Expand Down Expand Up @@ -3034,6 +3045,8 @@ void TypeScriptToAffineLoweringTSFuncPass::runOnFunction()
signalPassFailure();
}

addAccessorUnwindEdges(tsFuncContext);

LLVM_DEBUG(llvm::dbgs() << "\n!! Processing function: \n" << function.getName() << "\n";);

cleanupEmptyBlocksWithoutPredecessors(function);
Expand All @@ -3043,6 +3056,32 @@ void TypeScriptToAffineLoweringTSFuncPass::runOnFunction()
LLVM_DEBUG(verifyFunction(function););
}

// Each load or store through an interface's field inside a `try` ends its block with an AccessorUnwindEdgeOp to the
// block its getter or setter call unwinds to - now that the function is one CFG, the try and every region around
// the access lowered into it.
static void addAccessorUnwindEdges(TSFunctionContext &tsFuncContext)
{
llvm::MapVector<Operation *, mlir::Block *> unwindOf;
for (auto [op, unwindBlock] : tsFuncContext.accessorUnwinds)
{
unwindOf[op] = unwindBlock;
}

for (auto [op, unwindBlock] : unwindOf)
{
if (!unwindBlock || !unwindBlock->getParent() || op->getParentRegion() != unwindBlock->getParent())
{
continue;
}

auto *block = op->getBlock();
auto *continuation = block->splitBlock(std::next(op->getIterator()));
OpBuilder builder(op->getContext());
builder.setInsertionPointToEnd(block);
builder.create<mlir_ts::AccessorUnwindEdgeOp>(op->getLoc(), continuation, unwindBlock);
}
}

void TypeScriptToAffineLoweringFuncPass::runOnOperation()
{
auto function = getOperation();
Expand Down
110 changes: 91 additions & 19 deletions tslang/lib/TypeScript/LowerToLLVM.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,27 @@ static mlir::Value nullStringAsText(mlir::Location loc, mlir::Value text, Conver
return rewriter.create<LLVM::SelectOp>(loc, isNull, nullText, text);
}

static bool isInsidePresplitCoroutine(mlir::Operation *op);

// A function with Windows exception funclets: a variable-size alloca in it moves the stack, and an exception
// thrown by a call in a catch and caught by a typed catch of the same function then has the CRT write its catch
// object at the wrong address (a crash, or the wrong value).
static bool isInsideFunctionWithFunclets(mlir::Operation *op, const CompileOptions &compileOptions)
{
if (!compileOptions.isWindows)
{
return false;
}

if (auto llvmFuncOp = op->getParentOfType<LLVM::LLVMFuncOp>())
{
return llvmFuncOp.getPersonality().has_value();
}

auto funcOp = op->getParentOfType<mlir_ts::FuncOp>();
return funcOp && funcOp.getPersonality().value_or(false);
}

class PrintOpLowering : public TsLlvmPattern<mlir_ts::PrintOp>
{
public:
Expand Down Expand Up @@ -207,7 +228,20 @@ class PrintOpLowering : public TsLlvmPattern<mlir_ts::PrintOp>
}

auto size = values.size();
if (size > 1)
if (size > 1 && (isInsidePresplitCoroutine(op) || isInsideFunctionWithFunclets(op, tsLlvmContext->compileOptions)))
{
// the line on the heap, let go once written: no variable-size alloca where one breaks (see above)
mlir::Value result =
rewriter.create<mlir_ts::StringConcatOp>(loc, strType, values, rewriter.getBoolAttr(false));

mlir::Value valueAsLLVMType = rewriter.create<mlir_ts::DialectCastOp>(loc, tch.convertType(strType), result);
mlir::Value valueAsPtr = rewriter.create<LLVM::BitcastOp>(loc, ptrType, valueAsLLVMType);

rewriter.create<LLVM::CallOp>(loc, putsFuncOp, valueAsPtr);

ch.MemoryFree(valueAsPtr);
}
else if (size > 1)
{
// TODO: review, why we need stack recovery here
auto stack = rewriter.create<LLVM::StackSaveOp>(loc, i8PtrType);
Expand Down Expand Up @@ -571,20 +605,12 @@ struct InterfaceAccessorCell
static std::optional<InterfaceAccessorCell> of(mlir::Value reference, ConversionPatternRewriter &rewriter,
const CompileOptions &compileOptions)
{
auto interfaceSymbolRefOp = reference.getDefiningOp<mlir_ts::InterfaceSymbolRefOp>();
if (!interfaceSymbolRefOp || interfaceSymbolRefOp.getOptional().value_or(false)
|| interfaceSymbolRefOp->hasAttr(INTERFACE_FUNCTION_FIELD_WRITE_ATTR)
|| interfaceSymbolRefOp->hasAttr(INTERFACE_OPTIONAL_WRITE_ATTR))
{
return std::nullopt;
}

auto refType = dyn_cast<mlir_ts::RefType>(interfaceSymbolRefOp.getType());
if (!refType || isa<mlir_ts::FunctionType>(refType.getElementType()))
if (!isInterfaceAccessorCellRef(reference))
{
return std::nullopt;
}

auto interfaceSymbolRefOp = reference.getDefiningOp<mlir_ts::InterfaceSymbolRefOp>();
TypeHelper th(rewriter);
auto loc = interfaceSymbolRefOp.getLoc();
auto interfaceVal = rewriter.getRemappedValue(interfaceSymbolRefOp.getInterfaceVal());
Expand All @@ -603,6 +629,41 @@ struct InterfaceAccessorCell
return InterfaceAccessorCell{isCell, thisVal, slotValue, intPtrType, static_cast<unsigned>(sizeBits)};
}

// the block a load or a store in a `try` unwinds to: the AccessorUnwindEdgeOp after it says
static mlir::Block *unwindBlockOf(mlir::Operation *op)
{
auto edgeOp = dyn_cast_or_null<mlir_ts::AccessorUnwindEdgeOp>(op->getNextNode());
return edgeOp ? edgeOp.getUnwindDest() : nullptr;
}

// a call of the getter or the setter, as an invoke unwinding to `unwindBlock` in a `try`
static mlir::Value call(mlir::Location loc, ConversionPatternRewriter &rewriter, mlir::Type resultType,
ValueRange operands, mlir::Block *unwindBlock)
{
TypeHelper th(rewriter);
auto isVoid = isa<LLVM::LLVMVoidType>(resultType);
if (!unwindBlock)
{
SmallVector<mlir::Type> argTypes;
for (auto operand : operands.drop_front())
{
argTypes.push_back(operand.getType());
}

auto callOp = rewriter.create<LLVM::CallOp>(loc, LLVM::LLVMFunctionType::get(resultType, argTypes), operands);
return isVoid ? mlir::Value() : callOp.getResult();
}

auto *block = rewriter.getInsertionBlock();
auto *normalBlock = rewriter.splitBlock(block, rewriter.getInsertionPoint());
rewriter.setInsertionPointToEnd(block);
auto invokeOp = rewriter.create<LLVM::InvokeOp>(loc, isVoid ? TypeRange{} : TypeRange{resultType},
mlir::FlatSymbolRefAttr(), operands, normalBlock, ValueRange{},
unwindBlock, ValueRange{});
rewriter.setInsertionPointToStart(normalBlock);
return isVoid ? mlir::Value() : invokeOp.getResult();
}

// the getter (index 0) or the setter (1) out of the cell
mlir::Value accessor(mlir::Location loc, ConversionPatternRewriter &rewriter, int index)
{
Expand Down Expand Up @@ -2833,6 +2894,19 @@ struct CallHybridInternalOpLowering : public TsLlvmPattern<mlir_ts::CallHybridIn
}
};

struct AccessorUnwindEdgeOpLowering : public TsLlvmPattern<mlir_ts::AccessorUnwindEdgeOp>
{
using TsLlvmPattern<mlir_ts::AccessorUnwindEdgeOp>::TsLlvmPattern;

LogicalResult matchAndRewrite(mlir_ts::AccessorUnwindEdgeOp op, Adaptor transformed,
ConversionPatternRewriter &rewriter) const final
{
// the access before it unwinds there by an invoke of its own, when the slot is a cell
rewriter.replaceOpWithNewOp<LLVM::BrOp>(op, ValueRange{}, op.getNormalDest());
return success();
}
};

struct InvokeOpLowering : public TsLlvmPattern<mlir_ts::InvokeOp>
{
using TsLlvmPattern<mlir_ts::InvokeOp>::TsLlvmPattern;
Expand Down Expand Up @@ -5163,10 +5237,9 @@ struct LoadOpLowering : public TsLlvmPattern<mlir_ts::LoadOp>
{
// the field filled by a getter: call it
auto getterCallFunc = [&](OpBuilder &builder, Location location) -> mlir::Value {
TypeHelper th(rewriter);
auto getter = accessorCell->accessor(loc, rewriter, 0);
auto getterType = LLVM::LLVMFunctionType::get(elementTypeConverted, {th.getPtrType()});
return rewriter.create<LLVM::CallOp>(loc, getterType, ValueRange{getter, accessorCell->thisVal}).getResult();
return InterfaceAccessorCell::call(loc, rewriter, elementTypeConverted, ValueRange{getter, accessorCell->thisVal},
InterfaceAccessorCell::unwindBlockOf(loadOp));
};

loadedValue = clh.conditionalExpressionLowering(loc, elementTypeConverted, accessorCell->isCell, getterCallFunc,
Expand Down Expand Up @@ -5303,10 +5376,9 @@ struct StoreOpLowering : public TsLlvmPattern<mlir_ts::StoreOp>
clh.conditionalBlocksLowering(
hasSetter,
[&](OpBuilder &builder, Location location) -> ValueRange {
auto setterType = LLVM::LLVMFunctionType::get(
th.getVoidType(), {th.getPtrType(), transformed.getValue().getType()});
rewriter.create<LLVM::CallOp>(loc, setterType,
ValueRange{setter, accessorCell->thisVal, transformed.getValue()});
InterfaceAccessorCell::call(loc, rewriter, th.getVoidType(),
ValueRange{setter, accessorCell->thisVal, transformed.getValue()},
InterfaceAccessorCell::unwindBlockOf(storeOp));
return ValueRange{};
},
[&](OpBuilder &builder, Location location) -> ValueRange { return ValueRange{}; });
Expand Down Expand Up @@ -9419,7 +9491,7 @@ void TypeScriptToLLVMLoweringPass::runOnOperation()
InsertPropertyOpLowering, LengthOfOpLowering, SetLengthOfOpLowering, StringLengthOpLowering, StringResizeOpLowering, StringConcatOpLowering, StringCopyOpLowering,
SharedNewOpLowering, SharedValueRefOpLowering, SharedCountOpLowering,
StringCompareOpLowering, AnyCompareOpLowering, CharToStringOpLowering, UndefOpLowering, CopyStructOpLowering, MemoryCopyOpLowering, MemoryMoveOpLowering,
LoadSaveValueLowering, ThrowUnwindOpLowering, ThrowCallOpLowering, VariableOpLowering, DebugVariableOpLowering, AllocaOpLowering, InvokeOpLowering,
LoadSaveValueLowering, ThrowUnwindOpLowering, ThrowCallOpLowering, VariableOpLowering, DebugVariableOpLowering, AllocaOpLowering, InvokeOpLowering, AccessorUnwindEdgeOpLowering,
InvokeHybridOpLowering, VirtualSymbolRefOpLowering, ThisVirtualSymbolRefOpLowering, ThisSymbolRefOpLowering, InterfaceSymbolRefOpLowering,
NewInterfaceOpLowering, VTableOffsetRefOpLowering, LoadBoundRefOpLowering, StoreBoundRefOpLowering, CreateBoundRefOpLowering,
CreateBoundFunctionOpLowering, GetThisOpLowering, GetMethodOpLowering, TypeOfOpLowering, TypeOfAnyOpLowering, DebuggerOpLowering,
Expand Down
41 changes: 41 additions & 0 deletions tslang/lib/TypeScript/MLIRGenExpressions.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -563,6 +563,37 @@ namespace mlirgen
return mlirGen(leftHandSideExpressionAST.as<Expression>(), genContext);
}

// `++`/`--` on a get/set property (`o.prop++`): no reference to store back to, so the setter is called with the
// getter's value plus or minus one, as `o.prop += 1` does. The value is the new one for a prefix operator, and
// the old one for a postfix operator.
ValueOrLogicalResult MLIRGenImpl::mlirGenAccessorIncrement(mlir::Location location, SyntaxKind opCode, mlir::Value accessorValue,
bool prefix, const GenContext &genContext)
{
auto one = builder.create<mlir_ts::ConstantOp>(location, builder.getI32Type(), builder.getI32IntegerAttr(1));
mlir::Value step = one;
if (accessorValue.getType() != step.getType())
{
CAST(step, location, accessorValue.getType(), one, genContext);
}

auto binaryOpCode = opCode == SyntaxKind::PlusPlusToken ? SyntaxKind::PlusToken : SyntaxKind::MinusToken;
auto newValue = builder.create<mlir_ts::ArithmeticBinaryOp>(
location, accessorValue.getType(), builder.getI32IntegerAttr(static_cast<int32_t>(binaryOpCode)), accessorValue, step);

auto saved = mlirGenSaveLogicOneItem(location, accessorValue, newValue, genContext);
EXIT_IF_FAILED(saved)

return prefix ? mlir::Value(newValue) : accessorValue;
}

static bool isAccessorValue(mlir::Value value)
{
auto *defOp = value.getDefiningOp();
return defOp && mlir::isa<mlir_ts::AccessorOp, mlir_ts::ThisAccessorOp, mlir_ts::ThisIndirectAccessorOp,
mlir_ts::ThisIndexAccessorOp, mlir_ts::ThisIndirectIndexAccessorOp,
mlir_ts::BoundIndirectAccessorOp, mlir_ts::BoundIndirectIndexAccessorOp>(defOp);
}

ValueOrLogicalResult MLIRGenImpl::mlirGen(PrefixUnaryExpression prefixUnaryExpressionAST, const GenContext &genContext)
{
auto location = loc(prefixUnaryExpressionAST);
Expand Down Expand Up @@ -636,6 +667,11 @@ namespace mlirgen
return mlir::failure();
}

if (isAccessorValue(expressionValue) && mth.isNumericType(expressionValue.getType()))
{
return mlirGenAccessorIncrement(location, opCode, expressionValue, true, genContext);
}

return V(builder.create<mlir_ts::PrefixUnaryOp>(location, expressionValue.getType(),
builder.getI32IntegerAttr((int)opCode), expressionValue));
default:
Expand Down Expand Up @@ -667,6 +703,11 @@ namespace mlirgen
return mlir::failure();
}

if (isAccessorValue(expressionValue) && mth.isNumericType(expressionValue.getType()))
{
return mlirGenAccessorIncrement(location, opCode, expressionValue, false, genContext);
}

return V(builder.create<mlir_ts::PostfixUnaryOp>(location, expressionValue.getType(),
builder.getI32IntegerAttr((int)opCode), expressionValue));
default:
Expand Down
Loading
Loading