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 && inputs[1]) {
159 auto value = cast<IntegerAttr>(inputs[1]).getValue();
160 if (isInverted(1))
161 value = ~value;
162 if (value.isZero())
163 return IntegerAttr::get(
164 IntegerType::get(getContext(), value.getBitWidth()), value);
165 if (value.isAllOnes()) {
166 if (isInverted(0))
167 return {};
168
169 return getOperand(0);
170 }
171 }
172 return {};
173}
174
175LogicalResult AndInverterOp::canonicalize(AndInverterOp op,
176 PatternRewriter &rewriter) {
178 SmallVector<Value> uniqueValues;
179 SmallVector<bool> uniqueInverts;
180
181 APInt constValue =
182 APInt::getAllOnes(op.getResult().getType().getIntOrFloatBitWidth());
183
184 bool invertedConstFound = false;
185 bool flippedFound = false;
186
187 for (auto [value, inverted] : llvm::zip(op.getInputs(), op.getInverted())) {
188 bool newInverted = inverted;
189 if (auto constOp = value.getDefiningOp<hw::ConstantOp>()) {
190 if (inverted) {
191 constValue &= ~constOp.getValue();
192 invertedConstFound = true;
193 } else {
194 constValue &= constOp.getValue();
195 }
196 continue;
197 }
198
199 if (auto andInverterOp = value.getDefiningOp<synth::aig::AndInverterOp>()) {
200 if (andInverterOp.getInputs().size() == 1 &&
201 andInverterOp.isInverted(0)) {
202 value = andInverterOp.getOperand(0);
203 newInverted = andInverterOp.isInverted(0) ^ inverted;
204 flippedFound = true;
205 }
206 }
207
208 auto it = seen.find(value);
209 if (it == seen.end()) {
210 seen.insert({value, newInverted});
211 uniqueValues.push_back(value);
212 uniqueInverts.push_back(newInverted);
213 } else if (it->second != newInverted) {
214 // replace with const 0
215 rewriter.replaceOpWithNewOp<hw::ConstantOp>(
216 op, APInt::getZero(value.getType().getIntOrFloatBitWidth()));
217 return success();
218 }
219 }
220
221 // If the constant is zero, we can just replace with zero.
222 if (constValue.isZero()) {
223 rewriter.replaceOpWithNewOp<hw::ConstantOp>(op, constValue);
224 return success();
225 }
226
227 // No change.
228 if ((uniqueValues.size() == op.getInputs().size() && !flippedFound) ||
229 (!constValue.isAllOnes() && !invertedConstFound &&
230 uniqueValues.size() + 1 == op.getInputs().size()))
231 return failure();
232
233 if (!constValue.isAllOnes()) {
234 auto constOp = hw::ConstantOp::create(rewriter, op.getLoc(), constValue);
235 uniqueInverts.push_back(false);
236 uniqueValues.push_back(constOp);
237 }
238
239 // It means the input is reduced to all ones.
240 if (uniqueValues.empty()) {
241 rewriter.replaceOpWithNewOp<hw::ConstantOp>(op, constValue);
242 return success();
243 }
244
245 // build new op with reduced input values
246 replaceOpWithNewOpAndCopyNamehint<synth::aig::AndInverterOp>(
247 rewriter, op, uniqueValues, uniqueInverts);
248 return success();
249}
250
251APInt AndInverterOp::evaluate(ArrayRef<APInt> inputs) {
252 assert(inputs.size() == getNumOperands() &&
253 "Expected as many inputs as operands");
254 assert(!inputs.empty() && "Expected non-empty input list");
255 APInt result = APInt::getAllOnes(inputs.front().getBitWidth());
256 for (auto [idx, input] : llvm::enumerate(inputs)) {
257 if (isInverted(idx))
258 result &= ~input;
259 else
260 result &= input;
261 }
262 return result;
263}
264
265static Value lowerVariadicAndInverterOp(AndInverterOp op, OperandRange operands,
266 ArrayRef<bool> inverts,
267 PatternRewriter &rewriter) {
268 switch (operands.size()) {
269 case 0:
270 assert(0 && "cannot be called with empty operand range");
271 break;
272 case 1:
273 if (inverts[0])
274 return AndInverterOp::create(rewriter, op.getLoc(), operands[0], true);
275 else
276 return operands[0];
277 case 2:
278 return AndInverterOp::create(rewriter, op.getLoc(), operands[0],
279 operands[1], inverts[0], inverts[1]);
280 default:
281 auto firstHalf = operands.size() / 2;
282 auto lhs =
283 lowerVariadicAndInverterOp(op, operands.take_front(firstHalf),
284 inverts.take_front(firstHalf), rewriter);
285 auto rhs =
286 lowerVariadicAndInverterOp(op, operands.drop_front(firstHalf),
287 inverts.drop_front(firstHalf), rewriter);
288 return AndInverterOp::create(rewriter, op.getLoc(), lhs, rhs);
289 }
290 return Value();
291}
292
294 AndInverterOp op, PatternRewriter &rewriter) const {
295 if (op.getInputs().size() <= 2)
296 return failure();
297 // TODO: This is a naive implementation that creates a balanced binary tree.
298 // We can improve by analyzing the dataflow and creating a tree that
299 // improves the critical path or area.
300 rewriter.replaceOp(op, lowerVariadicAndInverterOp(
301 op, op.getOperands(), op.getInverted(), rewriter));
302 return success();
303}
304
306 mlir::Operation *op,
307 llvm::function_ref<bool(mlir::Value, mlir::Operation *)> isOperandReady) {
308 // Sort the operations topologically
309 auto walkResult = op->walk([&](Region *region) {
310 auto regionKindOp =
311 dyn_cast<mlir::RegionKindInterface>(region->getParentOp());
312 if (!regionKindOp ||
313 regionKindOp.hasSSADominance(region->getRegionNumber()))
314 return WalkResult::advance();
315
316 // Graph region.
317 for (auto &block : *region) {
318 if (!mlir::sortTopologically(&block, isOperandReady))
319 return WalkResult::interrupt();
320 }
321 return WalkResult::advance();
322 });
323
324 return success(!walkResult.wasInterrupted());
325}
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:265
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:305
The InstanceGraph op interface, see InstanceGraphInterface.td for more details.
mlir::LogicalResult matchAndRewrite(aig::AndInverterOp op, mlir::PatternRewriter &rewriter) const override
Definition SynthOps.cpp:293