CIRCT 22.0.0git
Loading...
Searching...
No Matches
CombFolds.cpp
Go to the documentation of this file.
1//===- CombFolds.cpp - Folds + Canonicalization for Comb operations -------===//
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/IR/Diagnostics.h"
14#include "mlir/IR/Matchers.h"
15#include "mlir/IR/PatternMatch.h"
16#include "llvm/ADT/SetVector.h"
17#include "llvm/ADT/SmallBitVector.h"
18#include "llvm/ADT/TypeSwitch.h"
19#include "llvm/Support/KnownBits.h"
20
21using namespace mlir;
22using namespace circt;
23using namespace comb;
24using namespace matchers;
25
26// Returns true if the op has one of its own results as an operand.
27static bool isOpTriviallyRecursive(Operation *op) {
28 return llvm::any_of(op->getOperands(), [op](auto operand) {
29 return operand.getDefiningOp() == op;
30 });
31}
32
33/// Create a new instance of a generic operation that only has value operands,
34/// and has a single result value whose type matches the first operand.
35///
36/// This should not be used to create instances of ops with attributes or with
37/// more complicated type signatures.
38static Value createGenericOp(Location loc, OperationName name,
39 ArrayRef<Value> operands, OpBuilder &builder) {
40 OperationState state(loc, name);
41 state.addOperands(operands);
42 state.addTypes(operands[0].getType());
43 return builder.create(state)->getResult(0);
44}
45
46static TypedAttr getIntAttr(const APInt &value, MLIRContext *context) {
47 return IntegerAttr::get(IntegerType::get(context, value.getBitWidth()),
48 value);
49}
50
51/// Flatten concat and mux operands into a vector.
52static void getConcatOperands(Value v, SmallVectorImpl<Value> &result) {
53 if (auto concat = v.getDefiningOp<ConcatOp>()) {
54 for (auto op : concat.getOperands())
55 getConcatOperands(op, result);
56 } else if (auto repl = v.getDefiningOp<ReplicateOp>()) {
57 for (size_t i = 0, e = repl.getMultiple(); i != e; ++i)
58 getConcatOperands(repl.getOperand(), result);
59 } else {
60 result.push_back(v);
61 }
62}
63
64// Return true if the op has SV attributes. Note that we cannot use a helper
65// function `hasSVAttributes` defined under SV dialect because of a cyclic
66// dependency.
67static bool hasSVAttributes(Operation *op) {
68 return op->hasAttr("sv.attributes");
69}
70
71namespace {
72template <typename SubType>
73struct ComplementMatcher {
74 SubType lhs;
75 ComplementMatcher(SubType lhs) : lhs(std::move(lhs)) {}
76 bool match(Operation *op) {
77 auto xorOp = dyn_cast<XorOp>(op);
78 return xorOp && xorOp.isBinaryNot() && lhs.match(op->getOperand(0));
79 }
80};
81} // end anonymous namespace
82
83template <typename SubType>
84static inline ComplementMatcher<SubType> m_Complement(const SubType &subExpr) {
85 return ComplementMatcher<SubType>(subExpr);
86}
87
88/// Return true if the op will be flattened afterwards. Op will be flattend if
89/// it has a single user which has a same op type. User must be in same block.
90static bool shouldBeFlattened(Operation *op) {
91 assert((isa<AndOp, OrOp, XorOp, AddOp, MulOp>(op) &&
92 "must be commutative operations"));
93 if (op->hasOneUse()) {
94 auto *user = *op->getUsers().begin();
95 return user->getName() == op->getName() &&
96 op->getAttrOfType<UnitAttr>("twoState") ==
97 user->getAttrOfType<UnitAttr>("twoState") &&
98 op->getBlock() == user->getBlock();
99 }
100 return false;
101}
102
103/// Flattens a single input in `op` if `hasOneUse` is true and it can be defined
104/// as an Op. Returns true if successful, and false otherwise.
105///
106/// Example: op(1, 2, op(3, 4), 5) -> op(1, 2, 3, 4, 5) // returns true
107///
108static bool tryFlatteningOperands(Operation *op, PatternRewriter &rewriter) {
109 // Skip if the operation should be flattened by another operation.
110 if (shouldBeFlattened(op))
111 return false;
112
113 auto inputs = op->getOperands();
114
115 SmallVector<Value, 4> newOperands;
116 SmallVector<Location, 4> newLocations{op->getLoc()};
117 newOperands.reserve(inputs.size());
118 struct Element {
119 decltype(inputs.begin()) current, end;
120 };
121
122 SmallVector<Element> worklist;
123 worklist.push_back({inputs.begin(), inputs.end()});
124 bool binFlag = op->hasAttrOfType<UnitAttr>("twoState");
125 bool changed = false;
126 while (!worklist.empty()) {
127 auto &element = worklist.back(); // Do not pop. Take ref.
128
129 // Pop when we finished traversing the current operand range.
130 if (element.current == element.end) {
131 worklist.pop_back();
132 continue;
133 }
134
135 Value value = *element.current++;
136 auto *flattenOp = value.getDefiningOp();
137 // If not defined by a compatible operation of the same kind and
138 // from the same block, keep this as-is.
139 if (!flattenOp || flattenOp->getName() != op->getName() ||
140 flattenOp == op || binFlag != op->hasAttrOfType<UnitAttr>("twoState") ||
141 flattenOp->getBlock() != op->getBlock()) {
142 newOperands.push_back(value);
143 continue;
144 }
145
146 // Don't duplicate logic when it has multiple uses.
147 if (!value.hasOneUse()) {
148 // We can fold a multi-use binary operation into this one if this allows a
149 // constant to fold though. For example, fold
150 // (or a, b, c, (or d, cst1), cst2) --> (or a, b, c, d, cst1, cst2)
151 // since the constants will both fold and we end up with the equiv cost.
152 //
153 // We don't do this for add/mul because the hardware won't be shared
154 // between the two ops if duplicated.
155 if (flattenOp->getNumOperands() != 2 || !isa<AndOp, OrOp, XorOp>(op) ||
156 !flattenOp->getOperand(1).getDefiningOp<hw::ConstantOp>() ||
157 !inputs.back().getDefiningOp<hw::ConstantOp>()) {
158 newOperands.push_back(value);
159 continue;
160 }
161 }
162
163 changed = true;
164
165 // Otherwise, push operands into worklist.
166 auto flattenOpInputs = flattenOp->getOperands();
167 worklist.push_back({flattenOpInputs.begin(), flattenOpInputs.end()});
168 newLocations.push_back(flattenOp->getLoc());
169 }
170
171 if (!changed)
172 return false;
173
174 Value result = createGenericOp(FusedLoc::get(op->getContext(), newLocations),
175 op->getName(), newOperands, rewriter);
176 if (binFlag)
177 result.getDefiningOp()->setAttr("twoState", rewriter.getUnitAttr());
178
179 replaceOpAndCopyNamehint(rewriter, op, result);
180 return true;
181}
182
183// Given a range of uses of an operation, find the lowest and highest bits
184// inclusive that are ever referenced. The range of uses must not be empty.
185static std::pair<size_t, size_t>
186getLowestBitAndHighestBitRequired(Operation *op, bool narrowTrailingBits,
187 size_t originalOpWidth) {
188 auto users = op->getUsers();
189 assert(!users.empty() &&
190 "getLowestBitAndHighestBitRequired cannot operate on "
191 "a empty list of uses.");
192
193 // when we don't want to narrowTrailingBits (namely in arithmetic
194 // operations), forcing lowestBitRequired = 0
195 size_t lowestBitRequired = narrowTrailingBits ? originalOpWidth - 1 : 0;
196 size_t highestBitRequired = 0;
197
198 for (auto *user : users) {
199 if (auto extractOp = dyn_cast<ExtractOp>(user)) {
200 size_t lowBit = extractOp.getLowBit();
201 size_t highBit =
202 cast<IntegerType>(extractOp.getType()).getWidth() + lowBit - 1;
203 highestBitRequired = std::max(highestBitRequired, highBit);
204 lowestBitRequired = std::min(lowestBitRequired, lowBit);
205 continue;
206 }
207
208 highestBitRequired = originalOpWidth - 1;
209 lowestBitRequired = 0;
210 break;
211 }
212
213 return {lowestBitRequired, highestBitRequired};
214}
215
216template <class OpTy>
217static bool narrowOperationWidth(OpTy op, bool narrowTrailingBits,
218 PatternRewriter &rewriter) {
219 IntegerType opType = dyn_cast<IntegerType>(op.getResult().getType());
220 if (!opType)
221 return false;
222
223 auto range = getLowestBitAndHighestBitRequired(op, narrowTrailingBits,
224 opType.getWidth());
225 if (range.second + 1 == opType.getWidth() && range.first == 0)
226 return false;
227
228 SmallVector<Value> args;
229 auto newType = rewriter.getIntegerType(range.second - range.first + 1);
230 for (auto inop : op.getOperands()) {
231 // deal with muxes here
232 if (inop.getType() != op.getType())
233 args.push_back(inop);
234 else
235 args.push_back(rewriter.createOrFold<ExtractOp>(inop.getLoc(), newType,
236 inop, range.first));
237 }
238 auto newop = OpTy::create(rewriter, op.getLoc(), newType, args);
239 newop->setDialectAttrs(op->getDialectAttrs());
240 if (op.getTwoState())
241 newop.setTwoState(true);
242
243 Value newResult = newop.getResult();
244 if (range.first)
245 newResult = rewriter.createOrFold<ConcatOp>(
246 op.getLoc(), newResult,
247 hw::ConstantOp::create(rewriter, op.getLoc(),
248 APInt::getZero(range.first)));
249 if (range.second + 1 < opType.getWidth())
250 newResult = rewriter.createOrFold<ConcatOp>(
251 op.getLoc(),
253 rewriter, op.getLoc(),
254 APInt::getZero(opType.getWidth() - range.second - 1)),
255 newResult);
256 rewriter.replaceOp(op, newResult);
257 return true;
258}
259
260//===----------------------------------------------------------------------===//
261// Unary Operations
262//===----------------------------------------------------------------------===//
263
264OpFoldResult ReplicateOp::fold(FoldAdaptor adaptor) {
265 if (isOpTriviallyRecursive(*this))
266 return {};
267
268 // Replicate one time -> noop.
269 if (cast<IntegerType>(getType()).getWidth() ==
270 getInput().getType().getIntOrFloatBitWidth())
271 return getInput();
272
273 // Constant fold.
274 if (auto input = dyn_cast_or_null<IntegerAttr>(adaptor.getInput())) {
275 if (input.getValue().getBitWidth() == 1) {
276 if (input.getValue().isZero())
277 return getIntAttr(
278 APInt::getZero(cast<IntegerType>(getType()).getWidth()),
279 getContext());
280 return getIntAttr(
281 APInt::getAllOnes(cast<IntegerType>(getType()).getWidth()),
282 getContext());
283 }
284
285 APInt result = APInt::getZeroWidth();
286 for (auto i = getMultiple(); i != 0; --i)
287 result = result.concat(input.getValue());
288 return getIntAttr(result, getContext());
289 }
290
291 return {};
292}
293
294OpFoldResult ParityOp::fold(FoldAdaptor adaptor) {
295 if (isOpTriviallyRecursive(*this))
296 return {};
297
298 // Constant fold.
299 if (auto input = dyn_cast_or_null<IntegerAttr>(adaptor.getInput()))
300 return getIntAttr(APInt(1, input.getValue().popcount() & 1), getContext());
301
302 return {};
303}
304
305//===----------------------------------------------------------------------===//
306// Binary Operations
307//===----------------------------------------------------------------------===//
308
309/// Performs constant folding `calculate` with element-wise behavior on the two
310/// attributes in `operands` and returns the result if possible.
311static Attribute constFoldBinaryOp(ArrayRef<Attribute> operands,
312 hw::PEO paramOpcode) {
313 assert(operands.size() == 2 && "binary op takes two operands");
314 if (!operands[0] || !operands[1])
315 return {};
316
317 // Fold constants with ParamExprAttr::get which handles simple constants as
318 // well as parameter expressions.
319 return hw::ParamExprAttr::get(paramOpcode, cast<TypedAttr>(operands[0]),
320 cast<TypedAttr>(operands[1]));
321}
322
323OpFoldResult ShlOp::fold(FoldAdaptor adaptor) {
324 if (isOpTriviallyRecursive(*this))
325 return {};
326
327 if (auto rhs = dyn_cast_or_null<IntegerAttr>(adaptor.getRhs())) {
328 if (rhs.getValue().isZero())
329 return getOperand(0);
330
331 unsigned width = getType().getIntOrFloatBitWidth();
332 if (rhs.getValue().uge(width))
333 return getIntAttr(APInt::getZero(width), getContext());
334 }
335 return constFoldBinaryOp(adaptor.getOperands(), hw::PEO::Shl);
336}
337
338LogicalResult ShlOp::canonicalize(ShlOp op, PatternRewriter &rewriter) {
340 return failure();
341
342 // ShlOp(x, cst) -> Concat(Extract(x), zeros)
343 APInt value;
344 if (!matchPattern(op.getRhs(), m_ConstantInt(&value)))
345 return failure();
346
347 unsigned width = cast<IntegerType>(op.getLhs().getType()).getWidth();
348 if (value.ugt(width))
349 value = width;
350 unsigned shift = value.getZExtValue();
351
352 // This case is handled by fold.
353 if (width <= shift || shift == 0)
354 return failure();
355
356 auto zeros =
357 hw::ConstantOp::create(rewriter, op.getLoc(), APInt::getZero(shift));
358
359 // Remove the high bits which would be removed by the Shl.
360 auto extract =
361 ExtractOp::create(rewriter, op.getLoc(), op.getLhs(), 0, width - shift);
362
363 replaceOpWithNewOpAndCopyNamehint<ConcatOp>(rewriter, op, extract, zeros);
364 return success();
365}
366
367OpFoldResult ShrUOp::fold(FoldAdaptor adaptor) {
368 if (isOpTriviallyRecursive(*this))
369 return {};
370
371 if (auto rhs = dyn_cast_or_null<IntegerAttr>(adaptor.getRhs())) {
372 if (rhs.getValue().isZero())
373 return getOperand(0);
374
375 unsigned width = getType().getIntOrFloatBitWidth();
376 if (rhs.getValue().uge(width))
377 return getIntAttr(APInt::getZero(width), getContext());
378 }
379 return constFoldBinaryOp(adaptor.getOperands(), hw::PEO::ShrU);
380}
381
382LogicalResult ShrUOp::canonicalize(ShrUOp op, PatternRewriter &rewriter) {
384 return failure();
385
386 // ShrUOp(x, cst) -> Concat(zeros, Extract(x))
387 APInt value;
388 if (!matchPattern(op.getRhs(), m_ConstantInt(&value)))
389 return failure();
390
391 unsigned width = cast<IntegerType>(op.getLhs().getType()).getWidth();
392 if (value.ugt(width))
393 value = width;
394 unsigned shift = value.getZExtValue();
395
396 // This case is handled by fold.
397 if (width <= shift || shift == 0)
398 return failure();
399
400 auto zeros =
401 hw::ConstantOp::create(rewriter, op.getLoc(), APInt::getZero(shift));
402
403 // Remove the low bits which would be removed by the Shr.
404 auto extract = ExtractOp::create(rewriter, op.getLoc(), op.getLhs(), shift,
405 width - shift);
406
407 replaceOpWithNewOpAndCopyNamehint<ConcatOp>(rewriter, op, zeros, extract);
408 return success();
409}
410
411OpFoldResult ShrSOp::fold(FoldAdaptor adaptor) {
412 if (isOpTriviallyRecursive(*this))
413 return {};
414
415 if (auto rhs = dyn_cast_or_null<IntegerAttr>(adaptor.getRhs()))
416 if (rhs.getValue().isZero())
417 return getOperand(0);
418 return constFoldBinaryOp(adaptor.getOperands(), hw::PEO::ShrS);
419}
420
421LogicalResult ShrSOp::canonicalize(ShrSOp op, PatternRewriter &rewriter) {
423 return failure();
424
425 // ShrSOp(x, cst) -> Concat(replicate(extract(x, topbit)),extract(x))
426 APInt value;
427 if (!matchPattern(op.getRhs(), m_ConstantInt(&value)))
428 return failure();
429
430 unsigned width = cast<IntegerType>(op.getLhs().getType()).getWidth();
431 if (value.ugt(width))
432 value = width;
433 unsigned shift = value.getZExtValue();
434
435 auto topbit =
436 rewriter.createOrFold<ExtractOp>(op.getLoc(), op.getLhs(), width - 1, 1);
437 auto sext = rewriter.createOrFold<ReplicateOp>(op.getLoc(), topbit, shift);
438
439 if (width == shift) {
440 replaceOpAndCopyNamehint(rewriter, op, {sext});
441 return success();
442 }
443
444 auto extract = ExtractOp::create(rewriter, op.getLoc(), op.getLhs(), shift,
445 width - shift);
446
447 replaceOpWithNewOpAndCopyNamehint<ConcatOp>(rewriter, op, sext, extract);
448 return success();
449}
450
451//===----------------------------------------------------------------------===//
452// Other Operations
453//===----------------------------------------------------------------------===//
454
455OpFoldResult ExtractOp::fold(FoldAdaptor adaptor) {
456 if (isOpTriviallyRecursive(*this))
457 return {};
458
459 // If we are extracting the entire input, then return it.
460 if (getInput().getType() == getType())
461 return getInput();
462
463 // Constant fold.
464 if (auto input = dyn_cast_or_null<IntegerAttr>(adaptor.getInput())) {
465 unsigned dstWidth = cast<IntegerType>(getType()).getWidth();
466 return getIntAttr(input.getValue().lshr(getLowBit()).trunc(dstWidth),
467 getContext());
468 }
469 return {};
470}
471
472// Transforms extract(lo, cat(a, b, c, d, e)) into
473// cat(extract(lo1, b), c, extract(lo2, d)).
474// innerCat must be the argument of the provided ExtractOp.
476 ConcatOp innerCat,
477 PatternRewriter &rewriter) {
478 auto reversedConcatArgs = llvm::reverse(innerCat.getInputs());
479 size_t beginOfFirstRelevantElement = 0;
480 auto it = reversedConcatArgs.begin();
481 size_t lowBit = op.getLowBit();
482
483 // This loop finds the first concatArg that is covered by the ExtractOp
484 for (; it != reversedConcatArgs.end(); it++) {
485 assert(beginOfFirstRelevantElement <= lowBit &&
486 "incorrectly moved past an element that lowBit has coverage over");
487 auto operand = *it;
488
489 size_t operandWidth = operand.getType().getIntOrFloatBitWidth();
490 if (lowBit < beginOfFirstRelevantElement + operandWidth) {
491 // A bit other than the first bit will be used in this element.
492 // ...... ........ ...
493 // ^---lowBit
494 // ^---beginOfFirstRelevantElement
495 //
496 // Edge-case close to the end of the range.
497 // ...... ........ ...
498 // ^---(position + operandWidth)
499 // ^---lowBit
500 // ^---beginOfFirstRelevantElement
501 //
502 // Edge-case close to the beginning of the rang
503 // ...... ........ ...
504 // ^---lowBit
505 // ^---beginOfFirstRelevantElement
506 //
507 break;
508 }
509
510 // extraction discards this element.
511 // ...... ........ ...
512 // | ^---lowBit
513 // ^---beginOfFirstRelevantElement
514 beginOfFirstRelevantElement += operandWidth;
515 }
516 assert(it != reversedConcatArgs.end() &&
517 "incorrectly failed to find an element which contains coverage of "
518 "lowBit");
519
520 SmallVector<Value> reverseConcatArgs;
521 size_t widthRemaining = cast<IntegerType>(op.getType()).getWidth();
522 size_t extractLo = lowBit - beginOfFirstRelevantElement;
523
524 // Transform individual arguments of innerCat(..., a, b, c,) into
525 // [ extract(a), b, extract(c) ], skipping an extract operation where
526 // possible.
527 for (; widthRemaining != 0 && it != reversedConcatArgs.end(); it++) {
528 auto concatArg = *it;
529 size_t operandWidth = concatArg.getType().getIntOrFloatBitWidth();
530 size_t widthToConsume = std::min(widthRemaining, operandWidth - extractLo);
531
532 if (widthToConsume == operandWidth && extractLo == 0) {
533 reverseConcatArgs.push_back(concatArg);
534 } else {
535 auto resultType = IntegerType::get(rewriter.getContext(), widthToConsume);
536 reverseConcatArgs.push_back(
537 ExtractOp::create(rewriter, op.getLoc(), resultType, *it, extractLo));
538 }
539
540 widthRemaining -= widthToConsume;
541
542 // Beyond the first element, all elements are extracted from position 0.
543 extractLo = 0;
544 }
545
546 if (reverseConcatArgs.size() == 1) {
547 replaceOpAndCopyNamehint(rewriter, op, reverseConcatArgs[0]);
548 } else {
549 replaceOpWithNewOpAndCopyNamehint<ConcatOp>(
550 rewriter, op, SmallVector<Value>(llvm::reverse(reverseConcatArgs)));
551 }
552 return success();
553}
554
555// Transforms extract(lo, replicate(a, N)) into replicate(a, N-c).
556static bool extractFromReplicate(ExtractOp op, ReplicateOp replicate,
557 PatternRewriter &rewriter) {
558 auto extractResultWidth = cast<IntegerType>(op.getType()).getWidth();
559 auto replicateEltWidth =
560 replicate.getOperand().getType().getIntOrFloatBitWidth();
561
562 // If the extract starts at the base of an element and is an even multiple,
563 // we can replace the extract with a smaller replicate.
564 if (op.getLowBit() % replicateEltWidth == 0 &&
565 extractResultWidth % replicateEltWidth == 0) {
566 replaceOpWithNewOpAndCopyNamehint<ReplicateOp>(rewriter, op, op.getType(),
567 replicate.getOperand());
568 return true;
569 }
570
571 // If the extract is completely contained in one element, extract from the
572 // element.
573 if (op.getLowBit() % replicateEltWidth + extractResultWidth <=
574 replicateEltWidth) {
575 replaceOpWithNewOpAndCopyNamehint<ExtractOp>(
576 rewriter, op, op.getType(), replicate.getOperand(),
577 op.getLowBit() % replicateEltWidth);
578 return true;
579 }
580
581 // We don't currently handle the case of extracting from non-whole elements,
582 // e.g. `extract (replicate 2-bit-thing, N), 1`.
583 return false;
584}
585
586LogicalResult ExtractOp::canonicalize(ExtractOp op, PatternRewriter &rewriter) {
588 return failure();
589 auto *inputOp = op.getInput().getDefiningOp();
590
591 // This turns out to be incredibly expensive. Disable until performance is
592 // addressed.
593#if 0
594 // If the extracted bits are all known, then return the result.
595 auto knownBits = computeKnownBits(op.getInput())
596 .extractBits(cast<IntegerType>(op.getType()).getWidth(),
597 op.getLowBit());
598 if (knownBits.isConstant()) {
599 replaceOpWithNewOpAndCopyNamehint<hw::ConstantOp>(rewriter, op,
600 knownBits.getConstant());
601 return success();
602 }
603#endif
604
605 // extract(olo, extract(ilo, x)) = extract(olo + ilo, x)
606 if (auto innerExtract = dyn_cast_or_null<ExtractOp>(inputOp)) {
607 replaceOpWithNewOpAndCopyNamehint<ExtractOp>(
608 rewriter, op, op.getType(), innerExtract.getInput(),
609 innerExtract.getLowBit() + op.getLowBit());
610 return success();
611 }
612
613 // extract(lo, cat(a, b, c, d, e)) = cat(extract(lo1, b), c, extract(lo2, d))
614 if (auto innerCat = dyn_cast_or_null<ConcatOp>(inputOp))
615 return extractConcatToConcatExtract(op, innerCat, rewriter);
616
617 // extract(lo, replicate(a))
618 if (auto replicate = dyn_cast_or_null<ReplicateOp>(inputOp))
619 if (extractFromReplicate(op, replicate, rewriter))
620 return success();
621
622 // `extract(and(a, cst))` -> `extract(a)` when the relevant bits of the
623 // and/or/xor are not modifying the extracted bits.
624 if (inputOp && inputOp->getNumOperands() == 2 &&
625 isa<AndOp, OrOp, XorOp>(inputOp)) {
626 if (auto cstRHS = inputOp->getOperand(1).getDefiningOp<hw::ConstantOp>()) {
627 auto extractedCst = cstRHS.getValue().extractBits(
628 cast<IntegerType>(op.getType()).getWidth(), op.getLowBit());
629 if (isa<OrOp, XorOp>(inputOp) && extractedCst.isZero()) {
630 replaceOpWithNewOpAndCopyNamehint<ExtractOp>(
631 rewriter, op, op.getType(), inputOp->getOperand(0), op.getLowBit());
632 return success();
633 }
634
635 // `extract(and(a, cst))` -> `concat(extract(a), 0)` if we only need one
636 // extract to represent the result. Turning it into a pile of extracts is
637 // always fine by our cost model, but we don't want to explode things into
638 // a ton of bits because it will bloat the IR and generated Verilog.
639 if (isa<AndOp>(inputOp)) {
640 // For our cost model, we only do this if the bit pattern is a
641 // contiguous series of ones.
642 unsigned lz = extractedCst.countLeadingZeros();
643 unsigned tz = extractedCst.countTrailingZeros();
644 unsigned pop = extractedCst.popcount();
645 if (extractedCst.getBitWidth() - lz - tz == pop) {
646 auto resultTy = rewriter.getIntegerType(pop);
647 SmallVector<Value> resultElts;
648 if (lz)
649 resultElts.push_back(hw::ConstantOp::create(rewriter, op.getLoc(),
650 APInt::getZero(lz)));
651 resultElts.push_back(rewriter.createOrFold<ExtractOp>(
652 op.getLoc(), resultTy, inputOp->getOperand(0),
653 op.getLowBit() + tz));
654 if (tz)
655 resultElts.push_back(hw::ConstantOp::create(rewriter, op.getLoc(),
656 APInt::getZero(tz)));
657 replaceOpWithNewOpAndCopyNamehint<ConcatOp>(rewriter, op, resultElts);
658 return success();
659 }
660 }
661 }
662 }
663
664 // `extract(lowBit, shl(1, x))` -> `x == lowBit` when a single bit is
665 // extracted.
666 if (cast<IntegerType>(op.getType()).getWidth() == 1 && inputOp)
667 if (auto shlOp = dyn_cast<ShlOp>(inputOp)) {
668 // Don't canonicalize if the shift is multiply used.
669 if (shlOp->hasOneUse())
670 if (auto lhsCst = shlOp.getLhs().getDefiningOp<hw::ConstantOp>())
671 if (lhsCst.getValue().isOne()) {
672 auto newCst = hw::ConstantOp::create(
673 rewriter, shlOp.getLoc(),
674 APInt(lhsCst.getValue().getBitWidth(), op.getLowBit()));
675 replaceOpWithNewOpAndCopyNamehint<ICmpOp>(
676 rewriter, op, ICmpPredicate::eq, shlOp->getOperand(1), newCst,
677 false);
678 return success();
679 }
680 }
681
682 return failure();
683}
684
685//===----------------------------------------------------------------------===//
686// Associative Variadic operations
687//===----------------------------------------------------------------------===//
688
689// Reduce all operands to a single value (either integer constant or parameter
690// expression) if all the operands are constants.
691static Attribute constFoldAssociativeOp(ArrayRef<Attribute> operands,
692 hw::PEO paramOpcode) {
693 assert(operands.size() > 1 && "caller should handle one-operand case");
694 // We can only fold anything in the case where all operands are known to be
695 // constants. Check the least common one first for an early out.
696 if (!operands[1] || !operands[0])
697 return {};
698
699 // This will fold to a simple constant if all operands are constant.
700 if (llvm::all_of(operands.drop_front(2),
701 [&](Attribute in) { return !!in; })) {
702 SmallVector<mlir::TypedAttr> typedOperands;
703 typedOperands.reserve(operands.size());
704 for (auto operand : operands) {
705 if (auto typedOperand = dyn_cast<mlir::TypedAttr>(operand))
706 typedOperands.push_back(typedOperand);
707 else
708 break;
709 }
710 if (typedOperands.size() == operands.size())
711 return hw::ParamExprAttr::get(paramOpcode, typedOperands);
712 }
713
714 return {};
715}
716
717/// When we find a logical operation (and, or, xor) with a constant e.g.
718/// `X & 42`, we want to push the constant into the computation of X if it leads
719/// to simplification.
720///
721/// This function handles the case where the logical operation has a concat
722/// operand. We check to see if we can simplify the concat, e.g. when it has
723/// constant operands.
724///
725/// This returns true when a simplification happens.
726static bool canonicalizeLogicalCstWithConcat(Operation *logicalOp,
727 size_t concatIdx, const APInt &cst,
728 PatternRewriter &rewriter) {
729 auto concatOp = logicalOp->getOperand(concatIdx).getDefiningOp<ConcatOp>();
730 assert((isa<AndOp, OrOp, XorOp>(logicalOp) && concatOp));
731
732 // Check to see if any operands can be simplified by pushing the logical op
733 // into all parts of the concat.
734 bool canSimplify =
735 llvm::any_of(concatOp->getOperands(), [&](Value operand) -> bool {
736 auto *operandOp = operand.getDefiningOp();
737 if (!operandOp)
738 return false;
739
740 // If the concat has a constant operand then we can transform this.
741 if (isa<hw::ConstantOp>(operandOp))
742 return true;
743 // If the concat has the same logical operation and that operation has
744 // a constant operation than we can fold it into that suboperation.
745 return operandOp->getName() == logicalOp->getName() &&
746 operandOp->hasOneUse() && operandOp->getNumOperands() != 0 &&
747 operandOp->getOperands().back().getDefiningOp<hw::ConstantOp>();
748 });
749
750 if (!canSimplify)
751 return false;
752
753 // Create a new instance of the logical operation. We have to do this the
754 // hard way since we're generic across a family of different ops.
755 auto createLogicalOp = [&](ArrayRef<Value> operands) -> Value {
756 return createGenericOp(logicalOp->getLoc(), logicalOp->getName(), operands,
757 rewriter);
758 };
759
760 // Ok, let's do the transformation. We do this by slicing up the constant
761 // for each unit of the concat and duplicate the operation into the
762 // sub-operand.
763 SmallVector<Value> newConcatOperands;
764 newConcatOperands.reserve(concatOp->getNumOperands());
765
766 // Work from MSB to LSB.
767 size_t nextOperandBit = concatOp.getType().getIntOrFloatBitWidth();
768 for (Value operand : concatOp->getOperands()) {
769 size_t operandWidth = operand.getType().getIntOrFloatBitWidth();
770 nextOperandBit -= operandWidth;
771 // Take a slice of the constant.
772 auto eltCst =
773 hw::ConstantOp::create(rewriter, logicalOp->getLoc(),
774 cst.lshr(nextOperandBit).trunc(operandWidth));
775
776 newConcatOperands.push_back(createLogicalOp({operand, eltCst}));
777 }
778
779 // Create the concat, and the rest of the logical op if we need it.
780 Value newResult =
781 ConcatOp::create(rewriter, concatOp.getLoc(), newConcatOperands);
782
783 // If we had a variadic logical op on the top level, then recreate it with the
784 // new concat and without the constant operand.
785 if (logicalOp->getNumOperands() > 2) {
786 auto origOperands = logicalOp->getOperands();
787 SmallVector<Value> operands;
788 // Take any stuff before the concat.
789 operands.append(origOperands.begin(), origOperands.begin() + concatIdx);
790 // Take any stuff after the concat but before the constant.
791 operands.append(origOperands.begin() + concatIdx + 1,
792 origOperands.begin() + (origOperands.size() - 1));
793 // Include the new concat.
794 operands.push_back(newResult);
795 newResult = createLogicalOp(operands);
796 }
797
798 replaceOpAndCopyNamehint(rewriter, logicalOp, newResult);
799 return true;
800}
801
802// Determines whether the inputs to a logical element are of opposite
803// comparisons and can lowered into a constant.
804static bool canCombineOppositeBinCmpIntoConstant(OperandRange operands) {
805 llvm::SmallDenseSet<std::tuple<ICmpPredicate, Value, Value>> seenPredicates;
806
807 for (auto op : operands) {
808 if (auto icmpOp = op.getDefiningOp<ICmpOp>();
809 icmpOp && icmpOp.getTwoState()) {
810 auto predicate = icmpOp.getPredicate();
811 auto lhs = icmpOp.getLhs();
812 auto rhs = icmpOp.getRhs();
813 if (seenPredicates.contains(
814 {ICmpOp::getNegatedPredicate(predicate), lhs, rhs}))
815 return true;
816
817 seenPredicates.insert({predicate, lhs, rhs});
818 }
819 }
820 return false;
821}
822
823OpFoldResult AndOp::fold(FoldAdaptor adaptor) {
824 if (isOpTriviallyRecursive(*this))
825 return {};
826
827 APInt value = APInt::getAllOnes(cast<IntegerType>(getType()).getWidth());
828
829 auto inputs = adaptor.getInputs();
830
831 // and(x, 01, 10) -> 00 -- annulment.
832 for (auto operand : inputs) {
833 if (!operand)
834 continue;
835 value &= cast<IntegerAttr>(operand).getValue();
836 if (value.isZero())
837 return getIntAttr(value, getContext());
838 }
839
840 // and(x, -1) -> x.
841 if (inputs.size() == 2 && inputs[1] &&
842 cast<IntegerAttr>(inputs[1]).getValue().isAllOnes())
843 return getInputs()[0];
844
845 // and(x, x, x) -> x. This also handles and(x) -> x.
846 if (llvm::all_of(getInputs(),
847 [&](auto in) { return in == this->getInputs()[0]; }))
848 return getInputs()[0];
849
850 // and(..., x, ..., ~x, ...) -> 0
851 for (Value arg : getInputs()) {
852 Value subExpr;
853 if (matchPattern(arg, m_Complement(m_Any(&subExpr)))) {
854 for (Value arg2 : getInputs())
855 if (arg2 == subExpr)
856 return getIntAttr(
857 APInt::getZero(cast<IntegerType>(getType()).getWidth()),
858 getContext());
859 }
860 }
861
862 // x0 = icmp(pred, x, y)
863 // x1 = icmp(!pred, x, y)
864 // and(x0, x1) -> 0
866 return getIntAttr(APInt::getZero(cast<IntegerType>(getType()).getWidth()),
867 getContext());
868
869 // Constant fold
870 return constFoldAssociativeOp(inputs, hw::PEO::And);
871}
872
873/// Returns a single common operand that all inputs of the operation `op` can
874/// be traced back to, or an empty `Value` if no such operand exists.
875///
876/// For example for `or(a[0], a[1], ..., a[n-1])` this function returns `a`
877/// (assuming the bit-width of `a` is `n`).
878template <typename Op>
879static Value getCommonOperand(Op op) {
880 if (!op.getType().isInteger(1))
881 return Value();
882
883 auto inputs = op.getInputs();
884 size_t size = inputs.size();
885
886 auto sourceOp = inputs[0].template getDefiningOp<ExtractOp>();
887 if (!sourceOp)
888 return Value();
889 Value source = sourceOp.getOperand();
890
891 // Fast path: the input size is not equal to the width of the source.
892 if (size != source.getType().getIntOrFloatBitWidth())
893 return Value();
894
895 // Tracks the bits that were encountered.
896 llvm::BitVector bits(size);
897 bits.set(sourceOp.getLowBit());
898
899 for (size_t i = 1; i != size; ++i) {
900 auto extractOp = inputs[i].template getDefiningOp<ExtractOp>();
901 if (!extractOp || extractOp.getOperand() != source)
902 return Value();
903 bits.set(extractOp.getLowBit());
904 }
905
906 return bits.all() ? source : Value();
907}
908
909/// Canonicalize an idempotent operation `op` so that only one input of any kind
910/// occurs.
911///
912/// Example: `and(x, y, x, z)` -> `and(x, y, z)`
913template <typename Op>
914static bool canonicalizeIdempotentInputs(Op op, PatternRewriter &rewriter) {
915 // Depth limit to search, in operations. Chosen arbitrarily, keep small.
916 constexpr unsigned limit = 3;
917 auto inputs = op.getInputs();
918
919 llvm::SmallSetVector<Value, 8> uniqueInputs(inputs.begin(), inputs.end());
920 llvm::SmallDenseSet<Op, 8> checked;
921 checked.insert(op);
922
923 struct OpWithDepth {
924 Op op;
925 unsigned depth;
926 };
927 llvm::SmallVector<OpWithDepth, 8> worklist;
928
929 auto enqueue = [&worklist, &checked, &op](Value input, unsigned depth) {
930 // Add to worklist if within depth limit, is defined in the same block by
931 // the same kind of operation, has same two-state-ness, and not enqueued
932 // previously.
933 if (depth < limit && input.getParentBlock() == op->getBlock()) {
934 auto inputOp = input.template getDefiningOp<Op>();
935 if (inputOp && inputOp.getTwoState() == op.getTwoState() &&
936 checked.insert(inputOp).second)
937 worklist.push_back({inputOp, depth + 1});
938 }
939 };
940
941 for (auto input : uniqueInputs)
942 enqueue(input, 0);
943
944 while (!worklist.empty()) {
945 auto item = worklist.pop_back_val();
946
947 for (auto input : item.op.getInputs()) {
948 uniqueInputs.remove(input);
949 enqueue(input, item.depth);
950 }
951 }
952
953 if (uniqueInputs.size() < inputs.size()) {
954 replaceOpWithNewOpAndCopyNamehint<Op>(rewriter, op, op.getType(),
955 uniqueInputs.getArrayRef(),
956 op.getTwoState());
957 return true;
958 }
959
960 return false;
961}
962
963LogicalResult AndOp::canonicalize(AndOp op, PatternRewriter &rewriter) {
965 return failure();
966
967 auto inputs = op.getInputs();
968 auto size = inputs.size();
969
970 // and(x, and(...)) -> and(x, ...) -- flatten
971 if (tryFlatteningOperands(op, rewriter))
972 return success();
973
974 // and(..., x, ..., x) -> and(..., x, ...) -- idempotent
975 // and(..., x, and(..., x, ...)) -> and(..., and(..., x, ...)) -- idempotent
976 // Trivial and(x), and(x, x) cases are handled by [AndOp::fold] above.
977 if (size > 1 && canonicalizeIdempotentInputs(op, rewriter))
978 return success();
979
980 assert(size > 1 && "expected 2 or more operands, `fold` should handle this");
981
982 // Patterns for and with a constant on RHS.
983 APInt value;
984 if (matchPattern(inputs.back(), m_ConstantInt(&value))) {
985 // and(..., '1) -> and(...) -- identity
986 if (value.isAllOnes()) {
987 replaceOpWithNewOpAndCopyNamehint<AndOp>(rewriter, op, op.getType(),
988 inputs.drop_back(), false);
989 return success();
990 }
991
992 // TODO: Combine multiple constants together even if they aren't at the
993 // end. and(..., c1, c2) -> and(..., c3) where c3 = c1 & c2 -- constant
994 // folding
995 APInt value2;
996 if (matchPattern(inputs[size - 2], m_ConstantInt(&value2))) {
997 auto cst = hw::ConstantOp::create(rewriter, op.getLoc(), value & value2);
998 SmallVector<Value, 4> newOperands(inputs.drop_back(/*n=*/2));
999 newOperands.push_back(cst);
1000 replaceOpWithNewOpAndCopyNamehint<AndOp>(rewriter, op, op.getType(),
1001 newOperands, false);
1002 return success();
1003 }
1004
1005 // Handle 'and' with a single bit constant on the RHS.
1006 if (size == 2 && value.isPowerOf2()) {
1007 // If the LHS is a replicate from a single bit, we can 'concat' it
1008 // into place. e.g.:
1009 // `replicate(x) & 4` -> `concat(zeros, x, zeros)`
1010 // TODO: Generalize this for non-single-bit operands.
1011 if (auto replicate = inputs[0].getDefiningOp<ReplicateOp>()) {
1012 auto replicateOperand = replicate.getOperand();
1013 if (replicateOperand.getType().isInteger(1)) {
1014 unsigned resultWidth = op.getType().getIntOrFloatBitWidth();
1015 auto trailingZeros = value.countTrailingZeros();
1016
1017 // Don't add zero bit constants unnecessarily.
1018 SmallVector<Value, 3> concatOperands;
1019 if (trailingZeros != resultWidth - 1) {
1020 auto highZeros = hw::ConstantOp::create(
1021 rewriter, op.getLoc(),
1022 APInt::getZero(resultWidth - trailingZeros - 1));
1023 concatOperands.push_back(highZeros);
1024 }
1025 concatOperands.push_back(replicateOperand);
1026 if (trailingZeros != 0) {
1027 auto lowZeros = hw::ConstantOp::create(
1028 rewriter, op.getLoc(), APInt::getZero(trailingZeros));
1029 concatOperands.push_back(lowZeros);
1030 }
1031 replaceOpWithNewOpAndCopyNamehint<ConcatOp>(
1032 rewriter, op, op.getType(), concatOperands);
1033 return success();
1034 }
1035 }
1036 }
1037
1038 // Narrow the op if the constant has leading or trailing zeros.
1039 //
1040 // and(a, 0b00101100) -> concat(0b00, and(extract(a), 0b1011), 0b00)
1041 unsigned leadingZeros = value.countLeadingZeros();
1042 unsigned trailingZeros = value.countTrailingZeros();
1043 if (leadingZeros > 0 || trailingZeros > 0) {
1044 unsigned maskLength = value.getBitWidth() - leadingZeros - trailingZeros;
1045
1046 // Extract the non-zero regions of the operands. Look through extracts.
1047 SmallVector<Value> operands;
1048 for (auto input : inputs.drop_back()) {
1049 unsigned offset = trailingZeros;
1050 while (auto extractOp = input.getDefiningOp<ExtractOp>()) {
1051 input = extractOp.getInput();
1052 offset += extractOp.getLowBit();
1053 }
1054 operands.push_back(ExtractOp::create(rewriter, op.getLoc(), input,
1055 offset, maskLength));
1056 }
1057
1058 // Add the narrowed mask if needed.
1059 auto narrowMask = value.extractBits(maskLength, trailingZeros);
1060 if (!narrowMask.isAllOnes())
1061 operands.push_back(hw::ConstantOp::create(
1062 rewriter, inputs.back().getLoc(), narrowMask));
1063
1064 // Create the narrow and op.
1065 Value narrowValue = operands.back();
1066 if (operands.size() > 1)
1067 narrowValue =
1068 AndOp::create(rewriter, op.getLoc(), operands, op.getTwoState());
1069 operands.clear();
1070
1071 // Concatenate the narrow and with the leading and trailing zeros.
1072 if (leadingZeros > 0)
1073 operands.push_back(hw::ConstantOp::create(
1074 rewriter, op.getLoc(), APInt::getZero(leadingZeros)));
1075 operands.push_back(narrowValue);
1076 if (trailingZeros > 0)
1077 operands.push_back(hw::ConstantOp::create(
1078 rewriter, op.getLoc(), APInt::getZero(trailingZeros)));
1079 replaceOpWithNewOpAndCopyNamehint<ConcatOp>(rewriter, op, operands);
1080 return success();
1081 }
1082
1083 // and(concat(x, cst1), a, b, c, cst2)
1084 // ==> and(a, b, c, concat(and(x,cst2'), and(cst1,cst2'')).
1085 // We do this for even more multi-use concats since they are "just wiring".
1086 for (size_t i = 0; i < size - 1; ++i) {
1087 if (auto concat = inputs[i].getDefiningOp<ConcatOp>())
1088 if (canonicalizeLogicalCstWithConcat(op, i, value, rewriter))
1089 return success();
1090 }
1091 }
1092
1093 // extracts only of and(...) -> and(extract()...)
1094 if (narrowOperationWidth(op, true, rewriter))
1095 return success();
1096
1097 // and(a[0], a[1], ..., a[n]) -> icmp eq(a, -1)
1098 if (auto source = getCommonOperand(op)) {
1099 auto cmpAgainst =
1100 hw::ConstantOp::create(rewriter, op.getLoc(), APInt::getAllOnes(size));
1101 replaceOpWithNewOpAndCopyNamehint<ICmpOp>(rewriter, op, ICmpPredicate::eq,
1102 source, cmpAgainst);
1103 return success();
1104 }
1105
1106 /// TODO: and(..., x, not(x)) -> and(..., 0) -- complement
1107 return failure();
1108}
1109
1110OpFoldResult OrOp::fold(FoldAdaptor adaptor) {
1111 if (isOpTriviallyRecursive(*this))
1112 return {};
1113
1114 auto value = APInt::getZero(cast<IntegerType>(getType()).getWidth());
1115 auto inputs = adaptor.getInputs();
1116 // or(x, 10, 01) -> 11
1117 for (auto operand : inputs) {
1118 if (!operand)
1119 continue;
1120 value |= cast<IntegerAttr>(operand).getValue();
1121 if (value.isAllOnes())
1122 return getIntAttr(value, getContext());
1123 }
1124
1125 // or(x, 0) -> x
1126 if (inputs.size() == 2 && inputs[1] &&
1127 cast<IntegerAttr>(inputs[1]).getValue().isZero())
1128 return getInputs()[0];
1129
1130 // or(x, x, x) -> x. This also handles or(x) -> x
1131 if (llvm::all_of(getInputs(),
1132 [&](auto in) { return in == this->getInputs()[0]; }))
1133 return getInputs()[0];
1134
1135 // or(..., x, ..., ~x, ...) -> -1
1136 for (Value arg : getInputs()) {
1137 Value subExpr;
1138 if (matchPattern(arg, m_Complement(m_Any(&subExpr)))) {
1139 for (Value arg2 : getInputs())
1140 if (arg2 == subExpr)
1141 return getIntAttr(
1142 APInt::getAllOnes(cast<IntegerType>(getType()).getWidth()),
1143 getContext());
1144 }
1145 }
1146
1147 // x0 = icmp(pred, x, y)
1148 // x1 = icmp(!pred, x, y)
1149 // or(x0, x1) -> 1
1150 if (canCombineOppositeBinCmpIntoConstant(getInputs()))
1151 return getIntAttr(
1152 APInt::getAllOnes(cast<IntegerType>(getType()).getWidth()),
1153 getContext());
1154
1155 // Constant fold
1156 return constFoldAssociativeOp(inputs, hw::PEO::Or);
1157}
1158
1159LogicalResult OrOp::canonicalize(OrOp op, PatternRewriter &rewriter) {
1160 if (isOpTriviallyRecursive(op))
1161 return failure();
1162
1163 auto inputs = op.getInputs();
1164 auto size = inputs.size();
1165
1166 // or(x, or(...)) -> or(x, ...) -- flatten
1167 if (tryFlatteningOperands(op, rewriter))
1168 return success();
1169
1170 // or(..., x, ..., x, ...) -> or(..., x) -- idempotent
1171 // or(..., x, or(..., x, ...)) -> or(..., or(..., x, ...)) -- idempotent
1172 // Trivial or(x), or(x, x) cases are handled by [OrOp::fold].
1173 if (size > 1 && canonicalizeIdempotentInputs(op, rewriter))
1174 return success();
1175
1176 assert(size > 1 && "expected 2 or more operands");
1177
1178 // Patterns for and with a constant on RHS.
1179 APInt value;
1180 if (matchPattern(inputs.back(), m_ConstantInt(&value))) {
1181 // or(..., '0) -> or(...) -- identity
1182 if (value.isZero()) {
1183 replaceOpWithNewOpAndCopyNamehint<OrOp>(rewriter, op, op.getType(),
1184 inputs.drop_back());
1185 return success();
1186 }
1187
1188 // or(..., c1, c2) -> or(..., c3) where c3 = c1 | c2 -- constant folding
1189 APInt value2;
1190 if (matchPattern(inputs[size - 2], m_ConstantInt(&value2))) {
1191 auto cst = hw::ConstantOp::create(rewriter, op.getLoc(), value | value2);
1192 SmallVector<Value, 4> newOperands(inputs.drop_back(/*n=*/2));
1193 newOperands.push_back(cst);
1194 replaceOpWithNewOpAndCopyNamehint<OrOp>(rewriter, op, op.getType(),
1195 newOperands);
1196 return success();
1197 }
1198
1199 // or(concat(x, cst1), a, b, c, cst2)
1200 // ==> or(a, b, c, concat(or(x,cst2'), or(cst1,cst2'')).
1201 // We do this for even more multi-use concats since they are "just wiring".
1202 for (size_t i = 0; i < size - 1; ++i) {
1203 if (auto concat = inputs[i].getDefiningOp<ConcatOp>())
1204 if (canonicalizeLogicalCstWithConcat(op, i, value, rewriter))
1205 return success();
1206 }
1207 }
1208
1209 // extracts only of or(...) -> or(extract()...)
1210 if (narrowOperationWidth(op, true, rewriter))
1211 return success();
1212
1213 // or(a[0], a[1], ..., a[n]) -> icmp ne(a, 0)
1214 if (auto source = getCommonOperand(op)) {
1215 auto cmpAgainst =
1216 hw::ConstantOp::create(rewriter, op.getLoc(), APInt::getZero(size));
1217 replaceOpWithNewOpAndCopyNamehint<ICmpOp>(rewriter, op, ICmpPredicate::ne,
1218 source, cmpAgainst);
1219 return success();
1220 }
1221
1222 // or(mux(c_1, a, 0), mux(c_2, a, 0), ..., mux(c_n, a, 0)) -> mux(or(c_1, c_2,
1223 // .., c_n), a, 0)
1224 if (auto firstMux = op.getOperand(0).getDefiningOp<comb::MuxOp>()) {
1225 APInt value;
1226 if (op.getTwoState() && firstMux.getTwoState() &&
1227 matchPattern(firstMux.getFalseValue(), m_ConstantInt(&value)) &&
1228 value.isZero()) {
1229 SmallVector<Value> conditions{firstMux.getCond()};
1230 auto check = [&](Value v) {
1231 auto mux = v.getDefiningOp<comb::MuxOp>();
1232 if (!mux)
1233 return false;
1234 conditions.push_back(mux.getCond());
1235 return mux.getTwoState() &&
1236 firstMux.getTrueValue() == mux.getTrueValue() &&
1237 firstMux.getFalseValue() == mux.getFalseValue();
1238 };
1239 if (llvm::all_of(op.getOperands().drop_front(), check)) {
1240 auto cond = comb::OrOp::create(rewriter, op.getLoc(), conditions, true);
1241 replaceOpWithNewOpAndCopyNamehint<comb::MuxOp>(
1242 rewriter, op, cond, firstMux.getTrueValue(),
1243 firstMux.getFalseValue(), true);
1244 return success();
1245 }
1246 }
1247 }
1248
1249 /// TODO: or(..., x, not(x)) -> or(..., '1) -- complement
1250 return failure();
1251}
1252
1253OpFoldResult XorOp::fold(FoldAdaptor adaptor) {
1254 if (isOpTriviallyRecursive(*this))
1255 return {};
1256
1257 auto size = getInputs().size();
1258 auto inputs = adaptor.getInputs();
1259
1260 // xor(x) -> x -- noop
1261 if (size == 1)
1262 return getInputs()[0];
1263
1264 // xor(x, x) -> 0 -- idempotent
1265 if (size == 2 && getInputs()[0] == getInputs()[1])
1266 return IntegerAttr::get(getType(), 0);
1267
1268 // xor(x, 0) -> x
1269 if (inputs.size() == 2 && inputs[1] &&
1270 cast<IntegerAttr>(inputs[1]).getValue().isZero())
1271 return getInputs()[0];
1272
1273 // xor(xor(x,1),1) -> x
1274 // but not self loop
1275 if (isBinaryNot()) {
1276 Value subExpr;
1277 if (matchPattern(getOperand(0), m_Complement(m_Any(&subExpr))) &&
1278 subExpr != getResult())
1279 return subExpr;
1280 }
1281
1282 // Constant fold
1283 return constFoldAssociativeOp(inputs, hw::PEO::Xor);
1284}
1285
1286// xor(icmp, a, b, 1) -> xor(icmp, a, b) if icmp has one user.
1287static void canonicalizeXorIcmpTrue(XorOp op, unsigned icmpOperand,
1288 PatternRewriter &rewriter) {
1289 auto icmp = op.getOperand(icmpOperand).getDefiningOp<ICmpOp>();
1290 auto negatedPred = ICmpOp::getNegatedPredicate(icmp.getPredicate());
1291
1292 Value result =
1293 ICmpOp::create(rewriter, icmp.getLoc(), negatedPred, icmp.getOperand(0),
1294 icmp.getOperand(1), icmp.getTwoState());
1295
1296 // If the xor had other operands, rebuild it.
1297 if (op.getNumOperands() > 2) {
1298 SmallVector<Value, 4> newOperands(op.getOperands());
1299 newOperands.pop_back();
1300 newOperands.erase(newOperands.begin() + icmpOperand);
1301 newOperands.push_back(result);
1302 result =
1303 XorOp::create(rewriter, op.getLoc(), newOperands, op.getTwoState());
1304 }
1305
1306 replaceOpAndCopyNamehint(rewriter, op, result);
1307}
1308
1309LogicalResult XorOp::canonicalize(XorOp op, PatternRewriter &rewriter) {
1310 if (isOpTriviallyRecursive(op))
1311 return failure();
1312
1313 auto inputs = op.getInputs();
1314 auto size = inputs.size();
1315 assert(size > 1 && "expected 2 or more operands");
1316
1317 // xor(..., x, x) -> xor (...) -- idempotent
1318 if (inputs[size - 1] == inputs[size - 2]) {
1319 assert(size > 2 &&
1320 "expected idempotent case for 2 elements handled already.");
1321 replaceOpWithNewOpAndCopyNamehint<XorOp>(rewriter, op, op.getType(),
1322 inputs.drop_back(/*n=*/2), false);
1323 return success();
1324 }
1325
1326 // Patterns for xor with a constant on RHS.
1327 APInt value;
1328 if (matchPattern(inputs.back(), m_ConstantInt(&value))) {
1329 // xor(..., 0) -> xor(...) -- identity
1330 if (value.isZero()) {
1331 replaceOpWithNewOpAndCopyNamehint<XorOp>(rewriter, op, op.getType(),
1332 inputs.drop_back(), false);
1333 return success();
1334 }
1335
1336 // xor(..., c1, c2) -> xor(..., c3) where c3 = c1 ^ c2.
1337 APInt value2;
1338 if (matchPattern(inputs[size - 2], m_ConstantInt(&value2))) {
1339 auto cst = hw::ConstantOp::create(rewriter, op.getLoc(), value ^ value2);
1340 SmallVector<Value, 4> newOperands(inputs.drop_back(/*n=*/2));
1341 newOperands.push_back(cst);
1342 replaceOpWithNewOpAndCopyNamehint<XorOp>(rewriter, op, op.getType(),
1343 newOperands, false);
1344 return success();
1345 }
1346
1347 bool isSingleBit = value.getBitWidth() == 1;
1348
1349 // Check for subexpressions that we can simplify.
1350 for (size_t i = 0; i < size - 1; ++i) {
1351 Value operand = inputs[i];
1352
1353 // xor(concat(x, cst1), a, b, c, cst2)
1354 // ==> xor(a, b, c, concat(xor(x,cst2'), xor(cst1,cst2'')).
1355 // We do this for even more multi-use concats since they are "just
1356 // wiring".
1357 if (auto concat = operand.getDefiningOp<ConcatOp>())
1358 if (canonicalizeLogicalCstWithConcat(op, i, value, rewriter))
1359 return success();
1360
1361 // xor(icmp, a, b, 1) -> xor(icmp, a, b) if icmp has one user.
1362 if (isSingleBit && operand.hasOneUse()) {
1363 assert(value == 1 && "single bit constant has to be one if not zero");
1364 if (auto icmp = operand.getDefiningOp<ICmpOp>())
1365 return canonicalizeXorIcmpTrue(op, i, rewriter), success();
1366 }
1367 }
1368 }
1369
1370 // xor(x, xor(...)) -> xor(x, ...) -- flatten
1371 if (tryFlatteningOperands(op, rewriter))
1372 return success();
1373
1374 // extracts only of xor(...) -> xor(extract()...)
1375 if (narrowOperationWidth(op, true, rewriter))
1376 return success();
1377
1378 // xor(a[0], a[1], ..., a[n]) -> parity(a)
1379 if (auto source = getCommonOperand(op)) {
1380 replaceOpWithNewOpAndCopyNamehint<ParityOp>(rewriter, op, source);
1381 return success();
1382 }
1383
1384 return failure();
1385}
1386
1387OpFoldResult SubOp::fold(FoldAdaptor adaptor) {
1388 if (isOpTriviallyRecursive(*this))
1389 return {};
1390
1391 // sub(x - x) -> 0
1392 if (getRhs() == getLhs())
1393 return getIntAttr(
1394 APInt::getZero(getLhs().getType().getIntOrFloatBitWidth()),
1395 getContext());
1396
1397 if (adaptor.getRhs()) {
1398 // If both are constants, we can unconditionally fold.
1399 if (adaptor.getLhs()) {
1400 // Constant fold (c1 - c2) => (c1 + -1*c2).
1401 auto negOne = getIntAttr(
1402 APInt::getAllOnes(getLhs().getType().getIntOrFloatBitWidth()),
1403 getContext());
1404 auto rhsNeg = hw::ParamExprAttr::get(
1405 hw::PEO::Mul, cast<TypedAttr>(adaptor.getRhs()), negOne);
1406 return hw::ParamExprAttr::get(hw::PEO::Add,
1407 cast<TypedAttr>(adaptor.getLhs()), rhsNeg);
1408 }
1409
1410 // sub(x - 0) -> x
1411 if (auto rhsC = dyn_cast<IntegerAttr>(adaptor.getRhs())) {
1412 if (rhsC.getValue().isZero())
1413 return getLhs();
1414 }
1415 }
1416
1417 return {};
1418}
1419
1420LogicalResult SubOp::canonicalize(SubOp op, PatternRewriter &rewriter) {
1421 if (isOpTriviallyRecursive(op))
1422 return failure();
1423
1424 // sub(x, cst) -> add(x, -cst)
1425 APInt value;
1426 if (matchPattern(op.getRhs(), m_ConstantInt(&value))) {
1427 auto negCst = hw::ConstantOp::create(rewriter, op.getLoc(), -value);
1428 replaceOpWithNewOpAndCopyNamehint<AddOp>(rewriter, op, op.getLhs(), negCst,
1429 false);
1430 return success();
1431 }
1432
1433 // extracts only of sub(...) -> sub(extract()...)
1434 if (narrowOperationWidth(op, false, rewriter))
1435 return success();
1436
1437 return failure();
1438}
1439
1440OpFoldResult AddOp::fold(FoldAdaptor adaptor) {
1441 if (isOpTriviallyRecursive(*this))
1442 return {};
1443
1444 auto size = getInputs().size();
1445
1446 // add(x) -> x -- noop
1447 if (size == 1u)
1448 return getInputs()[0];
1449
1450 // Constant fold constant operands.
1451 return constFoldAssociativeOp(adaptor.getOperands(), hw::PEO::Add);
1452}
1453
1454LogicalResult AddOp::canonicalize(AddOp op, PatternRewriter &rewriter) {
1455 if (isOpTriviallyRecursive(op))
1456 return failure();
1457
1458 auto inputs = op.getInputs();
1459 auto size = inputs.size();
1460 assert(size > 1 && "expected 2 or more operands");
1461
1462 APInt value, value2;
1463
1464 // add(..., 0) -> add(...) -- identity
1465 if (matchPattern(inputs.back(), m_ConstantInt(&value)) && value.isZero()) {
1466 replaceOpWithNewOpAndCopyNamehint<AddOp>(rewriter, op, op.getType(),
1467 inputs.drop_back(), false);
1468 return success();
1469 }
1470
1471 // add(..., c1, c2) -> add(..., c3) where c3 = c1 + c2 -- constant folding
1472 if (matchPattern(inputs[size - 1], m_ConstantInt(&value)) &&
1473 matchPattern(inputs[size - 2], m_ConstantInt(&value2))) {
1474 auto cst = hw::ConstantOp::create(rewriter, op.getLoc(), value + value2);
1475 SmallVector<Value, 4> newOperands(inputs.drop_back(/*n=*/2));
1476 newOperands.push_back(cst);
1477 replaceOpWithNewOpAndCopyNamehint<AddOp>(rewriter, op, op.getType(),
1478 newOperands, false);
1479 return success();
1480 }
1481
1482 // add(..., x, x) -> add(..., shl(x, 1))
1483 if (inputs[size - 1] == inputs[size - 2]) {
1484 SmallVector<Value, 4> newOperands(inputs.drop_back(/*n=*/2));
1485
1486 auto one = hw::ConstantOp::create(rewriter, op.getLoc(), op.getType(), 1);
1487 auto shiftLeftOp =
1488 comb::ShlOp::create(rewriter, op.getLoc(), inputs.back(), one, false);
1489
1490 newOperands.push_back(shiftLeftOp);
1491 replaceOpWithNewOpAndCopyNamehint<AddOp>(rewriter, op, op.getType(),
1492 newOperands, false);
1493 return success();
1494 }
1495
1496 auto shlOp = inputs[size - 1].getDefiningOp<comb::ShlOp>();
1497 // add(..., x, shl(x, c)) -> add(..., mul(x, (1 << c) + 1))
1498 if (shlOp && shlOp.getLhs() == inputs[size - 2] &&
1499 matchPattern(shlOp.getRhs(), m_ConstantInt(&value))) {
1500
1501 APInt one(/*numBits=*/value.getBitWidth(), 1, /*isSigned=*/false);
1502 auto rhs =
1503 hw::ConstantOp::create(rewriter, op.getLoc(), (one << value) + one);
1504
1505 std::array<Value, 2> factors = {shlOp.getLhs(), rhs};
1506 auto mulOp = comb::MulOp::create(rewriter, op.getLoc(), factors, false);
1507
1508 SmallVector<Value, 4> newOperands(inputs.drop_back(/*n=*/2));
1509 newOperands.push_back(mulOp);
1510 replaceOpWithNewOpAndCopyNamehint<AddOp>(rewriter, op, op.getType(),
1511 newOperands, false);
1512 return success();
1513 }
1514
1515 auto mulOp = inputs[size - 1].getDefiningOp<comb::MulOp>();
1516 // add(..., x, mul(x, c)) -> add(..., mul(x, c + 1))
1517 if (mulOp && mulOp.getInputs().size() == 2 &&
1518 mulOp.getInputs()[0] == inputs[size - 2] &&
1519 matchPattern(mulOp.getInputs()[1], m_ConstantInt(&value))) {
1520
1521 APInt one(/*numBits=*/value.getBitWidth(), 1, /*isSigned=*/false);
1522 auto rhs = hw::ConstantOp::create(rewriter, op.getLoc(), value + one);
1523 std::array<Value, 2> factors = {mulOp.getInputs()[0], rhs};
1524 auto newMulOp = comb::MulOp::create(rewriter, op.getLoc(), factors, false);
1525
1526 SmallVector<Value, 4> newOperands(inputs.drop_back(/*n=*/2));
1527 newOperands.push_back(newMulOp);
1528 replaceOpWithNewOpAndCopyNamehint<AddOp>(rewriter, op, op.getType(),
1529 newOperands, false);
1530 return success();
1531 }
1532
1533 // add(a, add(...)) -> add(a, ...) -- flatten
1534 if (tryFlatteningOperands(op, rewriter))
1535 return success();
1536
1537 // extracts only of add(...) -> add(extract()...)
1538 if (narrowOperationWidth(op, false, rewriter))
1539 return success();
1540
1541 // add(add(x, c1), c2) -> add(x, c1 + c2)
1542 auto addOp = inputs[0].getDefiningOp<comb::AddOp>();
1543 if (addOp && addOp.getInputs().size() == 2 &&
1544 matchPattern(addOp.getInputs()[1], m_ConstantInt(&value2)) &&
1545 inputs.size() == 2 && matchPattern(inputs[1], m_ConstantInt(&value))) {
1546
1547 auto rhs = hw::ConstantOp::create(rewriter, op.getLoc(), value + value2);
1548 replaceOpWithNewOpAndCopyNamehint<AddOp>(
1549 rewriter, op, op.getType(), ArrayRef<Value>{addOp.getInputs()[0], rhs},
1550 /*twoState=*/op.getTwoState() && addOp.getTwoState());
1551 return success();
1552 }
1553
1554 return failure();
1555}
1556
1557OpFoldResult MulOp::fold(FoldAdaptor adaptor) {
1558 if (isOpTriviallyRecursive(*this))
1559 return {};
1560
1561 auto size = getInputs().size();
1562 auto inputs = adaptor.getInputs();
1563
1564 // mul(x) -> x -- noop
1565 if (size == 1u)
1566 return getInputs()[0];
1567
1568 auto width = cast<IntegerType>(getType()).getWidth();
1569 if (width == 0)
1570 return getIntAttr(APInt::getZero(0), getContext());
1571
1572 APInt value(/*numBits=*/width, 1, /*isSigned=*/false);
1573
1574 // mul(x, 0, 1) -> 0 -- annulment
1575 for (auto operand : inputs) {
1576 if (!operand)
1577 continue;
1578 value *= cast<IntegerAttr>(operand).getValue();
1579 if (value.isZero())
1580 return getIntAttr(value, getContext());
1581 }
1582
1583 // Constant fold
1584 return constFoldAssociativeOp(inputs, hw::PEO::Mul);
1585}
1586
1587LogicalResult MulOp::canonicalize(MulOp op, PatternRewriter &rewriter) {
1588 if (isOpTriviallyRecursive(op))
1589 return failure();
1590
1591 auto inputs = op.getInputs();
1592 auto size = inputs.size();
1593 assert(size > 1 && "expected 2 or more operands");
1594
1595 APInt value, value2;
1596
1597 // mul(x, c) -> shl(x, log2(c)), where c is a power of two.
1598 if (size == 2 && matchPattern(inputs.back(), m_ConstantInt(&value)) &&
1599 value.isPowerOf2()) {
1600 auto shift = hw::ConstantOp::create(rewriter, op.getLoc(), op.getType(),
1601 value.exactLogBase2());
1602 auto shlOp =
1603 comb::ShlOp::create(rewriter, op.getLoc(), inputs[0], shift, false);
1604
1605 replaceOpWithNewOpAndCopyNamehint<MulOp>(rewriter, op, op.getType(),
1606 ArrayRef<Value>(shlOp), false);
1607 return success();
1608 }
1609
1610 // mul(..., 1) -> mul(...) -- identity
1611 if (matchPattern(inputs.back(), m_ConstantInt(&value)) && value.isOne()) {
1612 replaceOpWithNewOpAndCopyNamehint<MulOp>(rewriter, op, op.getType(),
1613 inputs.drop_back());
1614 return success();
1615 }
1616
1617 // mul(..., c1, c2) -> mul(..., c3) where c3 = c1 * c2 -- constant folding
1618 if (matchPattern(inputs[size - 1], m_ConstantInt(&value)) &&
1619 matchPattern(inputs[size - 2], m_ConstantInt(&value2))) {
1620 auto cst = hw::ConstantOp::create(rewriter, op.getLoc(), value * value2);
1621 SmallVector<Value, 4> newOperands(inputs.drop_back(/*n=*/2));
1622 newOperands.push_back(cst);
1623 replaceOpWithNewOpAndCopyNamehint<MulOp>(rewriter, op, op.getType(),
1624 newOperands);
1625 return success();
1626 }
1627
1628 // mul(a, mul(...)) -> mul(a, ...) -- flatten
1629 if (tryFlatteningOperands(op, rewriter))
1630 return success();
1631
1632 // extracts only of mul(...) -> mul(extract()...)
1633 if (narrowOperationWidth(op, false, rewriter))
1634 return success();
1635
1636 return failure();
1637}
1638
1639template <class Op, bool isSigned>
1640static OpFoldResult foldDiv(Op op, ArrayRef<Attribute> constants) {
1641 if (auto rhsValue = dyn_cast_or_null<IntegerAttr>(constants[1])) {
1642 // divu(x, 1) -> x, divs(x, 1) -> x
1643 if (rhsValue.getValue() == 1)
1644 return op.getLhs();
1645
1646 // If the divisor is zero, do not fold for now.
1647 if (rhsValue.getValue().isZero())
1648 return {};
1649 }
1650
1651 return constFoldBinaryOp(constants, isSigned ? hw::PEO::DivS : hw::PEO::DivU);
1652}
1653
1654OpFoldResult DivUOp::fold(FoldAdaptor adaptor) {
1655 if (isOpTriviallyRecursive(*this))
1656 return {};
1657 return foldDiv<DivUOp, /*isSigned=*/false>(*this, adaptor.getOperands());
1658}
1659
1660OpFoldResult DivSOp::fold(FoldAdaptor adaptor) {
1661 if (isOpTriviallyRecursive(*this))
1662 return {};
1663 return foldDiv<DivSOp, /*isSigned=*/true>(*this, adaptor.getOperands());
1664}
1665
1666template <class Op, bool isSigned>
1667static OpFoldResult foldMod(Op op, ArrayRef<Attribute> constants) {
1668 if (auto rhsValue = dyn_cast_or_null<IntegerAttr>(constants[1])) {
1669 // modu(x, 1) -> 0, mods(x, 1) -> 0
1670 if (rhsValue.getValue() == 1)
1671 return getIntAttr(APInt::getZero(op.getType().getIntOrFloatBitWidth()),
1672 op.getContext());
1673
1674 // If the divisor is zero, do not fold for now.
1675 if (rhsValue.getValue().isZero())
1676 return {};
1677 }
1678
1679 if (auto lhsValue = dyn_cast_or_null<IntegerAttr>(constants[0])) {
1680 // modu(0, x) -> 0, mods(0, x) -> 0
1681 if (lhsValue.getValue().isZero())
1682 return getIntAttr(APInt::getZero(op.getType().getIntOrFloatBitWidth()),
1683 op.getContext());
1684 }
1685
1686 return constFoldBinaryOp(constants, isSigned ? hw::PEO::ModS : hw::PEO::ModU);
1687}
1688
1689OpFoldResult ModUOp::fold(FoldAdaptor adaptor) {
1690 if (isOpTriviallyRecursive(*this))
1691 return {};
1692 return foldMod<ModUOp, /*isSigned=*/false>(*this, adaptor.getOperands());
1693}
1694
1695OpFoldResult ModSOp::fold(FoldAdaptor adaptor) {
1696 if (isOpTriviallyRecursive(*this))
1697 return {};
1698 return foldMod<ModSOp, /*isSigned=*/true>(*this, adaptor.getOperands());
1699}
1700//===----------------------------------------------------------------------===//
1701// ConcatOp
1702//===----------------------------------------------------------------------===//
1703
1704// Constant folding
1705OpFoldResult ConcatOp::fold(FoldAdaptor adaptor) {
1706 if (isOpTriviallyRecursive(*this))
1707 return {};
1708
1709 if (getNumOperands() == 1)
1710 return getOperand(0);
1711
1712 // If all the operands are constant, we can fold.
1713 for (auto attr : adaptor.getInputs())
1714 if (!attr || !isa<IntegerAttr>(attr))
1715 return {};
1716
1717 // If we got here, we can constant fold.
1718 unsigned resultWidth = getType().getIntOrFloatBitWidth();
1719 APInt result(resultWidth, 0);
1720
1721 unsigned nextInsertion = resultWidth;
1722 // Insert each chunk into the result.
1723 for (auto attr : adaptor.getInputs()) {
1724 auto chunk = cast<IntegerAttr>(attr).getValue();
1725 nextInsertion -= chunk.getBitWidth();
1726 result.insertBits(chunk, nextInsertion);
1727 }
1728
1729 return getIntAttr(result, getContext());
1730}
1731
1732LogicalResult ConcatOp::canonicalize(ConcatOp op, PatternRewriter &rewriter) {
1733 if (isOpTriviallyRecursive(op))
1734 return failure();
1735
1736 auto inputs = op.getInputs();
1737 auto size = inputs.size();
1738 assert(size > 1 && "expected 2 or more operands");
1739
1740 // This function is used when we flatten neighboring operands of a
1741 // (variadic) concat into a new vesion of the concat. first/last indices
1742 // are inclusive.
1743 auto flattenConcat = [&](size_t firstOpIndex, size_t lastOpIndex,
1744 ValueRange replacements) -> LogicalResult {
1745 SmallVector<Value, 4> newOperands;
1746 newOperands.append(inputs.begin(), inputs.begin() + firstOpIndex);
1747 newOperands.append(replacements.begin(), replacements.end());
1748 newOperands.append(inputs.begin() + lastOpIndex + 1, inputs.end());
1749 if (newOperands.size() == 1)
1750 replaceOpAndCopyNamehint(rewriter, op, newOperands[0]);
1751 else
1752 replaceOpWithNewOpAndCopyNamehint<ConcatOp>(rewriter, op, op.getType(),
1753 newOperands);
1754 return success();
1755 };
1756
1757 Value commonOperand = inputs[0];
1758 for (size_t i = 0; i != size; ++i) {
1759 // Check to see if all operands are the same.
1760 if (inputs[i] != commonOperand)
1761 commonOperand = Value();
1762
1763 // If an operand to the concat is itself a concat, then we can fold them
1764 // together.
1765 if (auto subConcat = inputs[i].getDefiningOp<ConcatOp>())
1766 return flattenConcat(i, i, subConcat->getOperands());
1767
1768 // Check for canonicalization due to neighboring operands.
1769 if (i != 0) {
1770 // Merge neighboring constants.
1771 if (auto cst = inputs[i].getDefiningOp<hw::ConstantOp>()) {
1772 if (auto prevCst = inputs[i - 1].getDefiningOp<hw::ConstantOp>()) {
1773 unsigned prevWidth = prevCst.getValue().getBitWidth();
1774 unsigned thisWidth = cst.getValue().getBitWidth();
1775 auto resultCst = cst.getValue().zext(prevWidth + thisWidth);
1776 resultCst |= prevCst.getValue().zext(prevWidth + thisWidth)
1777 << thisWidth;
1778 Value replacement =
1779 hw::ConstantOp::create(rewriter, op.getLoc(), resultCst);
1780 return flattenConcat(i - 1, i, replacement);
1781 }
1782 }
1783
1784 // If the two operands are the same, turn them into a replicate.
1785 if (inputs[i] == inputs[i - 1]) {
1786 Value replacement =
1787 rewriter.createOrFold<ReplicateOp>(op.getLoc(), inputs[i], 2);
1788 return flattenConcat(i - 1, i, replacement);
1789 }
1790
1791 // If this input is a replicate, see if we can fold it with the previous
1792 // one.
1793 if (auto repl = inputs[i].getDefiningOp<ReplicateOp>()) {
1794 // ... x, repl(x, n), ... ==> ..., repl(x, n+1), ...
1795 if (repl.getOperand() == inputs[i - 1]) {
1796 Value replacement = rewriter.createOrFold<ReplicateOp>(
1797 op.getLoc(), repl.getOperand(), repl.getMultiple() + 1);
1798 return flattenConcat(i - 1, i, replacement);
1799 }
1800 // ... repl(x, n), repl(x, m), ... ==> ..., repl(x, n+m), ...
1801 if (auto prevRepl = inputs[i - 1].getDefiningOp<ReplicateOp>()) {
1802 if (prevRepl.getOperand() == repl.getOperand()) {
1803 Value replacement = rewriter.createOrFold<ReplicateOp>(
1804 op.getLoc(), repl.getOperand(),
1805 repl.getMultiple() + prevRepl.getMultiple());
1806 return flattenConcat(i - 1, i, replacement);
1807 }
1808 }
1809 }
1810
1811 // ... repl(x, n), x, ... ==> ..., repl(x, n+1), ...
1812 if (auto repl = inputs[i - 1].getDefiningOp<ReplicateOp>()) {
1813 if (repl.getOperand() == inputs[i]) {
1814 Value replacement = rewriter.createOrFold<ReplicateOp>(
1815 op.getLoc(), inputs[i], repl.getMultiple() + 1);
1816 return flattenConcat(i - 1, i, replacement);
1817 }
1818 }
1819
1820 // Merge neighboring extracts of neighboring inputs, e.g.
1821 // {A[3], A[2]} -> A[3:2]
1822 if (auto extract = inputs[i].getDefiningOp<ExtractOp>()) {
1823 if (auto prevExtract = inputs[i - 1].getDefiningOp<ExtractOp>()) {
1824 if (extract.getInput() == prevExtract.getInput()) {
1825 auto thisWidth = cast<IntegerType>(extract.getType()).getWidth();
1826 if (prevExtract.getLowBit() == extract.getLowBit() + thisWidth) {
1827 auto prevWidth = prevExtract.getType().getIntOrFloatBitWidth();
1828 auto resType = rewriter.getIntegerType(thisWidth + prevWidth);
1829 Value replacement =
1830 ExtractOp::create(rewriter, op.getLoc(), resType,
1831 extract.getInput(), extract.getLowBit());
1832 return flattenConcat(i - 1, i, replacement);
1833 }
1834 }
1835 }
1836 }
1837 // Merge neighboring array extracts of neighboring inputs, e.g.
1838 // {Array[4], bitcast(Array[3:2])} -> bitcast(A[4:2])
1839
1840 // This represents a slice of an array.
1841 struct ArraySlice {
1842 Value input;
1843 Value index;
1844 size_t width;
1845 static std::optional<ArraySlice> get(Value value) {
1846 assert(isa<IntegerType>(value.getType()) && "expected integer type");
1847 if (auto arrayGet = value.getDefiningOp<hw::ArrayGetOp>())
1848 return ArraySlice{arrayGet.getInput(), arrayGet.getIndex(), 1};
1849 // array slice op is wrapped with bitcast.
1850 if (auto bitcast = value.getDefiningOp<hw::BitcastOp>())
1851 if (auto arraySlice =
1852 bitcast.getInput().getDefiningOp<hw::ArraySliceOp>())
1853 return ArraySlice{
1854 arraySlice.getInput(), arraySlice.getLowIndex(),
1855 hw::type_cast<hw::ArrayType>(arraySlice.getType())
1856 .getNumElements()};
1857 return std::nullopt;
1858 }
1859 };
1860 if (auto extractOpt = ArraySlice::get(inputs[i])) {
1861 if (auto prevExtractOpt = ArraySlice::get(inputs[i - 1])) {
1862 // Check that two array slices are mergable.
1863 if (prevExtractOpt->index.getType() == extractOpt->index.getType() &&
1864 prevExtractOpt->input == extractOpt->input &&
1865 hw::isOffset(extractOpt->index, prevExtractOpt->index,
1866 extractOpt->width)) {
1867 auto resType = hw::ArrayType::get(
1868 hw::type_cast<hw::ArrayType>(prevExtractOpt->input.getType())
1869 .getElementType(),
1870 extractOpt->width + prevExtractOpt->width);
1871 auto resIntType = rewriter.getIntegerType(hw::getBitWidth(resType));
1872 Value replacement = hw::BitcastOp::create(
1873 rewriter, op.getLoc(), resIntType,
1874 hw::ArraySliceOp::create(rewriter, op.getLoc(), resType,
1875 prevExtractOpt->input,
1876 extractOpt->index));
1877 return flattenConcat(i - 1, i, replacement);
1878 }
1879 }
1880 }
1881 }
1882 }
1883
1884 // If all operands were the same, then this is a replicate.
1885 if (commonOperand) {
1886 replaceOpWithNewOpAndCopyNamehint<ReplicateOp>(rewriter, op, op.getType(),
1887 commonOperand);
1888 return success();
1889 }
1890
1891 return failure();
1892}
1893
1894//===----------------------------------------------------------------------===//
1895// MuxOp
1896//===----------------------------------------------------------------------===//
1897
1898OpFoldResult MuxOp::fold(FoldAdaptor adaptor) {
1899 if (isOpTriviallyRecursive(*this))
1900 return {};
1901
1902 // mux (c, b, b) -> b
1903 if (getTrueValue() == getFalseValue() && getTrueValue() != getResult())
1904 return getTrueValue();
1905 if (auto tv = adaptor.getTrueValue())
1906 if (tv == adaptor.getFalseValue())
1907 return tv;
1908
1909 // mux(0, a, b) -> b
1910 // mux(1, a, b) -> a
1911 if (auto pred = dyn_cast_or_null<IntegerAttr>(adaptor.getCond())) {
1912 if (pred.getValue().isZero() && getFalseValue() != getResult())
1913 return getFalseValue();
1914 if (pred.getValue().isOne() && getTrueValue() != getResult())
1915 return getTrueValue();
1916 }
1917
1918 // mux(cond, 1, 0) -> cond
1919 if (getCond().getType() == getTrueValue().getType())
1920 if (auto tv = dyn_cast_or_null<IntegerAttr>(adaptor.getTrueValue()))
1921 if (auto fv = dyn_cast_or_null<IntegerAttr>(adaptor.getFalseValue()))
1922 if (tv.getValue().isOne() && fv.getValue().isZero() &&
1923 hw::getBitWidth(getType()) == 1 && getCond() != getResult())
1924 return getCond();
1925
1926 return {};
1927}
1928
1929/// Check to see if the condition to the specified mux is an equality
1930/// comparison `indexValue` and one or more constants. If so, put the
1931/// constants in the constants vector and return true, otherwise return false.
1932///
1933/// This is part of foldMuxChain.
1934///
1935static bool
1936getMuxChainCondConstant(Value cond, Value indexValue, bool isInverted,
1937 std::function<void(hw::ConstantOp)> constantFn) {
1938 // Handle `idx == 42` and `idx != 42`.
1939 if (auto cmp = cond.getDefiningOp<ICmpOp>()) {
1940 // TODO: We could handle things like "x < 2" as two entries.
1941 auto requiredPredicate =
1942 (isInverted ? ICmpPredicate::eq : ICmpPredicate::ne);
1943 if (cmp.getLhs() == indexValue && cmp.getPredicate() == requiredPredicate) {
1944 if (auto cst = cmp.getRhs().getDefiningOp<hw::ConstantOp>()) {
1945 constantFn(cst);
1946 return true;
1947 }
1948 }
1949 return false;
1950 }
1951
1952 // Handle mux(`idx == 1 || idx == 3`, value, muxchain).
1953 if (auto orOp = cond.getDefiningOp<OrOp>()) {
1954 if (!isInverted)
1955 return false;
1956 for (auto operand : orOp.getOperands())
1957 if (!getMuxChainCondConstant(operand, indexValue, isInverted, constantFn))
1958 return false;
1959 return true;
1960 }
1961
1962 // Handle mux(`idx != 1 && idx != 3`, muxchain, value).
1963 if (auto andOp = cond.getDefiningOp<AndOp>()) {
1964 if (isInverted)
1965 return false;
1966 for (auto operand : andOp.getOperands())
1967 if (!getMuxChainCondConstant(operand, indexValue, isInverted, constantFn))
1968 return false;
1969 return true;
1970 }
1971
1972 return false;
1973}
1974
1975/// Given a mux, check to see if the "on true" value (or "on false" value if
1976/// isFalseSide=true) is a mux tree with the same condition. This allows us
1977/// to turn things like `mux(VAL == 0, A, (mux (VAL == 1), B, C))` into
1978/// `array_get (array_create(A, B, C), VAL)` or a balanced mux tree which is far
1979/// more compact and allows synthesis tools to do more interesting
1980/// optimizations.
1981///
1982/// This returns false if we cannot form the mux tree (or do not want to) and
1983/// returns true if the mux was replaced.
1985 PatternRewriter &rewriter, MuxOp rootMux, bool isFalseSide,
1986 llvm::function_ref<MuxChainWithComparisonFoldingStyle(size_t indexWidth,
1987 size_t numEntries)>
1988 styleFn) {
1989 // Get the index value being compared. Later we check to see if it is
1990 // compared to a constant with the right predicate.
1991 auto rootCmp = rootMux.getCond().getDefiningOp<ICmpOp>();
1992 if (!rootCmp)
1993 return false;
1994 Value indexValue = rootCmp.getLhs();
1995
1996 // Return the value to use if the equality match succeeds.
1997 auto getCaseValue = [&](MuxOp mux) -> Value {
1998 return mux.getOperand(1 + unsigned(!isFalseSide));
1999 };
2000
2001 // Return the value to use if the equality match fails. This is the next
2002 // mux in the sequence or the "otherwise" value.
2003 auto getTreeValue = [&](MuxOp mux) -> Value {
2004 return mux.getOperand(1 + unsigned(isFalseSide));
2005 };
2006
2007 // Start scanning the mux tree to see what we've got. Keep track of the
2008 // constant comparison value and the SSA value to use when equal to it.
2009 SmallVector<Location> locationsFound;
2010 SmallVector<std::pair<hw::ConstantOp, Value>, 4> valuesFound;
2011
2012 /// Extract constants and values into `valuesFound` and return true if this is
2013 /// part of the mux tree, otherwise return false.
2014 auto collectConstantValues = [&](MuxOp mux) -> bool {
2016 mux.getCond(), indexValue, isFalseSide, [&](hw::ConstantOp cst) {
2017 valuesFound.push_back({cst, getCaseValue(mux)});
2018 locationsFound.push_back(mux.getCond().getLoc());
2019 locationsFound.push_back(mux->getLoc());
2020 });
2021 };
2022
2023 // Make sure the root is a correct comparison with a constant.
2024 if (!collectConstantValues(rootMux))
2025 return false;
2026
2027 // Make sure that we're not looking at the intermediate node in a mux tree.
2028 if (rootMux->hasOneUse()) {
2029 if (auto userMux = dyn_cast<MuxOp>(*rootMux->user_begin())) {
2030 if (getTreeValue(userMux) == rootMux.getResult() &&
2031 getMuxChainCondConstant(userMux.getCond(), indexValue, isFalseSide,
2032 [&](hw::ConstantOp cst) {}))
2033 return false;
2034 }
2035 }
2036
2037 // Scan up the tree linearly.
2038 auto nextTreeValue = getTreeValue(rootMux);
2039 while (1) {
2040 auto nextMux = nextTreeValue.getDefiningOp<MuxOp>();
2041 if (!nextMux || !nextMux->hasOneUse())
2042 break;
2043 if (!collectConstantValues(nextMux))
2044 break;
2045 nextTreeValue = getTreeValue(nextMux);
2046 }
2047
2048 auto indexWidth = cast<IntegerType>(indexValue.getType()).getWidth();
2049
2050 if (indexWidth > 20)
2051 return false; // Too big to make a table.
2052
2053 auto foldingStyle = styleFn(indexWidth, valuesFound.size());
2054 if (foldingStyle == MuxChainWithComparisonFoldingStyle::None)
2055 return false;
2056
2057 uint64_t tableSize = 1ULL << indexWidth;
2058
2059 // Ok, we're going to do the transformation, start by building the table
2060 // filled with the "otherwise" value.
2061 SmallVector<Value, 8> table(tableSize, nextTreeValue);
2062
2063 // Fill in entries in the table from the leaf to the root of the expression.
2064 // This ensures that any duplicate matches end up with the ultimate value,
2065 // which is the one closer to the root.
2066 for (auto &elt : llvm::reverse(valuesFound)) {
2067 uint64_t idx = elt.first.getValue().getZExtValue();
2068 assert(idx < table.size() && "constant should be same bitwidth as index");
2069 table[idx] = elt.second;
2070 }
2071
2073 SmallVector<Value> bits;
2074 comb::extractBits(rewriter, indexValue, bits);
2075 auto result = constructMuxTree(rewriter, rootMux->getLoc(), bits, table,
2076 nextTreeValue);
2077 replaceOpAndCopyNamehint(rewriter, rootMux, result);
2078 return true;
2079 }
2080
2082 "unknown folding style");
2083
2084 // The hw.array_create operation has the operand list in unintuitive order
2085 // with a[0] stored as the last element, not the first.
2086 std::reverse(table.begin(), table.end());
2087
2088 // Build the array_create and the array_get.
2089 auto fusedLoc = rewriter.getFusedLoc(locationsFound);
2090 auto array = rewriter.create<hw::ArrayCreateOp>(fusedLoc, table);
2091 replaceOpWithNewOpAndCopyNamehint<hw::ArrayGetOp>(rewriter, rootMux, array,
2092 indexValue);
2093 return true;
2094}
2095
2096/// Given a fully associative variadic operation like (a+b+c+d), break the
2097/// expression into two parts, one without the specified operand (e.g.
2098/// `tmp = a+b+d`) and one that combines that into the full expression (e.g.
2099/// `tmp+c`), and return the inner expression.
2100///
2101/// NOTE: This mutates the operation in place if it only has a single user,
2102/// which assumes that user will be removed.
2103///
2104static Value extractOperandFromFullyAssociative(Operation *fullyAssoc,
2105 size_t operandNo,
2106 PatternRewriter &rewriter) {
2107 assert(fullyAssoc->getNumOperands() >= 2 && "cannot split up unary ops");
2108 assert(operandNo < fullyAssoc->getNumOperands() && "Invalid operand #");
2109
2110 // If this expression already has two operands (the common case) no splitting
2111 // is necessary.
2112 if (fullyAssoc->getNumOperands() == 2)
2113 return fullyAssoc->getOperand(operandNo ^ 1);
2114
2115 // If the operation has a single use, mutate it in place.
2116 if (fullyAssoc->hasOneUse()) {
2117 rewriter.modifyOpInPlace(fullyAssoc,
2118 [&]() { fullyAssoc->eraseOperand(operandNo); });
2119 return fullyAssoc->getResult(0);
2120 }
2121
2122 // Form the new operation with the operands that remain.
2123 SmallVector<Value> operands;
2124 operands.append(fullyAssoc->getOperands().begin(),
2125 fullyAssoc->getOperands().begin() + operandNo);
2126 operands.append(fullyAssoc->getOperands().begin() + operandNo + 1,
2127 fullyAssoc->getOperands().end());
2128 Value opWithoutExcluded = createGenericOp(
2129 fullyAssoc->getLoc(), fullyAssoc->getName(), operands, rewriter);
2130 Value excluded = fullyAssoc->getOperand(operandNo);
2131
2132 Value fullResult =
2133 createGenericOp(fullyAssoc->getLoc(), fullyAssoc->getName(),
2134 ArrayRef<Value>{opWithoutExcluded, excluded}, rewriter);
2135 replaceOpAndCopyNamehint(rewriter, fullyAssoc, fullResult);
2136 return opWithoutExcluded;
2137}
2138
2139/// Fold things like `mux(cond, x|y|z|a, a)` -> `(x|y|z)&replicate(cond)|a` and
2140/// `mux(cond, a, x|y|z|a) -> `(x|y|z)&replicate(~cond) | a` (when isTrueOperand
2141/// is true. Return true on successful transformation, false if not.
2142///
2143/// These are various forms of "predicated ops" that can be handled with a
2144/// replicate/and combination.
2145static bool foldCommonMuxValue(MuxOp op, bool isTrueOperand,
2146 PatternRewriter &rewriter) {
2147 // Check to see the operand in question is an operation. If it is a port,
2148 // we can't simplify it.
2149 Operation *subExpr =
2150 (isTrueOperand ? op.getFalseValue() : op.getTrueValue()).getDefiningOp();
2151 if (!subExpr || subExpr->getNumOperands() < 2)
2152 return false;
2153
2154 // If this isn't an operation we can handle, don't spend energy on it.
2155 if (!isa<AndOp, XorOp, OrOp, MuxOp>(subExpr))
2156 return false;
2157
2158 // Check to see if the common value occurs in the operand list for the
2159 // subexpression op. If so, then we can simplify it.
2160 Value commonValue = isTrueOperand ? op.getTrueValue() : op.getFalseValue();
2161 size_t opNo = 0, e = subExpr->getNumOperands();
2162 while (opNo != e && subExpr->getOperand(opNo) != commonValue)
2163 ++opNo;
2164 if (opNo == e)
2165 return false;
2166
2167 // If we got a hit, then go ahead and simplify it!
2168 Value cond = op.getCond();
2169
2170 // `mux(cond, a, mux(cond2, a, b))` -> `mux(cond|cond2, a, b)`
2171 // `mux(cond, a, mux(cond2, b, a))` -> `mux(cond|~cond2, a, b)`
2172 // `mux(cond, mux(cond2, a, b), a)` -> `mux(~cond|cond2, a, b)`
2173 // `mux(cond, mux(cond2, b, a), a)` -> `mux(~cond|~cond2, a, b)`
2174 if (auto subMux = dyn_cast<MuxOp>(subExpr)) {
2175 if (subMux == op)
2176 return false;
2177
2178 Value otherValue;
2179 Value subCond = subMux.getCond();
2180
2181 // Invert th subCond if needed and dig out the 'b' value.
2182 if (subMux.getTrueValue() == commonValue)
2183 otherValue = subMux.getFalseValue();
2184 else if (subMux.getFalseValue() == commonValue) {
2185 otherValue = subMux.getTrueValue();
2186 subCond = createOrFoldNot(op.getLoc(), subCond, rewriter);
2187 } else {
2188 // We can't fold `mux(cond, a, mux(a, x, y))`.
2189 return false;
2190 }
2191
2192 // Invert the outer cond if needed, and combine the mux conditions.
2193 if (!isTrueOperand)
2194 cond = createOrFoldNot(op.getLoc(), cond, rewriter);
2195 cond = rewriter.createOrFold<OrOp>(op.getLoc(), cond, subCond, false);
2196 replaceOpWithNewOpAndCopyNamehint<MuxOp>(rewriter, op, cond, commonValue,
2197 otherValue, op.getTwoState());
2198 return true;
2199 }
2200
2201 // Invert the condition if needed. Or/Xor invert when dealing with
2202 // TrueOperand, And inverts for False operand.
2203 bool isaAndOp = isa<AndOp>(subExpr);
2204 if (isTrueOperand ^ isaAndOp)
2205 cond = createOrFoldNot(op.getLoc(), cond, rewriter);
2206
2207 auto extendedCond =
2208 rewriter.createOrFold<ReplicateOp>(op.getLoc(), op.getType(), cond);
2209
2210 // Cache this information before subExpr is erased by extraction below.
2211 bool isaXorOp = isa<XorOp>(subExpr);
2212 bool isaOrOp = isa<OrOp>(subExpr);
2213
2214 // Handle the fully associative ops, start by pulling out the subexpression
2215 // from a many operand version of the op.
2216 auto restOfAssoc =
2217 extractOperandFromFullyAssociative(subExpr, opNo, rewriter);
2218
2219 // `mux(cond, x|y|z|a, a)` -> `(x|y|z)&replicate(cond) | a`
2220 // `mux(cond, x^y^z^a, a)` -> `(x^y^z)&replicate(cond) ^ a`
2221 if (isaOrOp || isaXorOp) {
2222 auto masked = rewriter.createOrFold<AndOp>(op.getLoc(), extendedCond,
2223 restOfAssoc, false);
2224 if (isaXorOp)
2225 replaceOpWithNewOpAndCopyNamehint<XorOp>(rewriter, op, masked,
2226 commonValue, false);
2227 else
2228 replaceOpWithNewOpAndCopyNamehint<OrOp>(rewriter, op, masked, commonValue,
2229 false);
2230 return true;
2231 }
2232
2233 // `mux(cond, a, x&y&z&a)` -> `((x&y&z)|replicate(cond)) & a`
2234 assert(isaAndOp && "unexpected operation here");
2235 auto masked = rewriter.createOrFold<OrOp>(op.getLoc(), extendedCond,
2236 restOfAssoc, false);
2237 replaceOpWithNewOpAndCopyNamehint<AndOp>(rewriter, op, masked, commonValue,
2238 false);
2239 return true;
2240}
2241
2242/// This function is invoke when we find a mux with true/false operations that
2243/// have the same opcode. Check to see if we can strength reduce the mux by
2244/// applying it to less data by applying this transformation:
2245/// `mux(cond, op(a, b), op(a, c))` -> `op(a, mux(cond, b, c))`
2246static bool foldCommonMuxOperation(MuxOp mux, Operation *trueOp,
2247 Operation *falseOp,
2248 PatternRewriter &rewriter) {
2249 // Right now we only apply to concat.
2250 // TODO: Generalize this to and, or, xor, icmp(!), which all occur in practice
2251 if (!isa<ConcatOp>(trueOp))
2252 return false;
2253
2254 // Decode the operands, looking through recursive concats and replicates.
2255 SmallVector<Value> trueOperands, falseOperands;
2256 getConcatOperands(trueOp->getResult(0), trueOperands);
2257 getConcatOperands(falseOp->getResult(0), falseOperands);
2258
2259 size_t numTrueOperands = trueOperands.size();
2260 size_t numFalseOperands = falseOperands.size();
2261
2262 if (!numTrueOperands || !numFalseOperands ||
2263 (trueOperands.front() != falseOperands.front() &&
2264 trueOperands.back() != falseOperands.back()))
2265 return false;
2266
2267 // Pull all leading shared operands out into their own op if any are common.
2268 if (trueOperands.front() == falseOperands.front()) {
2269 SmallVector<Value> operands;
2270 size_t i;
2271 for (i = 0; i < numTrueOperands; ++i) {
2272 Value trueOperand = trueOperands[i];
2273 if (trueOperand == falseOperands[i])
2274 operands.push_back(trueOperand);
2275 else
2276 break;
2277 }
2278 if (i == numTrueOperands) {
2279 // Selecting between distinct, but lexically identical, concats.
2280 replaceOpAndCopyNamehint(rewriter, mux, trueOp->getResult(0));
2281 return true;
2282 }
2283
2284 Value sharedMSB;
2285 if (llvm::all_of(operands, [&](Value v) { return v == operands.front(); }))
2286 sharedMSB = rewriter.createOrFold<ReplicateOp>(
2287 mux->getLoc(), operands.front(), operands.size());
2288 else
2289 sharedMSB = rewriter.createOrFold<ConcatOp>(mux->getLoc(), operands);
2290 operands.clear();
2291
2292 // Get a concat of the LSB's on each side.
2293 operands.append(trueOperands.begin() + i, trueOperands.end());
2294 Value trueLSB = rewriter.createOrFold<ConcatOp>(trueOp->getLoc(), operands);
2295 operands.clear();
2296 operands.append(falseOperands.begin() + i, falseOperands.end());
2297 Value falseLSB =
2298 rewriter.createOrFold<ConcatOp>(falseOp->getLoc(), operands);
2299 // Merge the LSBs with a new mux and concat the MSB with the LSB to be
2300 // done.
2301 Value lsb = rewriter.createOrFold<MuxOp>(
2302 mux->getLoc(), mux.getCond(), trueLSB, falseLSB, mux.getTwoState());
2303 replaceOpWithNewOpAndCopyNamehint<ConcatOp>(rewriter, mux, sharedMSB, lsb);
2304 return true;
2305 }
2306
2307 // If trailing operands match, try to commonize them.
2308 if (trueOperands.back() == falseOperands.back()) {
2309 SmallVector<Value> operands;
2310 size_t i;
2311 for (i = 0;; ++i) {
2312 Value trueOperand = trueOperands[numTrueOperands - i - 1];
2313 if (trueOperand == falseOperands[numFalseOperands - i - 1])
2314 operands.push_back(trueOperand);
2315 else
2316 break;
2317 }
2318 std::reverse(operands.begin(), operands.end());
2319 Value sharedLSB = rewriter.createOrFold<ConcatOp>(mux->getLoc(), operands);
2320 operands.clear();
2321
2322 // Get a concat of the MSB's on each side.
2323 operands.append(trueOperands.begin(), trueOperands.end() - i);
2324 Value trueMSB = rewriter.createOrFold<ConcatOp>(trueOp->getLoc(), operands);
2325 operands.clear();
2326 operands.append(falseOperands.begin(), falseOperands.end() - i);
2327 Value falseMSB =
2328 rewriter.createOrFold<ConcatOp>(falseOp->getLoc(), operands);
2329 // Merge the MSBs with a new mux and concat the MSB with the LSB to be done.
2330 Value msb = rewriter.createOrFold<MuxOp>(
2331 mux->getLoc(), mux.getCond(), trueMSB, falseMSB, mux.getTwoState());
2332 replaceOpWithNewOpAndCopyNamehint<ConcatOp>(rewriter, mux, msb, sharedLSB);
2333 return true;
2334 }
2335
2336 return false;
2337}
2338
2339// If both arguments of the mux are arrays with the same elements, sink the
2340// mux and return a uniform array initializing all elements to it.
2341static bool foldMuxOfUniformArrays(MuxOp op, PatternRewriter &rewriter) {
2342 auto trueVec = op.getTrueValue().getDefiningOp<hw::ArrayCreateOp>();
2343 auto falseVec = op.getFalseValue().getDefiningOp<hw::ArrayCreateOp>();
2344 if (!trueVec || !falseVec)
2345 return false;
2346 if (!trueVec.isUniform() || !falseVec.isUniform())
2347 return false;
2348
2349 auto mux = MuxOp::create(rewriter, op.getLoc(), op.getCond(),
2350 trueVec.getUniformElement(),
2351 falseVec.getUniformElement(), op.getTwoState());
2352
2353 SmallVector<Value> values(trueVec.getInputs().size(), mux);
2354 rewriter.replaceOpWithNewOp<hw::ArrayCreateOp>(op, values);
2355 return true;
2356}
2357
2358/// If the mux condition is an operand to the op defining its true or false
2359/// value, replace the condition with 1 or 0.
2360static bool assumeMuxCondInOperand(Value muxCond, Value muxValue,
2361 bool constCond, PatternRewriter &rewriter) {
2362 if (!muxValue.hasOneUse())
2363 return false;
2364 auto *op = muxValue.getDefiningOp();
2365 if (!op || !isa_and_nonnull<CombDialect>(op->getDialect()))
2366 return false;
2367 if (!llvm::is_contained(op->getOperands(), muxCond))
2368 return false;
2369 OpBuilder::InsertionGuard guard(rewriter);
2370 rewriter.setInsertionPoint(op);
2371 auto condValue =
2372 hw::ConstantOp::create(rewriter, muxCond.getLoc(), APInt(1, constCond));
2373 rewriter.modifyOpInPlace(op, [&] {
2374 for (auto &use : op->getOpOperands())
2375 if (use.get() == muxCond)
2376 use.set(condValue);
2377 });
2378 return true;
2379}
2380
2381namespace {
2382struct MuxRewriter : public mlir::OpRewritePattern<MuxOp> {
2383 using OpRewritePattern::OpRewritePattern;
2384
2385 LogicalResult matchAndRewrite(MuxOp op,
2386 PatternRewriter &rewriter) const override;
2387};
2388
2390foldToArrayCreateOnlyWhenDense(size_t indexWidth, size_t numEntries) {
2391 // If the array is greater that 9 bits, it will take over 512 elements and
2392 // it will be too large for a single expression.
2393 if (indexWidth >= 9 || numEntries < 3)
2395
2396 // Next we need to see if the values are dense-ish. We don't want to have
2397 // a tremendous number of replicated entries in the array. Some sparsity is
2398 // ok though, so we require the table to be at least 5/8 utilized.
2399 uint64_t tableSize = 1ULL << indexWidth;
2400 if (numEntries >= tableSize * 5 / 8)
2403}
2404
2405LogicalResult MuxRewriter::matchAndRewrite(MuxOp op,
2406 PatternRewriter &rewriter) const {
2407 if (isOpTriviallyRecursive(op))
2408 return failure();
2409
2410 bool isSignlessInt = false;
2411 if (auto intType = dyn_cast<IntegerType>(op.getType()))
2412 isSignlessInt = intType.isSignless();
2413
2414 // If the op has a SV attribute, don't optimize it.
2415 if (hasSVAttributes(op))
2416 return failure();
2417 APInt value;
2418
2419 if (matchPattern(op.getTrueValue(), m_ConstantInt(&value)) && isSignlessInt) {
2420 if (value.getBitWidth() == 1) {
2421 // mux(a, 0, b) -> and(~a, b) for single-bit values.
2422 if (value.isZero()) {
2423 auto notCond = createOrFoldNot(op.getLoc(), op.getCond(), rewriter);
2424 replaceOpWithNewOpAndCopyNamehint<AndOp>(rewriter, op, notCond,
2425 op.getFalseValue(), false);
2426 return success();
2427 }
2428
2429 // mux(a, 1, b) -> or(a, b) for single-bit values.
2430 replaceOpWithNewOpAndCopyNamehint<OrOp>(rewriter, op, op.getCond(),
2431 op.getFalseValue(), false);
2432 return success();
2433 }
2434
2435 // Check for mux of two constants. There are many ways to simplify them.
2436 APInt value2;
2437 if (matchPattern(op.getFalseValue(), m_ConstantInt(&value2))) {
2438 // When both inputs are constants and differ by only one bit, we can
2439 // simplify by splitting the mux into up to three contiguous chunks: one
2440 // for the differing bit and up to two for the bits that are the same.
2441 // E.g. mux(a, 3'h2, 0) -> concat(0, mux(a, 1, 0), 0) -> concat(0, a, 0)
2442 APInt xorValue = value ^ value2;
2443 if (xorValue.isPowerOf2()) {
2444 unsigned leadingZeros = xorValue.countLeadingZeros();
2445 unsigned trailingZeros = value.getBitWidth() - leadingZeros - 1;
2446 SmallVector<Value, 3> operands;
2447
2448 // Concat operands go from MSB to LSB, so we handle chunks in reverse
2449 // order of bit indexes.
2450 // For the chunks that are identical (i.e. correspond to 0s in
2451 // xorValue), we can extract directly from either input value, and we
2452 // arbitrarily pick the trueValue().
2453
2454 if (leadingZeros > 0)
2455 operands.push_back(rewriter.createOrFold<ExtractOp>(
2456 op.getLoc(), op.getTrueValue(), trailingZeros + 1, leadingZeros));
2457
2458 // Handle the differing bit, which should simplify into either cond or
2459 // ~cond.
2460 auto v1 = rewriter.createOrFold<ExtractOp>(
2461 op.getLoc(), op.getTrueValue(), trailingZeros, 1);
2462 auto v2 = rewriter.createOrFold<ExtractOp>(
2463 op.getLoc(), op.getFalseValue(), trailingZeros, 1);
2464 operands.push_back(rewriter.createOrFold<MuxOp>(
2465 op.getLoc(), op.getCond(), v1, v2, false));
2466
2467 if (trailingZeros > 0)
2468 operands.push_back(rewriter.createOrFold<ExtractOp>(
2469 op.getLoc(), op.getTrueValue(), 0, trailingZeros));
2470
2471 replaceOpWithNewOpAndCopyNamehint<ConcatOp>(rewriter, op, op.getType(),
2472 operands);
2473 return success();
2474 }
2475
2476 // If the true value is all ones and the false is all zeros then we have a
2477 // replicate pattern.
2478 if (value.isAllOnes() && value2.isZero()) {
2479 replaceOpWithNewOpAndCopyNamehint<ReplicateOp>(
2480 rewriter, op, op.getType(), op.getCond());
2481 return success();
2482 }
2483 }
2484 }
2485
2486 if (matchPattern(op.getFalseValue(), m_ConstantInt(&value)) &&
2487 isSignlessInt && value.getBitWidth() == 1) {
2488 // mux(a, b, 0) -> and(a, b) for single-bit values.
2489 if (value.isZero()) {
2490 replaceOpWithNewOpAndCopyNamehint<AndOp>(rewriter, op, op.getCond(),
2491 op.getTrueValue(), false);
2492 return success();
2493 }
2494
2495 // mux(a, b, 1) -> or(~a, b) for single-bit values.
2496 // falseValue() is known to be a single-bit 1, which we can use for
2497 // the 1 in the representation of ~ using xor.
2498 auto notCond = rewriter.createOrFold<XorOp>(op.getLoc(), op.getCond(),
2499 op.getFalseValue(), false);
2500 replaceOpWithNewOpAndCopyNamehint<OrOp>(rewriter, op, notCond,
2501 op.getTrueValue(), false);
2502 return success();
2503 }
2504
2505 // mux(!a, b, c) -> mux(a, c, b)
2506 Value subExpr;
2507 Operation *condOp = op.getCond().getDefiningOp();
2508 if (condOp && matchPattern(condOp, m_Complement(m_Any(&subExpr))) &&
2509 op.getTwoState()) {
2510 replaceOpWithNewOpAndCopyNamehint<MuxOp>(rewriter, op, op.getType(),
2511 subExpr, op.getFalseValue(),
2512 op.getTrueValue(), true);
2513 return success();
2514 }
2515
2516 // Same but with Demorgan's law.
2517 // mux(and(~a, ~b, ~c), x, y) -> mux(or(a, b, c), y, x)
2518 // mux(or(~a, ~b, ~c), x, y) -> mux(and(a, b, c), y, x)
2519 if (condOp && condOp->hasOneUse()) {
2520 SmallVector<Value> invertedOperands;
2521
2522 /// Scan all the operands to see if they are complemented. If so, build a
2523 /// vector of them and return true, otherwise return false.
2524 auto getInvertedOperands = [&]() -> bool {
2525 for (Value operand : condOp->getOperands()) {
2526 if (matchPattern(operand, m_Complement(m_Any(&subExpr))))
2527 invertedOperands.push_back(subExpr);
2528 else
2529 return false;
2530 }
2531 return true;
2532 };
2533
2534 if (isa<AndOp>(condOp) && getInvertedOperands()) {
2535 auto newOr =
2536 rewriter.createOrFold<OrOp>(op.getLoc(), invertedOperands, false);
2537 replaceOpWithNewOpAndCopyNamehint<MuxOp>(
2538 rewriter, op, newOr, op.getFalseValue(), op.getTrueValue(),
2539 op.getTwoState());
2540 return success();
2541 }
2542 if (isa<OrOp>(condOp) && getInvertedOperands()) {
2543 auto newAnd =
2544 rewriter.createOrFold<AndOp>(op.getLoc(), invertedOperands, false);
2545 replaceOpWithNewOpAndCopyNamehint<MuxOp>(
2546 rewriter, op, newAnd, op.getFalseValue(), op.getTrueValue(),
2547 op.getTwoState());
2548 return success();
2549 }
2550 }
2551
2552 if (auto falseMux = op.getFalseValue().getDefiningOp<MuxOp>();
2553 falseMux && falseMux != op) {
2554 // mux(selector, x, mux(selector, y, z) = mux(selector, x, z)
2555 if (op.getCond() == falseMux.getCond()) {
2556 replaceOpWithNewOpAndCopyNamehint<MuxOp>(
2557 rewriter, op, op.getCond(), op.getTrueValue(),
2558 falseMux.getFalseValue(), op.getTwoStateAttr());
2559 return success();
2560 }
2561
2562 // Check to see if we can fold a mux tree into an array_create/get pair.
2563 if (foldMuxChainWithComparison(rewriter, op, /*isFalse*/ true,
2564 foldToArrayCreateOnlyWhenDense))
2565 return success();
2566 }
2567
2568 if (auto trueMux = op.getTrueValue().getDefiningOp<MuxOp>();
2569 trueMux && trueMux != op) {
2570 // mux(selector, mux(selector, a, b), c) = mux(selector, a, c)
2571 if (op.getCond() == trueMux.getCond()) {
2572 replaceOpWithNewOpAndCopyNamehint<MuxOp>(
2573 rewriter, op, op.getCond(), trueMux.getTrueValue(),
2574 op.getFalseValue(), op.getTwoStateAttr());
2575 return success();
2576 }
2577
2578 // Check to see if we can fold a mux tree into an array_create/get pair.
2579 if (foldMuxChainWithComparison(rewriter, op, /*isFalseSide*/ false,
2580 foldToArrayCreateOnlyWhenDense))
2581 return success();
2582 }
2583
2584 // mux(c1, mux(c2, a, b), mux(c2, a, c)) -> mux(c2, a, mux(c1, b, c))
2585 if (auto trueMux = dyn_cast_or_null<MuxOp>(op.getTrueValue().getDefiningOp()),
2586 falseMux = dyn_cast_or_null<MuxOp>(op.getFalseValue().getDefiningOp());
2587 trueMux && falseMux && trueMux.getCond() == falseMux.getCond() &&
2588 trueMux.getTrueValue() == falseMux.getTrueValue() && trueMux != op &&
2589 falseMux != op) {
2590 auto subMux = MuxOp::create(
2591 rewriter, rewriter.getFusedLoc({trueMux.getLoc(), falseMux.getLoc()}),
2592 op.getCond(), trueMux.getFalseValue(), falseMux.getFalseValue());
2593 replaceOpWithNewOpAndCopyNamehint<MuxOp>(rewriter, op, trueMux.getCond(),
2594 trueMux.getTrueValue(), subMux,
2595 op.getTwoStateAttr());
2596 return success();
2597 }
2598
2599 // mux(c1, mux(c2, a, b), mux(c2, c, b)) -> mux(c2, mux(c1, a, c), b)
2600 if (auto trueMux = dyn_cast_or_null<MuxOp>(op.getTrueValue().getDefiningOp()),
2601 falseMux = dyn_cast_or_null<MuxOp>(op.getFalseValue().getDefiningOp());
2602 trueMux && falseMux && trueMux.getCond() == falseMux.getCond() &&
2603 trueMux.getFalseValue() == falseMux.getFalseValue() && trueMux != op &&
2604 falseMux != op) {
2605 auto subMux = MuxOp::create(
2606 rewriter, rewriter.getFusedLoc({trueMux.getLoc(), falseMux.getLoc()}),
2607 op.getCond(), trueMux.getTrueValue(), falseMux.getTrueValue());
2608 replaceOpWithNewOpAndCopyNamehint<MuxOp>(rewriter, op, trueMux.getCond(),
2609 subMux, trueMux.getFalseValue(),
2610 op.getTwoStateAttr());
2611 return success();
2612 }
2613
2614 // mux(c1, mux(c2, a, b), mux(c3, a, b)) -> mux(mux(c1, c2, c3), a, b)
2615 if (auto trueMux = dyn_cast_or_null<MuxOp>(op.getTrueValue().getDefiningOp()),
2616 falseMux = dyn_cast_or_null<MuxOp>(op.getFalseValue().getDefiningOp());
2617 trueMux && falseMux &&
2618 trueMux.getTrueValue() == falseMux.getTrueValue() &&
2619 trueMux.getFalseValue() == falseMux.getFalseValue() && trueMux != op &&
2620 falseMux != op) {
2621 auto subMux =
2622 MuxOp::create(rewriter,
2623 rewriter.getFusedLoc(
2624 {op.getLoc(), trueMux.getLoc(), falseMux.getLoc()}),
2625 op.getCond(), trueMux.getCond(), falseMux.getCond());
2626 replaceOpWithNewOpAndCopyNamehint<MuxOp>(
2627 rewriter, op, subMux, trueMux.getTrueValue(), trueMux.getFalseValue(),
2628 op.getTwoStateAttr());
2629 return success();
2630 }
2631
2632 // mux(cond, x|y|z|a, a) -> (x|y|z)&replicate(cond) | a
2633 if (foldCommonMuxValue(op, false, rewriter))
2634 return success();
2635 // mux(cond, a, x|y|z|a) -> (x|y|z)&replicate(~cond) | a
2636 if (foldCommonMuxValue(op, true, rewriter))
2637 return success();
2638
2639 // `mux(cond, op(a, b), op(a, c))` -> `op(a, mux(cond, b, c))`
2640 if (Operation *trueOp = op.getTrueValue().getDefiningOp())
2641 if (Operation *falseOp = op.getFalseValue().getDefiningOp())
2642 if (trueOp->getName() == falseOp->getName())
2643 if (foldCommonMuxOperation(op, trueOp, falseOp, rewriter))
2644 return success();
2645
2646 // extracts only of mux(...) -> mux(extract()...)
2647 if (narrowOperationWidth(op, true, rewriter))
2648 return success();
2649
2650 // mux(cond, repl(n, a1), repl(n, a2)) -> repl(n, mux(cond, a1, a2))
2651 if (foldMuxOfUniformArrays(op, rewriter))
2652 return success();
2653
2654 // mux(cond, opA(cond), opB(cond)) -> mux(cond, opA(1), opB(1))
2655 if (op.getTrueValue().getDefiningOp() &&
2656 op.getTrueValue().getDefiningOp() != op)
2657 if (assumeMuxCondInOperand(op.getCond(), op.getTrueValue(), true, rewriter))
2658 return success();
2659 if (op.getFalseValue().getDefiningOp() &&
2660 op.getFalseValue().getDefiningOp() != op)
2661
2662 if (assumeMuxCondInOperand(op.getCond(), op.getFalseValue(), false,
2663 rewriter))
2664 return success();
2665
2666 return failure();
2667}
2668
2669static bool foldArrayOfMuxes(hw::ArrayCreateOp op, PatternRewriter &rewriter) {
2670 // Do not fold uniform or singleton arrays to avoid duplicating muxes.
2671 if (op.getInputs().empty() || op.isUniform())
2672 return false;
2673 auto inputs = op.getInputs();
2674 if (inputs.size() <= 1)
2675 return false;
2676
2677 // Check the operands to the array create. Ensure all of them are the
2678 // same op with the same number of operands.
2679 auto first = inputs[0].getDefiningOp<comb::MuxOp>();
2680 if (!first || hasSVAttributes(first))
2681 return false;
2682
2683 // Check whether all operands are muxes with the same condition.
2684 for (size_t i = 1, n = inputs.size(); i < n; ++i) {
2685 auto input = inputs[i].getDefiningOp<comb::MuxOp>();
2686 if (!input || first.getCond() != input.getCond())
2687 return false;
2688 }
2689
2690 // Collect the true and the false branches into arrays.
2691 SmallVector<Value> trues{first.getTrueValue()};
2692 SmallVector<Value> falses{first.getFalseValue()};
2693 SmallVector<Location> locs{first->getLoc()};
2694 bool isTwoState = true;
2695 for (size_t i = 1, n = inputs.size(); i < n; ++i) {
2696 auto input = inputs[i].getDefiningOp<comb::MuxOp>();
2697 trues.push_back(input.getTrueValue());
2698 falses.push_back(input.getFalseValue());
2699 locs.push_back(input->getLoc());
2700 if (!input.getTwoState())
2701 isTwoState = false;
2702 }
2703
2704 // Define the location of the array create as the aggregate of all muxes.
2705 auto loc = FusedLoc::get(op.getContext(), locs);
2706
2707 // Replace the create with an aggregate operation. Push the create op
2708 // into the operands of the aggregate operation.
2709 auto arrayTy = op.getType();
2710 auto trueValues = hw::ArrayCreateOp::create(rewriter, loc, arrayTy, trues);
2711 auto falseValues = hw::ArrayCreateOp::create(rewriter, loc, arrayTy, falses);
2712 rewriter.replaceOpWithNewOp<comb::MuxOp>(op, arrayTy, first.getCond(),
2713 trueValues, falseValues, isTwoState);
2714 return true;
2715}
2716
2717struct ArrayRewriter : public mlir::OpRewritePattern<hw::ArrayCreateOp> {
2718 using OpRewritePattern::OpRewritePattern;
2719
2720 LogicalResult matchAndRewrite(hw::ArrayCreateOp op,
2721 PatternRewriter &rewriter) const override {
2722 if (foldArrayOfMuxes(op, rewriter))
2723 return success();
2724 return failure();
2725 }
2726};
2727
2728} // namespace
2729
2730void MuxOp::getCanonicalizationPatterns(RewritePatternSet &results,
2731 MLIRContext *context) {
2732 results.insert<MuxRewriter, ArrayRewriter>(context);
2733}
2734
2735//===----------------------------------------------------------------------===//
2736// ICmpOp
2737//===----------------------------------------------------------------------===//
2738
2739// Calculate the result of a comparison when the LHS and RHS are both
2740// constants.
2741static bool applyCmpPredicate(ICmpPredicate predicate, const APInt &lhs,
2742 const APInt &rhs) {
2743 switch (predicate) {
2744 case ICmpPredicate::eq:
2745 return lhs.eq(rhs);
2746 case ICmpPredicate::ne:
2747 return lhs.ne(rhs);
2748 case ICmpPredicate::slt:
2749 return lhs.slt(rhs);
2750 case ICmpPredicate::sle:
2751 return lhs.sle(rhs);
2752 case ICmpPredicate::sgt:
2753 return lhs.sgt(rhs);
2754 case ICmpPredicate::sge:
2755 return lhs.sge(rhs);
2756 case ICmpPredicate::ult:
2757 return lhs.ult(rhs);
2758 case ICmpPredicate::ule:
2759 return lhs.ule(rhs);
2760 case ICmpPredicate::ugt:
2761 return lhs.ugt(rhs);
2762 case ICmpPredicate::uge:
2763 return lhs.uge(rhs);
2764 case ICmpPredicate::ceq:
2765 return lhs.eq(rhs);
2766 case ICmpPredicate::cne:
2767 return lhs.ne(rhs);
2768 case ICmpPredicate::weq:
2769 return lhs.eq(rhs);
2770 case ICmpPredicate::wne:
2771 return lhs.ne(rhs);
2772 }
2773 llvm_unreachable("unknown comparison predicate");
2774}
2775
2776// Returns the result of applying the predicate when the LHS and RHS are the
2777// exact same value.
2778static bool applyCmpPredicateToEqualOperands(ICmpPredicate predicate) {
2779 switch (predicate) {
2780 case ICmpPredicate::eq:
2781 case ICmpPredicate::sle:
2782 case ICmpPredicate::sge:
2783 case ICmpPredicate::ule:
2784 case ICmpPredicate::uge:
2785 case ICmpPredicate::ceq:
2786 case ICmpPredicate::weq:
2787 return true;
2788 case ICmpPredicate::ne:
2789 case ICmpPredicate::slt:
2790 case ICmpPredicate::sgt:
2791 case ICmpPredicate::ult:
2792 case ICmpPredicate::ugt:
2793 case ICmpPredicate::cne:
2794 case ICmpPredicate::wne:
2795 return false;
2796 }
2797 llvm_unreachable("unknown comparison predicate");
2798}
2799
2800OpFoldResult ICmpOp::fold(FoldAdaptor adaptor) {
2801 // gt a, a -> false
2802 // gte a, a -> true
2803 if (getLhs() == getRhs()) {
2804 auto val = applyCmpPredicateToEqualOperands(getPredicate());
2805 return IntegerAttr::get(getType(), val);
2806 }
2807
2808 // gt 1, 2 -> false
2809 if (auto lhs = dyn_cast_or_null<IntegerAttr>(adaptor.getLhs())) {
2810 if (auto rhs = dyn_cast_or_null<IntegerAttr>(adaptor.getRhs())) {
2811 auto val =
2812 applyCmpPredicate(getPredicate(), lhs.getValue(), rhs.getValue());
2813 return IntegerAttr::get(getType(), val);
2814 }
2815 }
2816 return {};
2817}
2818
2819// Given a range of operands, computes the number of matching prefix and
2820// suffix elements. This does not perform cross-element matching.
2821template <typename Range>
2822static size_t computeCommonPrefixLength(const Range &a, const Range &b) {
2823 size_t commonPrefixLength = 0;
2824 auto ia = a.begin();
2825 auto ib = b.begin();
2826
2827 for (; ia != a.end() && ib != b.end(); ia++, ib++, commonPrefixLength++) {
2828 if (*ia != *ib) {
2829 break;
2830 }
2831 }
2832
2833 return commonPrefixLength;
2834}
2835
2836static size_t getTotalWidth(ArrayRef<Value> operands) {
2837 size_t totalWidth = 0;
2838 for (auto operand : operands) {
2839 // getIntOrFloatBitWidth should never raise, since all arguments to
2840 // ConcatOp are integers.
2841 ssize_t width = operand.getType().getIntOrFloatBitWidth();
2842 assert(width >= 0);
2843 totalWidth += width;
2844 }
2845 return totalWidth;
2846}
2847
2848/// Reduce the strength icmp(concat(...), concat(...)) by doing a element-wise
2849/// comparison on common prefix and suffixes. Returns success() if a rewriting
2850/// happens. This handles both concat and replicate.
2851static LogicalResult matchAndRewriteCompareConcat(ICmpOp op, Operation *lhs,
2852 Operation *rhs,
2853 PatternRewriter &rewriter) {
2854 // It is safe to assume that [{lhsOperands, rhsOperands}.size() > 0] and
2855 // all elements have non-zero length. Both these invariants are verified
2856 // by the ConcatOp verifier.
2857 SmallVector<Value> lhsOperands, rhsOperands;
2858 getConcatOperands(lhs->getResult(0), lhsOperands);
2859 getConcatOperands(rhs->getResult(0), rhsOperands);
2860 ArrayRef<Value> lhsOperandsRef = lhsOperands, rhsOperandsRef = rhsOperands;
2861
2862 auto formCatOrReplicate = [&](Location loc,
2863 ArrayRef<Value> operands) -> Value {
2864 assert(!operands.empty());
2865 Value sameElement = operands[0];
2866 for (size_t i = 1, e = operands.size(); i != e && sameElement; ++i)
2867 if (sameElement != operands[i])
2868 sameElement = Value();
2869 if (sameElement)
2870 return rewriter.createOrFold<ReplicateOp>(loc, sameElement,
2871 operands.size());
2872 return rewriter.createOrFold<ConcatOp>(loc, operands);
2873 };
2874
2875 auto replaceWith = [&](ICmpPredicate predicate, Value lhs,
2876 Value rhs) -> LogicalResult {
2877 replaceOpWithNewOpAndCopyNamehint<ICmpOp>(rewriter, op, predicate, lhs, rhs,
2878 op.getTwoState());
2879 return success();
2880 };
2881
2882 size_t commonPrefixLength =
2883 computeCommonPrefixLength(lhsOperands, rhsOperands);
2884 if (commonPrefixLength == lhsOperands.size()) {
2885 // cat(a, b, c) == cat(a, b, c) -> 1
2886 bool result = applyCmpPredicateToEqualOperands(op.getPredicate());
2887 replaceOpWithNewOpAndCopyNamehint<hw::ConstantOp>(rewriter, op,
2888 APInt(1, result));
2889 return success();
2890 }
2891
2892 size_t commonSuffixLength = computeCommonPrefixLength(
2893 llvm::reverse(lhsOperandsRef), llvm::reverse(rhsOperandsRef));
2894
2895 size_t commonPrefixTotalWidth =
2896 getTotalWidth(lhsOperandsRef.take_front(commonPrefixLength));
2897 size_t commonSuffixTotalWidth =
2898 getTotalWidth(lhsOperandsRef.take_back(commonSuffixLength));
2899 auto lhsOnly = lhsOperandsRef.drop_front(commonPrefixLength)
2900 .drop_back(commonSuffixLength);
2901 auto rhsOnly = rhsOperandsRef.drop_front(commonPrefixLength)
2902 .drop_back(commonSuffixLength);
2903
2904 auto replaceWithoutReplicatingSignBit = [&]() {
2905 auto newLhs = formCatOrReplicate(lhs->getLoc(), lhsOnly);
2906 auto newRhs = formCatOrReplicate(rhs->getLoc(), rhsOnly);
2907 return replaceWith(op.getPredicate(), newLhs, newRhs);
2908 };
2909
2910 auto replaceWithReplicatingSignBit = [&]() {
2911 auto firstNonEmptyValue = lhsOperands[0];
2912 auto firstNonEmptyElemWidth =
2913 firstNonEmptyValue.getType().getIntOrFloatBitWidth();
2914 Value signBit = rewriter.createOrFold<ExtractOp>(
2915 op.getLoc(), firstNonEmptyValue, firstNonEmptyElemWidth - 1, 1);
2916
2917 auto newLhs = ConcatOp::create(rewriter, lhs->getLoc(), signBit, lhsOnly);
2918 auto newRhs = ConcatOp::create(rewriter, rhs->getLoc(), signBit, rhsOnly);
2919 return replaceWith(op.getPredicate(), newLhs, newRhs);
2920 };
2921
2922 if (ICmpOp::isPredicateSigned(op.getPredicate())) {
2923 // scmp(cat(..x, b), cat(..y, b)) == scmp(cat(..x), cat(..y))
2924 if (commonPrefixTotalWidth == 0 && commonSuffixTotalWidth > 0)
2925 return replaceWithoutReplicatingSignBit();
2926
2927 // scmp(cat(a, ..x, b), cat(a, ..y, b)) == scmp(cat(sgn(a), ..x),
2928 // cat(sgn(b), ..y)) Note that we cannot perform this optimization if
2929 // [width(b) = 0 && width(a) <= 1]. since that common prefix is the sign
2930 // bit. Doing the rewrite can result in an infinite loop.
2931 if (commonPrefixTotalWidth > 1 || commonSuffixTotalWidth > 0)
2932 return replaceWithReplicatingSignBit();
2933
2934 } else if (commonPrefixTotalWidth > 0 || commonSuffixTotalWidth > 0) {
2935 // ucmp(cat(a, ..x, b), cat(a, ..y, b)) = ucmp(cat(..x), cat(..y))
2936 return replaceWithoutReplicatingSignBit();
2937 }
2938
2939 return failure();
2940}
2941
2942/// Given an equality comparison with a constant value and some operand that has
2943/// known bits, simplify the comparison to check only the unknown bits of the
2944/// input.
2945///
2946/// One simple example of this is that `concat(0, stuff) == 0` can be simplified
2947/// to `stuff == 0`, or `and(x, 3) == 0` can be simplified to
2948/// `extract x[1:0] == 0`
2950 ICmpOp cmpOp, const KnownBits &bitAnalysis, const APInt &rhsCst,
2951 PatternRewriter &rewriter) {
2952
2953 // If any of the known bits disagree with any of the comparison bits, then
2954 // we can constant fold this comparison right away.
2955 APInt bitsKnown = bitAnalysis.Zero | bitAnalysis.One;
2956 if ((bitsKnown & rhsCst) != bitAnalysis.One) {
2957 // If we discover a mismatch then we know an "eq" comparison is false
2958 // and a "ne" comparison is true!
2959 bool result = cmpOp.getPredicate() == ICmpPredicate::ne;
2960 replaceOpWithNewOpAndCopyNamehint<hw::ConstantOp>(rewriter, cmpOp,
2961 APInt(1, result));
2962 return;
2963 }
2964
2965 // Check to see if we can prove the result entirely of the comparison (in
2966 // which we bail out early), otherwise build a list of values to concat and a
2967 // smaller constant to compare against.
2968 SmallVector<Value> newConcatOperands;
2969 auto newConstant = APInt::getZeroWidth();
2970
2971 // Ok, some (maybe all) bits are known and some others may be unknown.
2972 // Extract out segments of the operand and compare against the
2973 // corresponding bits.
2974 unsigned knownMSB = bitsKnown.countLeadingOnes();
2975
2976 Value operand = cmpOp.getLhs();
2977
2978 // Ok, some bits are known but others are not. Extract out sequences of
2979 // bits that are unknown and compare just those bits. We work from MSB to
2980 // LSB.
2981 while (knownMSB != bitsKnown.getBitWidth()) {
2982 // Drop any high bits that are known.
2983 if (knownMSB)
2984 bitsKnown = bitsKnown.trunc(bitsKnown.getBitWidth() - knownMSB);
2985
2986 // Find the span of unknown bits, and extract it.
2987 unsigned unknownBits = bitsKnown.countLeadingZeros();
2988 unsigned lowBit = bitsKnown.getBitWidth() - unknownBits;
2989 auto spanOperand = rewriter.createOrFold<ExtractOp>(
2990 operand.getLoc(), operand, /*lowBit=*/lowBit,
2991 /*bitWidth=*/unknownBits);
2992 auto spanConstant = rhsCst.lshr(lowBit).trunc(unknownBits);
2993
2994 // Add this info to the concat we're generating.
2995 newConcatOperands.push_back(spanOperand);
2996 // FIXME(llvm merge, cc697fc292b0): concat doesn't work with zero bit values
2997 // newConstant = newConstant.concat(spanConstant);
2998 if (newConstant.getBitWidth() != 0)
2999 newConstant = newConstant.concat(spanConstant);
3000 else
3001 newConstant = spanConstant;
3002
3003 // Drop the unknown bits in prep for the next chunk.
3004 unsigned newWidth = bitsKnown.getBitWidth() - unknownBits;
3005 bitsKnown = bitsKnown.trunc(newWidth);
3006 knownMSB = bitsKnown.countLeadingOnes();
3007 }
3008
3009 // If all the operands to the concat are foldable then we have an identity
3010 // situation where all the sub-elements equal each other. This implies that
3011 // the overall result is foldable.
3012 if (newConcatOperands.empty()) {
3013 bool result = cmpOp.getPredicate() == ICmpPredicate::eq;
3014 replaceOpWithNewOpAndCopyNamehint<hw::ConstantOp>(rewriter, cmpOp,
3015 APInt(1, result));
3016 return;
3017 }
3018
3019 // If we have a single operand remaining, use it, otherwise form a concat.
3020 Value concatResult =
3021 rewriter.createOrFold<ConcatOp>(operand.getLoc(), newConcatOperands);
3022
3023 // Form the comparison against the smaller constant.
3024 auto newConstantOp = hw::ConstantOp::create(
3025 rewriter, cmpOp.getOperand(1).getLoc(), newConstant);
3026
3027 replaceOpWithNewOpAndCopyNamehint<ICmpOp>(rewriter, cmpOp,
3028 cmpOp.getPredicate(), concatResult,
3029 newConstantOp, cmpOp.getTwoState());
3030}
3031
3032// Simplify icmp eq(xor(a,b,cst1), cst2) -> icmp eq(xor(a,b), cst1^cst2).
3033static void combineEqualityICmpWithXorOfConstant(ICmpOp cmpOp, XorOp xorOp,
3034 const APInt &rhs,
3035 PatternRewriter &rewriter) {
3036 auto ip = rewriter.saveInsertionPoint();
3037 rewriter.setInsertionPoint(xorOp);
3038
3039 auto xorRHS = xorOp.getOperands().back().getDefiningOp<hw::ConstantOp>();
3040 auto newRHS = hw::ConstantOp::create(rewriter, xorRHS->getLoc(),
3041 xorRHS.getValue() ^ rhs);
3042 Value newLHS;
3043 switch (xorOp.getNumOperands()) {
3044 case 1:
3045 // This isn't common but is defined so we need to handle it.
3046 newLHS = hw::ConstantOp::create(rewriter, xorOp.getLoc(),
3047 APInt::getZero(rhs.getBitWidth()));
3048 break;
3049 case 2:
3050 // The binary case is the most common.
3051 newLHS = xorOp.getOperand(0);
3052 break;
3053 default:
3054 // The general case forces us to form a new xor with the remaining operands.
3055 SmallVector<Value> newOperands(xorOp.getOperands());
3056 newOperands.pop_back();
3057 newLHS = XorOp::create(rewriter, xorOp.getLoc(), newOperands, false);
3058 break;
3059 }
3060
3061 bool xorMultipleUses = !xorOp->hasOneUse();
3062
3063 // If the xor has multiple uses (not just the compare, then we need/want to
3064 // replace them as well.
3065 if (xorMultipleUses)
3066 replaceOpWithNewOpAndCopyNamehint<XorOp>(rewriter, xorOp, newLHS, xorRHS,
3067 false);
3068
3069 // Replace the comparison.
3070 rewriter.restoreInsertionPoint(ip);
3071 replaceOpWithNewOpAndCopyNamehint<ICmpOp>(
3072 rewriter, cmpOp, cmpOp.getPredicate(), newLHS, newRHS, false);
3073}
3074
3075LogicalResult ICmpOp::canonicalize(ICmpOp op, PatternRewriter &rewriter) {
3076 if (isOpTriviallyRecursive(op))
3077 return failure();
3078 APInt lhs, rhs;
3079
3080 // icmp 1, x -> icmp x, 1
3081 if (matchPattern(op.getLhs(), m_ConstantInt(&lhs))) {
3082 assert(!matchPattern(op.getRhs(), m_ConstantInt(&rhs)) &&
3083 "Should be folded");
3084 replaceOpWithNewOpAndCopyNamehint<ICmpOp>(
3085 rewriter, op, ICmpOp::getFlippedPredicate(op.getPredicate()),
3086 op.getRhs(), op.getLhs(), op.getTwoState());
3087 return success();
3088 }
3089
3090 // Canonicalize with RHS constant
3091 if (matchPattern(op.getRhs(), m_ConstantInt(&rhs))) {
3092 auto getConstant = [&](APInt constant) -> Value {
3093 return hw::ConstantOp::create(rewriter, op.getLoc(), std::move(constant));
3094 };
3095
3096 auto replaceWith = [&](ICmpPredicate predicate, Value lhs,
3097 Value rhs) -> LogicalResult {
3098 replaceOpWithNewOpAndCopyNamehint<ICmpOp>(rewriter, op, predicate, lhs,
3099 rhs, op.getTwoState());
3100 return success();
3101 };
3102
3103 auto replaceWithConstantI1 = [&](bool constant) -> LogicalResult {
3104 replaceOpWithNewOpAndCopyNamehint<hw::ConstantOp>(rewriter, op,
3105 APInt(1, constant));
3106 return success();
3107 };
3108
3109 switch (op.getPredicate()) {
3110 case ICmpPredicate::slt:
3111 // x < max -> x != max
3112 if (rhs.isMaxSignedValue())
3113 return replaceWith(ICmpPredicate::ne, op.getLhs(), op.getRhs());
3114 // x < min -> false
3115 if (rhs.isMinSignedValue())
3116 return replaceWithConstantI1(0);
3117 // x < min+1 -> x == min
3118 if ((rhs - 1).isMinSignedValue())
3119 return replaceWith(ICmpPredicate::eq, op.getLhs(),
3120 getConstant(rhs - 1));
3121 break;
3122 case ICmpPredicate::sgt:
3123 // x > min -> x != min
3124 if (rhs.isMinSignedValue())
3125 return replaceWith(ICmpPredicate::ne, op.getLhs(), op.getRhs());
3126 // x > max -> false
3127 if (rhs.isMaxSignedValue())
3128 return replaceWithConstantI1(0);
3129 // x > max-1 -> x == max
3130 if ((rhs + 1).isMaxSignedValue())
3131 return replaceWith(ICmpPredicate::eq, op.getLhs(),
3132 getConstant(rhs + 1));
3133 break;
3134 case ICmpPredicate::ult:
3135 // x < max -> x != max
3136 if (rhs.isAllOnes())
3137 return replaceWith(ICmpPredicate::ne, op.getLhs(), op.getRhs());
3138 // x < min -> false
3139 if (rhs.isZero())
3140 return replaceWithConstantI1(0);
3141 // x < min+1 -> x == min
3142 if ((rhs - 1).isZero())
3143 return replaceWith(ICmpPredicate::eq, op.getLhs(),
3144 getConstant(rhs - 1));
3145
3146 // x < 0xE0 -> extract(x, 5..7) != 0b111
3147 if (rhs.countLeadingOnes() + rhs.countTrailingZeros() ==
3148 rhs.getBitWidth()) {
3149 auto numOnes = rhs.countLeadingOnes();
3150 auto smaller = ExtractOp::create(rewriter, op.getLoc(), op.getLhs(),
3151 rhs.getBitWidth() - numOnes, numOnes);
3152 return replaceWith(ICmpPredicate::ne, smaller,
3153 getConstant(APInt::getAllOnes(numOnes)));
3154 }
3155
3156 break;
3157 case ICmpPredicate::ugt:
3158 // x > min -> x != min
3159 if (rhs.isZero())
3160 return replaceWith(ICmpPredicate::ne, op.getLhs(), op.getRhs());
3161 // x > max -> false
3162 if (rhs.isAllOnes())
3163 return replaceWithConstantI1(0);
3164 // x > max-1 -> x == max
3165 if ((rhs + 1).isAllOnes())
3166 return replaceWith(ICmpPredicate::eq, op.getLhs(),
3167 getConstant(rhs + 1));
3168
3169 // x > 0x07 -> extract(x, 3..7) != 0b00000
3170 if ((rhs + 1).isPowerOf2()) {
3171 auto numOnes = rhs.countTrailingOnes();
3172 auto newWidth = rhs.getBitWidth() - numOnes;
3173 auto smaller = ExtractOp::create(rewriter, op.getLoc(), op.getLhs(),
3174 numOnes, newWidth);
3175 return replaceWith(ICmpPredicate::ne, smaller,
3176 getConstant(APInt::getZero(newWidth)));
3177 }
3178
3179 break;
3180 case ICmpPredicate::sle:
3181 // x <= max -> true
3182 if (rhs.isMaxSignedValue())
3183 return replaceWithConstantI1(1);
3184 // x <= c -> x < (c+1)
3185 return replaceWith(ICmpPredicate::slt, op.getLhs(), getConstant(rhs + 1));
3186 case ICmpPredicate::sge:
3187 // x >= min -> true
3188 if (rhs.isMinSignedValue())
3189 return replaceWithConstantI1(1);
3190 // x >= c -> x > (c-1)
3191 return replaceWith(ICmpPredicate::sgt, op.getLhs(), getConstant(rhs - 1));
3192 case ICmpPredicate::ule:
3193 // x <= max -> true
3194 if (rhs.isAllOnes())
3195 return replaceWithConstantI1(1);
3196 // x <= c -> x < (c+1)
3197 return replaceWith(ICmpPredicate::ult, op.getLhs(), getConstant(rhs + 1));
3198 case ICmpPredicate::uge:
3199 // x >= min -> true
3200 if (rhs.isZero())
3201 return replaceWithConstantI1(1);
3202 // x >= c -> x > (c-1)
3203 return replaceWith(ICmpPredicate::ugt, op.getLhs(), getConstant(rhs - 1));
3204 case ICmpPredicate::eq:
3205 if (rhs.getBitWidth() == 1) {
3206 if (rhs.isZero()) {
3207 // x == 0 -> x ^ 1
3208 replaceOpWithNewOpAndCopyNamehint<XorOp>(rewriter, op, op.getLhs(),
3209 getConstant(APInt(1, 1)),
3210 op.getTwoState());
3211 return success();
3212 }
3213 if (rhs.isAllOnes()) {
3214 // x == 1 -> x
3215 replaceOpAndCopyNamehint(rewriter, op, op.getLhs());
3216 return success();
3217 }
3218 }
3219 break;
3220 case ICmpPredicate::ne:
3221 if (rhs.getBitWidth() == 1) {
3222 if (rhs.isZero()) {
3223 // x != 0 -> x
3224 replaceOpAndCopyNamehint(rewriter, op, op.getLhs());
3225 return success();
3226 }
3227 if (rhs.isAllOnes()) {
3228 // x != 1 -> x ^ 1
3229 replaceOpWithNewOpAndCopyNamehint<XorOp>(rewriter, op, op.getLhs(),
3230 getConstant(APInt(1, 1)),
3231 op.getTwoState());
3232 return success();
3233 }
3234 }
3235 break;
3236 case ICmpPredicate::ceq:
3237 case ICmpPredicate::cne:
3238 case ICmpPredicate::weq:
3239 case ICmpPredicate::wne:
3240 break;
3241 }
3242
3243 // We have some specific optimizations for comparison with a constant that
3244 // are only supported for equality comparisons.
3245 if (op.getPredicate() == ICmpPredicate::eq ||
3246 op.getPredicate() == ICmpPredicate::ne) {
3247 // Simplify `icmp(value_with_known_bits, rhscst)` into some extracts
3248 // with a smaller constant. We only support equality comparisons for
3249 // this.
3250 auto knownBits = computeKnownBits(op.getLhs());
3251 if (!knownBits.isUnknown())
3252 return combineEqualityICmpWithKnownBitsAndConstant(op, knownBits, rhs,
3253 rewriter),
3254 success();
3255
3256 // Simplify icmp eq(xor(a,b,cst1), cst2) -> icmp eq(xor(a,b),
3257 // cst1^cst2).
3258 if (auto xorOp = op.getLhs().getDefiningOp<XorOp>())
3259 if (xorOp.getOperands().back().getDefiningOp<hw::ConstantOp>())
3260 return combineEqualityICmpWithXorOfConstant(op, xorOp, rhs, rewriter),
3261 success();
3262
3263 // Simplify icmp eq(replicate(v, n), c) -> icmp eq(v, c) if c is zero or
3264 // all one.
3265 if (auto replicateOp = op.getLhs().getDefiningOp<ReplicateOp>())
3266 if (rhs.isAllOnes() || rhs.isZero()) {
3267 auto width = replicateOp.getInput().getType().getIntOrFloatBitWidth();
3268 auto cst =
3269 hw::ConstantOp::create(rewriter, op.getLoc(),
3270 rhs.isAllOnes() ? APInt::getAllOnes(width)
3271 : APInt::getZero(width));
3272 replaceOpWithNewOpAndCopyNamehint<ICmpOp>(
3273 rewriter, op, op.getPredicate(), replicateOp.getInput(), cst,
3274 op.getTwoState());
3275 return success();
3276 }
3277 }
3278 }
3279
3280 // icmp(cat(prefix, a, b, suffix), cat(prefix, c, d, suffix)) => icmp(cat(a,
3281 // b), cat(c, d)). contains special handling for sign bit in signed
3282 // compressions.
3283 if (Operation *opLHS = op.getLhs().getDefiningOp())
3284 if (Operation *opRHS = op.getRhs().getDefiningOp())
3285 if (isa<ConcatOp, ReplicateOp>(opLHS) &&
3286 isa<ConcatOp, ReplicateOp>(opRHS)) {
3287 if (succeeded(matchAndRewriteCompareConcat(op, opLHS, opRHS, rewriter)))
3288 return success();
3289 }
3290
3291 return failure();
3292}
assert(baseType &&"element must be base type")
static SmallVector< T > concat(const SmallVectorImpl< T > &a, const SmallVectorImpl< T > &b)
Returns a new vector containing the concatenation of vectors a and b.
Definition CalyxOps.cpp:540
static KnownBits computeKnownBits(Value v, unsigned depth)
Given an integer SSA value, check to see if we know anything about the result of the computation.
static bool foldMuxOfUniformArrays(MuxOp op, PatternRewriter &rewriter)
static Attribute constFoldAssociativeOp(ArrayRef< Attribute > operands, hw::PEO paramOpcode)
static Attribute constFoldBinaryOp(ArrayRef< Attribute > operands, hw::PEO paramOpcode)
Performs constant folding calculate with element-wise behavior on the two attributes in operands and ...
static bool applyCmpPredicateToEqualOperands(ICmpPredicate predicate)
static ComplementMatcher< SubType > m_Complement(const SubType &subExpr)
Definition CombFolds.cpp:84
static bool canonicalizeLogicalCstWithConcat(Operation *logicalOp, size_t concatIdx, const APInt &cst, PatternRewriter &rewriter)
When we find a logical operation (and, or, xor) with a constant e.g.
static bool narrowOperationWidth(OpTy op, bool narrowTrailingBits, PatternRewriter &rewriter)
static OpFoldResult foldDiv(Op op, ArrayRef< Attribute > constants)
static Value getCommonOperand(Op op)
Returns a single common operand that all inputs of the operation op can be traced back to,...
static bool canCombineOppositeBinCmpIntoConstant(OperandRange operands)
static void getConcatOperands(Value v, SmallVectorImpl< Value > &result)
Flatten concat and mux operands into a vector.
Definition CombFolds.cpp:52
static Value extractOperandFromFullyAssociative(Operation *fullyAssoc, size_t operandNo, PatternRewriter &rewriter)
Given a fully associative variadic operation like (a+b+c+d), break the expression into two parts,...
static bool getMuxChainCondConstant(Value cond, Value indexValue, bool isInverted, std::function< void(hw::ConstantOp)> constantFn)
Check to see if the condition to the specified mux is an equality comparison indexValue and one or mo...
static TypedAttr getIntAttr(const APInt &value, MLIRContext *context)
Definition CombFolds.cpp:46
static bool shouldBeFlattened(Operation *op)
Return true if the op will be flattened afterwards.
Definition CombFolds.cpp:90
static void canonicalizeXorIcmpTrue(XorOp op, unsigned icmpOperand, PatternRewriter &rewriter)
static bool assumeMuxCondInOperand(Value muxCond, Value muxValue, bool constCond, PatternRewriter &rewriter)
If the mux condition is an operand to the op defining its true or false value, replace the condition ...
static bool extractFromReplicate(ExtractOp op, ReplicateOp replicate, PatternRewriter &rewriter)
static void combineEqualityICmpWithXorOfConstant(ICmpOp cmpOp, XorOp xorOp, const APInt &rhs, PatternRewriter &rewriter)
static size_t getTotalWidth(ArrayRef< Value > operands)
static bool foldCommonMuxOperation(MuxOp mux, Operation *trueOp, Operation *falseOp, PatternRewriter &rewriter)
This function is invoke when we find a mux with true/false operations that have the same opcode.
static std::pair< size_t, size_t > getLowestBitAndHighestBitRequired(Operation *op, bool narrowTrailingBits, size_t originalOpWidth)
static bool tryFlatteningOperands(Operation *op, PatternRewriter &rewriter)
Flattens a single input in op if hasOneUse is true and it can be defined as an Op.
static bool isOpTriviallyRecursive(Operation *op)
Definition CombFolds.cpp:27
static bool canonicalizeIdempotentInputs(Op op, PatternRewriter &rewriter)
Canonicalize an idempotent operation op so that only one input of any kind occurs.
static bool applyCmpPredicate(ICmpPredicate predicate, const APInt &lhs, const APInt &rhs)
static void combineEqualityICmpWithKnownBitsAndConstant(ICmpOp cmpOp, const KnownBits &bitAnalysis, const APInt &rhsCst, PatternRewriter &rewriter)
Given an equality comparison with a constant value and some operand that has known bits,...
static bool hasSVAttributes(Operation *op)
Definition CombFolds.cpp:67
static LogicalResult extractConcatToConcatExtract(ExtractOp op, ConcatOp innerCat, PatternRewriter &rewriter)
static OpFoldResult foldMod(Op op, ArrayRef< Attribute > constants)
static size_t computeCommonPrefixLength(const Range &a, const Range &b)
static bool foldCommonMuxValue(MuxOp op, bool isTrueOperand, PatternRewriter &rewriter)
Fold things like mux(cond, x|y|z|a, a) -> (x|y|z)&replicate(cond)|a and mux(cond, a,...
static LogicalResult matchAndRewriteCompareConcat(ICmpOp op, Operation *lhs, Operation *rhs, PatternRewriter &rewriter)
Reduce the strength icmp(concat(...), concat(...)) by doing a element-wise comparison on common prefi...
static Value createGenericOp(Location loc, OperationName name, ArrayRef< Value > operands, OpBuilder &builder)
Create a new instance of a generic operation that only has value operands, and has a single result va...
Definition CombFolds.cpp:38
static TypedAttr getIntAttr(MLIRContext *ctx, Type t, const APInt &value)
static std::optional< APSInt > getConstant(Attribute operand)
Determine the value of a constant operand for the sake of constant folding.
create(low_bit, result_type, input=None)
Definition comb.py:187
create(elements)
Definition hw.py:483
create(array_value, low_index, ret_type)
Definition hw.py:466
create(data_type, value)
Definition hw.py:441
create(data_type, value)
Definition hw.py:433
Direction get(bool isOutput)
Returns an output direction if isOutput is true, otherwise returns an input direction.
Definition CalyxOps.cpp:55
void extractBits(OpBuilder &builder, Value val, SmallVectorImpl< Value > &bits)
Extract bits from a value.
Definition CombOps.cpp:78
bool foldMuxChainWithComparison(PatternRewriter &rewriter, MuxOp rootMux, bool isFalseSide, llvm::function_ref< MuxChainWithComparisonFoldingStyle(size_t indexWidth, size_t numEntries)> styleFn)
Mux chain folding that converts chains of muxes with index comparisons into array operations or balan...
Value createOrFoldNot(Location loc, Value value, OpBuilder &builder, bool twoState=false)
Create a `‘Not’' gate on a value.
Definition CombOps.cpp:66
MuxChainWithComparisonFoldingStyle
Enum for mux chain folding styles.
Definition CombOps.h:94
@ BalancedMuxTree
Definition CombOps.h:94
KnownBits computeKnownBits(Value value)
Compute "known bits" information about the specified value - the set of bits that are guaranteed to a...
Value constructMuxTree(OpBuilder &builder, Location loc, ArrayRef< Value > selectors, ArrayRef< Value > leafNodes, Value outOfBoundsValue)
Construct a mux tree for given leaf nodes.
Definition CombOps.cpp:105
uint64_t getWidth(Type t)
Definition ESIPasses.cpp:32
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.
Definition Naming.cpp:73
Definition comb.py:1