Skip to content

Commit 1ee0d22

Browse files
committed
[MLIR][Standard] Erase redundant assertions std.assert
Differential Revision: https://reviews.llvm.org/D83118
1 parent bcedc4f commit 1ee0d22

File tree

3 files changed

+50
-0
lines changed

3 files changed

+50
-0
lines changed

mlir/include/mlir/Dialect/StandardOps/IR/Ops.td

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -467,6 +467,8 @@ def AssertOp : Std_Op<"assert"> {
467467

468468
// AssertOp is fully verified by its traits.
469469
let verifier = ?;
470+
471+
let hasCanonicalizer = 1;
470472
}
471473

472474
//===----------------------------------------------------------------------===//

mlir/lib/Dialect/StandardOps/IR/Ops.cpp

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -439,6 +439,31 @@ OpFoldResult AndOp::fold(ArrayRef<Attribute> operands) {
439439
[](APInt a, APInt b) { return a & b; });
440440
}
441441

442+
//===----------------------------------------------------------------------===//
443+
// AssertOp
444+
//===----------------------------------------------------------------------===//
445+
446+
namespace {
447+
struct EraseRedundantAssertions : public OpRewritePattern<AssertOp> {
448+
using OpRewritePattern<AssertOp>::OpRewritePattern;
449+
450+
LogicalResult matchAndRewrite(AssertOp op,
451+
PatternRewriter &rewriter) const override {
452+
// Erase assertion if argument is constant true.
453+
if (matchPattern(op.arg(), m_One())) {
454+
rewriter.eraseOp(op);
455+
return success();
456+
}
457+
return failure();
458+
}
459+
};
460+
} // namespace
461+
462+
void AssertOp::getCanonicalizationPatterns(OwningRewritePatternList &patterns,
463+
MLIRContext *context) {
464+
patterns.insert<EraseRedundantAssertions>(context);
465+
}
466+
442467
//===----------------------------------------------------------------------===//
443468
// AssumeAlignmentOp
444469
//===----------------------------------------------------------------------===//

mlir/test/Dialect/Standard/canonicalize-cf.mlir

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -138,3 +138,26 @@ func @cond_br_pass_through_fail(%cond : i1) {
138138
^bb2:
139139
return
140140
}
141+
142+
// -----
143+
144+
// Erase assertion if condition is known to be true at compile time.
145+
// CHECK-LABEL: @assert_true
146+
func @assert_true() {
147+
// CHECK-NOT: assert
148+
%true = constant true
149+
assert %true, "Computer says no"
150+
return
151+
}
152+
153+
// -----
154+
155+
// Keep assertion if condition unknown at compile time.
156+
// CHECK-LABEL: @assert
157+
// CHECK-SAME: (%[[ARG:.*]]: i1)
158+
func @assert(%arg : i1) {
159+
// CHECK: assert %[[ARG]], "Computer says no"
160+
assert %arg, "Computer says no"
161+
return
162+
}
163+

0 commit comments

Comments
 (0)