CIRCT 22.0.0git
Loading...
Searching...
No Matches
SynthOps.cpp
Go to the documentation of this file.
1//===----------------------------------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
13#include "mlir/Analysis/TopologicalSortUtils.h"
14#include "mlir/IR/BuiltinAttributes.h"
15#include "mlir/IR/Matchers.h"
16#include "mlir/IR/OpDefinition.h"
17#include "mlir/IR/PatternMatch.h"
18#include "llvm/ADT/APInt.h"
19#include "llvm/Support/Casting.h"
20#include "llvm/Support/LogicalResult.h"
21
22using namespace mlir;
23using namespace circt;
24using namespace circt::synth::mig;
25using namespace circt::synth::aig;
26
27#define GET_OP_CLASSES
28#include "circt/Dialect/Synth/Synth.cpp.inc"
29
30LogicalResult MajorityInverterOp::verify() {
31 if (getNumOperands() % 2 != 1)
32 return emitOpError("requires an odd number of operands");
33
34 return success();
35}
36
37llvm::APInt MajorityInverterOp::evaluate(ArrayRef<APInt> inputs) {
38 assert(inputs.size() == getNumOperands() &&
39 "Number of inputs must match number of operands");
40
41 if (inputs.size() == 3) {
42 auto a = (isInverted(0) ? ~inputs[0] : inputs[0]);
43 auto b = (isInverted(1) ? ~inputs[1] : inputs[1]);
44 auto c = (isInverted(2) ? ~inputs[2] : inputs[2]);
45 return (a & b) | (a & c) | (b & c);
46 }
47
48 // General case for odd number of inputs != 3
49 auto width = inputs[0].getBitWidth();
50 APInt result(width, 0);
51
52 for (size_t bit = 0; bit < width; ++bit) {
53 size_t count = 0;
54 for (size_t i = 0; i < inputs.size(); ++i) {
55 // Count the number of 1s, considering inversion.
56 if (isInverted(i) ^ inputs[i][bit])
57 count++;
58 }
59
60 if (count > inputs.size() / 2)
61 result.setBit(bit);
62 }
63
64 return result;
65}
66
67OpFoldResult MajorityInverterOp::fold(FoldAdaptor adaptor) {
68 // TODO: Implement maj(x, 1, 1) = 1, maj(x, 0, 0) = 0
69
70 SmallVector<APInt, 3> inputValues;
71 for (auto input : adaptor.getInputs()) {
72 auto attr = llvm::dyn_cast_or_null<IntegerAttr>(input);
73 if (!attr)
74 return {};
75 inputValues.push_back(attr.getValue());
76 }
77
78 auto result = evaluate(inputValues);
79 return IntegerAttr::get(getType(), result);
80}
81
82LogicalResult MajorityInverterOp::canonicalize(MajorityInverterOp op,
83 PatternRewriter &rewriter) {
84 if (op.getNumOperands() == 1) {
85 if (op.getInverted()[0])
86 return failure();
87 rewriter.replaceOp(op, op.getOperand(0));
88 return success();
89 }
90
91 // For now, only support 3 operands.
92 if (op.getNumOperands() != 3)
93 return failure();
94
95 // Return if the idx-th operand is a constant (inverted if necessary),
96 // otherwise return std::nullopt.
97 auto getConstant = [&](unsigned index) -> std::optional<llvm::APInt> {
98 APInt value;
99 if (mlir::matchPattern(op.getInputs()[index], mlir::m_ConstantInt(&value)))
100 return op.isInverted(index) ? ~value : value;
101 return std::nullopt;
102 };
103
104 // Replace the op with the idx-th operand (inverted if necessary).
105 auto replaceWithIndex = [&](int index) {
106 bool inverted = op.isInverted(index);
107 if (inverted)
108 rewriter.replaceOpWithNewOp<MajorityInverterOp>(
109 op, op.getType(), op.getOperand(index), true);
110 else
111 rewriter.replaceOp(op, op.getOperand(index));
112 return success();
113 };
114
115 // Pattern match following cases:
116 // maj_inv(x, x, y) -> x
117 // maj_inv(x, y, not y) -> x
118 for (int i = 0; i < 2; ++i) {
119 for (int j = i + 1; j < 3; ++j) {
120 int k = 3 - (i + j);
121 assert(k >= 0 && k < 3);
122 // If we have two identical operands, we can fold.
123 if (op.getOperand(i) == op.getOperand(j)) {
124 // If they are inverted differently, we can fold to the third.
125 if (op.isInverted(i) != op.isInverted(j))
126 return replaceWithIndex(k);
127 return replaceWithIndex(i);
128 }
129
130 // If i and j are constant.
131 if (auto c1 = getConstant(i)) {
132 if (auto c2 = getConstant(j)) {
133 // If both constants are equal, we can fold.
134 if (*c1 == *c2) {
135 rewriter.replaceOpWithNewOp<hw::ConstantOp>(
136 op, op.getType(), mlir::IntegerAttr::get(op.getType(), *c1));
137 return success();
138 }
139 // If constants are complementary, we can fold.
140 if (*c1 == ~*c2)
141 return replaceWithIndex(k);
142 }
143 }
144 }
145 }
146 return failure();
147}
148
149//===----------------------------------------------------------------------===//
150// AIG Operations
151//===----------------------------------------------------------------------===//
152
153OpFoldResult AndInverterOp::fold(FoldAdaptor adaptor) {
154 if (getNumOperands() == 1 && !isInverted(0))
155 return getOperand(0);
156
157 auto inputs = adaptor.getInputs();
158 if (inputs.size() == 2)
159 if (auto intAttr = dyn_cast_or_null<IntegerAttr>(inputs[1])) {
160 auto value = intAttr.getValue();
161 if (isInverted(1))
162 value = ~value;
163 if (value.isZero())
164 return IntegerAttr::get(
165 IntegerType::get(getContext(), value.getBitWidth()), value);
166 if (value.isAllOnes()) {
167 if (isInverted(0))
168 return {};
169
170 return getOperand(0);
171 }
172 }
173 return {};
174}
175
176LogicalResult AndInverterOp::canonicalize(AndInverterOp op,
177 PatternRewriter &rewriter) {
179 SmallVector<Value> uniqueValues;
180 SmallVector<bool> uniqueInverts;
181
182 APInt constValue =
183 APInt::getAllOnes(op.getResult().getType().getIntOrFloatBitWidth());
184
185 bool invertedConstFound = false;
186 bool flippedFound = false;
187
188 for (auto [value, inverted] : llvm::zip(op.getInputs(), op.getInverted())) {
189 bool newInverted = inverted;
190 if (auto constOp = value.getDefiningOp<hw::ConstantOp>()) {
191 if (inverted) {
192 constValue &= ~constOp.getValue();
193 invertedConstFound = true;
194 } else {
195 constValue &= constOp.getValue();
196 }
197 continue;
198 }
199
200 if (auto andInverterOp = value.getDefiningOp<synth::aig::AndInverterOp>()) {
201 if (andInverterOp.getInputs().size() == 1 &&
202 andInverterOp.isInverted(0)) {
203 value = andInverterOp.getOperand(0);
204 newInverted = andInverterOp.isInverted(0) ^ inverted;
205 flippedFound = true;
206 }
207 }
208
209 auto it = seen.find(value);
210 if (it == seen.end()) {
211 seen.insert({value, newInverted});
212 uniqueValues.push_back(value);
213 uniqueInverts.push_back(newInverted);
214 } else if (it->second != newInverted) {
215 // replace with const 0
216 rewriter.replaceOpWithNewOp<hw::ConstantOp>(
217 op, APInt::getZero(value.getType().getIntOrFloatBitWidth()));
218 return success();
219 }
220 }
221
222 // If the constant is zero, we can just replace with zero.
223 if (constValue.isZero()) {
224 rewriter.replaceOpWithNewOp<hw::ConstantOp>(op, constValue);
225 return success();
226 }
227
228 // No change.
229 if ((uniqueValues.size() == op.getInputs().size() && !flippedFound) ||
230 (!constValue.isAllOnes() && !invertedConstFound &&
231 uniqueValues.size() + 1 == op.getInputs().size()))
232 return failure();
233
234 if (!constValue.isAllOnes()) {
235 auto constOp = hw::ConstantOp::create(rewriter, op.getLoc(), constValue);
236 uniqueInverts.push_back(false);
237 uniqueValues.push_back(constOp);
238 }
239
240 // It means the input is reduced to all ones.
241 if (uniqueValues.empty()) {
242 rewriter.replaceOpWithNewOp<hw::ConstantOp>(op, constValue);
243 return success();
244 }
245
246 // build new op with reduced input values
247 replaceOpWithNewOpAndCopyNamehint<synth::aig::AndInverterOp>(
248 rewriter, op, uniqueValues, uniqueInverts);
249 return success();
250}
251
252APInt AndInverterOp::evaluate(ArrayRef<APInt> inputs) {
253 assert(inputs.size() == getNumOperands() &&
254 "Expected as many inputs as operands");
255 assert(!inputs.empty() && "Expected non-empty input list");
256 APInt result = APInt::getAllOnes(inputs.front().getBitWidth());
257 for (auto [idx, input] : llvm::enumerate(inputs)) {
258 if (isInverted(idx))
259 result &= ~input;
260 else
261 result &= input;
262 }
263 return result;
264}
265
266static Value lowerVariadicAndInverterOp(AndInverterOp op, OperandRange operands,
267 ArrayRef<bool> inverts,
268 PatternRewriter &rewriter) {
269 switch (operands.size()) {
270 case 0:
271 assert(0 && "cannot be called with empty operand range");
272 break;
273 case 1:
274 if (inverts[0])
275 return AndInverterOp::create(rewriter, op.getLoc(), operands[0], true);
276 else
277 return operands[0];
278 case 2:
279 return AndInverterOp::create(rewriter, op.getLoc(), operands[0],
280 operands[1], inverts[0], inverts[1]);
281 default:
282 auto firstHalf = operands.size() / 2;
283 auto lhs =
284 lowerVariadicAndInverterOp(op, operands.take_front(firstHalf),
285 inverts.take_front(firstHalf), rewriter);
286 auto rhs =
287 lowerVariadicAndInverterOp(op, operands.drop_front(firstHalf),
288 inverts.drop_front(firstHalf), rewriter);
289 return AndInverterOp::create(rewriter, op.getLoc(), lhs, rhs);
290 }
291 return Value();
292}
293
295 AndInverterOp op, PatternRewriter &rewriter) const {
296 if (op.getInputs().size() <= 2)
297 return failure();
298 // TODO: This is a naive implementation that creates a balanced binary tree.
299 // We can improve by analyzing the dataflow and creating a tree that
300 // improves the critical path or area.
301 rewriter.replaceOp(op, lowerVariadicAndInverterOp(
302 op, op.getOperands(), op.getInverted(), rewriter));
303 return success();
304}
305
307 mlir::Operation *op,
308 llvm::function_ref<bool(mlir::Value, mlir::Operation *)> isOperandReady) {
309 // Sort the operations topologically
310 auto walkResult = op->walk([&](Region *region) {
311 auto regionKindOp =
312 dyn_cast<mlir::RegionKindInterface>(region->getParentOp());
313 if (!regionKindOp ||
314 regionKindOp.hasSSADominance(region->getRegionNumber()))
315 return WalkResult::advance();
316
317 // Graph region.
318 for (auto &block : *region) {
319 if (!mlir::sortTopologically(&block, isOperandReady))
320 return WalkResult::interrupt();
321 }
322 return WalkResult::advance();
323 });
324
325 return success(!walkResult.wasInterrupted());
326}
assert(baseType &&"element must be base type")
static std::optional< APSInt > getConstant(Attribute operand)
Determine the value of a constant operand for the sake of constant folding.
static Value lowerVariadicAndInverterOp(AndInverterOp op, OperandRange operands, ArrayRef< bool > inverts, PatternRewriter &rewriter)
Definition SynthOps.cpp:266
create(data_type, value)
Definition hw.py:433
LogicalResult topologicallySortGraphRegionBlocks(mlir::Operation *op, llvm::function_ref< bool(mlir::Value, mlir::Operation *)> isOperandReady)
This function performs a topological sort on the operations within each block of graph regions in the...
Definition SynthOps.cpp:306
The InstanceGraph op interface, see InstanceGraphInterface.td for more details.
mlir::LogicalResult matchAndRewrite(aig::AndInverterOp op, mlir::PatternRewriter &rewriter) const override
Definition SynthOps.cpp:294