23 #include "mlir/IR/Dominance.h"
24 #include "mlir/IR/ImplicitLocOpBuilder.h"
25 #include "mlir/IR/Threading.h"
26 #include "mlir/Pass/Pass.h"
27 #include "llvm/ADT/EquivalenceClasses.h"
28 #include "llvm/ADT/SetVector.h"
29 #include "llvm/ADT/TinyPtrVector.h"
30 #include "llvm/ADT/TypeSwitch.h"
31 #include "llvm/Support/Debug.h"
33 #define DEBUG_TYPE "infer-resets"
37 #define GEN_PASS_DEF_INFERRESETS
38 #include "circt/Dialect/FIRRTL/Passes.h.inc"
42 using circt::igraph::InstanceOpInterface;
45 using llvm::BumpPtrAllocator;
46 using llvm::MapVector;
47 using llvm::SmallDenseSet;
48 using llvm::SmallSetVector;
49 using mlir::FailureOr;
50 using mlir::InferTypeOpInterface;
51 using mlir::WalkOrder;
53 using namespace circt;
54 using namespace firrtl;
71 std::optional<unsigned> existingPort;
72 StringAttr newPortName;
74 ResetDomain(Value reset) : reset(reset) {}
78 inline bool operator==(
const ResetDomain &a,
const ResetDomain &b) {
79 return (a.isTop == b.isTop && a.reset == b.reset);
81 inline bool operator!=(
const ResetDomain &a,
const ResetDomain &b) {
88 if (
auto arg = dyn_cast<BlockArgument>(reset)) {
89 auto module = cast<FModuleOp>(arg.getParentRegion()->getParentOp());
90 return {module.getPortNameAttr(arg.getArgNumber()), module};
92 auto op = reset.getDefiningOp();
93 return {op->getAttrOfType<StringAttr>(
"name"),
94 op->getParentOfType<FModuleOp>()};
109 auto it = cache.find(type);
110 if (it != cache.end())
112 auto nullBit = [&]() {
119 .
Case<ClockType>([&](
auto type) {
120 return builder.create<AsClockPrimOp>(nullBit());
122 .Case<AsyncResetType>([&](
auto type) {
123 return builder.create<AsAsyncResetPrimOp>(nullBit());
125 .Case<SIntType, UIntType>([&](
auto type) {
126 return builder.create<ConstantOp>(
127 type, APInt::getZero(type.getWidth().value_or(1)));
129 .Case<BundleType>([&](
auto type) {
130 auto wireOp = builder.create<WireOp>(type);
131 for (
unsigned i = 0, e = type.getNumElements(); i < e; ++i) {
132 auto fieldType = type.getElementTypePreservingConst(i);
135 builder.create<SubfieldOp>(fieldType, wireOp.getResult(), i);
138 return wireOp.getResult();
140 .Case<FVectorType>([&](
auto type) {
141 auto wireOp = builder.create<WireOp>(type);
143 builder, type.getElementTypePreservingConst(), cache);
144 for (
unsigned i = 0, e = type.getNumElements(); i < e; ++i) {
145 auto acc = builder.create<SubindexOp>(zero.getType(),
146 wireOp.getResult(), i);
149 return wireOp.getResult();
151 .Case<ResetType, AnalogType>(
152 [&](
auto type) {
return builder.create<InvalidValueOp>(type); })
154 llvm_unreachable(
"switch handles all types");
157 cache.insert({type, value});
174 Value reset, Value resetValue) {
178 bool resetValueUsed =
false;
180 for (
auto &use : target.getUses()) {
181 Operation *useOp = use.getOwner();
182 builder.setInsertionPoint(useOp);
183 TypeSwitch<Operation *>(useOp)
186 .Case<ConnectOp, MatchingConnectOp>([&](
auto op) {
187 if (op.getDest() != target)
189 LLVM_DEBUG(llvm::dbgs() <<
" - Insert mux into " << op <<
"\n");
191 builder.create<MuxPrimOp>(reset, resetValue, op.getSrc());
192 op.getSrcMutable().assign(muxOp);
193 resetValueUsed =
true;
196 .Case<SubfieldOp>([&](
auto op) {
198 builder.create<SubfieldOp>(resetValue, op.getFieldIndexAttr());
200 resetValueUsed =
true;
202 resetSubValue.erase();
205 .Case<SubindexOp>([&](
auto op) {
207 builder.create<SubindexOp>(resetValue, op.getIndexAttr());
209 resetValueUsed =
true;
211 resetSubValue.erase();
214 .Case<SubaccessOp>([&](
auto op) {
215 if (op.getInput() != target)
218 builder.create<SubaccessOp>(resetValue, op.getIndex());
220 resetValueUsed =
true;
222 resetSubValue.erase();
225 return resetValueUsed;
240 bool operator<(
const ResetSignal &other)
const {
return field < other.field; }
241 bool operator==(
const ResetSignal &other)
const {
242 return field == other.field;
244 bool operator!=(
const ResetSignal &other)
const {
return !(*
this == other); }
264 using ResetDrives = SmallVector<ResetDrive, 1>;
267 using ResetNetwork = llvm::iterator_range<
268 llvm::EquivalenceClasses<ResetSignal>::member_iterator>;
271 enum class ResetKind { Async, Sync };
273 static StringRef resetKindToStringRef(
const ResetKind &kind) {
275 case ResetKind::Async:
277 case ResetKind::Sync:
280 llvm_unreachable(
"unhandled reset kind");
296 static bool isEqual(
const ResetSignal &lhs,
const ResetSignal &rhs) {
302 template <
typename T>
305 case ResetKind::Async:
306 return os <<
"async";
307 case ResetKind::Sync:
417 struct InferResetsPass
418 :
public circt::firrtl::impl::InferResetsBase<InferResetsPass> {
419 void runOnOperation()
override;
420 void runOnOperationInner();
423 using InferResetsBase::InferResetsBase;
424 InferResetsPass(
const InferResetsPass &other) : InferResetsBase(other) {}
429 void traceResets(CircuitOp circuit);
430 void traceResets(InstanceOp inst);
431 void traceResets(Value dst, Value src, Location loc);
432 void traceResets(Value value);
433 void traceResets(Type dstType, Value dst,
unsigned dstID, Type srcType,
434 Value src,
unsigned srcID, Location loc);
436 LogicalResult inferAndUpdateResets();
437 FailureOr<ResetKind> inferReset(ResetNetwork net);
438 LogicalResult updateReset(ResetNetwork net, ResetKind kind);
444 LogicalResult collectAnnos(CircuitOp circuit);
450 FailureOr<std::optional<Value>> collectAnnos(FModuleOp module);
452 LogicalResult buildDomains(CircuitOp circuit);
453 void buildDomains(FModuleOp module,
const InstancePath &instPath,
455 unsigned indent = 0);
457 void determineImpl();
458 void determineImpl(FModuleOp module, ResetDomain &domain);
460 LogicalResult implementFullReset();
461 LogicalResult implementFullReset(FModuleOp module, ResetDomain &domain);
462 void implementFullReset(Operation *op, FModuleOp module, Value actualReset);
464 LogicalResult verifyNoAbstractReset();
470 ResetNetwork getResetNetwork(ResetSignal signal) {
471 return llvm::make_range(resetClasses.findLeader(signal),
472 resetClasses.member_end());
476 ResetDrives &getResetDrives(ResetNetwork net) {
477 return resetDrives[*net.begin()];
482 ResetSignal guessRoot(ResetNetwork net);
483 ResetSignal guessRoot(ResetSignal signal) {
484 return guessRoot(getResetNetwork(signal));
491 llvm::EquivalenceClasses<ResetSignal> resetClasses;
494 DenseMap<ResetSignal, ResetDrives> resetDrives;
499 DenseMap<Operation *, Value> annotatedResets;
503 MapVector<FModuleOp, SmallVector<std::pair<ResetDomain, InstancePath>, 1>>
510 std::unique_ptr<InstancePathCache> instancePathCache;
514 void InferResetsPass::runOnOperation() {
515 runOnOperationInner();
516 resetClasses = llvm::EquivalenceClasses<ResetSignal>();
518 annotatedResets.clear();
520 instancePathCache.reset(
nullptr);
521 markAnalysesPreserved<InstanceGraph>();
524 void InferResetsPass::runOnOperationInner() {
525 instanceGraph = &getAnalysis<InstanceGraph>();
526 instancePathCache = std::make_unique<InstancePathCache>(*instanceGraph);
529 traceResets(getOperation());
532 if (failed(inferAndUpdateResets()))
533 return signalPassFailure();
536 if (failed(collectAnnos(getOperation())))
537 return signalPassFailure();
540 if (failed(buildDomains(getOperation())))
541 return signalPassFailure();
547 if (failed(implementFullReset()))
548 return signalPassFailure();
551 if (failed(verifyNoAbstractReset()))
552 return signalPassFailure();
556 return std::make_unique<InferResetsPass>();
559 ResetSignal InferResetsPass::guessRoot(ResetNetwork net) {
560 ResetDrives &drives = getResetDrives(net);
561 ResetSignal bestSignal = *net.begin();
562 unsigned bestNumDrives = -1;
564 for (
auto signal : net) {
566 if (isa_and_nonnull<InvalidValueOp>(
567 signal.field.getValue().getDefiningOp()))
572 unsigned numDrives = 0;
573 for (
auto &drive : drives)
574 if (drive.dst == signal)
580 if (numDrives < bestNumDrives) {
581 bestNumDrives = numDrives;
600 .
Case<BundleType>([](
auto type) {
602 for (
auto e : type.getElements())
607 [](
auto type) {
return getMaxFieldID(type.getElementType()) + 1; })
608 .Default([](
auto) {
return 0; });
611 static unsigned getFieldID(BundleType type,
unsigned index) {
612 assert(index < type.getNumElements());
614 for (
unsigned i = 0; i < index; ++i)
622 assert(type.getNumElements() &&
"Bundle must have >0 fields");
624 for (
const auto &e : llvm::enumerate(type.getElements())) {
626 if (fieldID < numSubfields)
628 fieldID -= numSubfields;
630 assert(
false &&
"field id outside bundle");
636 if (oldType.isGround()) {
642 if (
auto bundleType = type_dyn_cast<BundleType>(oldType)) {
650 if (
auto vectorType = type_dyn_cast<FVectorType>(oldType)) {
651 if (vectorType.getNumElements() == 0)
668 if (
auto arg = dyn_cast<BlockArgument>(value)) {
669 auto module = cast<FModuleOp>(arg.getOwner()->getParentOp());
670 string += module.getPortName(arg.getArgNumber());
674 auto *op = value.getDefiningOp();
675 return TypeSwitch<Operation *, bool>(op)
676 .Case<InstanceOp, MemOp>([&](
auto op) {
677 string += op.getName();
680 op.getPortName(cast<OpResult>(value).getResultNumber()).getValue();
683 .Case<WireOp, NodeOp, RegOp, RegResetOp>([&](
auto op) {
684 string += op.getName();
687 .Default([](
auto) {
return false; });
691 SmallString<64> name;
696 auto type = value.getType();
699 if (
auto bundleType = type_dyn_cast<BundleType>(type)) {
702 auto &element = bundleType.getElements()[index];
705 string += element.name.getValue();
708 localID = localID -
getFieldID(bundleType, index);
709 }
else if (
auto vecType = type_dyn_cast<FVectorType>(type)) {
712 type = vecType.getElementType();
719 llvm_unreachable(
"unsupported type");
731 return TypeSwitch<Type, bool>(type)
733 return type.getRecursiveTypeProperties().hasUninferredReset;
735 .Default([](
auto) {
return false; });
742 void InferResetsPass::traceResets(CircuitOp circuit) {
744 llvm::dbgs() <<
"\n";
745 debugHeader(
"Tracing uninferred resets") <<
"\n\n";
748 SmallVector<std::pair<FModuleOp, SmallVector<Operation *>>> moduleToOps;
750 for (
auto module : circuit.getOps<FModuleOp>())
751 moduleToOps.push_back({module, {}});
753 hw::InnerRefNamespace irn{getAnalysis<SymbolTable>(),
754 getAnalysis<hw::InnerSymbolTableCollection>()};
756 mlir::parallelForEach(circuit.getContext(), moduleToOps, [](
auto &e) {
757 e.first.walk([&](Operation *op) {
761 op->getResultTypes(),
762 [](mlir::Type type) { return typeContainsReset(type); }) ||
763 llvm::any_of(op->getOperandTypes(), typeContainsReset))
764 e.second.push_back(op);
768 for (
auto &[_, ops] : moduleToOps)
769 for (
auto *op : ops) {
770 TypeSwitch<Operation *>(op)
771 .Case<FConnectLike>([&](
auto op) {
772 traceResets(op.getDest(), op.getSrc(), op.getLoc());
774 .Case<InstanceOp>([&](
auto op) { traceResets(op); })
775 .Case<RefSendOp>([&](
auto op) {
777 traceResets(op.getType().getType(), op.getResult(), 0,
778 op.getBase().getType().getPassiveType(), op.getBase(),
781 .Case<RefResolveOp>([&](
auto op) {
783 traceResets(op.getType(), op.getResult(), 0,
784 op.getRef().getType().getType(), op.getRef(), 0,
787 .Case<Forceable>([&](Forceable op) {
788 if (
auto node = dyn_cast<NodeOp>(op.getOperation()))
789 traceResets(node.getResult(), node.getInput(), node.getLoc());
791 if (op.isForceable())
792 traceResets(op.getDataType(), op.getData(), 0, op.getDataType(),
793 op.getDataRef(), 0, op.getLoc());
795 .Case<RWProbeOp>([&](RWProbeOp op) {
796 auto ist = irn.lookup(op.getTarget());
799 auto baseType = op.getType().getType();
800 traceResets(baseType, op.getResult(), 0, baseType.getPassiveType(),
801 ref.getValue(), ref.getFieldID(), op.getLoc());
803 .Case<UninferredResetCastOp, ConstCastOp, RefCastOp>([&](
auto op) {
804 traceResets(op.getResult(), op.getInput(), op.getLoc());
806 .Case<InvalidValueOp>([&](
auto op) {
815 auto type = op.getType();
818 LLVM_DEBUG(llvm::dbgs() <<
"Uniquify " << op <<
"\n");
819 ImplicitLocOpBuilder builder(op->getLoc(), op);
821 llvm::make_early_inc_range(llvm::drop_begin(op->getUses()))) {
827 auto newOp = builder.create<InvalidValueOp>(type);
832 .Case<SubfieldOp>([&](
auto op) {
835 BundleType bundleType = op.getInput().getType();
836 auto index = op.getFieldIndex();
837 traceResets(op.getType(), op.getResult(), 0,
838 bundleType.getElements()[index].type, op.getInput(),
842 .Case<SubindexOp, SubaccessOp>([&](
auto op) {
855 FVectorType vectorType = op.getInput().getType();
856 traceResets(op.getType(), op.getResult(), 0,
857 vectorType.getElementType(), op.getInput(),
861 .Case<RefSubOp>([&](RefSubOp op) {
863 auto aggType = op.getInput().getType().getType();
864 uint64_t fieldID = TypeSwitch<FIRRTLBaseType, uint64_t>(aggType)
865 .Case<FVectorType>([](
auto type) {
868 .Case<BundleType>([&](
auto type) {
871 traceResets(op.getType(), op.getResult(), 0,
872 op.getResult().getType(), op.getInput(), fieldID,
880 void InferResetsPass::traceResets(InstanceOp inst) {
882 auto module = inst.getReferencedModule<FModuleOp>(*instanceGraph);
885 LLVM_DEBUG(llvm::dbgs() <<
"Visiting instance " << inst.getName() <<
"\n");
888 for (
const auto &it : llvm::enumerate(inst.getResults())) {
889 auto dir = module.getPortDirection(it.index());
890 Value dstPort = module.getArgument(it.index());
891 Value srcPort = it.value();
892 if (dir == Direction::Out)
893 std::swap(dstPort, srcPort);
894 traceResets(dstPort, srcPort, it.value().getLoc());
900 void InferResetsPass::traceResets(Value dst, Value src, Location loc) {
902 traceResets(dst.getType(), dst, 0, src.getType(), src, 0, loc);
907 void InferResetsPass::traceResets(Type dstType, Value dst,
unsigned dstID,
908 Type srcType, Value src,
unsigned srcID,
910 if (
auto dstBundle = type_dyn_cast<BundleType>(dstType)) {
911 auto srcBundle = type_cast<BundleType>(srcType);
912 for (
unsigned dstIdx = 0, e = dstBundle.getNumElements(); dstIdx < e;
914 auto dstField = dstBundle.getElements()[dstIdx].name;
915 auto srcIdx = srcBundle.getElementIndex(dstField);
918 auto &dstElt = dstBundle.getElements()[dstIdx];
919 auto &srcElt = srcBundle.getElements()[*srcIdx];
921 traceResets(srcElt.type, src, srcID +
getFieldID(srcBundle, *srcIdx),
922 dstElt.type, dst, dstID +
getFieldID(dstBundle, dstIdx),
925 traceResets(dstElt.type, dst, dstID +
getFieldID(dstBundle, dstIdx),
926 srcElt.type, src, srcID +
getFieldID(srcBundle, *srcIdx),
933 if (
auto dstVector = type_dyn_cast<FVectorType>(dstType)) {
934 auto srcVector = type_cast<FVectorType>(srcType);
935 auto srcElType = srcVector.getElementType();
936 auto dstElType = dstVector.getElementType();
949 traceResets(dstElType, dst, dstID +
getFieldID(dstVector), srcElType, src,
955 if (
auto dstRef = type_dyn_cast<RefType>(dstType)) {
956 auto srcRef = type_cast<RefType>(srcType);
957 return traceResets(dstRef.getType(), dst, dstID, srcRef.getType(), src,
962 auto dstBase = type_dyn_cast<FIRRTLBaseType>(dstType);
963 auto srcBase = type_dyn_cast<FIRRTLBaseType>(srcType);
964 if (!dstBase || !srcBase)
966 if (!type_isa<ResetType>(dstBase) && !type_isa<ResetType>(srcBase))
971 LLVM_DEBUG(llvm::dbgs() <<
"Visiting driver '" << dstField <<
"' = '"
972 << srcField <<
"' (" << dstType <<
" = " << srcType
978 ResetSignal dstLeader =
979 *resetClasses.findLeader(resetClasses.insert({dstField, dstBase}));
980 ResetSignal srcLeader =
981 *resetClasses.findLeader(resetClasses.insert({srcField, srcBase}));
984 ResetSignal unionLeader = *resetClasses.unionSets(dstLeader, srcLeader);
985 assert(unionLeader == dstLeader || unionLeader == srcLeader);
990 if (dstLeader != srcLeader) {
991 auto &unionDrives = resetDrives[unionLeader];
992 auto mergedDrivesIt =
993 resetDrives.find(unionLeader == dstLeader ? srcLeader : dstLeader);
994 if (mergedDrivesIt != resetDrives.end()) {
995 unionDrives.append(mergedDrivesIt->second);
996 resetDrives.erase(mergedDrivesIt);
1002 resetDrives[unionLeader].push_back(
1003 {{dstField, dstBase}, {srcField, srcBase}, loc});
1010 LogicalResult InferResetsPass::inferAndUpdateResets() {
1012 llvm::dbgs() <<
"\n";
1015 for (
auto it = resetClasses.begin(),
end = resetClasses.end(); it !=
end;
1017 if (!it->isLeader())
1019 ResetNetwork net = llvm::make_range(resetClasses.member_begin(it),
1020 resetClasses.member_end());
1023 auto kind = inferReset(net);
1028 if (failed(updateReset(net, *kind)))
1034 FailureOr<ResetKind> InferResetsPass::inferReset(ResetNetwork net) {
1035 LLVM_DEBUG(llvm::dbgs() <<
"Inferring reset network with "
1036 << std::distance(net.begin(), net.end())
1040 unsigned asyncDrives = 0;
1041 unsigned syncDrives = 0;
1042 unsigned invalidDrives = 0;
1043 for (ResetSignal signal : net) {
1045 if (type_isa<AsyncResetType>(signal.type))
1047 else if (type_isa<UIntType>(signal.type))
1050 isa_and_nonnull<InvalidValueOp>(
1051 signal.field.getValue().getDefiningOp()))
1054 LLVM_DEBUG(llvm::dbgs() <<
"- Found " << asyncDrives <<
" async, "
1055 << syncDrives <<
" sync, " << invalidDrives
1056 <<
" invalid drives\n");
1059 if (asyncDrives == 0 && syncDrives == 0 && invalidDrives == 0) {
1060 ResetSignal root = guessRoot(net);
1061 auto diag = mlir::emitError(root.field.getValue().getLoc())
1062 <<
"reset network never driven with concrete type";
1063 for (ResetSignal signal : net)
1064 diag.attachNote(signal.field.getLoc()) <<
"here: ";
1069 if (asyncDrives > 0 && syncDrives > 0) {
1070 ResetSignal root = guessRoot(net);
1071 bool majorityAsync = asyncDrives >= syncDrives;
1072 auto diag = mlir::emitError(root.field.getValue().getLoc())
1074 SmallString<32> fieldName;
1076 diag <<
" \"" << fieldName <<
"\"";
1077 diag <<
" simultaneously connected to async and sync resets";
1078 diag.attachNote(root.field.getValue().getLoc())
1079 <<
"majority of connections to this reset are "
1080 << (majorityAsync ?
"async" :
"sync");
1081 for (
auto &drive : getResetDrives(net)) {
1082 if ((type_isa<AsyncResetType>(drive.dst.type) && !majorityAsync) ||
1083 (type_isa<AsyncResetType>(drive.src.type) && !majorityAsync) ||
1084 (type_isa<UIntType>(drive.dst.type) && majorityAsync) ||
1085 (type_isa<UIntType>(drive.src.type) && majorityAsync))
1086 diag.attachNote(drive.loc)
1087 << (type_isa<AsyncResetType>(drive.src.type) ?
"async" :
"sync")
1096 auto kind = (asyncDrives ? ResetKind::Async : ResetKind::Sync);
1097 LLVM_DEBUG(llvm::dbgs() <<
"- Inferred as " << kind <<
"\n");
1105 LogicalResult InferResetsPass::updateReset(ResetNetwork net, ResetKind kind) {
1106 LLVM_DEBUG(llvm::dbgs() <<
"Updating reset network with "
1107 << std::distance(net.begin(), net.end())
1108 <<
" nodes to " << kind <<
"\n");
1112 if (kind == ResetKind::Async)
1120 SmallSetVector<Operation *, 16> worklist;
1121 SmallDenseSet<Operation *> moduleWorklist;
1122 SmallDenseSet<std::pair<Operation *, Operation *>> extmoduleWorklist;
1123 for (
auto signal : net) {
1124 Value value = signal.field.getValue();
1125 if (!isa<BlockArgument>(value) &&
1126 !isa_and_nonnull<WireOp, RegOp, RegResetOp, InstanceOp, InvalidValueOp,
1127 ConstCastOp, RefCastOp, UninferredResetCastOp,
1128 RWProbeOp>(value.getDefiningOp()))
1130 if (updateReset(signal.field, resetType)) {
1131 for (
auto user : value.getUsers())
1132 worklist.insert(user);
1133 if (
auto blockArg = dyn_cast<BlockArgument>(value))
1134 moduleWorklist.insert(blockArg.getOwner()->getParentOp());
1135 else if (
auto instOp = value.getDefiningOp<InstanceOp>()) {
1136 if (
auto extmodule =
1137 instOp.getReferencedModule<FExtModuleOp>(*instanceGraph))
1138 extmoduleWorklist.insert({extmodule, instOp});
1139 }
else if (
auto uncast = value.getDefiningOp<UninferredResetCastOp>()) {
1140 uncast.replaceAllUsesWith(uncast.getInput());
1150 while (!worklist.empty()) {
1151 auto *wop = worklist.pop_back_val();
1152 SmallVector<Type, 2> types;
1153 if (
auto op = dyn_cast<InferTypeOpInterface>(wop)) {
1155 SmallVector<Type, 2> types;
1156 if (failed(op.inferReturnTypes(op->getContext(), op->getLoc(),
1157 op->getOperands(), op->getAttrDictionary(),
1158 op->getPropertiesStorage(),
1159 op->getRegions(), types)))
1164 for (
auto it : llvm::zip(op->getResults(), types)) {
1165 auto newType = std::get<1>(it);
1166 if (std::get<0>(it).getType() == newType)
1168 std::get<0>(it).setType(newType);
1169 for (
auto *user : std::get<0>(it).getUsers())
1170 worklist.insert(user);
1172 LLVM_DEBUG(llvm::dbgs() <<
"- Inferred " << *op <<
"\n");
1173 }
else if (
auto uop = dyn_cast<UninferredResetCastOp>(wop)) {
1174 for (
auto *user : uop.getResult().getUsers())
1175 worklist.insert(user);
1176 uop.replaceAllUsesWith(uop.getInput());
1177 LLVM_DEBUG(llvm::dbgs() <<
"- Inferred " << uop <<
"\n");
1183 for (
auto *op : moduleWorklist) {
1184 auto module = dyn_cast<FModuleOp>(op);
1188 SmallVector<Attribute> argTypes;
1189 argTypes.reserve(module.getNumPorts());
1190 for (
auto arg : module.getArguments())
1193 module->setAttr(FModuleLike::getPortTypesAttrName(),
1195 LLVM_DEBUG(llvm::dbgs()
1196 <<
"- Updated type of module '" << module.getName() <<
"'\n");
1200 for (
auto pair : extmoduleWorklist) {
1201 auto module = cast<FExtModuleOp>(pair.first);
1202 auto instOp = cast<InstanceOp>(pair.second);
1204 SmallVector<Attribute> types;
1205 for (
auto type : instOp.getResultTypes())
1208 module->setAttr(FModuleLike::getPortTypesAttrName(),
1210 LLVM_DEBUG(llvm::dbgs()
1211 <<
"- Updated type of extmodule '" << module.getName() <<
"'\n");
1221 if (oldType.isGround()) {
1227 if (
auto bundleType = type_dyn_cast<BundleType>(oldType)) {
1229 SmallVector<BundleType::BundleElement> fields(bundleType.begin(),
1232 fields[index].type, fieldID -
getFieldID(bundleType, index), fieldType);
1237 if (
auto vectorType = type_dyn_cast<FVectorType>(oldType)) {
1238 auto newType =
updateType(vectorType.getElementType(),
1239 fieldID -
getFieldID(vectorType), fieldType);
1241 vectorType.isConst());
1244 llvm_unreachable(
"unknown aggregate type");
1251 auto oldType = type_cast<FIRRTLType>(field.
getValue().getType());
1257 if (oldType == newType)
1259 LLVM_DEBUG(llvm::dbgs() <<
"- Updating '" << field <<
"' from " << oldType
1260 <<
" to " << newType <<
"\n");
1269 LogicalResult InferResetsPass::collectAnnos(CircuitOp circuit) {
1271 llvm::dbgs() <<
"\n";
1272 debugHeader(
"Gather reset annotations") <<
"\n\n";
1274 SmallVector<std::pair<FModuleOp, std::optional<Value>>> results;
1275 for (
auto module : circuit.getOps<FModuleOp>())
1276 results.push_back({module, {}});
1278 if (failed(mlir::failableParallelForEach(
1279 circuit.getContext(), results, [&](
auto &moduleAndResult) {
1280 auto result = collectAnnos(moduleAndResult.first);
1283 moduleAndResult.second = *result;
1288 for (
auto [module, reset] : results)
1289 if (reset.has_value())
1290 annotatedResets.insert({module, *reset});
1294 FailureOr<std::optional<Value>>
1295 InferResetsPass::collectAnnos(FModuleOp module) {
1296 bool anyFailed =
false;
1297 SmallSetVector<std::pair<Annotation, Location>, 4> conflictingAnnos;
1301 bool ignore =
false;
1302 AnnotationSet::removeAnnotations(module, [&](
Annotation anno) {
1305 conflictingAnnos.insert({anno, module.getLoc()});
1310 module.emitError(
"''FullResetAnnotation' cannot target module; must "
1311 "target port or wire/node instead");
1322 auto checkAnnotations = [&](
Annotation anno, Value arg) {
1324 ResetKind expectedResetKind;
1325 if (
auto rt = anno.
getMember<StringAttr>(
"resetType")) {
1327 expectedResetKind = ResetKind::Sync;
1328 }
else if (rt ==
"async") {
1329 expectedResetKind = ResetKind::Async;
1331 mlir::emitError(arg.getLoc(),
1332 "'FullResetAnnotation' requires resetType == 'sync' "
1333 "| 'async', but got resetType == ")
1339 mlir::emitError(arg.getLoc(),
1340 "'FullResetAnnotation' requires resetType == "
1341 "'sync' | 'async', but got no resetType");
1346 bool isAsync = expectedResetKind == ResetKind::Async;
1347 bool validUint =
false;
1348 if (
auto uintT = dyn_cast<UIntType>(arg.getType()))
1349 validUint = uintT.getWidth() == 1;
1350 if ((isAsync && !isa<AsyncResetType>(arg.getType())) ||
1351 (!isAsync && !validUint)) {
1352 auto kind = resetKindToStringRef(expectedResetKind);
1353 mlir::emitError(arg.getLoc(),
1354 "'FullResetAnnotation' with resetType == '")
1355 << kind <<
"' must target " << kind <<
" reset, but targets "
1362 conflictingAnnos.insert({anno, reset.getLoc()});
1368 mlir::emitError(arg.getLoc(),
1369 "'ExcludeFromFullResetAnnotation' cannot "
1370 "target port/wire/node; must target module instead");
1376 AnnotationSet::removePortAnnotations(module,
1378 Value arg = module.getArgument(argNum);
1379 return checkAnnotations(anno, arg);
1385 module.getBody().walk([&](Operation *op) {
1387 if (!isa<WireOp, NodeOp>(op)) {
1392 "reset annotations must target module, port, or wire/node");
1399 AnnotationSet::removeAnnotations(op, [&](
Annotation anno) {
1400 auto arg = op->getResult(0);
1401 return checkAnnotations(anno, arg);
1410 if (!ignore && !reset) {
1411 LLVM_DEBUG(llvm::dbgs()
1412 <<
"No reset annotation for " << module.getName() <<
"\n");
1413 return std::optional<Value>();
1417 if (conflictingAnnos.size() > 1) {
1418 auto diag = module.emitError(
"multiple reset annotations on module '")
1419 << module.getName() <<
"'";
1420 for (
auto &annoAndLoc : conflictingAnnos)
1421 diag.attachNote(annoAndLoc.second)
1422 <<
"conflicting " << annoAndLoc.first.getClassAttr() <<
":";
1428 llvm::dbgs() <<
"Annotated reset for " << module.getName() <<
": ";
1430 llvm::dbgs() <<
"no domain\n";
1431 else if (
auto arg = dyn_cast<BlockArgument>(reset))
1432 llvm::dbgs() <<
"port " << module.getPortName(arg.getArgNumber()) <<
"\n";
1434 llvm::dbgs() <<
"wire "
1435 << reset.getDefiningOp()->getAttrOfType<StringAttr>(
"name")
1441 return std::optional<Value>(reset);
1453 LogicalResult InferResetsPass::buildDomains(CircuitOp circuit) {
1455 llvm::dbgs() <<
"\n";
1456 debugHeader(
"Build full reset domains") <<
"\n\n";
1460 auto &instGraph = getAnalysis<InstanceGraph>();
1461 auto module = dyn_cast<FModuleOp>(*instGraph.getTopLevelNode()->getModule());
1463 LLVM_DEBUG(llvm::dbgs()
1464 <<
"Skipping circuit because main module is no `firrtl.module`");
1467 buildDomains(module,
InstancePath{}, Value{}, instGraph);
1470 bool anyFailed =
false;
1471 for (
auto &it : domains) {
1472 auto module = cast<FModuleOp>(it.first);
1473 auto &domainConflicts = it.second;
1474 if (domainConflicts.size() <= 1)
1478 SmallDenseSet<Value> printedDomainResets;
1479 auto diag = module.emitError(
"module '")
1481 <<
"' instantiated in different reset domains";
1482 for (
auto &it : domainConflicts) {
1483 ResetDomain &domain = it.first;
1484 const auto &path = it.second;
1485 auto inst = path.leaf();
1486 auto loc = path.empty() ? module.getLoc() : inst.getLoc();
1487 auto ¬e = diag.attachNote(loc);
1491 note <<
"root instance";
1493 note <<
"instance '";
1496 [&](InstanceOpInterface inst) { note << inst.getInstanceName(); },
1497 [&]() { note <<
"/"; });
1505 note <<
" reset domain rooted at '" << nameAndModule.first.getValue()
1506 <<
"' of module '" << nameAndModule.second.getName() <<
"'";
1509 if (printedDomainResets.insert(domain.reset).second) {
1510 diag.attachNote(domain.reset.getLoc())
1511 <<
"reset domain '" << nameAndModule.first.getValue()
1512 <<
"' of module '" << nameAndModule.second.getName()
1513 <<
"' declared here:";
1516 note <<
" no reset domain";
1519 return failure(anyFailed);
1522 void InferResetsPass::buildDomains(FModuleOp module,
1527 llvm::dbgs().indent(indent * 2) <<
"Visiting ";
1528 if (instPath.
empty())
1529 llvm::dbgs() <<
"$root";
1531 llvm::dbgs() << instPath.
leaf().getInstanceName();
1532 llvm::dbgs() <<
" (" << module.getName() <<
")\n";
1536 ResetDomain domain(parentReset);
1537 auto it = annotatedResets.find(module);
1538 if (it != annotatedResets.end()) {
1539 domain.isTop =
true;
1540 domain.reset = it->second;
1546 auto &entries = domains[module];
1547 if (llvm::all_of(entries,
1548 [&](
const auto &entry) {
return entry.first != domain; }))
1549 entries.push_back({domain, instPath});
1552 for (
auto *record : *instGraph[module]) {
1553 auto submodule = dyn_cast<FModuleOp>(*record->getTarget()->getModule());
1557 instancePathCache->appendInstance(instPath, record->getInstance());
1558 buildDomains(submodule, childPath, domain.reset, instGraph, indent + 1);
1563 void InferResetsPass::determineImpl() {
1565 llvm::dbgs() <<
"\n";
1566 debugHeader(
"Determine implementation") <<
"\n\n";
1568 for (
auto &it : domains) {
1569 auto module = cast<FModuleOp>(it.first);
1570 auto &domain = it.second.back().first;
1571 determineImpl(module, domain);
1591 void InferResetsPass::determineImpl(FModuleOp module, ResetDomain &domain) {
1594 LLVM_DEBUG(llvm::dbgs() <<
"Planning reset for " << module.getName() <<
"\n");
1599 LLVM_DEBUG(llvm::dbgs() <<
"- Rooting at local value "
1601 domain.existingValue = domain.reset;
1602 if (
auto blockArg = dyn_cast<BlockArgument>(domain.reset))
1603 domain.existingPort = blockArg.getArgNumber();
1610 auto neededType = domain.reset.getType();
1611 LLVM_DEBUG(llvm::dbgs() <<
"- Looking for existing port " << neededName
1613 auto portNames = module.getPortNames();
1614 auto ports = llvm::zip(portNames, module.getArguments());
1615 auto portIt = llvm::find_if(
1616 ports, [&](
auto port) {
return std::get<0>(port) == neededName; });
1617 if (portIt != ports.end() && std::get<1>(*portIt).getType() == neededType) {
1618 LLVM_DEBUG(llvm::dbgs()
1619 <<
"- Reusing existing port " << neededName <<
"\n");
1620 domain.existingValue = std::get<1>(*portIt);
1621 domain.existingPort = std::distance(ports.begin(), portIt);
1631 if (portIt != ports.end()) {
1632 LLVM_DEBUG(llvm::dbgs()
1633 <<
"- Existing " << neededName <<
" has incompatible type "
1634 << std::get<1>(*portIt).getType() <<
"\n");
1636 unsigned suffix = 0;
1640 Twine(
"_") + Twine(suffix++));
1641 }
while (llvm::is_contained(portNames, newName));
1642 LLVM_DEBUG(llvm::dbgs()
1643 <<
"- Creating uniquified port " << newName <<
"\n");
1644 domain.newPortName = newName;
1650 LLVM_DEBUG(llvm::dbgs() <<
"- Creating new port " << neededName <<
"\n");
1651 domain.newPortName = neededName;
1659 LogicalResult InferResetsPass::implementFullReset() {
1661 llvm::dbgs() <<
"\n";
1664 for (
auto &it : domains)
1665 if (failed(implementFullReset(cast<FModuleOp>(it.first),
1666 it.second.back().first)))
1676 LogicalResult InferResetsPass::implementFullReset(FModuleOp module,
1677 ResetDomain &domain) {
1678 LLVM_DEBUG(llvm::dbgs() <<
"Implementing full reset for " << module.getName()
1682 if (!domain.reset) {
1683 LLVM_DEBUG(llvm::dbgs()
1684 <<
"- Skipping because module explicitly has no domain\n");
1689 Value actualReset = domain.existingValue;
1690 if (domain.newPortName) {
1691 PortInfo portInfo{domain.newPortName,
1692 domain.reset.getType(),
1695 domain.reset.getLoc()};
1696 module.insertPorts({{0, portInfo}});
1697 actualReset = module.getArgument(0);
1698 LLVM_DEBUG(llvm::dbgs()
1699 <<
"- Inserted port " << domain.newPortName <<
"\n");
1703 llvm::dbgs() <<
"- Using ";
1704 if (
auto blockArg = dyn_cast<BlockArgument>(actualReset))
1705 llvm::dbgs() <<
"port #" << blockArg.getArgNumber() <<
" ";
1707 llvm::dbgs() <<
"wire/node ";
1713 SmallVector<Operation *> opsToUpdate;
1714 module.walk([&](Operation *op) {
1715 if (isa<InstanceOp, RegOp, RegResetOp>(op))
1716 opsToUpdate.push_back(op);
1723 if (!isa<BlockArgument>(actualReset)) {
1724 mlir::DominanceInfo dom(module);
1729 auto *resetOp = actualReset.getDefiningOp();
1730 if (!opsToUpdate.empty() && !dom.dominates(resetOp, opsToUpdate[0])) {
1731 LLVM_DEBUG(llvm::dbgs()
1732 <<
"- Reset doesn't dominate all uses, needs to be moved\n");
1736 auto nodeOp = dyn_cast<NodeOp>(resetOp);
1737 if (nodeOp && !dom.dominates(nodeOp.getInput(), opsToUpdate[0])) {
1738 LLVM_DEBUG(llvm::dbgs()
1739 <<
"- Promoting node to wire for move: " << nodeOp <<
"\n");
1740 auto builder = ImplicitLocOpBuilder::atBlockBegin(nodeOp.getLoc(),
1741 nodeOp->getBlock());
1742 auto wireOp = builder.create<WireOp>(
1743 nodeOp.getResult().getType(), nodeOp.getNameAttr(),
1744 nodeOp.getNameKindAttr(), nodeOp.getAnnotationsAttr(),
1745 nodeOp.getInnerSymAttr(), nodeOp.getForceableAttr());
1747 nodeOp->replaceAllUsesWith(wireOp);
1748 nodeOp->removeAttr(nodeOp.getInnerSymAttrName());
1752 nodeOp.setNameKind(NameKindEnum::DroppableName);
1753 nodeOp.setAnnotationsAttr(
ArrayAttr::get(builder.getContext(), {}));
1754 builder.setInsertionPointAfter(nodeOp);
1755 emitConnect(builder, wireOp.getResult(), nodeOp.getResult());
1757 actualReset = wireOp.getResult();
1758 domain.existingValue = wireOp.getResult();
1763 Block *targetBlock = dom.findNearestCommonDominator(
1764 resetOp->getBlock(), opsToUpdate[0]->getBlock());
1766 if (targetBlock != resetOp->getBlock())
1767 llvm::dbgs() <<
"- Needs to be moved to different block\n";
1776 auto getParentInBlock = [](Operation *op,
Block *block) {
1777 while (op && op->getBlock() != block)
1778 op = op->getParentOp();
1781 auto *resetOpInTarget = getParentInBlock(resetOp, targetBlock);
1782 auto *firstOpInTarget = getParentInBlock(opsToUpdate[0], targetBlock);
1788 if (resetOpInTarget->isBeforeInBlock(firstOpInTarget))
1789 resetOp->moveBefore(resetOpInTarget);
1791 resetOp->moveBefore(firstOpInTarget);
1796 for (
auto *op : opsToUpdate)
1797 implementFullReset(op, module, actualReset);
1804 void InferResetsPass::implementFullReset(Operation *op, FModuleOp module,
1805 Value actualReset) {
1806 ImplicitLocOpBuilder builder(op->getLoc(), op);
1809 if (
auto instOp = dyn_cast<InstanceOp>(op)) {
1813 auto refModule = instOp.getReferencedModule<FModuleOp>(*instanceGraph);
1816 auto domainIt = domains.find(refModule);
1817 if (domainIt == domains.end())
1819 auto &domain = domainIt->second.back().first;
1822 LLVM_DEBUG(llvm::dbgs()
1823 <<
"- Update instance '" << instOp.getName() <<
"'\n");
1827 if (domain.newPortName) {
1828 LLVM_DEBUG(llvm::dbgs() <<
" - Adding new result as reset\n");
1830 auto newInstOp = instOp.cloneAndInsertPorts(
1832 {domain.newPortName,
1833 type_cast<FIRRTLBaseType>(actualReset.getType()),
1835 instReset = newInstOp.getResult(0);
1838 instOp.replaceAllUsesWith(newInstOp.getResults().drop_front());
1839 instanceGraph->replaceInstance(instOp, newInstOp);
1842 }
else if (domain.existingPort.has_value()) {
1843 auto idx = *domain.existingPort;
1844 instReset = instOp.getResult(idx);
1845 LLVM_DEBUG(llvm::dbgs() <<
" - Using result #" << idx <<
" as reset\n");
1855 assert(instReset && actualReset);
1856 builder.setInsertionPointAfter(instOp);
1862 if (
auto regOp = dyn_cast<RegOp>(op)) {
1866 LLVM_DEBUG(llvm::dbgs() <<
"- Adding full reset to " << regOp <<
"\n");
1868 auto newRegOp = builder.create<RegResetOp>(
1869 regOp.getResult().getType(), regOp.getClockVal(), actualReset, zero,
1870 regOp.getNameAttr(), regOp.getNameKindAttr(), regOp.getAnnotations(),
1871 regOp.getInnerSymAttr(), regOp.getForceableAttr());
1872 regOp.getResult().replaceAllUsesWith(newRegOp.getResult());
1873 if (regOp.getForceable())
1874 regOp.getRef().replaceAllUsesWith(newRegOp.getRef());
1880 if (
auto regOp = dyn_cast<RegResetOp>(op)) {
1883 if (type_isa<AsyncResetType>(regOp.getResetSignal().getType()) ||
1884 type_isa<UIntType>(actualReset.getType())) {
1885 LLVM_DEBUG(llvm::dbgs() <<
"- Skipping (has reset) " << regOp <<
"\n");
1888 if (failed(regOp.verifyInvariants()))
1889 signalPassFailure();
1892 LLVM_DEBUG(llvm::dbgs() <<
"- Updating reset of " << regOp <<
"\n");
1894 auto reset = regOp.getResetSignal();
1895 auto value = regOp.getResetValue();
1901 builder.setInsertionPointAfterValue(regOp.getResult());
1902 auto mux = builder.create<MuxPrimOp>(reset, value, regOp.getResult());
1906 builder.setInsertionPoint(regOp);
1908 regOp.getResetSignalMutable().assign(actualReset);
1909 regOp.getResetValueMutable().assign(zero);
1913 LogicalResult InferResetsPass::verifyNoAbstractReset() {
1914 bool hasAbstractResetPorts =
false;
1915 for (FModuleLike module :
1916 getOperation().
getBodyBlock()->getOps<FModuleLike>()) {
1917 for (
PortInfo port : module.getPorts()) {
1918 if (getBaseOfType<ResetType>(port.type)) {
1919 auto diag = emitError(port.loc)
1920 <<
"a port \"" << port.getName()
1921 <<
"\" with abstract reset type was unable to be "
1922 "inferred by InferResets (is this a top-level port?)";
1923 diag.attachNote(module->getLoc())
1924 <<
"the module with this uninferred reset port was defined here";
1925 hasAbstractResetPorts =
true;
1930 if (hasAbstractResetPorts)
assert(baseType &&"element must be base type")
static Value createZeroValue(ImplicitLocOpBuilder &builder, FIRRTLBaseType type, SmallDenseMap< FIRRTLBaseType, Value > &cache)
Construct a zero value of the given type using the given builder.
static unsigned getFieldID(BundleType type, unsigned index)
static std::pair< StringAttr, FModuleOp > getResetNameAndModule(Value reset)
Return the name and parent module of a reset.
static unsigned getIndexForFieldID(BundleType type, unsigned fieldID)
static FIRRTLBaseType updateType(FIRRTLBaseType oldType, unsigned fieldID, FIRRTLBaseType fieldType)
Update the type of a single field within a type.
static bool isUselessVec(FIRRTLBaseType oldType, unsigned fieldID)
static StringAttr getResetName(Value reset)
Return the name of a reset.
static bool insertResetMux(ImplicitLocOpBuilder &builder, Value target, Value reset, Value resetValue)
Helper function that inserts reset multiplexer into all ConnectOps with the given target.
static bool getFieldName(const FieldRef &fieldRef, SmallString< 32 > &string)
static bool typeContainsReset(Type type)
Check whether a type contains a ResetType.
static bool getDeclName(Value value, SmallString< 32 > &string)
static unsigned getMaxFieldID(FIRRTLBaseType type)
static InstancePath empty
static Block * getBodyBlock(FModuleLike mod)
This class represents a reference to a specific field or element of an aggregate value.
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.
This class provides a read-only projection of an annotation.
AttrClass getMember(StringAttr name) const
Return a member of the annotation.
bool isClass(Args... names) const
Return true if this annotation matches any of the specified class names.
bool isConst()
Returns true if this is a 'const' type that can only hold compile-time constant values.
FIRRTLBaseType getConstType(bool isConst)
Return a 'const' or non-'const' version of this type.
This class implements the same functionality as TypeSwitch except that it uses firrtl::type_dyn_cast ...
FIRRTLTypeSwitch< T, ResultT > & Case(CallableT &&caseFn)
Add a case on the given type.
This graph tracks modules and where they are instantiated.
An instance path composed of a series of instances.
InstanceOpInterface leaf() const
Direction get(bool isOutput)
Returns an output direction if isOutput is true, otherwise returns an input direction.
constexpr const char * excludeFromFullResetAnnoClass
Annotation that marks a module as not belonging to any reset domain.
FieldRef getFieldRefForTarget(const hw::InnerSymTarget &ist)
Get FieldRef pointing to the specified inner symbol target, which must be valid.
constexpr const char * excludeMemToRegAnnoClass
igraph::InstancePathCache InstancePathCache
FIRRTLBaseType getBaseType(Type type)
If it is a base type, return it as is.
FIRRTLType mapBaseType(FIRRTLType type, function_ref< FIRRTLBaseType(FIRRTLBaseType)> fn)
Return a FIRRTLType with its base type component mutated by the given function.
constexpr const char * fullResetAnnoClass
Annotation that marks a reset (port or wire) and domain.
std::pair< std::string, bool > getFieldName(const FieldRef &fieldRef, bool nameSafe=false)
Get a string identifier representing the FieldRef.
llvm::raw_ostream & operator<<(llvm::raw_ostream &os, const InstanceInfo::LatticeValue &value)
void emitConnect(OpBuilder &builder, Location loc, Value lhs, Value rhs)
Emit a connect between two values.
std::unique_ptr< mlir::Pass > createInferResetsPass()
The InstanceGraph op interface, see InstanceGraphInterface.td for more details.
llvm::raw_ostream & debugHeader(llvm::StringRef str, int width=80)
Write a "header"-like string to the debug stream with a certain width.
inline ::llvm::hash_code hash_value(const FieldRef &fieldRef)
Get a hash code for a FieldRef.
bool operator==(uint64_t a, const FVInt &b)
bool operator!=(uint64_t a, const FVInt &b)
bool operator<(const AppID &a, const AppID &b)
This holds the name and type that describes the module's ports.
static ResetSignal getEmptyKey()
static ResetSignal getTombstoneKey()
static bool isEqual(const ResetSignal &lhs, const ResetSignal &rhs)
static unsigned getHashValue(const ResetSignal &x)