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
535 changes: 496 additions & 39 deletions tslang/include/TypeScript/MLIRLogic/MLIRCodeLogic.h

Large diffs are not rendered by default.

53 changes: 53 additions & 0 deletions tslang/include/TypeScript/MLIRLogic/MLIRTypeHelper.h
Original file line number Diff line number Diff line change
Expand Up @@ -4083,6 +4083,59 @@ class MLIRTypeHelper
return mergeType(location, existType, currentType, merged);
}

// whether `literalType` is a number literal whose value `type`, a number type, holds as it is
bool numberLiteralFits(mlir::Type literalType, mlir::Type type)
{
auto literal = dyn_cast<mlir_ts::LiteralType>(literalType);
if (!literal || isa<mlir_ts::LiteralType>(type))
{
return false;
}

auto value = literal.getValue();
if (auto intType = dyn_cast<mlir::IntegerType>(type))
{
llvm::APSInt intValue;
if (auto intAttr = dyn_cast<mlir::IntegerAttr>(value); intAttr && !isa<mlir::BoolAttr>(value))
{
auto literalInt = dyn_cast<mlir::IntegerType>(intAttr.getType());
intValue = llvm::APSInt(intAttr.getValue(), literalInt && literalInt.isUnsigned());
}
else if (auto floatAttr = dyn_cast<mlir::FloatAttr>(value))
{
auto isExact = false;
intValue = llvm::APSInt(128, false);
if (floatAttr.getValue().convertToInteger(intValue, llvm::APFloat::rmTowardZero, &isExact) != llvm::APFloat::opOK ||
!isExact)
{
return false;
}
}
else
{
return false;
}

auto width = intType.getWidth();
if (!intValue.isRepresentableByInt64() || width > 64)
{
return false;
}

auto number = intValue.getExtValue();
auto fitsUnsigned = number >= 0 && (width == 64 || static_cast<uint64_t>(number) < (uint64_t(1) << width));
auto fitsSigned = width == 64 || (number >= -(int64_t(1) << (width - 1)) && number < (int64_t(1) << (width - 1)));
return intType.isUnsigned() ? fitsUnsigned : intType.isSigned() ? fitsSigned : fitsSigned || fitsUnsigned;
}

if (isa<mlir_ts::NumberType>(type) || type.isF64())
{
return isa<mlir::IntegerAttr, mlir::FloatAttr>(value) && !isa<mlir::BoolAttr>(value);
}

return false;
}

mlir::Type mergeType(mlir::Location location, mlir::Type existType, mlir::Type currentType, bool& merged)
{
merged = false;
Expand Down
22 changes: 22 additions & 0 deletions tslang/include/TypeScript/TypeScriptOps.td
Original file line number Diff line number Diff line change
Expand Up @@ -2608,6 +2608,28 @@ def TypeScript_AtomicCmpXchgOp : TypeScript_Op<"CmpXchg"> {
let results = (outs AnyType:$res);
}

def TypeScript_AtomicLoadOp : TypeScript_Op<"AtomicLoad"> {
let summary = "atomicload command";
let description = [{
The "atomicload" builtin operation: an LLVM `load atomic` of the value $ptr points at. An
alignment of none is the natural alignment of the value.
}];

let arguments = (ins TypeScript_AnyRefLike:$ptr, I32Attr:$ordering, OptionalAttr<StrAttr>:$syncscope, OptionalAttr<I64Attr>:$alignment, UnitAttr:$volatile_);
let results = (outs AnyType:$res);
}

def TypeScript_AtomicStoreOp : TypeScript_Op<"AtomicStore"> {
let summary = "atomicstore command";
let description = [{
The "atomicstore" builtin operation: an LLVM `store atomic` of $value where $ptr points. An
alignment of none is the natural alignment of the value.
}];

let arguments = (ins TypeScript_AnyRefLike:$ptr, AnyType:$value, I32Attr:$ordering, OptionalAttr<StrAttr>:$syncscope, OptionalAttr<I64Attr>:$alignment, UnitAttr:$volatile_);
let results = (outs );
}

def TypeScript_FenceOp : TypeScript_Op<"Fence"> {
let summary = "fence command";
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 @@ -3124,7 +3124,7 @@ void AddTsAffineLegalOps(ConversionTarget &target)
mlir_ts::CreateUnionInstanceOp, mlir_ts::GetValueFromUnionOp, mlir_ts::GetTypeInfoFromUnionOp,
mlir_ts::OptionalOp, mlir_ts::OptionalValueOp, mlir_ts::OptionalUndefOp,
mlir_ts::LoadLibraryPermanentlyOp, mlir_ts::SearchForAddressOfSymbolOp,
mlir_ts::AtomicRMWOp, mlir_ts::AtomicCmpXchgOp, mlir_ts::FenceOp, mlir_ts::InlineAsmOp,
mlir_ts::AtomicRMWOp, mlir_ts::AtomicCmpXchgOp, mlir_ts::AtomicLoadOp, mlir_ts::AtomicStoreOp, mlir_ts::FenceOp, mlir_ts::InlineAsmOp,
mlir_ts::CallIntrinsicOp, mlir_ts::LinkerOptionsOp>();
#ifdef ENABLE_TYPED_GC
target.addLegalOp<
Expand Down
60 changes: 59 additions & 1 deletion tslang/lib/TypeScript/LowerToLLVM.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -8548,6 +8548,64 @@ struct AtomicCmpXchgOpLowering : public TsLlvmPattern<mlir_ts::AtomicCmpXchgOp>
}
};

