CIRCT 24.0.0git
Loading...
Searching...
No Matches
SeqOps.cpp
Go to the documentation of this file.
1//===- SeqOps.cpp - Implement the Seq 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//
9// This file implements sequential ops.
10//
11//===----------------------------------------------------------------------===//
12
18#include "mlir/Analysis/TopologicalSortUtils.h"
19#include "mlir/Dialect/Arith/IR/Arith.h"
20#include "mlir/IR/Builders.h"
21#include "mlir/IR/DialectImplementation.h"
22#include "mlir/IR/Matchers.h"
23#include "mlir/IR/PatternMatch.h"
24
26#include "llvm/ADT/SmallString.h"
27
28using namespace mlir;
29using namespace circt;
30using namespace seq;
31
32bool circt::seq::isValidIndexValues(Value hlmemHandle, ValueRange addresses) {
33 auto memType = cast<seq::HLMemType>(hlmemHandle.getType());
34 auto shape = memType.getShape();
35 if (shape.size() != addresses.size())
36 return false;
37
38 for (auto [dim, addr] : llvm::zip(shape, addresses)) {
39 auto addrType = dyn_cast<IntegerType>(addr.getType());
40 if (!addrType)
41 return false;
42 if (addrType.getIntOrFloatBitWidth() != llvm::Log2_64_Ceil(dim))
43 return false;
44 }
45 return true;
46}
47
48// If there was no name specified, check to see if there was a useful name
49// specified in the asm file.
50static void setNameFromResult(OpAsmParser &parser, OperationState &result) {
51 if (result.attributes.getNamed("name"))
52 return;
53 // If there is no explicit name attribute, get it from the SSA result name.
54 // If numeric, just use an empty name.
55 StringRef resultName = parser.getResultName(0).first;
56 if (!resultName.empty() && isdigit(resultName[0]))
57 resultName = "";
58 result.addAttribute("name", parser.getBuilder().getStringAttr(resultName));
59}
60
61static bool canElideName(OpAsmPrinter &p, Operation *op) {
62 if (!op->hasAttr("name"))
63 return true;
64
65 auto name = op->getAttrOfType<StringAttr>("name").getValue();
66 if (name.empty())
67 return true;
68
69 SmallString<32> resultNameStr;
70 llvm::raw_svector_ostream tmpStream(resultNameStr);
71 p.printOperand(op->getResult(0), tmpStream);
72 auto actualName = tmpStream.str().drop_front();
73 return actualName == name;
74}
75
76static ParseResult
77parseOptionalTypeMatch(OpAsmParser &parser, Type refType,
78 std::optional<OpAsmParser::UnresolvedOperand> operand,
79 Type &type) {
80 if (operand)
81 type = refType;
82 return success();
83}
84
85static void printOptionalTypeMatch(OpAsmPrinter &p, Operation *op, Type refType,
86 Value operand, Type type) {
87 // Nothing to do - this is strictly an implicit parsing helper.
88}
89
91 OpAsmParser &parser, Type refType,
92 std::optional<OpAsmParser::UnresolvedOperand> operand, Type &type) {
93 if (operand)
94 type = seq::ImmutableType::get(refType);
95 return success();
96}
97
98static void printOptionalImmutableTypeMatch(OpAsmPrinter &p, Operation *op,
99 Type refType, Value operand,
100 Type type) {
101 // Nothing to do - this is strictly an implicit parsing helper.
102}
103
104//===----------------------------------------------------------------------===//
105// ReadPortOp
106//===----------------------------------------------------------------------===//
107
108ParseResult ReadPortOp::parse(OpAsmParser &parser, OperationState &result) {
109 llvm::SMLoc loc = parser.getCurrentLocation();
110
111 OpAsmParser::UnresolvedOperand memOperand, rdenOperand;
112 bool hasRdEn = false;
113 llvm::SmallVector<OpAsmParser::UnresolvedOperand, 2> addressOperands;
114 seq::HLMemType memType;
115
116 if (parser.parseOperand(memOperand) ||
117 parser.parseOperandList(addressOperands, OpAsmParser::Delimiter::Square))
118 return failure();
119
120 if (succeeded(parser.parseOptionalKeyword("rden"))) {
121 if (failed(parser.parseOperand(rdenOperand)))
122 return failure();
123 hasRdEn = true;
124 }
125
126 if (parser.parseOptionalAttrDict(result.attributes) || parser.parseColon() ||
127 parser.parseType(memType))
128 return failure();
129
130 llvm::SmallVector<Type> operandTypes = memType.getAddressTypes();
131 operandTypes.insert(operandTypes.begin(), memType);
132
133 llvm::SmallVector<OpAsmParser::UnresolvedOperand> allOperands = {memOperand};
134 llvm::copy(addressOperands, std::back_inserter(allOperands));
135 if (hasRdEn) {
136 operandTypes.push_back(parser.getBuilder().getI1Type());
137 allOperands.push_back(rdenOperand);
138 }
139
140 if (parser.resolveOperands(allOperands, operandTypes, loc, result.operands))
141 return failure();
142
143 result.addTypes(memType.getElementType());
144
145 llvm::SmallVector<int32_t, 2> operandSizes;
146 operandSizes.push_back(1); // memory handle
147 operandSizes.push_back(addressOperands.size());
148 operandSizes.push_back(hasRdEn ? 1 : 0);
149 result.addAttribute("operandSegmentSizes",
150 parser.getBuilder().getDenseI32ArrayAttr(operandSizes));
151 return success();
152}
153
154void ReadPortOp::print(OpAsmPrinter &p) {
155 p << " " << getMemory() << "[" << getAddresses() << "]";
156 if (getRdEn())
157 p << " rden " << getRdEn();
158 p.printOptionalAttrDict((*this)->getAttrs(), {"operandSegmentSizes"});
159 p << " : " << getMemory().getType();
160}
161
162void ReadPortOp::getAsmResultNames(OpAsmSetValueNameFn setNameFn) {
163 auto memName = getMemory().getDefiningOp<seq::HLMemOp>().getName();
164 setNameFn(getReadData(), (memName + "_rdata").str());
165}
166
167void ReadPortOp::build(OpBuilder &builder, OperationState &result, Value memory,
168 ValueRange addresses, Value rdEn, unsigned latency) {
169 auto memType = cast<seq::HLMemType>(memory.getType());
170 ReadPortOp::build(builder, result, memType.getElementType(), memory,
171 addresses, rdEn, latency);
172}
173
174//===----------------------------------------------------------------------===//
175// WritePortOp
176//===----------------------------------------------------------------------===//
177
178ParseResult WritePortOp::parse(OpAsmParser &parser, OperationState &result) {
179 llvm::SMLoc loc = parser.getCurrentLocation();
180 OpAsmParser::UnresolvedOperand memOperand, dataOperand, wrenOperand;
181 llvm::SmallVector<OpAsmParser::UnresolvedOperand, 2> addressOperands;
182 seq::HLMemType memType;
183
184 if (parser.parseOperand(memOperand) ||
185 parser.parseOperandList(addressOperands,
186 OpAsmParser::Delimiter::Square) ||
187 parser.parseOperand(dataOperand) || parser.parseKeyword("wren") ||
188 parser.parseOperand(wrenOperand) ||
189 parser.parseOptionalAttrDict(result.attributes) || parser.parseColon() ||
190 parser.parseType(memType))
191 return failure();
192
193 llvm::SmallVector<Type> operandTypes = memType.getAddressTypes();
194 operandTypes.insert(operandTypes.begin(), memType);
195 operandTypes.push_back(memType.getElementType());
196 operandTypes.push_back(parser.getBuilder().getI1Type());
197
198 llvm::SmallVector<OpAsmParser::UnresolvedOperand, 2> allOperands(
199 addressOperands);
200 allOperands.insert(allOperands.begin(), memOperand);
201 allOperands.push_back(dataOperand);
202 allOperands.push_back(wrenOperand);
203
204 if (parser.resolveOperands(allOperands, operandTypes, loc, result.operands))
205 return failure();
206
207 return success();
208}
209
210void WritePortOp::print(OpAsmPrinter &p) {
211 p << " " << getMemory() << "[" << getAddresses() << "] " << getInData()
212 << " wren " << getWrEn();
213 p.printOptionalAttrDict((*this)->getAttrs());
214 p << " : " << getMemory().getType();
215}
216
217//===----------------------------------------------------------------------===//
218// HLMemOp
219//===----------------------------------------------------------------------===//
220
221void HLMemOp::getAsmResultNames(OpAsmSetValueNameFn setNameFn) {
222 setNameFn(getHandle(), getName());
223}
224
225void HLMemOp::build(OpBuilder &builder, OperationState &result, Value clk,
226 Value rst, StringRef name, llvm::ArrayRef<int64_t> shape,
227 Type elementType) {
228 HLMemType t = HLMemType::get(builder.getContext(), shape, elementType);
229 HLMemOp::build(builder, result, t, clk, rst, name);
230}
231
232//===----------------------------------------------------------------------===//
233// FIFOOp
234//===----------------------------------------------------------------------===//
235
236// Flag threshold custom directive
237static ParseResult parseFIFOFlagThreshold(OpAsmParser &parser,
238 IntegerAttr &threshold,
239 Type &outputFlagType,
240 StringRef directive) {
241 // look for an optional "almost_full $threshold" group.
242 if (succeeded(parser.parseOptionalKeyword(directive))) {
243 int64_t thresholdValue;
244 if (succeeded(parser.parseInteger(thresholdValue))) {
245 threshold = parser.getBuilder().getI64IntegerAttr(thresholdValue);
246 outputFlagType = parser.getBuilder().getI1Type();
247 return success();
248 }
249 return parser.emitError(parser.getNameLoc(),
250 "expected integer value after " + directive +
251 " directive");
252 }
253 return success();
254}
255
256ParseResult parseFIFOAFThreshold(OpAsmParser &parser, IntegerAttr &threshold,
257 Type &outputFlagType) {
258 return parseFIFOFlagThreshold(parser, threshold, outputFlagType,
259 "almost_full");
260}
261
262ParseResult parseFIFOAEThreshold(OpAsmParser &parser, IntegerAttr &threshold,
263 Type &outputFlagType) {
264 return parseFIFOFlagThreshold(parser, threshold, outputFlagType,
265 "almost_empty");
266}
267
268void printFIFOAFThreshold(OpAsmPrinter &p, Operation *op, IntegerAttr threshold,
269 Type outputFlagType) {
270 if (threshold)
271 p << "almost_full"
272 << " " << threshold.getInt();
273}
274
275void printFIFOAEThreshold(OpAsmPrinter &p, Operation *op, IntegerAttr threshold,
276 Type outputFlagType) {
277 if (threshold)
278 p << "almost_empty"
279 << " " << threshold.getInt();
280}
281
282void FIFOOp::getAsmResultNames(OpAsmSetValueNameFn setNameFn) {
283 setNameFn(getOutput(), "out");
284 setNameFn(getEmpty(), "empty");
285 setNameFn(getFull(), "full");
286 if (auto ae = getAlmostEmpty())
287 setNameFn(ae, "almostEmpty");
288 if (auto af = getAlmostFull())
289 setNameFn(af, "almostFull");
290}
291
292LogicalResult FIFOOp::verify() {
293 auto aet = getAlmostEmptyThreshold();
294 auto aft = getAlmostFullThreshold();
295 size_t depth = getDepth();
296 if (aft.has_value() && aft.value() > depth)
297 return emitOpError("almost full threshold must be <= FIFO depth");
298
299 if (aet.has_value() && aet.value() > depth)
300 return emitOpError("almost empty threshold must be <= FIFO depth");
301
302 return success();
303}
304
305//===----------------------------------------------------------------------===//
306// CompRegOp
307//===----------------------------------------------------------------------===//
308
309/// Suggest a name for each result value based on the saved result names
310/// attribute.
311void CompRegOp::getAsmResultNames(OpAsmSetValueNameFn setNameFn) {
312 if (auto name = getName())
313 setNameFn(getResult(), *name);
314}
315
316template <typename TOp>
317LogicalResult verifyResets(TOp op) {
318 if ((op.getReset() == nullptr) ^ (op.getResetValue() == nullptr))
319 return op->emitOpError(
320 "either reset and resetValue or neither must be specified");
321 bool hasReset = op.getReset() != nullptr;
322 if (hasReset && op.getResetValue().getType() != op.getInput().getType())
323 return op->emitOpError("reset value must be the same type as the input");
324
325 return success();
326}
327
328std::optional<size_t> CompRegOp::getTargetResultIndex() { return 0; }
329
330LogicalResult CompRegOp::verify() { return verifyResets(*this); }
331
332//===----------------------------------------------------------------------===//
333// CompRegClockEnabledOp
334//===----------------------------------------------------------------------===//
335
336/// Suggest a name for each result value based on the saved result names
337/// attribute.
338void CompRegClockEnabledOp::getAsmResultNames(OpAsmSetValueNameFn setNameFn) {
339 if (auto name = getName())
340 setNameFn(getResult(), *name);
341}
342
343std::optional<size_t> CompRegClockEnabledOp::getTargetResultIndex() {
344 return 0;
345}
346
347LogicalResult CompRegClockEnabledOp::verify() { return verifyResets(*this); }
348
349LogicalResult CompRegClockEnabledOp::canonicalize(CompRegClockEnabledOp op,
350 PatternRewriter &rewriter) {
351 // reg(comb.mux(en, d, ?), en) -> reg(d, en)
352 // reg(arith.select(en, d, ?), en) -> reg(d, en)
353 auto *inputOp = op.getInput().getDefiningOp();
354 if (isa_and_nonnull<comb::MuxOp, arith::SelectOp>(inputOp) &&
355 inputOp->getOperand(0) == op.getClockEnable()) {
356 rewriter.modifyOpInPlace(
357 op, [&] { op.getInputMutable().assign(inputOp->getOperand(1)); });
358 return success();
359 }
360
361 // Match constant clock enable values.
362 APInt en;
363 if (mlir::matchPattern(op.getClockEnable(), mlir::m_ConstantInt(&en))) {
364 if (en.isAllOnes()) {
365 rewriter.replaceOpWithNewOp<seq::CompRegOp>(
366 op, op.getInput(), op.getClk(), op.getNameAttr(), op.getReset(),
367 op.getResetValue(), op.getInitialValue(), op.getInnerSymAttr());
368 return success();
369 }
370 }
371
372 return failure();
373}
374
375//===----------------------------------------------------------------------===//
376// ShiftRegOp
377//===----------------------------------------------------------------------===//
378
379void ShiftRegOp::getAsmResultNames(OpAsmSetValueNameFn setNameFn) {
380 // If the wire has an optional 'name' attribute, use it.
381 if (auto name = getName())
382 setNameFn(getResult(), *name);
383}
384
385std::optional<size_t> ShiftRegOp::getTargetResultIndex() { return 0; }
386
387LogicalResult ShiftRegOp::verify() {
388 if (failed(verifyResets(*this)))
389 return failure();
390 return success();
391}
392
393//===----------------------------------------------------------------------===//
394// FirRegOp
395//===----------------------------------------------------------------------===//
396
397void FirRegOp::build(OpBuilder &builder, OperationState &result, Value input,
398 Value clk, StringAttr name, hw::InnerSymAttr innerSym,
399 Attribute preset) {
400
401 OpBuilder::InsertionGuard guard(builder);
402
403 result.addOperands(input);
404 result.addOperands(clk);
405
406 result.addAttribute(getNameAttrName(result.name), name);
407
408 if (innerSym)
409 result.addAttribute(getInnerSymAttrName(result.name), innerSym);
410
411 if (preset)
412 result.addAttribute(getPresetAttrName(result.name), preset);
413
414 result.addTypes(input.getType());
415}
416
417void FirRegOp::build(OpBuilder &builder, OperationState &result, Value input,
418 Value clk, StringAttr name, Value reset, Value resetValue,
419 hw::InnerSymAttr innerSym, bool isAsync,
420 Attribute preset) {
421
422 OpBuilder::InsertionGuard guard(builder);
423
424 result.addOperands(input);
425 result.addOperands(clk);
426 result.addOperands(reset);
427 result.addOperands(resetValue);
428
429 result.addAttribute(getNameAttrName(result.name), name);
430 if (isAsync)
431 result.addAttribute(getIsAsyncAttrName(result.name), builder.getUnitAttr());
432
433 if (innerSym)
434 result.addAttribute(getInnerSymAttrName(result.name), innerSym);
435
436 if (preset)
437 result.addAttribute(getPresetAttrName(result.name), preset);
438
439 result.addTypes(input.getType());
440}
441
442ParseResult FirRegOp::parse(OpAsmParser &parser, OperationState &result) {
443 auto &builder = parser.getBuilder();
444 llvm::SMLoc loc = parser.getCurrentLocation();
445
446 using Op = OpAsmParser::UnresolvedOperand;
447
448 Op next, clk;
449 if (parser.parseOperand(next) || parser.parseKeyword("clock") ||
450 parser.parseOperand(clk))
451 return failure();
452
453 if (succeeded(parser.parseOptionalKeyword("sym"))) {
454 hw::InnerSymAttr innerSym;
455 if (parser.parseCustomAttributeWithFallback(innerSym, /*type=*/nullptr,
456 "inner_sym", result.attributes))
457 return failure();
458 }
459
460 // Parse reset [sync|async] %reset, %value
461 std::optional<std::pair<Op, Op>> resetAndValue;
462 if (succeeded(parser.parseOptionalKeyword("reset"))) {
463 bool isAsync;
464 if (succeeded(parser.parseOptionalKeyword("async")))
465 isAsync = true;
466 else if (succeeded(parser.parseOptionalKeyword("sync")))
467 isAsync = false;
468 else
469 return parser.emitError(loc, "invalid reset, expected 'sync' or 'async'");
470 if (isAsync)
471 result.attributes.append("isAsync", builder.getUnitAttr());
472
473 resetAndValue = {{}, {}};
474 if (parser.parseOperand(resetAndValue->first) || parser.parseComma() ||
475 parser.parseOperand(resetAndValue->second))
476 return failure();
477 }
478
479 std::optional<APInt> presetValue;
480 llvm::SMLoc presetValueLoc;
481 if (succeeded(parser.parseOptionalKeyword("preset"))) {
482 presetValueLoc = parser.getCurrentLocation();
483 OptionalParseResult presetIntResult =
484 parser.parseOptionalInteger(presetValue.emplace());
485 if (!presetIntResult.has_value() || failed(*presetIntResult))
486 return parser.emitError(presetValueLoc, "expected integer value");
487 if (presetValue->isNegative())
488 return parser.emitError(presetValueLoc,
489 "preset value must not be negative");
490 }
491
492 Type ty;
493 if (parser.parseOptionalAttrDict(result.attributes) || parser.parseColon() ||
494 parser.parseType(ty))
495 return failure();
496 result.addTypes({ty});
497
498 if (presetValue) {
499 uint64_t width = 0;
500 if (hw::type_isa<seq::ClockType>(ty)) {
501 width = 1;
502 } else {
503 int64_t maybeWidth = hw::getBitWidth(ty);
504 if (maybeWidth < 0)
505 return parser.emitError(presetValueLoc,
506 "cannot preset register of unknown width");
507 width = maybeWidth;
508 }
509
510 APInt presetResult = presetValue->sextOrTrunc(width);
511 if (presetResult.zextOrTrunc(presetValue->getBitWidth()) != *presetValue)
512 return parser.emitError(presetValueLoc, "preset value too large");
513
514 auto builder = parser.getBuilder();
515 auto presetTy = builder.getIntegerType(width);
516 auto resultAttr = builder.getIntegerAttr(presetTy, presetResult);
517 result.addAttribute("preset", resultAttr);
518 }
519
520 setNameFromResult(parser, result);
521
522 if (parser.resolveOperand(next, ty, result.operands))
523 return failure();
524
525 Type clkTy = ClockType::get(result.getContext());
526 if (parser.resolveOperand(clk, clkTy, result.operands))
527 return failure();
528
529 if (resetAndValue) {
530 Type i1 = IntegerType::get(result.getContext(), 1);
531 if (parser.resolveOperand(resetAndValue->first, i1, result.operands) ||
532 parser.resolveOperand(resetAndValue->second, ty, result.operands))
533 return failure();
534 }
535
536 return success();
537}
538
539void FirRegOp::print(::mlir::OpAsmPrinter &p) {
540 SmallVector<StringRef> elidedAttrs = {
541 getInnerSymAttrName(), getIsAsyncAttrName(), getPresetAttrName()};
542
543 p << ' ' << getNext() << " clock " << getClk();
544
545 if (auto sym = getInnerSymAttr()) {
546 p << " sym ";
547 sym.print(p);
548 }
549
550 if (hasReset()) {
551 p << " reset " << (getIsAsync() ? "async" : "sync") << ' ';
552 p << getReset() << ", " << getResetValue();
553 }
554
555 if (auto preset = getPresetAttr()) {
556 p << " preset ";
557
558 // Don't emit negative integers to match the parsing logic.
559 const auto &presetVal = preset.getValue();
560 if (presetVal.isNonNegative())
561 p << presetVal;
562 else
563 p << presetVal.zext(presetVal.getBitWidth() + 1);
564 }
565
566 if (canElideName(p, *this))
567 elidedAttrs.push_back("name");
568
569 p.printOptionalAttrDict((*this)->getAttrs(), elidedAttrs);
570 p << " : " << getNext().getType();
571}
572
573/// Verifier for the FIR register op.
574LogicalResult FirRegOp::verify() {
575 if (getReset() || getResetValue() || getIsAsync()) {
576 if (!getReset() || !getResetValue())
577 return emitOpError("must specify reset and reset value");
578 } else {
579 if (getIsAsync())
580 return emitOpError("register with no reset cannot be async");
581 }
582 if (auto preset = getPresetAttr()) {
583 int64_t presetWidth = hw::getBitWidth(preset.getType());
584 int64_t width = hw::getBitWidth(getType());
585 if (preset.getType() != getType() && presetWidth != width)
586 return emitOpError("preset type width must match register type");
587 }
588 return success();
589}
590
591/// Suggest a name for each result value based on the saved result names
592/// attribute.
593void FirRegOp::getAsmResultNames(OpAsmSetValueNameFn setNameFn) {
594 // If the register has an optional 'name' attribute, use it.
595 if (!getName().empty())
596 setNameFn(getResult(), getName());
597}
598
599std::optional<size_t> FirRegOp::getTargetResultIndex() { return 0; }
600
601LogicalResult FirRegOp::canonicalize(FirRegOp op, PatternRewriter &rewriter) {
602
603 // If the register has a constant zero reset, drop the reset and reset value
604 // altogether (And preserve the PresetAttr).
605 if (auto reset = op.getReset()) {
606 if (auto constOp = reset.getDefiningOp<hw::ConstantOp>()) {
607 if (constOp.getValue().isZero()) {
608 auto newOp = FirRegOp::create(rewriter, op.getLoc(), op.getNext(),
609 op.getClk(), op.getNameAttr(),
610 op.getInnerSymAttr(), op.getPresetAttr());
611 newOp->setDiscardableAttrs(op->getDiscardableAttrDictionary());
612 rewriter.replaceOp(op, newOp);
613 return success();
614 }
615 }
616 }
617
618 // If the register has a symbol, we can't optimize it away.
619 if (op.getInnerSymAttr())
620 return failure();
621
622 // Replace a register with a trivial feedback or constant clock with a
623 // constant zero.
624 // TODO: Once HW aggregate constant values are supported, move this
625 // canonicalization to the folder.
626 auto isConstant = [&]() -> bool {
627 if (op.getNext() == op.getResult())
628 return true;
629 if (auto clk = op.getClk().getDefiningOp<seq::ToClockOp>())
630 return clk.getInput().getDefiningOp<hw::ConstantOp>();
631 return false;
632 };
633
634 // Preset can block canonicalization only if it is non-zero.
635 bool replaceWithConstZero = true;
636 if (auto preset = op.getPresetAttr())
637 if (!preset.getValue().isZero())
638 replaceWithConstZero = false;
639
640 if (isConstant() && !op.getResetValue() && replaceWithConstZero) {
641 if (isa<seq::ClockType>(op.getType())) {
642 rewriter.replaceOpWithNewOp<seq::ConstClockOp>(
643 op, seq::ClockConstAttr::get(rewriter.getContext(), ClockConst::Low));
644 } else {
645 auto constant = hw::ConstantOp::create(
646 rewriter, op.getLoc(), APInt::getZero(hw::getBitWidth(op.getType())));
647 rewriter.replaceOpWithNewOp<hw::BitcastOp>(op, op.getType(), constant);
648 }
649 return success();
650 }
651
652 // Canonicalize registers with mux-based constant drivers.
653 // This pattern matches registers where the next value is a mux with one
654 // branch being the register itself (creating a self-loop) and the other
655 // branch being a constant. In such cases, the register effectively holds a
656 // constant value and can be replaced with that constant.
657 if (auto nextMux = op.getNext().getDefiningOp<comb::MuxOp>()) {
658 // Reject optimization if register has preset attribute (for simplicity)
659 if (op.getPresetAttr())
660 return failure();
661
662 Attribute value;
663 Value replacedValue;
664
665 // Check if true branch is self-loop and false branch is constant
666 if (nextMux.getTrueValue() == op.getResult() &&
667 matchPattern(nextMux.getFalseValue(), m_Constant(&value))) {
668 replacedValue = nextMux.getFalseValue();
669 }
670 // Check if false branch is self-loop and true branch is constant
671 else if (nextMux.getFalseValue() == op.getResult() &&
672 matchPattern(nextMux.getTrueValue(), m_Constant(&value))) {
673 replacedValue = nextMux.getTrueValue();
674 }
675
676 if (!replacedValue)
677 return failure();
678
679 // Verify reset value compatibility: if register has reset, it must be
680 // a constant that matches the mux constant
681 if (op.getResetValue()) {
682 Attribute resetConst;
683 if (matchPattern(op.getResetValue(), m_Constant(&resetConst))) {
684 if (resetConst != value)
685 return failure();
686 } else {
687 // Non-constant reset value prevents optimization
688 return failure();
689 }
690 }
691
692 assert(replacedValue);
693 // Apply the optimization if all conditions are met
694 rewriter.replaceOp(op, replacedValue);
695 return success();
696 }
697
698 // For reset-less 1d array registers, replace an uninitialized element with
699 // constant zero. For example, let `r` be a 2xi1 register and its next value
700 // be `{foo, r[0]}`. `r[0]` is connected to itself so will never be
701 // initialized. If we don't enable aggregate preservation, `r_0` is replaced
702 // with `0`. Hence this canonicalization replaces 0th element of the next
703 // value with zero to match the behaviour.
704 if (!op.getReset() && !op.getPresetAttr()) {
705 if (auto arrayCreate = op.getNext().getDefiningOp<hw::ArrayCreateOp>()) {
706 // For now only support 1d arrays.
707 // TODO: Support nested arrays and bundles.
708 if (isa<IntegerType>(
709 hw::type_cast<hw::ArrayType>(op.getResult().getType())
710 .getElementType())) {
711 SmallVector<Value> nextOperands;
712 bool changed = false;
713 for (const auto &[i, value] :
714 llvm::enumerate(arrayCreate.getOperands())) {
715 auto index = arrayCreate.getOperands().size() - i - 1;
716 APInt elementIndex;
717 // Check that the corresponding operand is op's element.
718 if (auto arrayGet = value.getDefiningOp<hw::ArrayGetOp>())
719 if (arrayGet.getInput() == op.getResult() &&
720 matchPattern(arrayGet.getIndex(),
721 m_ConstantInt(&elementIndex)) &&
722 elementIndex == index) {
723 nextOperands.push_back(hw::ConstantOp::create(
724 rewriter, op.getLoc(),
725 APInt::getZero(hw::getBitWidth(arrayGet.getType()))));
726 changed = true;
727 continue;
728 }
729 nextOperands.push_back(value);
730 }
731 // If one of the operands is self loop, update the next value.
732 if (changed) {
733 auto newNextVal = hw::ArrayCreateOp::create(
734 rewriter, arrayCreate.getLoc(), nextOperands);
735 if (arrayCreate->hasOneUse()) {
736 // If the original next value has a single use, we can replace the
737 // value directly.
738 rewriter.replaceOp(arrayCreate, newNextVal);
739 } else {
740 // Otherwise, update the register's next operand in place.
741 rewriter.modifyOpInPlace(
742 op, [&] { op.getNextMutable().assign(newNextVal); });
743 }
744
745 return success();
746 }
747 }
748 }
749 }
750
751 return failure();
752}
753
754OpFoldResult FirRegOp::fold(FoldAdaptor adaptor) {
755 // If the register has a symbol or preset value, we can't optimize it away.
756 // TODO: Handle a preset value.
757 if (getInnerSymAttr())
758 return {};
759
760 auto presetAttr = getPresetAttr();
761
762 // If the register is held in permanent reset, replace it with its reset
763 // value. This works trivially if the reset is asynchronous and therefore
764 // level-sensitive, in which case it will always immediately assume the reset
765 // value in silicon. If it is synchronous, the register value is undefined
766 // until the first clock edge at which point it becomes the reset value, in
767 // which case we simply define the initial value to already be the reset
768 // value. Works only if no preset.
769 if (!presetAttr)
770 if (auto reset = getReset())
771 if (auto constOp = reset.getDefiningOp<hw::ConstantOp>())
772 if (constOp.getValue().isOne())
773 return getResetValue();
774
775 // If the register's next value is trivially it's current value, or the
776 // register is never clocked, we can replace the register with a constant
777 // value.
778 bool isTrivialFeedback = (getNext() == getResult());
779 bool isNeverClocked =
780 adaptor.getClk() != nullptr; // clock operand is constant
781 if (!isTrivialFeedback && !isNeverClocked)
782 return {};
783
784 // If the register has a const reset value, and no preset, we can replace it
785 // with the const reset. We cannot replace it with a non-constant reset value.
786 if (auto resetValue = getResetValue()) {
787 if (auto *op = resetValue.getDefiningOp()) {
788 if (op->hasTrait<OpTrait::ConstantLike>() && !presetAttr)
789 return resetValue;
790 if (auto constOp = dyn_cast<hw::ConstantOp>(op))
791 if (presetAttr.getValue() == constOp.getValue())
792 return resetValue;
793 }
794 return {};
795 }
796
797 // Otherwise we want to replace the register with a constant 0. For now this
798 // only works with integer types.
799 auto intType = dyn_cast<IntegerType>(getType());
800 if (!intType)
801 return {};
802 // If preset present, then replace with preset.
803 if (presetAttr)
804 return presetAttr;
805 return IntegerAttr::get(intType, 0);
806}
807
808//===----------------------------------------------------------------------===//
809// ClockGateOp
810//===----------------------------------------------------------------------===//
811
812OpFoldResult ClockGateOp::fold(FoldAdaptor adaptor) {
813 // Forward the clock if one of the enables is always true.
814 if (isConstantOne(adaptor.getEnable()) ||
815 isConstantOne(adaptor.getTestEnable()))
816 return getInput();
817
818 // Fold to a constant zero clock if the enables are always false.
819 if (isConstantZero(adaptor.getEnable()) &&
820 (!getTestEnable() || isConstantZero(adaptor.getTestEnable())))
821 return ClockConstAttr::get(getContext(), ClockConst::Low);
822
823 // Forward constant zero clocks.
824 if (auto clockAttr = dyn_cast_or_null<ClockConstAttr>(adaptor.getInput()))
825 if (clockAttr.getValue() == ClockConst::Low)
826 return ClockConstAttr::get(getContext(), ClockConst::Low);
827
828 // Transitive clock gating - eliminate clock gates that are driven by an
829 // identical enable signal somewhere higher in the clock gate hierarchy.
830 auto clockGateInputOp = getInput().getDefiningOp<ClockGateOp>();
831 while (clockGateInputOp) {
832 if (clockGateInputOp.getEnable() == getEnable() &&
833 clockGateInputOp.getTestEnable() == getTestEnable())
834 return getInput();
835 clockGateInputOp = clockGateInputOp.getInput().getDefiningOp<ClockGateOp>();
836 }
837
838 return {};
839}
840
841LogicalResult ClockGateOp::canonicalize(ClockGateOp op,
842 PatternRewriter &rewriter) {
843 // Remove constant false test enable.
844 if (auto testEnable = op.getTestEnable()) {
845 if (auto constOp = testEnable.getDefiningOp<hw::ConstantOp>()) {
846 if (constOp.getValue().isZero()) {
847 rewriter.modifyOpInPlace(op,
848 [&] { op.getTestEnableMutable().clear(); });
849 return success();
850 }
851 }
852 }
853
854 return failure();
855}
856
857std::optional<size_t> ClockGateOp::getTargetResultIndex() {
858 return std::nullopt;
859}
860
861//===----------------------------------------------------------------------===//
862// ClockMuxOp
863//===----------------------------------------------------------------------===//
864
865OpFoldResult ClockMuxOp::fold(FoldAdaptor adaptor) {
866 if (isConstantOne(adaptor.getCond()))
867 return getTrueClock();
868 if (isConstantZero(adaptor.getCond()))
869 return getFalseClock();
870 return {};
871}
872
873//===----------------------------------------------------------------------===//
874// ClockDividerOp
875//===----------------------------------------------------------------------===//
876
877LogicalResult ClockDividerOp::canonicalize(ClockDividerOp op,
878 PatternRewriter &rewriter) {
879 // clock_div(clock_div(clock, a), b) -> clock_div(clock, a + b)
880 if (auto innerDiv = op.getInput().getDefiningOp<ClockDividerOp>()) {
881 auto outerPow2 = op.getPow2();
882 auto innerPow2 = innerDiv.getPow2();
883 auto combinedPow2 = outerPow2 + innerPow2;
884
885 rewriter.replaceOpWithNewOp<ClockDividerOp>(op, innerDiv.getInput(),
886 combinedPow2);
887 return success();
888 }
889 return failure();
890}
891
892//===----------------------------------------------------------------------===//
893// FirMemOp
894//===----------------------------------------------------------------------===//
895
896LogicalResult FirMemOp::canonicalize(FirMemOp op, PatternRewriter &rewriter) {
897 // Do not change memories if symbols point to them.
898 if (op.getInnerSymAttr())
899 return failure();
900
901 bool readOnly = true, writeOnly = true;
902
903 // If the memory has no read ports, erase it.
904 for (auto *user : op->getUsers()) {
905 if (isa<FirMemReadOp, FirMemReadWriteOp>(user)) {
906 writeOnly = false;
907 }
908 if (isa<FirMemWriteOp, FirMemReadWriteOp>(user)) {
909 readOnly = false;
910 }
911 assert((isa<FirMemReadOp, FirMemWriteOp, FirMemReadWriteOp>(user)) &&
912 "invalid seq.firmem user");
913 }
914 if (writeOnly) {
915 for (auto *user : llvm::make_early_inc_range(op->getUsers()))
916 rewriter.eraseOp(user);
917
918 rewriter.eraseOp(op);
919 return success();
920 }
921
922 if (readOnly && !op.getInit()) {
923 // Replace all read ports with a constant 0.
924 for (auto *user : llvm::make_early_inc_range(op->getUsers())) {
925 auto readOp = cast<FirMemReadOp>(user);
926 Value zero = hw::ConstantOp::create(
927 rewriter, readOp.getLoc(),
928 APInt::getZero(hw::getBitWidth(readOp.getType())));
929 if (readOp.getType() != zero.getType())
930 zero = hw::BitcastOp::create(rewriter, readOp.getLoc(),
931 readOp.getType(), zero);
932 rewriter.replaceOp(readOp, zero);
933 }
934 rewriter.eraseOp(op);
935 return success();
936 }
937 return failure();
938}
939
940void FirMemOp::getAsmResultNames(OpAsmSetValueNameFn setNameFn) {
941 auto nameAttr = (*this)->getAttrOfType<StringAttr>("name");
942 if (!nameAttr.getValue().empty())
943 setNameFn(getResult(), nameAttr.getValue());
944}
945
946std::optional<size_t> FirMemOp::getTargetResultIndex() { return 0; }
947
948template <class Op>
949static LogicalResult verifyFirMemMask(Op op) {
950 if (auto mask = op.getMask()) {
951 auto memType = op.getMemory().getType();
952 if (!memType.getMaskWidth())
953 return op.emitOpError("has mask operand but memory type '")
954 << memType << "' has no mask";
955 auto expected = IntegerType::get(op.getContext(), *memType.getMaskWidth());
956 if (mask.getType() != expected)
957 return op.emitOpError("has mask operand of type '")
958 << mask.getType() << "', but memory type requires '" << expected
959 << "'";
960 }
961 return success();
962}
963
964LogicalResult FirMemWriteOp::verify() { return verifyFirMemMask(*this); }
965LogicalResult FirMemReadWriteOp::verify() { return verifyFirMemMask(*this); }
966
967static bool isConstClock(Value value) {
968 if (!value)
969 return false;
970 return value.getDefiningOp<seq::ConstClockOp>();
971}
972
973static bool isConstZero(Value value) {
974 if (value)
975 if (auto constOp = value.getDefiningOp<hw::ConstantOp>())
976 return constOp.getValue().isZero();
977 return false;
978}
979
980static bool isConstAllOnes(Value value) {
981 if (value)
982 if (auto constOp = value.getDefiningOp<hw::ConstantOp>())
983 return constOp.getValue().isAllOnes();
984 return false;
985}
986
987LogicalResult FirMemReadOp::canonicalize(FirMemReadOp op,
988 PatternRewriter &rewriter) {
989 // Remove the enable if it is constant true.
990 if (isConstAllOnes(op.getEnable())) {
991 rewriter.modifyOpInPlace(op, [&] { op.getEnableMutable().erase(0); });
992 return success();
993 }
994 return failure();
995}
996
997LogicalResult FirMemWriteOp::canonicalize(FirMemWriteOp op,
998 PatternRewriter &rewriter) {
999 // Remove the write port if it is trivially dead.
1000 if (isConstZero(op.getEnable()) || isConstZero(op.getMask()) ||
1001 isConstClock(op.getClk())) {
1002 auto memOp = op.getMemory().getDefiningOp<FirMemOp>();
1003 if (memOp.getInnerSymAttr())
1004 return failure();
1005 rewriter.eraseOp(op);
1006 return success();
1007 }
1008 bool anyChanges = false;
1009
1010 // Remove the enable if it is constant true.
1011 if (auto enable = op.getEnable(); isConstAllOnes(enable)) {
1012 rewriter.modifyOpInPlace(op, [&] { op.getEnableMutable().erase(0); });
1013 anyChanges = true;
1014 }
1015
1016 // Remove the mask if it is all ones.
1017 if (auto mask = op.getMask(); isConstAllOnes(mask)) {
1018 rewriter.modifyOpInPlace(op, [&] { op.getMaskMutable().erase(0); });
1019 anyChanges = true;
1020 }
1021
1022 return success(anyChanges);
1023}
1024
1025LogicalResult FirMemReadWriteOp::canonicalize(FirMemReadWriteOp op,
1026 PatternRewriter &rewriter) {
1027 // Replace the read-write port with a read port if the write behavior is
1028 // trivially disabled.
1029 if (isConstZero(op.getEnable()) || isConstZero(op.getMask()) ||
1030 isConstClock(op.getClk()) || isConstZero(op.getMode())) {
1031 auto opAttrs = op->getAttrs();
1032 auto opAttrNames = op.getAttributeNames();
1033 auto newOp = rewriter.replaceOpWithNewOp<FirMemReadOp>(
1034 op, op.getMemory(), op.getAddress(), op.getClk(), op.getEnable());
1035 for (auto namedAttr : opAttrs)
1036 if (!llvm::is_contained(opAttrNames, namedAttr.getName()))
1037 newOp->setAttr(namedAttr.getName(), namedAttr.getValue());
1038 return success();
1039 }
1040 bool anyChanges = false;
1041
1042 // Remove the enable if it is constant true.
1043 if (auto enable = op.getEnable(); isConstAllOnes(enable)) {
1044 rewriter.modifyOpInPlace(op, [&] { op.getEnableMutable().erase(0); });
1045 anyChanges = true;
1046 }
1047
1048 // Remove the mask if it is all ones.
1049 if (auto mask = op.getMask(); isConstAllOnes(mask)) {
1050 rewriter.modifyOpInPlace(op, [&] { op.getMaskMutable().erase(0); });
1051 anyChanges = true;
1052 }
1053
1054 return success(anyChanges);
1055}
1056
1057//===----------------------------------------------------------------------===//
1058// ConstClockOp
1059//===----------------------------------------------------------------------===//
1060
1061OpFoldResult ConstClockOp::fold(FoldAdaptor adaptor) {
1062 return ClockConstAttr::get(getContext(), getValue());
1063}
1064
1065//===----------------------------------------------------------------------===//
1066// ToClockOp/FromClockOp
1067//===----------------------------------------------------------------------===//
1068
1069LogicalResult ToClockOp::canonicalize(ToClockOp op, PatternRewriter &rewriter) {
1070 if (auto fromClock = op.getInput().getDefiningOp<FromClockOp>()) {
1071 rewriter.replaceOp(op, fromClock.getInput());
1072 return success();
1073 }
1074 return failure();
1075}
1076
1077OpFoldResult ToClockOp::fold(FoldAdaptor adaptor) {
1078 if (auto fromClock = getInput().getDefiningOp<FromClockOp>())
1079 return fromClock.getInput();
1080 if (auto intAttr = dyn_cast_or_null<IntegerAttr>(adaptor.getInput())) {
1081 auto value =
1082 intAttr.getValue().isZero() ? ClockConst::Low : ClockConst::High;
1083 return ClockConstAttr::get(getContext(), value);
1084 }
1085 return {};
1086}
1087
1088LogicalResult FromClockOp::canonicalize(FromClockOp op,
1089 PatternRewriter &rewriter) {
1090 if (auto toClock = op.getInput().getDefiningOp<ToClockOp>()) {
1091 rewriter.replaceOp(op, toClock.getInput());
1092 return success();
1093 }
1094 return failure();
1095}
1096
1097OpFoldResult FromClockOp::fold(FoldAdaptor adaptor) {
1098 if (auto toClock = getInput().getDefiningOp<ToClockOp>())
1099 return toClock.getInput();
1100 if (auto clockAttr = dyn_cast_or_null<ClockConstAttr>(adaptor.getInput())) {
1101 auto ty = IntegerType::get(getContext(), 1);
1102 return IntegerAttr::get(ty, clockAttr.getValue() == ClockConst::High);
1103 }
1104 return {};
1105}
1106
1107//===----------------------------------------------------------------------===//
1108// ClockInverterOp
1109//===----------------------------------------------------------------------===//
1110
1111OpFoldResult ClockInverterOp::fold(FoldAdaptor adaptor) {
1112 if (auto chainedInv = getInput().getDefiningOp<ClockInverterOp>())
1113 return chainedInv.getInput();
1114 if (auto clockAttr = dyn_cast_or_null<ClockConstAttr>(adaptor.getInput())) {
1115 auto clockIn = clockAttr.getValue() == ClockConst::High;
1116 return ClockConstAttr::get(getContext(),
1117 clockIn ? ClockConst::Low : ClockConst::High);
1118 }
1119 return {};
1120}
1121
1122//===----------------------------------------------------------------------===//
1123// FIR memory helper
1124//===----------------------------------------------------------------------===//
1125
1126FirMemory::FirMemory(hw::HWModuleGeneratedOp op) {
1127 depth = op->getAttrOfType<IntegerAttr>("depth").getInt();
1128 numReadPorts = op->getAttrOfType<IntegerAttr>("numReadPorts").getUInt();
1129 numWritePorts = op->getAttrOfType<IntegerAttr>("numWritePorts").getUInt();
1131 op->getAttrOfType<IntegerAttr>("numReadWritePorts").getUInt();
1132 readLatency = op->getAttrOfType<IntegerAttr>("readLatency").getUInt();
1133 writeLatency = op->getAttrOfType<IntegerAttr>("writeLatency").getUInt();
1134 dataWidth = op->getAttrOfType<IntegerAttr>("width").getUInt();
1135 if (op->hasAttrOfType<IntegerAttr>("maskGran"))
1136 maskGran = op->getAttrOfType<IntegerAttr>("maskGran").getUInt();
1137 else
1139 readUnderWrite = op->getAttrOfType<seq::RUWAttr>("readUnderWrite").getValue();
1141 op->getAttrOfType<seq::WUWAttr>("writeUnderWrite").getValue();
1142 if (auto clockIDsAttr = op->getAttrOfType<ArrayAttr>("writeClockIDs"))
1143 for (auto clockID : clockIDsAttr)
1144 writeClockIDs.push_back(
1145 cast<IntegerAttr>(clockID).getValue().getZExtValue());
1146 initFilename = op->getAttrOfType<StringAttr>("initFilename").getValue();
1147 initIsBinary = op->getAttrOfType<BoolAttr>("initIsBinary").getValue();
1148 initIsInline = op->getAttrOfType<BoolAttr>("initIsInline").getValue();
1149}
1150
1151LogicalResult InitialOp::verify() {
1152 // Check outputs.
1153 auto *terminator = this->getBody().front().getTerminator();
1154 if (terminator->getOperands().size() != getNumResults())
1155 return emitError() << "result type doesn't match with the terminator";
1156 for (auto [lhs, rhs] :
1157 llvm::zip(terminator->getOperands().getTypes(), getResultTypes())) {
1158 if (cast<seq::ImmutableType>(rhs).getInnerType() != lhs)
1159 return emitError() << cast<seq::ImmutableType>(rhs).getInnerType()
1160 << " is expected but got " << lhs;
1161 }
1162
1163 auto blockArgs = this->getBody().front().getArguments();
1164
1165 if (blockArgs.size() != getNumOperands())
1166 return emitError() << "operand type doesn't match with the block arg";
1167
1168 for (auto [blockArg, operand] : llvm::zip(blockArgs, getOperands())) {
1169 if (blockArg.getType() !=
1170 cast<ImmutableType>(operand.getType()).getInnerType())
1171 return emitError()
1172 << blockArg.getType() << " is expected but got "
1173 << cast<ImmutableType>(operand.getType()).getInnerType();
1174 }
1175 return success();
1176}
1177void InitialOp::build(OpBuilder &builder, OperationState &result,
1178 TypeRange resultTypes, std::function<void()> ctor) {
1179 OpBuilder::InsertionGuard guard(builder);
1180
1181 builder.createBlock(result.addRegion());
1182 SmallVector<Type> types;
1183 for (auto t : resultTypes)
1184 types.push_back(seq::ImmutableType::get(t));
1185
1186 result.addTypes(types);
1187
1188 if (ctor)
1189 ctor();
1190}
1191
1192TypedValue<seq::ImmutableType>
1193circt::seq::createConstantInitialValue(OpBuilder builder, Location loc,
1194 mlir::IntegerAttr attr) {
1195 auto initial = seq::InitialOp::create(builder, loc, attr.getType(), [&]() {
1196 auto constant = hw::ConstantOp::create(builder, loc, attr);
1197 seq::YieldOp::create(builder, loc, ArrayRef<Value>{constant});
1198 });
1199 return cast<TypedValue<seq::ImmutableType>>(initial->getResult(0));
1200}
1201
1202mlir::TypedValue<seq::ImmutableType>
1203circt::seq::createConstantInitialValue(OpBuilder builder, Operation *op) {
1204 assert(op->getNumResults() == 1 &&
1205 op->hasTrait<mlir::OpTrait::ConstantLike>());
1206 auto initial = seq::InitialOp::create(
1207 builder, op->getLoc(), op->getResultTypes(), [&]() {
1208 auto *clonedOp = builder.clone(*op);
1209 seq::YieldOp::create(builder, op->getLoc(), clonedOp->getResults());
1210 });
1211 return cast<mlir::TypedValue<seq::ImmutableType>>(initial.getResult(0));
1212}
1213
1214Value circt::seq::unwrapImmutableValue(TypedValue<seq::ImmutableType> value) {
1215 auto resultNum = cast<OpResult>(value).getResultNumber();
1216 auto initialOp = value.getDefiningOp<seq::InitialOp>();
1217 assert(initialOp);
1218 return initialOp.getBodyBlock()->getTerminator()->getOperand(resultNum);
1219}
1220
1221FailureOr<seq::InitialOp> circt::seq::mergeInitialOps(Block *block) {
1222 SmallVector<Operation *> initialOps;
1223 for (auto &op : *block)
1224 if (isa<seq::InitialOp>(op))
1225 initialOps.push_back(&op);
1226
1227 if (!mlir::computeTopologicalSorting(initialOps, {}))
1228 return block->getParentOp()->emitError() << "initial ops cannot be "
1229 << "topologically sorted";
1230
1231 // No need to merge if there is only one initial op.
1232 if (initialOps.size() <= 1)
1233 return initialOps.empty() ? seq::InitialOp()
1234 : cast<seq::InitialOp>(initialOps[0]);
1235
1236 auto initialOp = cast<seq::InitialOp>(initialOps.front());
1237 auto yieldOp = cast<seq::YieldOp>(initialOp.getBodyBlock()->getTerminator());
1238
1239 llvm::MapVector<Value, Value>
1240 resultToYieldOperand; // seq.immutable value to operand.
1241
1242 for (auto [result, operand] :
1243 llvm::zip(initialOp.getResults(), yieldOp->getOperands()))
1244 resultToYieldOperand.insert({result, operand});
1245
1246 for (size_t i = 1; i < initialOps.size(); ++i) {
1247 auto currentInitialOp = cast<seq::InitialOp>(initialOps[i]);
1248 auto operands = currentInitialOp->getOperands();
1249 for (auto [blockArg, operand] :
1250 llvm::zip(currentInitialOp.getBodyBlock()->getArguments(), operands)) {
1251 if (auto initOp = operand.getDefiningOp<seq::InitialOp>()) {
1252 assert(resultToYieldOperand.count(operand) &&
1253 "it must be visited already");
1254 blockArg.replaceAllUsesWith(resultToYieldOperand.lookup(operand));
1255 } else {
1256 // Otherwise add the operand to the current block.
1257 initialOp.getBodyBlock()->addArgument(
1258 cast<seq::ImmutableType>(operand.getType()).getInnerType(),
1259 operand.getLoc());
1260 initialOp.getInputsMutable().append(operand);
1261 }
1262 }
1263
1264 auto currentYieldOp =
1265 cast<seq::YieldOp>(currentInitialOp.getBodyBlock()->getTerminator());
1266
1267 for (auto [result, operand] : llvm::zip(currentInitialOp.getResults(),
1268 currentYieldOp->getOperands()))
1269 resultToYieldOperand.insert({result, operand});
1270
1271 // Append the operands of the current yield op to the original yield op.
1272 yieldOp.getOperandsMutable().append(currentYieldOp.getOperands());
1273 currentYieldOp->erase();
1274
1275 // Append the operations of the current initial op to the original initial
1276 // op.
1277 initialOp.getBodyBlock()->getOperations().splice(
1278 initialOp.end(), currentInitialOp.getBodyBlock()->getOperations());
1279 }
1280
1281 // Move the terminator to the end of the block.
1282 yieldOp->moveBefore(initialOp.getBodyBlock(),
1283 initialOp.getBodyBlock()->end());
1284
1285 auto builder = OpBuilder::atBlockBegin(block);
1286 SmallVector<Type> types;
1287 for (auto [result, operand] : resultToYieldOperand)
1288 types.push_back(operand.getType());
1289
1290 // Create a new initial op which accumulates the results of the merged initial
1291 // ops.
1292 auto newInitial = seq::InitialOp::create(builder, initialOp.getLoc(), types);
1293 newInitial.getInputsMutable().append(initialOp.getInputs());
1294
1295 for (auto [resultAndOperand, newResult] :
1296 llvm::zip(resultToYieldOperand, newInitial.getResults()))
1297 resultAndOperand.first.replaceAllUsesWith(newResult);
1298
1299 // Update the block arguments of the new initial op.
1300 for (auto oldBlockArg : initialOp.getBodyBlock()->getArguments()) {
1301 auto blockArg = newInitial.getBodyBlock()->addArgument(
1302 oldBlockArg.getType(), oldBlockArg.getLoc());
1303 oldBlockArg.replaceAllUsesWith(blockArg);
1304 }
1305
1306 newInitial.getBodyBlock()->getOperations().splice(
1307 newInitial.end(), initialOp.getBodyBlock()->getOperations());
1308
1309 // Clean up.
1310 while (!initialOps.empty())
1311 initialOps.pop_back_val()->erase();
1312
1313 return newInitial;
1314}
1315
1316//===----------------------------------------------------------------------===//
1317// TableGen generated logic.
1318//===----------------------------------------------------------------------===//
1319
1320// Provide the autogenerated implementation guts for the Op classes.
1321#define GET_OP_CLASSES
1322#include "circt/Dialect/Seq/Seq.cpp.inc"
assert(baseType &&"element must be base type")
MlirType elementType
Definition CHIRRTL.cpp:29
#define isdigit(x)
Definition FIRLexer.cpp:26
static bool isConstZero(Value value)
false return failure()
Parse an optional keyword or string and set instance into 'result'.
return success()
static std::optional< APInt > getInt(Value value)
Helper to convert a value to a constant integer if it is one.
void printFIFOAFThreshold(OpAsmPrinter &p, Operation *op, IntegerAttr threshold, Type outputFlagType)
Definition SeqOps.cpp:268
static bool isConstClock(Value value)
Definition SeqOps.cpp:967
static ParseResult parseFIFOFlagThreshold(OpAsmParser &parser, IntegerAttr &threshold, Type &outputFlagType, StringRef directive)
Definition SeqOps.cpp:237
static void printOptionalTypeMatch(OpAsmPrinter &p, Operation *op, Type refType, Value operand, Type type)
Definition SeqOps.cpp:85
static bool isConstAllOnes(Value value)
Definition SeqOps.cpp:980
static ParseResult parseOptionalImmutableTypeMatch(OpAsmParser &parser, Type refType, std::optional< OpAsmParser::UnresolvedOperand > operand, Type &type)
Definition SeqOps.cpp:90
void printFIFOAEThreshold(OpAsmPrinter &p, Operation *op, IntegerAttr threshold, Type outputFlagType)
Definition SeqOps.cpp:275
LogicalResult verifyResets(TOp op)
Definition SeqOps.cpp:317
static bool canElideName(OpAsmPrinter &p, Operation *op)
Definition SeqOps.cpp:61
ParseResult parseFIFOAEThreshold(OpAsmParser &parser, IntegerAttr &threshold, Type &outputFlagType)
Definition SeqOps.cpp:262
static LogicalResult verifyFirMemMask(Op op)
Definition SeqOps.cpp:949
static void printOptionalImmutableTypeMatch(OpAsmPrinter &p, Operation *op, Type refType, Value operand, Type type)
Definition SeqOps.cpp:98
static ParseResult parseOptionalTypeMatch(OpAsmParser &parser, Type refType, std::optional< OpAsmParser::UnresolvedOperand > operand, Type &type)
Definition SeqOps.cpp:77
static void setNameFromResult(OpAsmParser &parser, OperationState &result)
Definition SeqOps.cpp:50
ParseResult parseFIFOAFThreshold(OpAsmParser &parser, IntegerAttr &threshold, Type &outputFlagType)
Definition SeqOps.cpp:256
static InstancePath empty
create(elements, Type result_type=None)
Definition hw.py:486
create(data_type, value)
Definition hw.py:444
create(data_type, value)
Definition hw.py:433
bool isConstant(Operation *op)
Return true if the specified operation has a constant value.
StringAttr getName(ArrayAttr names, size_t idx)
Return the name at the specified index of the ArrayAttr or null if it cannot be determined.
FailureOr< seq::InitialOp > mergeInitialOps(Block *block)
Definition SeqOps.cpp:1221
bool isValidIndexValues(Value hlmemHandle, ValueRange addresses)
Definition SeqOps.cpp:32
mlir::TypedValue< seq::ImmutableType > createConstantInitialValue(OpBuilder builder, Location loc, mlir::IntegerAttr attr)
Definition SeqOps.cpp:1193
The InstanceGraph op interface, see InstanceGraphInterface.td for more details.
static bool isConstantZero(Attribute operand)
Determine whether a constant operand is a zero value.
Definition FoldUtils.h:28
static bool isConstantOne(Attribute operand)
Determine whether a constant operand is a one value.
Definition FoldUtils.h:35
function_ref< void(Value, StringRef)> OpAsmSetValueNameFn
Definition LLVM.h:190
Definition seq.py:1
seq::WUW writeUnderWrite
Definition SeqOps.h:53
seq::RUW readUnderWrite
Definition SeqOps.h:52
FirMemory(hw::HWModuleGeneratedOp op)
Definition SeqOps.cpp:1126
SmallVector< int32_t > writeClockIDs
Definition SeqOps.h:54
size_t numReadWritePorts
Definition SeqOps.h:46
StringRef initFilename
Definition SeqOps.h:55