19#include "mlir/IR/PatternMatch.h"
20#include "mlir/Transforms/WalkPatternRewriteDriver.h"
21#include "llvm/Support/LogicalResult.h"
28#define GEN_PASS_DEF_SIMPLIFYTRUTHTABLE
29#include "circt/Dialect/Comb/Passes.h.inc"
37 return llvm::any_of(op->getOperands(), [op](
auto operand) {
38 return operand.getDefiningOp() == op;
44 using OpRewritePattern::OpRewritePattern;
46 LogicalResult matchAndRewrite(TruthTableOp op,
47 PatternRewriter &rewriter)
const override {
51 const auto inputs = op.getInputs();
52 const auto table = op.getLookupTable();
53 size_t numInputs = inputs.size();
59 bool allSame = llvm::all_equal(table);
61 bool firstValue = table[0];
69 APInt truthTable(table.size(), 0);
70 for (
size_t i = 0; i < table.size(); ++i)
71 truthTable.setBitVal(i, table[i]);
77 int dependentInput = -1;
78 unsigned numDependencies = 0;
79 APInt negativeCofactor, positiveCofactor;
81 for (
size_t bitPos = 0; bitPos < numInputs; ++bitPos) {
82 std::tie(negativeCofactor, positiveCofactor) =
86 if (negativeCofactor != positiveCofactor) {
88 dependentInput = numInputs - 1 - bitPos;
92 if (numDependencies > 1)
98 if (numDependencies != 1)
103 size_t bitPositionInTable = numInputs - 1 - dependentInput;
104 size_t idxWhen1 = 1ull << bitPositionInTable;
105 bool isIdentity = table[idxWhen1];
108 Value input = inputs[dependentInput];
115 replaceOpWithNewOpAndCopyNamehint<TruthTableOp>(
116 rewriter, op, ValueRange{input}, ArrayRef<bool>{
true,
false});
122class SimplifyTruthTablePass
123 :
public impl::SimplifyTruthTableBase<SimplifyTruthTablePass> {
125 using SimplifyTruthTableBase::SimplifyTruthTableBase;
126 void runOnOperation()
override;
131void SimplifyTruthTablePass::runOnOperation() {
132 Operation *op = getOperation();
133 MLIRContext *
context = op->getContext();
136 walkAndApplyPatterns(op, std::move(
patterns));
static bool isOpTriviallyRecursive(Operation *op)
static std::unique_ptr< Context > context
The InstanceGraph op interface, see InstanceGraphInterface.td for more details.
void replaceOpAndCopyNamehint(PatternRewriter &rewriter, Operation *op, Value newValue)
A wrapper of PatternRewriter::replaceOp to propagate "sv.namehint" attribute.
std::pair< llvm::APInt, llvm::APInt > computeCofactors(const llvm::APInt &f, unsigned numVars, unsigned varIndex)
Compute cofactor of a Boolean function for a given variable.