// LLVM wants an atomic load or store aligned; none given is the natural alignment of the value
static uint64_t atomicAccessAlignment(const mlir::TypeConverter *typeConverter, mlir::Type llvmType, std::optional<uint64_t> alignment)
{
if (alignment.has_value() && *alignment > 0)
{
return *alignment;
}

LLVMTypeConverterHelper llvmtch(static_cast<const LLVMTypeConverter *>(typeConverter));
return llvmtch.getTypeAllocSizeInBytes(llvmType);
}

struct AtomicLoadOpLowering : public TsLlvmPattern<mlir_ts::AtomicLoadOp>
{
using TsLlvmPattern<mlir_ts::AtomicLoadOp>::TsLlvmPattern;

LogicalResult matchAndRewrite(mlir_ts::AtomicLoadOp op, Adaptor transformed,
ConversionPatternRewriter &rewriter) const final
{
TypeConverterHelper tch(getTypeConverter());
auto llvmType = tch.convertType(op.getType());
rewriter.replaceOpWithNewOp<LLVM::LoadOp>(
op,
llvmType,
transformed.getPtr(),
atomicAccessAlignment(getTypeConverter(), llvmType, transformed.getAlignment()),
transformed.getVolatile_(),
/*isNonTemporal=*/false,
/*isInvariant=*/false,
/*isInvariantGroup=*/false,
(LLVM::AtomicOrdering)transformed.getOrdering(),
transformed.getSyncscope().value_or(StringRef()));
return success();
}
};

struct AtomicStoreOpLowering : public TsLlvmPattern<mlir_ts::AtomicStoreOp>
{
using TsLlvmPattern<mlir_ts::AtomicStoreOp>::TsLlvmPattern;

LogicalResult matchAndRewrite(mlir_ts::AtomicStoreOp op, Adaptor transformed,
ConversionPatternRewriter &rewriter) const final
{
auto value = transformed.getValue();
rewriter.replaceOpWithNewOp<LLVM::StoreOp>(
op,
value,
transformed.getPtr(),
atomicAccessAlignment(getTypeConverter(), value.getType(), transformed.getAlignment()),
transformed.getVolatile_(),
/*isNonTemporal=*/false,
/*isInvariantGroup=*/false,
(LLVM::AtomicOrdering)transformed.getOrdering(),
transformed.getSyncscope().value_or(StringRef()));
return success();
}
};

