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);
316 void markInvalidValueOp(InvalidValueOp invalid);
317 void markAggregateConstantOp(AggregateConstantOp constant);
318 void markInstanceOp(InstanceOp instance);
319 void markObjectOp(ObjectOp
object);
320 template <
typename OpTy>
321 void markConstantValueOp(OpTy op);
323 void visitConnectLike(FConnectLike connect,
FieldRef changedFieldRef);
324 void visitRefSend(RefSendOp send,
FieldRef changedFieldRef);
325 void visitRefResolve(RefResolveOp resolve,
FieldRef changedFieldRef);
326 void mergeOnlyChangedLatticeValue(Value dest, Value src,
328 void visitNode(NodeOp node,
FieldRef changedFieldRef);
329 void visitOperation(Operation *op,
FieldRef changedFieldRef);
336 DenseMap<FieldRef, LatticeValue> latticeValues;
339 SmallPtrSet<Block *, 16> executableBlocks;
343 SmallVector<FieldRef, 64> changedLatticeValueWorklist;
346 DenseMap<FieldRef, llvm::TinyPtrVector<Operation *>> fieldRefToUsers;
350 llvm::DenseMap<Value, FieldRef> valueToFieldRef;
354 DenseMap<BlockArgument, llvm::TinyPtrVector<Value>>
355 resultPortToInstanceResultMapping;
359 llvm::ScopedPrinter logger{llvm::dbgs()};
365void IMConstPropPass::runOnOperation() {
366 auto circuit = getOperation();
368 { logger.startLine() <<
"IMConstProp : " << circuit.getName() <<
"\n"; });
370 instanceGraph = &getAnalysis<InstanceGraph>();
373 for (
auto &op : circuit.getOps()) {
375 if (
auto module = dyn_cast<FModuleOp>(op)) {
376 if (module.isPublic()) {
377 markBlockExecutable(module.getBodyBlock());
379 markOverdefined(port);
386 if (isa<hw::HierPathOp>(op))
393 auto symbolUses = SymbolTable::getSymbolUses(&op);
396 for (
const auto &use : *symbolUses) {
397 if (
auto symRef = dyn_cast<FlatSymbolRefAttr>(use.getSymbolRef())) {
398 if (
auto *igNode = instanceGraph->lookupOrNull(symRef.getAttr())) {
399 if (
auto module = dyn_cast<FModuleOp>(*igNode->getModule())) {
400 LLVM_DEBUG(llvm::dbgs()
401 <<
"Unknown use of " << module.getModuleNameAttr()
402 <<
" in " << op.getName()
403 <<
", marking inputs as overdefined\n");
404 markBlockExecutable(module.getBodyBlock());
406 markOverdefined(port);
414 while (!changedLatticeValueWorklist.empty()) {
415 FieldRef changedFieldRef = changedLatticeValueWorklist.pop_back_val();
416 for (Operation *user : fieldRefToUsers[changedFieldRef]) {
417 if (isBlockExecutable(user->getBlock()))
418 visitOperation(user, changedFieldRef);
423 mlir::parallelForEach(circuit.getContext(),
424 circuit.getBodyBlock()->getOps<FModuleOp>(),
425 [&](
auto op) { rewriteModuleBody(op); });
428 instanceGraph =
nullptr;
429 latticeValues.clear();
430 executableBlocks.clear();
431 assert(changedLatticeValueWorklist.empty());
432 fieldRefToUsers.clear();
433 valueToFieldRef.clear();
434 resultPortToInstanceResultMapping.clear();
440LatticeValue IMConstPropPass::getExtendedLatticeValue(
FieldRef value,
442 bool allowTruncation) {
444 auto it = latticeValues.find(value);
445 if (it == latticeValues.end())
446 return LatticeValue();
448 auto result = it->second;
450 if (result.isUnknown() || result.isOverdefined())
454 if (isa<PropertyType>(destType))
457 auto constant = result.getConstant();
460 auto intAttr = dyn_cast<IntegerAttr>(constant);
461 assert(intAttr &&
"unsupported lattice attribute kind");
466 if (
auto boolAttr = dyn_cast<BoolAttr>(intAttr))
472 return LatticeValue::getOverdefined();
475 auto resultConstant = intAttr.getAPSInt();
476 auto destWidth = baseType.getBitWidthOrSentinel();
478 return LatticeValue::getOverdefined();
479 if (resultConstant.getBitWidth() == (
unsigned)destWidth)
484 return LatticeValue(IntegerAttr::get(destType.getContext(), resultConstant));
491void IMConstPropPass::markBlockExecutable(Block *block) {
492 if (!executableBlocks.insert(block).second)
497 for (
auto ba : block->getArguments())
501 for (
auto &op : *block) {
503 TypeSwitch<Operation *>(&op)
504 .Case<RegOp, RegResetOp>(
505 [&](
auto reg) { markOverdefined(op.getResult(0)); })
506 .Case<WireOp>([&](
auto wire) { markWireOp(wire); })
507 .Case<ConstantOp, SpecialConstantOp, StringConstantOp,
508 FIntegerConstantOp, BoolConstantOp>(
509 [&](
auto constOp) { markConstantValueOp(constOp); })
510 .Case<AggregateConstantOp>(
511 [&](
auto aggConstOp) { markAggregateConstantOp(aggConstOp); })
512 .Case<InvalidValueOp>(
513 [&](
auto invalid) { markInvalidValueOp(invalid); })
514 .Case<InstanceOp>([&](
auto instance) { markInstanceOp(instance); })
515 .Case<ObjectOp>([&](
auto obj) { markObjectOp(obj); })
516 .Case<MemOp>([&](
auto mem) { markMemOp(mem); })
518 [&](
auto layer) { markBlockExecutable(layer.getBody(0)); })
519 .Default([&](
auto _) {
520 if (isa<mlir::UnrealizedConversionCastOp, VerbatimExprOp,
521 VerbatimWireOp, SubaccessOp>(op) ||
522 op.getNumOperands() == 0) {
526 for (
auto result : op.getResults())
527 markOverdefined(result);
539 bool hasAggregateOperand =
540 llvm::any_of(op.getOperandTypes(), [](Type type) {
541 return type_isa<FVectorType, BundleType>(type);
544 for (
auto result : op.getResults())
545 if (hasAggregateOperand ||
546 type_isa<FVectorType, BundleType>(result.getType()))
547 markOverdefined(result);
554 for (
auto operand : op.getOperands()) {
555 auto fieldRef = getOrCacheFieldRefFromValue(operand);
556 auto firrtlType = type_dyn_cast<FIRRTLType>(operand.getType());
560 if (type_isa<PropertyType>(firrtlType)) {
561 fieldRefToUsers[fieldRef].push_back(&op);
565 fieldRefToUsers[fieldRef.
getSubField(fieldID)].push_back(&op);
573void IMConstPropPass::markWireOp(WireOp wire) {
574 auto type = type_dyn_cast<FIRRTLType>(wire.getResult().getType());
575 if (!type ||
hasDontTouch(wire.getResult()) || wire.isForceable()) {
576 for (
auto result : wire.getResults())
577 markOverdefined(result);
584void IMConstPropPass::markMemOp(MemOp mem) {
585 for (
auto result : mem.getResults())
586 markOverdefined(result);
589template <
typename OpTy>
590void IMConstPropPass::markConstantValueOp(OpTy op) {
591 mergeLatticeValue(getOrCacheFieldRefFromValue(op),
592 LatticeValue(op.getValueAttr()));
595void IMConstPropPass::markAggregateConstantOp(AggregateConstantOp constant) {
596 walkGroundTypes(constant.getType(), [&](uint64_t fieldID,
auto,
auto) {
597 mergeLatticeValue(FieldRef(constant, fieldID),
598 LatticeValue(cast<IntegerAttr>(
599 constant.getAttributeFromFieldID(fieldID))));
603void IMConstPropPass::markInvalidValueOp(InvalidValueOp invalid) {
604 markOverdefined(invalid.getResult());
609void IMConstPropPass::markInstanceOp(InstanceOp instance) {
611 Operation *op = instance.getReferencedModule(*instanceGraph);
615 if (!isa<FModuleOp>(op)) {
616 auto module = dyn_cast<FModuleLike>(op);
617 for (
size_t resultNo = 0, e = instance.getNumResults(); resultNo != e;
619 auto portVal = instance.getResult(resultNo);
621 if (module.getPortDirection(resultNo) == Direction::In)
625 markOverdefined(portVal);
631 auto fModule = cast<FModuleOp>(op);
632 markBlockExecutable(fModule.getBodyBlock());
636 for (
size_t resultNo = 0, e = instance.getNumResults(); resultNo != e;
638 auto instancePortVal = instance.getResult(resultNo);
641 if (fModule.getPortDirection(resultNo) == Direction::In)
646 BlockArgument modulePortVal = fModule.getArgument(resultNo);
648 resultPortToInstanceResultMapping[modulePortVal].push_back(instancePortVal);
652 mergeLatticeValue(instancePortVal, modulePortVal);
656void IMConstPropPass::markObjectOp(ObjectOp obj) {
658 markOverdefined(obj);
661static std::optional<uint64_t>
664 assert(!type_isa<RefType>(connectionType));
675void IMConstPropPass::mergeOnlyChangedLatticeValue(Value dest, Value src,
679 auto destType = dest.getType();
680 if (
auto refType = type_dyn_cast<RefType>(destType))
681 destType = refType.getType();
683 if (!isa<FIRRTLType>(destType)) {
686 markOverdefined(src);
687 return markOverdefined(dest);
690 auto fieldRefSrc = getOrCacheFieldRefFromValue(src);
691 auto fieldRefDest = getOrCacheFieldRefFromValue(dest);
695 if (
auto srcOffset =
getFieldIDOffset(changedFieldRef, destType, fieldRefSrc))
696 mergeLatticeValue(fieldRefDest.getSubField(*srcOffset),
697 fieldRefSrc.getSubField(*srcOffset));
701 if (
auto destOffset =
703 mergeLatticeValue(fieldRefDest.getSubField(*destOffset),
704 fieldRefSrc.getSubField(*destOffset));
707void IMConstPropPass::visitConnectLike(FConnectLike connect,
710 auto destType =
connect.getDest().getType();
711 if (
auto refType = type_dyn_cast<RefType>(destType))
712 destType = refType.getType();
715 if (!isa<FIRRTLType>(destType)) {
716 markOverdefined(
connect.getSrc());
717 return markOverdefined(
connect.getDest());
720 auto fieldRefSrc = getOrCacheFieldRefFromValue(
connect.getSrc());
721 auto fieldRefDest = getOrCacheFieldRefFromValue(
connect.getDest());
722 if (
auto subaccess = fieldRefDest.getValue().getDefiningOp<SubaccessOp>()) {
726 Value parent = subaccess.getInput();
727 while (parent.getDefiningOp() &&
728 parent.getDefiningOp()->getNumOperands() > 0)
729 parent = parent.getDefiningOp()->getOperand(0);
730 return markOverdefined(parent);
733 auto propagateElementLattice = [&](uint64_t fieldID,
FIRRTLType destType) {
734 auto fieldRefDestConnected = fieldRefDest.getSubField(fieldID);
735 assert(!firrtl::type_isa<FIRRTLBaseType>(destType) ||
736 firrtl::type_cast<FIRRTLBaseType>(destType).isGround());
740 getExtendedLatticeValue(fieldRefSrc.getSubField(fieldID), destType);
741 if (srcValue.isUnknown())
746 if (
auto blockArg = dyn_cast<BlockArgument>(fieldRefDest.getValue())) {
747 for (
auto userOfResultPort : resultPortToInstanceResultMapping[blockArg])
752 return mergeLatticeValue(fieldRefDestConnected, srcValue);
755 auto dest = cast<mlir::OpResult>(fieldRefDest.getValue());
760 return mergeLatticeValue(fieldRefDestConnected, srcValue);
764 if (
auto instance = dest.getDefiningOp<InstanceOp>()) {
766 mergeLatticeValue(fieldRefDestConnected, srcValue);
767 auto mod = instance.getReferencedModule<FModuleOp>(*instanceGraph);
771 BlockArgument modulePortVal = mod.getArgument(dest.getResultNumber());
773 return mergeLatticeValue(
774 FieldRef(modulePortVal, fieldRefDestConnected.getFieldID()),
780 if (dest.getDefiningOp<MemOp>())
784 if (isa_and_nonnull<ObjectSubfieldOp>(dest.getDefiningOp()))
787 connect.emitError(
"connectlike operation unhandled by IMConstProp")
788 .attachNote(
connect.getDest().getLoc())
789 <<
"connect destination is here";
792 if (
auto srcOffset =
getFieldIDOffset(changedFieldRef, destType, fieldRefSrc))
793 propagateElementLattice(
795 firrtl::type_cast<FIRRTLType>(
798 if (
auto relativeDest =
800 propagateElementLattice(
802 firrtl::type_cast<FIRRTLType>(
806void IMConstPropPass::visitRefSend(RefSendOp send,
FieldRef changedFieldRef) {
808 return mergeOnlyChangedLatticeValue(send.getResult(), send.getBase(),
812void IMConstPropPass::visitRefResolve(RefResolveOp resolve,
816 return mergeOnlyChangedLatticeValue(resolve.getResult(), resolve.getRef(),
820void IMConstPropPass::visitNode(NodeOp node,
FieldRef changedFieldRef) {
821 if (
hasDontTouch(node.getResult()) || node.isForceable()) {
822 for (
auto result : node.getResults())
823 markOverdefined(result);
827 return mergeOnlyChangedLatticeValue(node.getResult(), node.getInput(),
837void IMConstPropPass::visitOperation(Operation *op,
FieldRef changedField) {
839 if (
auto connectLikeOp = dyn_cast<FConnectLike>(op))
840 return visitConnectLike(connectLikeOp, changedField);
841 if (
auto sendOp = dyn_cast<RefSendOp>(op))
842 return visitRefSend(sendOp, changedField);
843 if (
auto resolveOp = dyn_cast<RefResolveOp>(op))
844 return visitRefResolve(resolveOp, changedField);
845 if (
auto nodeOp = dyn_cast<NodeOp>(op))
846 return visitNode(nodeOp, changedField);
857 auto isOverdefinedFn = [&](Value value) {
858 return isOverdefined(getOrCacheFieldRefFromValue(value));
860 if (llvm::all_of(op->getResults(), isOverdefinedFn))
865 if (op->getNumOperands() > 128) {
866 for (
auto value : op->getResults())
867 markOverdefined(value);
873 SmallVector<Attribute, 8> operandConstants;
874 operandConstants.reserve(op->getNumOperands());
875 bool hasUnknown =
false;
876 for (Value operand : op->getOperands()) {
878 auto &operandLattice = latticeValues[getOrCacheFieldRefFromValue(operand)];
883 if (operandLattice.isUnknown())
888 if (operandLattice.isConstant())
889 operandConstants.push_back(operandLattice.getValue());
891 operandConstants.push_back({});
896 SmallVector<OpFoldResult, 8> foldResults;
897 foldResults.reserve(op->getNumResults());
898 if (failed(op->fold(operandConstants, foldResults))) {
900 logger.startLine() <<
"Folding Failed operation : '" << op->getName()
906 for (
auto value : op->getResults())
907 markOverdefined(value);
912 logger.getOStream() <<
"\n";
913 logger.startLine() <<
"Folding operation : '" << op->getName() <<
"\n";
915 logger.getOStream() <<
"( ";
916 for (
auto cst : operandConstants)
918 logger.getOStream() <<
"{} ";
920 logger.getOStream() << cst <<
" ";
922 logger.getOStream() <<
") -> { ";
924 for (
auto &r : foldResults) {
925 logger.getOStream() << r <<
" ";
928 logger.getOStream() <<
"}\n";
935 if (foldResults.empty())
936 return visitOperation(op, changedField);
939 assert(foldResults.size() == op->getNumResults() &&
"invalid result size");
940 for (
unsigned i = 0, e = foldResults.size(); i != e; ++i) {
942 LatticeValue resultLattice;
943 OpFoldResult foldResult = foldResults[i];
944 if (Attribute foldAttr = dyn_cast<Attribute>(foldResult)) {
945 if (
auto intAttr = dyn_cast<IntegerAttr>(foldAttr))
946 resultLattice = LatticeValue(intAttr);
947 else if (
auto strAttr = dyn_cast<StringAttr>(foldAttr))
948 resultLattice = LatticeValue(strAttr);
950 resultLattice = LatticeValue::getOverdefined();
953 latticeValues[getOrCacheFieldRefFromValue(cast<Value>(foldResult))];
956 mergeLatticeValue(getOrCacheFieldRefFromValue(op->getResult(i)),
961void IMConstPropPass::rewriteModuleBody(FModuleOp module) {
962 auto *body =
module.getBodyBlock();
964 if (!executableBlocks.count(body))
967 auto builder = OpBuilder::atBlockBegin(body);
971 auto cursor = builder.create<firrtl::ConstantOp>(
module.getLoc(), APSInt(1));
972 builder.setInsertionPoint(cursor);
975 DenseMap<std::pair<Attribute, Type>, Operation *> constPool;
977 std::function<Value(Attribute, Type, Location)> getConst =
978 [&](Attribute constantValue, Type type, Location loc) -> Value {
979 auto constIt = constPool.find({constantValue, type});
980 if (constIt != constPool.end()) {
981 auto *cst = constIt->second;
983 cst->setLoc(builder.getFusedLoc({cst->getLoc(), loc}));
984 return cst->getResult(0);
986 OpBuilder::InsertionGuard x(builder);
987 builder.setInsertionPoint(cursor);
992 if (
auto refType = type_dyn_cast<RefType>(type)) {
993 assert(!type_cast<RefType>(type).getForceable() &&
994 "Attempting to materialize rwprobe of constant, shouldn't happen");
995 auto inner = getConst(constantValue, refType.getType(), loc);
997 cst = builder.create<RefSendOp>(loc, inner);
999 cst =
module->getDialect()->materializeConstant(builder, constantValue,
1001 assert(cst &&
"all FIRRTL constants can be materialized");
1002 constPool.insert({{constantValue, type}, cst});
1003 return cst->getResult(0);
1008 auto replaceValueIfPossible = [&](Value value) ->
bool {
1012 auto replaceIfNotConnect = [&value](Value replacement) {
1013 value.replaceUsesWithIf(replacement, [](OpOperand &operand) {
1014 return !isa<FConnectLike>(operand.getOwner()) ||
1015 operand.getOperandNumber() != 0;
1021 if (it == latticeValues.end() || it->second.isOverdefined() ||
1022 it->second.isUnknown())
1028 if (!type_isa<FIRRTLBaseType, RefType, FIntegerType, StringType, BoolType>(
1033 getConst(it->second.getValue(), value.getType(), value.
getLoc());
1035 replaceIfNotConnect(cstValue);
1040 for (
auto &port : body->getArguments())
1041 replaceValueIfPossible(port);
1049 bool aboveCursor =
false;
1050 module.walk<mlir::WalkOrder::PostOrder, mlir::ReverseIterator>(
1051 [&](Operation *op) {
1052 auto dropIfDead = [&](Operation *op, const Twine &debugPrefix) {
1053 if (op->use_empty() &&
1054 (wouldOpBeTriviallyDead(op) || isDeletableWireOrRegOrNode(op))) {
1056 { logger.getOStream() << debugPrefix << " : " << op << "\n"; });
1066 dropIfDead(op,
"Trivially dead materialized constant");
1067 return WalkResult::advance();
1073 return WalkResult::advance();
1077 if (
auto connect = dyn_cast<FConnectLike>(op)) {
1078 if (
auto *destOp =
connect.getDest().getDefiningOp()) {
1079 auto fieldRef = getOrCacheFieldRefFromValue(
connect.getDest());
1085 auto type = type_dyn_cast<FIRRTLType>(
connect.getDest().getType());
1087 return WalkResult::advance();
1088 auto baseType = type_dyn_cast<FIRRTLBaseType>(type);
1089 if (baseType && !baseType.isGround())
1090 return WalkResult::advance();
1092 !isOverdefined(fieldRef)) {
1097 return WalkResult::advance();
1102 if (op->getNumResults() != 1 && !isa<InstanceOp>(op))
1103 return WalkResult::advance();
1106 if (dropIfDead(op,
"Trivially dead"))
1107 return WalkResult::advance();
1111 if (op->hasTrait<mlir::OpTrait::ConstantLike>())
1112 return WalkResult::advance();
1115 builder.setInsertionPoint(op);
1116 bool foldedAny =
false;
1117 for (
auto result : op->getResults())
1118 foldedAny |= replaceValueIfPossible(result);
1124 if (foldedAny && dropIfDead(op,
"Made dead"))
1125 return WalkResult::advance();
1127 return WalkResult::advance();
1132 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)