21#include "mlir/IR/Iterators.h"
22#include "mlir/IR/Threading.h"
23#include "mlir/Pass/Pass.h"
24#include "llvm/ADT/APSInt.h"
25#include "llvm/ADT/TinyPtrVector.h"
26#include "llvm/Support/Debug.h"
27#include "llvm/Support/ScopedPrinter.h"
31#define GEN_PASS_DEF_IMCONSTPROP
32#include "circt/Dialect/FIRRTL/Passes.h.inc"
37using namespace firrtl;
39#define DEBUG_TYPE "IMCP"
43 return isa<WireOp, RegResetOp, RegOp>(op);
48 return isa<SubindexOp, SubaccessOp, SubfieldOp, OpenSubfieldOp,
49 OpenSubindexOp, RefSubOp>(op);
55 return isa<NodeOp, RefResolveOp, RefSendOp>(op);
64 if (type_isa<RefType>(op->getResult(0).getType()))
98 LatticeValue() : valueAndTag(nullptr, Kind::Unknown) {}
100 LatticeValue(IntegerAttr attr)
101 : valueAndTag(attr, Kind::Constant) {}
102 LatticeValue(StringAttr attr)
103 : valueAndTag(attr, Kind::Constant) {}
105 static LatticeValue getOverdefined() {
107 result.markOverdefined();
111 bool isUnknown()
const {
return valueAndTag.getInt() == Kind::Unknown; }
112 bool isConstant()
const {
return valueAndTag.getInt() == Kind::Constant; }
113 bool isOverdefined()
const {
114 return valueAndTag.getInt() == Kind::Overdefined;
118 void markOverdefined() {
119 valueAndTag.setPointerAndInt(
nullptr, Kind::Overdefined);
123 void markConstant(IntegerAttr value) {
124 valueAndTag.setPointerAndInt(value, Kind::Constant);
129 Attribute getValue()
const {
return valueAndTag.getPointer(); }
139 bool mergeIn(LatticeValue rhs) {
141 if (isOverdefined() || rhs.isUnknown())
146 valueAndTag = rhs.valueAndTag;
153 if (valueAndTag != rhs.valueAndTag) {
160 bool operator==(
const LatticeValue &other)
const {
161 return valueAndTag == other.valueAndTag;
163 bool operator!=(
const LatticeValue &other)
const {
164 return valueAndTag != other.valueAndTag;
170 llvm::PointerIntPair<Attribute, 2, Kind> valueAndTag;
176 const LatticeValue &lattice) {
177 if (lattice.isUnknown())
178 return os <<
"<Unknown>";
179 if (lattice.isOverdefined())
180 return os <<
"<Overdefined>";
181 return os <<
"<" << lattice.getConstant() <<
">";
185struct IMConstPropPass
186 :
public circt::firrtl::impl::IMConstPropBase<IMConstPropPass> {
188 void runOnOperation()
override;
189 void rewriteModuleBody(FModuleOp module);
192 bool isBlockExecutable(Block *block)
const {
193 return executableBlocks.count(block);
196 bool isOverdefined(
FieldRef value)
const {
197 auto it = latticeValues.find(value);
198 return it != latticeValues.end() && it->second.isOverdefined();
203 void markOverdefined(Value value) {
204 FieldRef fieldRef = getOrCacheFieldRefFromValue(value);
205 auto firrtlType = type_dyn_cast<FIRRTLType>(value.getType());
206 if (!firrtlType || type_isa<PropertyType>(firrtlType)) {
207 markOverdefined(fieldRef);
218 void markOverdefined(
FieldRef value) {
219 auto &entry = latticeValues[value];
220 if (!entry.isOverdefined()) {
223 <<
"Setting overdefined : (" <<
getFieldName(value).first <<
")\n";
225 entry.markOverdefined();
226 changedLatticeValueWorklist.push_back(value);
233 void mergeLatticeValue(
FieldRef value, LatticeValue &valueEntry,
234 LatticeValue source) {
235 if (valueEntry.mergeIn(source)) {
238 <<
"Changed to " << valueEntry <<
" : (" << value <<
")\n";
240 changedLatticeValueWorklist.push_back(value);
244 void mergeLatticeValue(
FieldRef value, LatticeValue source) {
246 if (source.isUnknown())
248 mergeLatticeValue(value, latticeValues[value], source);
254 auto it = latticeValues.find(from);
255 if (it == latticeValues.end())
257 mergeLatticeValue(result, it->second);
260 void mergeLatticeValue(Value result, Value from) {
261 FieldRef fieldRefFrom = getOrCacheFieldRefFromValue(from);
262 FieldRef fieldRefResult = getOrCacheFieldRefFromValue(result);
263 if (!type_isa<FIRRTLType>(result.getType()))
264 return mergeLatticeValue(fieldRefResult, fieldRefFrom);
266 if (type_isa<PropertyType>(result.getType()))
267 return mergeLatticeValue(fieldRefResult, fieldRefFrom);
269 [&](uint64_t fieldID,
auto,
auto) {
270 mergeLatticeValue(fieldRefResult.getSubField(fieldID),
271 fieldRefFrom.getSubField(fieldID));
280 void setLatticeValue(
FieldRef value, LatticeValue source) {
282 if (source.isUnknown())
286 auto &valueEntry = latticeValues[value];
287 if (valueEntry != source) {
288 changedLatticeValueWorklist.push_back(value);
296 FieldRef getOrCacheFieldRefFromValue(Value value) {
297 if (!value.getDefiningOp() || !
isAggregate(value.getDefiningOp()))
299 auto &fieldRef = valueToFieldRef[value];
309 bool allowTruncation =
false);
312 void markBlockExecutable(Block *block);
313 void markWireOp(WireOp wireOrReg);
314 void markMemOp(MemOp mem);
315 void markDPICallIntrinsicOp(DPICallIntrinsicOp dpi);
317 void markInvalidValueOp(InvalidValueOp invalid);
318 void markAggregateConstantOp(AggregateConstantOp constant);
319 void markInstanceOp(InstanceOp instance);
320 void markObjectOp(ObjectOp
object);
321 template <
typename OpTy>
322 void markConstantValueOp(OpTy op);
324 void visitConnectLike(FConnectLike connect,
FieldRef changedFieldRef);
325 void visitRefSend(RefSendOp send,
FieldRef changedFieldRef);
326 void visitRefResolve(RefResolveOp resolve,
FieldRef changedFieldRef);
327 void mergeOnlyChangedLatticeValue(Value dest, Value src,
329 void visitNode(NodeOp node,
FieldRef changedFieldRef);
330 void visitOperation(Operation *op,
FieldRef changedFieldRef);
337 DenseMap<FieldRef, LatticeValue> latticeValues;
340 SmallPtrSet<Block *, 16> executableBlocks;
344 SmallVector<FieldRef, 64> changedLatticeValueWorklist;
347 DenseMap<FieldRef, llvm::TinyPtrVector<Operation *>> fieldRefToUsers;
351 llvm::DenseMap<Value, FieldRef> valueToFieldRef;
355 DenseMap<BlockArgument, llvm::TinyPtrVector<Value>>
356 resultPortToInstanceResultMapping;
360 llvm::ScopedPrinter logger{llvm::dbgs()};
366void IMConstPropPass::runOnOperation() {
367 auto circuit = getOperation();
369 { logger.startLine() <<
"IMConstProp : " << circuit.getName() <<
"\n"; });
371 instanceGraph = &getAnalysis<InstanceGraph>();
374 for (
auto &op : circuit.getOps()) {
376 if (
auto module = dyn_cast<FModuleOp>(op)) {
377 if (module.isPublic()) {
378 markBlockExecutable(module.getBodyBlock());
380 markOverdefined(port);
387 if (isa<hw::HierPathOp>(op))
394 auto symbolUses = SymbolTable::getSymbolUses(&op);
397 for (
const auto &use : *symbolUses) {
398 if (
auto symRef = dyn_cast<FlatSymbolRefAttr>(use.getSymbolRef())) {
399 if (
auto *igNode = instanceGraph->lookupOrNull(symRef.getAttr())) {
400 if (
auto module = dyn_cast<FModuleOp>(*igNode->getModule())) {
401 LLVM_DEBUG(llvm::dbgs()
402 <<
"Unknown use of " << module.getModuleNameAttr()
403 <<
" in " << op.getName()
404 <<
", marking inputs as overdefined\n");
405 markBlockExecutable(module.getBodyBlock());
407 markOverdefined(port);
415 while (!changedLatticeValueWorklist.empty()) {
416 FieldRef changedFieldRef = changedLatticeValueWorklist.pop_back_val();
417 for (Operation *user : fieldRefToUsers[changedFieldRef]) {
418 if (isBlockExecutable(user->getBlock()))
419 visitOperation(user, changedFieldRef);
424 mlir::parallelForEach(circuit.getContext(),
425 circuit.getBodyBlock()->getOps<FModuleOp>(),
426 [&](
auto op) { rewriteModuleBody(op); });
429 instanceGraph =
nullptr;
430 latticeValues.clear();
431 executableBlocks.clear();
432 assert(changedLatticeValueWorklist.empty());
433 fieldRefToUsers.clear();
434 valueToFieldRef.clear();
435 resultPortToInstanceResultMapping.clear();
441LatticeValue IMConstPropPass::getExtendedLatticeValue(
FieldRef value,
443 bool allowTruncation) {
445 auto it = latticeValues.find(value);
446 if (it == latticeValues.end())
447 return LatticeValue();
449 auto result = it->second;
451 if (result.isUnknown() || result.isOverdefined())
455 if (isa<PropertyType>(destType))
458 auto constant = result.getConstant();
461 auto intAttr = dyn_cast<IntegerAttr>(constant);
462 assert(intAttr &&
"unsupported lattice attribute kind");
467 if (
auto boolAttr = dyn_cast<BoolAttr>(intAttr))
473 return LatticeValue::getOverdefined();
476 auto resultConstant = intAttr.getAPSInt();
477 auto destWidth = baseType.getBitWidthOrSentinel();
479 return LatticeValue::getOverdefined();
480 if (resultConstant.getBitWidth() == (
unsigned)destWidth)
485 return LatticeValue(IntegerAttr::get(destType.getContext(), resultConstant));
492void IMConstPropPass::markBlockExecutable(Block *block) {
493 if (!executableBlocks.insert(block).second)
498 for (
auto ba : block->getArguments())
502 for (
auto &op : *block) {
504 TypeSwitch<Operation *>(&op)
505 .Case<RegOp, RegResetOp>(
506 [&](
auto reg) { markOverdefined(op.getResult(0)); })
507 .Case<WireOp>([&](
auto wire) { markWireOp(wire); })
508 .Case<ConstantOp, SpecialConstantOp, StringConstantOp,
509 FIntegerConstantOp, BoolConstantOp>(
510 [&](
auto constOp) { markConstantValueOp(constOp); })
511 .Case<AggregateConstantOp>(
512 [&](
auto aggConstOp) { markAggregateConstantOp(aggConstOp); })
513 .Case<InvalidValueOp>(
514 [&](
auto invalid) { markInvalidValueOp(invalid); })
515 .Case<InstanceOp>([&](
auto instance) { markInstanceOp(instance); })
516 .Case<ObjectOp>([&](
auto obj) { markObjectOp(obj); })
517 .Case<MemOp>([&](
auto mem) { markMemOp(mem); })
519 [&](
auto layer) { markBlockExecutable(layer.getBody(0)); })
520 .Case<DPICallIntrinsicOp>(
521 [&](
auto dpi) { markDPICallIntrinsicOp(dpi); })
522 .Default([&](
auto _) {
523 if (isa<mlir::UnrealizedConversionCastOp, VerbatimExprOp,
524 VerbatimWireOp, SubaccessOp>(op) ||
525 op.getNumOperands() == 0) {
529 for (
auto result : op.getResults())
530 markOverdefined(result);
542 bool hasAggregateOperand =
543 llvm::any_of(op.getOperandTypes(), [](Type type) {
544 return type_isa<FVectorType, BundleType>(type);
547 for (
auto result : op.getResults())
548 if (hasAggregateOperand ||
549 type_isa<FVectorType, BundleType>(result.getType()))
550 markOverdefined(result);
557 for (
auto operand : op.getOperands()) {
558 auto fieldRef = getOrCacheFieldRefFromValue(operand);
559 auto firrtlType = type_dyn_cast<FIRRTLType>(operand.getType());
563 if (type_isa<PropertyType>(firrtlType)) {
564 fieldRefToUsers[fieldRef].push_back(&op);
568 fieldRefToUsers[fieldRef.
getSubField(fieldID)].push_back(&op);
576void IMConstPropPass::markWireOp(WireOp wire) {
577 auto type = type_dyn_cast<FIRRTLType>(wire.getResult().getType());
578 if (!type ||
hasDontTouch(wire.getResult()) || wire.isForceable()) {
579 for (
auto result : wire.getResults())
580 markOverdefined(result);
587void IMConstPropPass::markMemOp(MemOp mem) {
588 for (
auto result : mem.getResults())
589 markOverdefined(result);
592void IMConstPropPass::markDPICallIntrinsicOp(DPICallIntrinsicOp dpi) {
593 if (
auto result = dpi.getResult())
594 markOverdefined(result);
597template <
typename OpTy>
598void IMConstPropPass::markConstantValueOp(OpTy op) {
599 mergeLatticeValue(getOrCacheFieldRefFromValue(op),
600 LatticeValue(op.getValueAttr()));
603void IMConstPropPass::markAggregateConstantOp(AggregateConstantOp constant) {
604 walkGroundTypes(constant.getType(), [&](uint64_t fieldID,
auto,
auto) {
605 mergeLatticeValue(FieldRef(constant, fieldID),
606 LatticeValue(cast<IntegerAttr>(
607 constant.getAttributeFromFieldID(fieldID))));
611void IMConstPropPass::markInvalidValueOp(InvalidValueOp invalid) {
612 markOverdefined(invalid.getResult());
617void IMConstPropPass::markInstanceOp(InstanceOp instance) {
619 Operation *op = instance.getReferencedModule(*instanceGraph);
623 if (!isa<FModuleOp>(op)) {
624 auto module = dyn_cast<FModuleLike>(op);
625 for (
size_t resultNo = 0, e = instance.getNumResults(); resultNo != e;
627 auto portVal = instance.getResult(resultNo);
629 if (module.getPortDirection(resultNo) == Direction::In)
633 markOverdefined(portVal);
639 auto fModule = cast<FModuleOp>(op);
640 markBlockExecutable(fModule.getBodyBlock());
644 for (
size_t resultNo = 0, e = instance.getNumResults(); resultNo != e;
646 auto instancePortVal = instance.getResult(resultNo);
649 if (fModule.getPortDirection(resultNo) == Direction::In)
654 BlockArgument modulePortVal = fModule.getArgument(resultNo);
656 resultPortToInstanceResultMapping[modulePortVal].push_back(instancePortVal);
660 mergeLatticeValue(instancePortVal, modulePortVal);
664void IMConstPropPass::markObjectOp(ObjectOp obj) {
666 markOverdefined(obj);
669static std::optional<uint64_t>
672 assert(!type_isa<RefType>(connectionType));
683void IMConstPropPass::mergeOnlyChangedLatticeValue(Value dest, Value src,
687 auto destType = dest.getType();
688 if (
auto refType = type_dyn_cast<RefType>(destType))
689 destType = refType.getType();
691 if (!isa<FIRRTLType>(destType)) {
694 markOverdefined(src);
695 return markOverdefined(dest);
698 auto fieldRefSrc = getOrCacheFieldRefFromValue(src);
699 auto fieldRefDest = getOrCacheFieldRefFromValue(dest);
703 if (
auto srcOffset =
getFieldIDOffset(changedFieldRef, destType, fieldRefSrc))
704 mergeLatticeValue(fieldRefDest.getSubField(*srcOffset),
705 fieldRefSrc.getSubField(*srcOffset));
709 if (
auto destOffset =
711 mergeLatticeValue(fieldRefDest.getSubField(*destOffset),
712 fieldRefSrc.getSubField(*destOffset));
715void IMConstPropPass::visitConnectLike(FConnectLike connect,
718 auto destType =
connect.getDest().getType();
719 if (
auto refType = type_dyn_cast<RefType>(destType))
720 destType = refType.getType();
723 if (!isa<FIRRTLType>(destType)) {
724 markOverdefined(
connect.getSrc());
725 return markOverdefined(
connect.getDest());
728 auto fieldRefSrc = getOrCacheFieldRefFromValue(
connect.getSrc());
729 auto fieldRefDest = getOrCacheFieldRefFromValue(
connect.getDest());
730 if (
auto subaccess = fieldRefDest.getValue().getDefiningOp<SubaccessOp>()) {
734 Value parent = subaccess.getInput();
735 while (parent.getDefiningOp() &&
736 parent.getDefiningOp()->getNumOperands() > 0)
737 parent = parent.getDefiningOp()->getOperand(0);
738 return markOverdefined(parent);
741 auto propagateElementLattice = [&](uint64_t fieldID,
FIRRTLType destType) {
742 auto fieldRefDestConnected = fieldRefDest.getSubField(fieldID);
743 assert(!firrtl::type_isa<FIRRTLBaseType>(destType) ||
744 firrtl::type_cast<FIRRTLBaseType>(destType).isGround());
748 getExtendedLatticeValue(fieldRefSrc.getSubField(fieldID), destType);
749 if (srcValue.isUnknown())
754 if (
auto blockArg = dyn_cast<BlockArgument>(fieldRefDest.getValue())) {
755 for (
auto userOfResultPort : resultPortToInstanceResultMapping[blockArg])
760 return mergeLatticeValue(fieldRefDestConnected, srcValue);
763 auto dest = cast<mlir::OpResult>(fieldRefDest.getValue());
768 return mergeLatticeValue(fieldRefDestConnected, srcValue);
772 if (
auto instance = dest.getDefiningOp<InstanceOp>()) {
774 mergeLatticeValue(fieldRefDestConnected, srcValue);
775 auto mod = instance.getReferencedModule<FModuleOp>(*instanceGraph);
779 BlockArgument modulePortVal = mod.getArgument(dest.getResultNumber());
781 return mergeLatticeValue(
782 FieldRef(modulePortVal, fieldRefDestConnected.getFieldID()),
788 if (dest.getDefiningOp<MemOp>())
792 if (isa_and_nonnull<ObjectSubfieldOp>(dest.getDefiningOp()))
795 connect.emitError(
"connectlike operation unhandled by IMConstProp")
796 .attachNote(
connect.getDest().getLoc())
797 <<
"connect destination is here";
800 if (
auto srcOffset =
getFieldIDOffset(changedFieldRef, destType, fieldRefSrc))
801 propagateElementLattice(
803 firrtl::type_cast<FIRRTLType>(
806 if (
auto relativeDest =
808 propagateElementLattice(
810 firrtl::type_cast<FIRRTLType>(
814void IMConstPropPass::visitRefSend(RefSendOp send,
FieldRef changedFieldRef) {
816 return mergeOnlyChangedLatticeValue(send.getResult(), send.getBase(),
820void IMConstPropPass::visitRefResolve(RefResolveOp resolve,
824 return mergeOnlyChangedLatticeValue(resolve.getResult(), resolve.getRef(),
828void IMConstPropPass::visitNode(NodeOp node,
FieldRef changedFieldRef) {
829 if (
hasDontTouch(node.getResult()) || node.isForceable()) {
830 for (
auto result : node.getResults())
831 markOverdefined(result);
835 return mergeOnlyChangedLatticeValue(node.getResult(), node.getInput(),
845void IMConstPropPass::visitOperation(Operation *op,
FieldRef changedField) {
847 if (
auto connectLikeOp = dyn_cast<FConnectLike>(op))
848 return visitConnectLike(connectLikeOp, changedField);
849 if (
auto sendOp = dyn_cast<RefSendOp>(op))
850 return visitRefSend(sendOp, changedField);
851 if (
auto resolveOp = dyn_cast<RefResolveOp>(op))
852 return visitRefResolve(resolveOp, changedField);
853 if (
auto nodeOp = dyn_cast<NodeOp>(op))
854 return visitNode(nodeOp, changedField);
865 auto isOverdefinedFn = [&](Value value) {
866 return isOverdefined(getOrCacheFieldRefFromValue(value));
868 if (llvm::all_of(op->getResults(), isOverdefinedFn))
873 if (op->getNumOperands() > 128) {
874 for (
auto value : op->getResults())
875 markOverdefined(value);
881 SmallVector<Attribute, 8> operandConstants;
882 operandConstants.reserve(op->getNumOperands());
883 bool hasUnknown =
false;
884 for (Value operand : op->getOperands()) {
886 auto &operandLattice = latticeValues[getOrCacheFieldRefFromValue(operand)];
891 if (operandLattice.isUnknown())
896 if (operandLattice.isConstant())
897 operandConstants.push_back(operandLattice.getValue());
899 operandConstants.push_back({});
904 SmallVector<OpFoldResult, 8> foldResults;
905 foldResults.reserve(op->getNumResults());
906 if (failed(op->fold(operandConstants, foldResults))) {
908 logger.startLine() <<
"Folding Failed operation : '" << op->getName()
914 for (
auto value : op->getResults())
915 markOverdefined(value);
920 logger.getOStream() <<
"\n";
921 logger.startLine() <<
"Folding operation : '" << op->getName() <<
"\n";
923 logger.getOStream() <<
"( ";
924 for (
auto cst : operandConstants)
926 logger.getOStream() <<
"{} ";
928 logger.getOStream() << cst <<
" ";
930 logger.getOStream() <<
") -> { ";
932 for (
auto &r : foldResults) {
933 logger.getOStream() << r <<
" ";
936 logger.getOStream() <<
"}\n";
943 if (foldResults.empty())
944 return visitOperation(op, changedField);
947 assert(foldResults.size() == op->getNumResults() &&
"invalid result size");
948 for (
unsigned i = 0, e = foldResults.size(); i != e; ++i) {
950 LatticeValue resultLattice;
951 OpFoldResult foldResult = foldResults[i];
952 if (Attribute foldAttr = dyn_cast<Attribute>(foldResult)) {
953 if (
auto intAttr = dyn_cast<IntegerAttr>(foldAttr))
954 resultLattice = LatticeValue(intAttr);
955 else if (
auto strAttr = dyn_cast<StringAttr>(foldAttr))
956 resultLattice = LatticeValue(strAttr);
958 resultLattice = LatticeValue::getOverdefined();
961 latticeValues[getOrCacheFieldRefFromValue(cast<Value>(foldResult))];
964 mergeLatticeValue(getOrCacheFieldRefFromValue(op->getResult(i)),
969void IMConstPropPass::rewriteModuleBody(FModuleOp module) {
970 auto *body =
module.getBodyBlock();
972 if (!executableBlocks.count(body))
975 auto builder = OpBuilder::atBlockBegin(body);
979 auto cursor = builder.create<firrtl::ConstantOp>(
module.getLoc(), APSInt(1));
980 builder.setInsertionPoint(cursor);
983 DenseMap<std::pair<Attribute, Type>, Operation *> constPool;
985 std::function<Value(Attribute, Type, Location)> getConst =
986 [&](Attribute constantValue, Type type, Location loc) -> Value {
987 auto constIt = constPool.find({constantValue, type});
988 if (constIt != constPool.end()) {
989 auto *cst = constIt->second;
991 cst->setLoc(builder.getFusedLoc({cst->getLoc(), loc}));
992 return cst->getResult(0);
994 OpBuilder::InsertionGuard x(builder);
995 builder.setInsertionPoint(cursor);
1000 if (
auto refType = type_dyn_cast<RefType>(type)) {
1001 assert(!type_cast<RefType>(type).getForceable() &&
1002 "Attempting to materialize rwprobe of constant, shouldn't happen");
1003 auto inner = getConst(constantValue, refType.getType(), loc);
1005 cst = builder.create<RefSendOp>(loc, inner);
1007 cst =
module->getDialect()->materializeConstant(builder, constantValue,
1009 assert(cst &&
"all FIRRTL constants can be materialized");
1010 constPool.insert({{constantValue, type}, cst});
1011 return cst->getResult(0);
1016 auto replaceValueIfPossible = [&](Value value) ->
bool {
1020 auto replaceIfNotConnect = [&value](Value replacement) {
1021 value.replaceUsesWithIf(replacement, [](OpOperand &operand) {
1022 return !isa<FConnectLike>(operand.getOwner()) ||
1023 operand.getOperandNumber() != 0;
1029 if (it == latticeValues.end() || it->second.isOverdefined() ||
1030 it->second.isUnknown())
1036 if (!type_isa<FIRRTLBaseType, RefType, FIntegerType, StringType, BoolType>(
1041 getConst(it->second.getValue(), value.getType(), value.
getLoc());
1043 replaceIfNotConnect(cstValue);
1048 for (
auto &port : body->getArguments())
1049 replaceValueIfPossible(port);
1057 bool aboveCursor =
false;
1058 module.walk<mlir::WalkOrder::PostOrder, mlir::ReverseIterator>(
1059 [&](Operation *op) {
1060 auto dropIfDead = [&](Operation *op, const Twine &debugPrefix) {
1061 if (op->use_empty() &&
1062 (wouldOpBeTriviallyDead(op) || isDeletableWireOrRegOrNode(op))) {
1064 { logger.getOStream() << debugPrefix << " : " << op << "\n"; });
1074 dropIfDead(op,
"Trivially dead materialized constant");
1075 return WalkResult::advance();
1081 return WalkResult::advance();
1085 if (
auto connect = dyn_cast<FConnectLike>(op)) {
1086 if (
auto *destOp =
connect.getDest().getDefiningOp()) {
1087 auto fieldRef = getOrCacheFieldRefFromValue(
connect.getDest());
1093 auto type = type_dyn_cast<FIRRTLType>(
connect.getDest().getType());
1095 return WalkResult::advance();
1096 auto baseType = type_dyn_cast<FIRRTLBaseType>(type);
1097 if (baseType && !baseType.isGround())
1098 return WalkResult::advance();
1100 !isOverdefined(fieldRef)) {
1105 return WalkResult::advance();
1110 if (op->getNumResults() != 1 && !isa<InstanceOp>(op))
1111 return WalkResult::advance();
1114 if (dropIfDead(op,
"Trivially dead"))
1115 return WalkResult::advance();
1119 if (op->hasTrait<mlir::OpTrait::ConstantLike>())
1120 return WalkResult::advance();
1123 builder.setInsertionPoint(op);
1124 bool foldedAny =
false;
1125 for (
auto result : op->getResults())
1126 foldedAny |= replaceValueIfPossible(result);
1132 if (foldedAny && dropIfDead(op,
"Made dead"))
1133 return WalkResult::advance();
1135 return WalkResult::advance();
1140 return std::make_unique<IMConstPropPass>();
assert(baseType &&"element must be base type")
static std::optional< APSInt > getConstant(Attribute operand)
Determine the value of a constant operand for the sake of constant folding.
static bool isNodeLike(Operation *op)
static bool isWireOrReg(Operation *op)
Return true if this is a wire or register.
static bool isAggregate(Operation *op)
Return true if this is an aggregate indexer.
static std::optional< uint64_t > getFieldIDOffset(FieldRef changedFieldRef, Type connectionType, FieldRef connectedValueFieldRef)
static bool isDeletableWireOrRegOrNode(Operation *op)
Return true if this is a wire or register we're allowed to delete.
static unsigned getFieldID(BundleType type, unsigned index)
static Block * getBodyBlock(FModuleLike mod)
This class represents a reference to a specific field or element of an aggregate value.
FieldRef getSubField(unsigned subFieldID) const
Get a reference to a subfield.
unsigned getFieldID() const
Get the field ID of this FieldRef, which is a unique identifier mapped to a specific field in a bundl...
Value getValue() const
Get the Value which created this location.
Location getLoc() const
Get the location associated with the value of this field ref.
This class provides a read-only projection over the MLIR attributes that represent a set of annotatio...
This graph tracks modules and where they are instantiated.
connect(destination, source)
FIRRTLBaseType getBaseType(Type type)
If it is a base type, return it as is.
FieldRef getFieldRefFromValue(Value value, bool lookThroughCasts=false)
Get the FieldRef from a value.
void walkGroundTypes(FIRRTLType firrtlType, llvm::function_ref< void(uint64_t, FIRRTLBaseType, bool)> fn)
Walk leaf ground types in the firrtlType and apply the function fn.
bool isConstant(Operation *op)
Return true if the specified operation has a constant value.
std::unique_ptr< mlir::Pass > createIMConstPropPass()
bool hasDontTouch(Value value)
Check whether a block argument ("port") or the operation defining a value has a DontTouch annotation,...
llvm::raw_ostream & operator<<(llvm::raw_ostream &os, const InstanceInfo::LatticeValue &value)
bool hasDroppableName(Operation *op)
Return true if the name is droppable.
std::pair< std::string, bool > getFieldName(const FieldRef &fieldRef, bool nameSafe=false)
Get a string identifier representing the FieldRef.
::mlir::Type getFinalTypeByFieldID(Type type, uint64_t fieldID)
uint64_t getMaxFieldID(Type)
static bool operator==(const ModulePort &a, const ModulePort &b)
The InstanceGraph op interface, see InstanceGraphInterface.td for more details.
APSInt extOrTruncZeroWidth(APSInt value, unsigned width)
A safe version of APSInt::extOrTrunc that will NOT assert on zero-width signed APSInts.
bool operator!=(uint64_t a, const FVInt &b)
reg(value, clock, reset=None, reset_value=None, name=None, sym_name=None)