struct FenceOpLowering : public TsLlvmPattern<mlir_ts::FenceOp>
{
using TsLlvmPattern<mlir_ts::FenceOp>::TsLlvmPattern;
Expand Down Expand Up @@ -9673,7 +9731,7 @@ void TypeScriptToLLVMLoweringPass::runOnOperation()
#endif
,
SwitchStateInternalOpLowering, LoadLibraryPermanentlyOpLowering, SearchForAddressOfSymbolOpLowering,
AtomicRMWOpLowering, AtomicCmpXchgOpLowering, FenceOpLowering, InlineAsmOpLowering, CallIntrinsicOpLowering, LinkerOptionsOpLowering>(
AtomicRMWOpLowering, AtomicCmpXchgOpLowering, AtomicLoadOpLowering, AtomicStoreOpLowering, FenceOpLowering, InlineAsmOpLowering, CallIntrinsicOpLowering, LinkerOptionsOpLowering>(
typeConverter, &getContext(), &tsLlvmContext);

if (tsLlvmContext.compileOptions.isWindows)
Expand Down
30 changes: 28 additions & 2 deletions tslang/lib/TypeScript/MLIRGenAccessCall.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2128,6 +2128,32 @@ namespace mlirgen
argumentTypes.push_back(type);
}

// an array literal is generated for its parameter's type: `[250]` evaluates s32[], and fits
// `data: u8[]` as its elements fit u8 (`new TypedArray<u8>([250])` of a class with a second
// constructor found none that took s32[]); an empty one fits any array
auto argumentFit = [&](size_t index, mlir::Type param) {
auto fit = overloadArgumentFit(location, argumentTypes[index], param);
auto arrayParam = dyn_cast<mlir_ts::ArrayType>(mth.stripOptionalType(param));
if (fit > 0 || !arrayParam || arguments[index] != SyntaxKind::ArrayLiteralExpression)
{
return fit;
}

auto elementsFit = 3;
for (auto element : arguments[index].as<ArrayLiteralExpression>()->elements)
{
auto elementType = element == SyntaxKind::SpreadElement ? mlir::Type() : evaluate(element, genContext);
if (!elementType)
{
return 0;
}

elementsFit = std::min(elementsFit, overloadArgumentFit(location, elementType, arrayParam.getElementType()));
}

return elementsFit;
};

auto bestScore = -1;
auto best = -1;
for (auto candidate : candidates)
Expand All @@ -2154,7 +2180,7 @@ namespace mlirgen
continue;
}

auto argFit = overloadArgumentFit(location, argumentTypes[index], param);
auto argFit = argumentFit(index, param);
fits &= argFit > 0;
score += argFit;
}
Expand All @@ -2169,7 +2195,7 @@ namespace mlirgen

for (auto index = fixedParams.size(); index < argumentTypes.size(); index++)
{
auto argFit = overloadArgumentFit(location, argumentTypes[index], restType);
auto argFit = argumentFit(index, restType);
fits &= argFit > 0;
score += argFit;
}
Expand Down
41 changes: 39 additions & 2 deletions tslang/lib/TypeScript/MLIRGenExpressions.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1584,10 +1584,47 @@ namespace mlirgen
MLIRValueGuard<bool> sharedElementsRefusedGuard(sharedElementsRefused);
sharedElementsRefused = false;

// `type Uint8Array = TypedArray<u8>`: `new Uint8Array([250])` names a class its alias already
// gave type arguments, which neither the constructor's arguments nor the receiver override.
// Inferred from the arguments, it was a TypedArray<s32>.
auto namesSpecializedAlias = [&](mlir_ts::ClassType classType) {
if (getGenericClassInfoByFullName(classType.getName().getValue()))
{
// the generic class itself
return false;
}

auto classInfo = getClassInfoByFullName(classType.getName().getValue());
if (!classInfo || !classInfo->originClassType)
{
return false;
}

auto genericClassInfo = getGenericClassInfoByFullName(classInfo->originClassType.getName().getValue());
StringRef name;
if (typeExpression == SyntaxKind::Identifier)
{
name = MLIRHelper::getName(typeExpression.as<Identifier>(), stringAllocator);
}
else if (typeExpression == SyntaxKind::PropertyAccessExpression)
{
name = MLIRHelper::getName(typeExpression.as<PropertyAccessExpression>()->name, stringAllocator);
}

return genericClassInfo && !name.empty() && name != genericClassInfo->name;
};

