Skip to content

fix: don't assert when calculating log2 of non-power-of-two number, fail instead. #192

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
May 28, 2024
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
18 changes: 12 additions & 6 deletions mlir/lib/Dialect/PDL/IR/Builtins.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -85,20 +85,26 @@ LogicalResult static unaryOp(PatternRewriter &rewriter, PDLResultList &results,

results.push_back(rewriter.getIntegerAttr(integerType, resultInt));
} else if constexpr (T == UnaryOpKind::log2) {
auto getIntegerAsAttr = [&](const APSInt &value) {
auto getIntegerAsAttr = [&](const APSInt &value) -> Attribute {
// Only calculate values for exact log2.
int32_t log2Value = value.exactLogBase2();
assert(log2Value >= 0 &&
"log2 of an integer is expected to return an exact integer.");
if (log2Value < 0)
return Attribute();
return rewriter.getIntegerAttr(
integerType,
APSInt(APInt(bitWidth, log2Value), integerType.isUnsigned()));
};
// for log2 we treat signless integer as signed
Attribute log2IntegerAttr;
if (integerType.isSignless())
results.push_back(
getIntegerAsAttr(APSInt(operandIntAttr.getValue(), false)));
log2IntegerAttr =
getIntegerAsAttr(APSInt(operandIntAttr.getValue(), false));
else
results.push_back(getIntegerAsAttr(operandIntAttr.getAPSInt()));
log2IntegerAttr = getIntegerAsAttr(operandIntAttr.getAPSInt());
// Return failure if log2 value isn't exact.
if (!log2IntegerAttr)
return failure();
results.push_back(log2IntegerAttr);
} else if constexpr (T == UnaryOpKind::abs) {
if (integerType.isSigned()) {
// check overflow
Expand Down
9 changes: 7 additions & 2 deletions mlir/unittests/Dialect/PDL/BuiltinTest.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -613,8 +613,13 @@ TEST_F(BuiltinTest, log2) {
auto zeroI32 = rewriter.getI32IntegerAttr(0);
{
TestPDLResultList results(1);
EXPECT_DEATH(static_cast<void>(builtin::log2(rewriter, results, {zeroI32})),
"log2 of an integer is expected to return an exact integer.");
EXPECT_FALSE(builtin::log2(rewriter, results, {zeroI32}).succeeded());
}

auto minusOneI32 = rewriter.getI32IntegerAttr(-1);
{
TestPDLResultList results(1);
EXPECT_FALSE(builtin::log2(rewriter, results, {minusOneI32}).succeeded());
}

auto fourF16 = rewriter.getF16FloatAttr(4.0);
Expand Down