22 #include "mlir/IR/Threading.h"
23 #include "mlir/Pass/Pass.h"
24 #include "llvm/Support/Debug.h"
26 #define DEBUG_TYPE "firrtl-lower-signatures"
30 #define GEN_PASS_DEF_LOWERSIGNATURES
31 #include "circt/Dialect/FIRRTL/Passes.h.inc"
35 using namespace circt;
36 using namespace firrtl;
44 AttrCache(MLIRContext *context) {
53 AttrCache(
const AttrCache &) =
default;
55 StringAttr nameAttr, sPortDirections, sPortNames, sPortTypes, sPortLocations,
56 sPortAnnotations, sInternalPaths;
59 struct FieldMapEntry :
public PortInfo {
69 using E =
typename T::ElementType;
70 using V = SmallVector<E>;
73 using const_iterator =
typename V::const_iterator;
75 template <
typename Container>
76 FieldIDSearch(
const Container &src) {
77 if constexpr (std::is_convertible_v<Container, Attribute>)
82 std::sort(vals.begin(), vals.end(), fieldComp);
85 std::pair<const_iterator, const_iterator> find(uint64_t low,
86 uint64_t high)
const {
87 return {std::lower_bound(vals.begin(), vals.end(), low, fieldCompInt2),
88 std::upper_bound(vals.begin(), vals.end(), high, fieldCompInt1)};
91 bool empty(uint64_t low, uint64_t high)
const {
92 auto [b, e] = find(low, high);
97 static constexpr
auto fieldComp = [](
const E &lhs,
const E &rhs) {
98 return lhs.getFieldID() < rhs.getFieldID();
100 static constexpr
auto fieldCompInt2 = [](
const E &lhs, uint64_t rhs) {
101 return lhs.getFieldID() < rhs;
103 static constexpr
auto fieldCompInt1 = [](uint64_t lhs,
const E &rhs) {
104 return lhs < rhs.getFieldID();
112 static hw::InnerSymAttr
114 const FieldIDSearch<hw::InnerSymAttr> &syms,
115 uint64_t low, uint64_t high) {
116 auto [b, e] = syms.find(low, high);
117 SmallVector<hw::InnerSymPropertiesAttr, 4> newSyms(b, e);
120 for (
auto &sym : newSyms)
122 ctx, sym.getName(), sym.getFieldID() - low, sym.getSymVisibility());
128 const FieldIDSearch<AnnotationSet> &annos, uint64_t low,
131 auto [b, e] = annos.find(low, high);
139 size_t portID,
const PortInfo &port,
bool isFlip,
140 Twine name,
FIRRTLType type, uint64_t fieldID,
141 const FieldIDSearch<hw::InnerSymAttr> &syms,
142 const FieldIDSearch<AnnotationSet> &annos) {
143 auto *ctx = type.getContext();
145 .
Case<BundleType>([&](BundleType bundle) -> LogicalResult {
148 if (conv != Convention::Scalarized && bundle.isPassive()) {
149 auto lastId = fieldID + bundle.getMaxFieldID();
159 for (
auto [idx, elem] : llvm::enumerate(bundle.getElements())) {
161 mod, newPorts, conv, portID, port, isFlip ^ elem.isFlip,
162 name +
"_" + elem.
name.getValue(), elem.type,
163 fieldID + bundle.getFieldID(idx), syms, annos)))
165 if (!syms.empty(fieldID, fieldID))
166 return mod.emitError(
"Port [")
168 <<
"] should be subdivided, but cannot be because of "
170 << port.
sym.getSymIfExists(fieldID) <<
"] on a bundle";
171 if (!annos.empty(fieldID, fieldID)) {
172 auto err = mod.emitError(
"Port [")
174 <<
"] should be subdivided, but cannot be because of "
176 auto [b, e] = annos.find(fieldID, fieldID);
177 err << b->getClass() <<
"(" << b->getFieldID() <<
")";
180 err <<
", " << b->getClass() <<
"(" << b->getFieldID() <<
")";
181 err <<
"] on a bundle";
188 .Case<FVectorType>([&](FVectorType vector) -> LogicalResult {
189 if (conv != Convention::Scalarized &&
190 vector.getElementType().isPassive()) {
191 auto lastId = fieldID + vector.getMaxFieldID();
201 for (
size_t i = 0, e = vector.getNumElements(); i < e; ++i) {
203 mod, newPorts, conv, portID, port, isFlip,
204 name +
"_" + Twine(i), vector.getElementType(),
205 fieldID + vector.getFieldID(i), syms, annos)))
207 if (!syms.empty(fieldID, fieldID))
208 return mod.emitError(
"Port [")
210 <<
"] should be subdivided, but cannot be because of "
212 << port.
sym.getSymIfExists(fieldID) <<
"] on a vector";
213 if (!annos.empty(fieldID, fieldID)) {
214 auto err = mod.emitError(
"Port [")
216 <<
"] should be subdivided, but cannot be because of "
218 auto [b, e] = annos.find(fieldID, fieldID);
219 err << b->getClass();
222 err <<
", " << b->getClass();
223 err <<
"] on a vector";
230 .Case<FEnumType>([&](FEnumType fenum) {
return failure(); })
249 for (
auto [idx, port] : llvm::enumerate(mod.getPorts())) {
252 port.name.getValue(), type_cast<FIRRTLType>(port.type), 0,
253 FieldIDSearch<hw::InnerSymAttr>(port.sym),
254 FieldIDSearch<AnnotationSet>(port.annotations))))
263 ImplicitLocOpBuilder theBuilder(module.getLoc(), module.getContext());
266 if (
auto mod = dyn_cast<FModuleOp>(module.getOperation())) {
267 Block *body = mod.getBodyBlock();
268 theBuilder.setInsertionPointToStart(body);
269 auto oldNumArgs = body->getNumArguments();
274 SmallVector<Value> bounceWires(oldNumArgs);
275 for (
auto &p : newPorts) {
276 auto newArg = body->addArgument(p.type, p.loc);
279 if (p.fieldID != 0) {
280 auto &wire = bounceWires[p.portID];
283 .create<WireOp>(module.getPortType(p.portID),
284 module.getPortNameAttr(p.portID),
285 NameKindEnum::InterestingName)
288 bounceWires[p.portID] = newArg;
293 for (
auto idx = 0U; idx < oldNumArgs; ++idx) {
294 if (!bounceWires[idx]) {
295 bounceWires[idx] = theBuilder
296 .create<WireOp>(module.getPortType(idx),
297 module.getPortNameAttr(idx))
300 body->getArgument(idx).replaceAllUsesWith(bounceWires[idx]);
304 body->eraseArguments(0, oldNumArgs);
307 for (
auto &p : newPorts) {
308 if (isa<BlockArgument>(bounceWires[p.portID]))
312 theBuilder, body->getArgument(p.resultID),
318 body->getArgument(p.resultID));
322 SmallVector<NamedAttribute, 8> newModuleAttrs;
325 for (
auto attr : module->getAttrDictionary())
328 if (attr.getName() !=
"portNames" && attr.getName() !=
"portDirections" &&
329 attr.getName() !=
"portTypes" && attr.getName() !=
"portAnnotations" &&
330 attr.getName() !=
"portSymbols" && attr.getName() !=
"portLocations" &&
331 attr.getName() !=
"internalPaths")
332 newModuleAttrs.push_back(attr);
334 SmallVector<Direction> newPortDirections;
335 SmallVector<Attribute> newPortNames;
336 SmallVector<Attribute> newPortTypes;
337 SmallVector<Attribute> newPortSyms;
338 SmallVector<Attribute> newPortLocations;
339 SmallVector<Attribute, 8> newPortAnnotations;
340 SmallVector<Attribute> newInternalPaths;
342 bool hasInternalPaths =
false;
343 auto internalPaths = module->getAttrOfType<ArrayAttr>(
"internalPaths");
344 for (
auto p : newPorts) {
346 newPortNames.push_back(p.name);
347 newPortDirections.push_back(p.direction);
348 newPortSyms.push_back(p.sym);
349 newPortLocations.push_back(p.loc);
350 newPortAnnotations.push_back(p.annotations.getArrayAttr());
352 auto internalPath = cast<InternalPathAttr>(internalPaths[p.portID]);
353 newInternalPaths.push_back(internalPath);
354 if (internalPath.getPath())
355 hasInternalPaths =
true;
359 newModuleAttrs.push_back(NamedAttribute(
360 cache.sPortDirections,
363 newModuleAttrs.push_back(
364 NamedAttribute(cache.sPortNames, theBuilder.getArrayAttr(newPortNames)));
366 newModuleAttrs.push_back(
367 NamedAttribute(cache.sPortTypes, theBuilder.getArrayAttr(newPortTypes)));
369 newModuleAttrs.push_back(NamedAttribute(
370 cache.sPortLocations, theBuilder.getArrayAttr(newPortLocations)));
372 newModuleAttrs.push_back(NamedAttribute(
373 cache.sPortAnnotations, theBuilder.getArrayAttr(newPortAnnotations)));
375 assert(newInternalPaths.empty() ||
376 newInternalPaths.size() == newPorts.size());
377 if (hasInternalPaths) {
378 newModuleAttrs.emplace_back(cache.sInternalPaths,
379 theBuilder.getArrayAttr(newInternalPaths));
383 module->setAttrs(newModuleAttrs);
384 FModuleLike::fixupPortSymsArray(newPortSyms, theBuilder.getContext());
385 module.setPortSymbols(newPortSyms);
390 const DenseMap<StringAttr, PortConversion> &ports) {
391 mod->walk([&](InstanceOp inst) ->
void {
392 ImplicitLocOpBuilder theBuilder(inst.getLoc(), inst);
393 const auto &modPorts = ports.at(inst.getModuleNameAttr().getAttr());
396 SmallVector<PortInfo> instPorts;
397 for (
auto p : modPorts) {
401 instPorts.push_back(p);
403 auto annos = inst.getAnnotations();
404 auto newOp = theBuilder.create<InstanceOp>(
405 instPorts, inst.getModuleName(), inst.getName(), inst.getNameKind(),
406 annos.getValue(), inst.getLayers(), inst.getLowerToBind(),
407 inst.getInnerSymAttr());
409 auto oldDict = inst->getDiscardableAttrDictionary();
410 auto newDict = newOp->getDiscardableAttrDictionary();
411 auto oldNames = inst.getPortNamesAttr();
412 SmallVector<NamedAttribute> newAttrs;
413 for (
auto na : oldDict)
414 if (!newDict.contains(na.getName()))
415 newOp->setDiscardableAttr(na.getName(), na.getValue());
418 SmallVector<WireOp> bounce(inst.getNumResults());
419 for (
auto p : modPorts) {
421 if (p.fieldID == 0) {
422 inst.getResult(p.portID).replaceAllUsesWith(
423 newOp.getResult(p.resultID));
426 if (!bounce[p.portID]) {
427 bounce[p.portID] = theBuilder.create<WireOp>(
428 inst.getResult(p.portID).getType(),
429 theBuilder.getStringAttr(
430 inst.getName() +
"." +
431 cast<StringAttr>(oldNames[p.portID]).getValue()));
432 inst.getResult(p.portID).replaceAllUsesWith(
433 bounce[p.portID].getResult());
437 emitConnect(theBuilder, newOp.getResult(p.resultID),
444 newOp.getResult(p.resultID));
448 for (
auto *use : llvm::make_early_inc_range(inst->getUsers())) {
449 assert(isa<MatchingConnectOp>(use) || isa<ConnectOp>(use));
462 struct LowerSignaturesPass
463 :
public circt::firrtl::impl::LowerSignaturesBase<LowerSignaturesPass> {
464 void runOnOperation()
override;
469 void LowerSignaturesPass::runOnOperation() {
472 AttrCache cache(&getContext());
474 DenseMap<StringAttr, PortConversion> portMap;
475 auto circuit = getOperation();
477 for (
auto mod : circuit.getOps<FModuleLike>()) {
479 portMap[mod.getNameAttr()])
481 return signalPassFailure();
483 parallelForEach(&getContext(), circuit.getOps<FModuleOp>(),
484 [&portMap](FModuleOp mod) { lowerModuleBody(mod, portMap); });
489 return std::make_unique<LowerSignaturesPass>();
assert(baseType &&"element must be base type")
static InstancePath empty
static LogicalResult computeLowering(FModuleLike mod, Convention conv, PortConversion &newPorts)
static AnnotationSet annosForFieldIDRange(MLIRContext *ctx, const FieldIDSearch< AnnotationSet > &annos, uint64_t low, uint64_t high)
static LogicalResult lowerModuleSignature(FModuleLike module, Convention conv, AttrCache &cache, PortConversion &newPorts)
static LogicalResult computeLoweringImpl(FModuleLike mod, PortConversion &newPorts, Convention conv, size_t portID, const PortInfo &port, bool isFlip, Twine name, FIRRTLType type, uint64_t fieldID, const FieldIDSearch< hw::InnerSymAttr > &syms, const FieldIDSearch< AnnotationSet > &annos)
static void lowerModuleBody(FModuleOp mod, const DenseMap< StringAttr, PortConversion > &ports)
static hw::InnerSymAttr symbolsForFieldIDRange(MLIRContext *ctx, const FieldIDSearch< hw::InnerSymAttr > &syms, uint64_t low, uint64_t high)
This class provides a read-only projection over the MLIR attributes that represent a set of annotatio...
void addAnnotations(ArrayRef< Annotation > annotations)
Add more annotations to this annotation set.
MLIRContext * getContext() const
Return the MLIRContext corresponding to this AnnotationSet.
This class provides a read-only projection of an annotation.
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.
Base class for the port conversion of a particular port.
Direction get(bool isOutput)
Returns an output direction if isOutput is true, otherwise returns an input direction.
mlir::DenseBoolArrayAttr packAttribute(MLIRContext *context, ArrayRef< Direction > directions)
Return a DenseBoolArrayAttr containing the packed representation of an array of directions.
std::unique_ptr< mlir::Pass > createLowerSignaturesPass()
This is the pass constructor.
Value getValueByFieldID(ImplicitLocOpBuilder builder, Value value, unsigned fieldID)
This gets the value targeted by a field id.
void emitConnect(OpBuilder &builder, Location loc, Value lhs, Value rhs)
Emit a connect between two values.
The InstanceGraph op interface, see InstanceGraphInterface.td for more details.
llvm::raw_ostream & debugPassHeader(const mlir::Pass *pass, int width=80)
Write a boilerplate header for a pass to the debug stream.
This holds the name and type that describes the module's ports.