auto classOfType = dyn_cast<mlir_ts::ClassType>(value.getType());
auto inferTypeArguments = newExpression->typeArguments.size() == 0 && !(classOfType && namesSpecializedAlias(classOfType));
if (!inferTypeArguments)
{
unspecialized = mlir::Value();
}

// `new Set([2, 4, 6, 8])`: a generic class written without type arguments takes them from
// its constructor's arguments (see inferClassTypeFromConstructorArguments). Ahead of the
// receiver below, which overrides it: `const s: Set<number> = new Set([1, 2])` is Set<number>.
if (newExpression->typeArguments.size() == 0 && newExpression->arguments.size() > 0)
if (inferTypeArguments && newExpression->arguments.size() > 0)
{
if (auto classType = dyn_cast<mlir_ts::ClassType>(value.getType()))
{
Expand Down Expand Up @@ -1625,7 +1662,7 @@ namespace mlirgen
// arguments takes them from the type it is given to, when that is the same class. Its
// type parameter defaults (`Map<K = any, V = any>`) made Map<any, any> otherwise, a
// different layout, and the cast to the declared type crashed at run time.
if (newExpression->typeArguments.size() == 0 && genContext.receiverType)
if (inferTypeArguments && genContext.receiverType)
{
if (auto classType = dyn_cast<mlir_ts::ClassType>(value.getType()))
{
Expand Down
16 changes: 15 additions & 1 deletion tslang/lib/TypeScript/MLIRGenGenerics.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,21 @@ namespace mlirgen
auto currentType = concreteType;
auto name = namedGenType.getName().getValue();
auto existType = results.lookup(name);
if (existType)
if (existType && mth.numberLiteralFits(currentType, existType))
{
// a number literal yields to the type T already has, when it holds its value: in
// `add<T>(ta: TA<T>, v: T)`, `add(new TA<u16>(...), 2)` is T = u16 with 2 cast to it, where
// merging the two made T the literal's s32, and TA<u16> no longer passed for TA<s32>
LLVM_DEBUG(llvm::dbgs() << "\n!! literal " << currentType << " yields to: " << existType << "\n";);
currentType = existType;
}
else if (existType && mth.numberLiteralFits(existType, currentType))
{
// ...in either order: `add2<T>(v: T, ta: TA<T>)`
LLVM_DEBUG(llvm::dbgs() << "\n!! literal " << existType << " yields to: " << currentType << "\n";);
results[name] = currentType;
}
else if (existType)
{
auto merged = false;
currentType = mth.mergeType(location, existType, currentType, merged);
Expand Down
16 changes: 15 additions & 1 deletion tslang/lib/TypeScript/MLIRGenTypes.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -382,7 +382,21 @@ namespace mlirgen
LLVM_DEBUG(llvm::dbgs() << "\n!! replacing existing type for: " << name
<< " exist type: " << existType.second << " new type: " << type << "\n";);

if (!isa<mlir_ts::NamedGenericType>(existType.second) && mergeTypes)
if (!isa<mlir_ts::NamedGenericType>(existType.second) && mergeTypes && !arrayMerge &&
mth.numberLiteralFits(type, existType.second))
{
// a number literal argument yields to the type T already has from another one, when
// it holds the literal's value: `add<T>(ta: TA<T>, i: int, v: T)` called as
// `add(new TA<u16>(...), 0, 2)` is T = u16, the literal cast to it. Merged, T was the
// literal's s32, and TA<u16> did not pass for TA<s32>.
type = existType.second;
}
else if (!isa<mlir_ts::NamedGenericType>(existType.second) && mergeTypes && !arrayMerge &&
mth.numberLiteralFits(existType.second, type))
{
// ...in either order: `add2<T>(v: T, ta: TA<T>)`
}
else if (!isa<mlir_ts::NamedGenericType>(existType.second) && mergeTypes)
{
auto merged = false;
if (arrayMerge)
Expand Down
Loading
Loading