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"
36using namespace firrtl;
44 AttrCache(MLIRContext *context) {
45 nameAttr = StringAttr::get(context,
"name");
46 sPortDirections = StringAttr::get(context,
"portDirections");
47 sPortNames = StringAttr::get(context,
"portNames");
48 sPortTypes = StringAttr::get(context,
"portTypes");
49 sPortLocations = StringAttr::get(context,
"portLocations");
50 sPortAnnotations = StringAttr::get(context,
"portAnnotations");
51 sPortDomains = StringAttr::get(context,
"domainInfo");
52 sInternalPaths = StringAttr::get(context,
"internalPaths");
53 aEmpty = ArrayAttr::get(context, {});
55 AttrCache(
const AttrCache &) =
default;
57 StringAttr nameAttr, sPortDirections, sPortNames, sPortTypes, sPortLocations,
58 sPortAnnotations, sPortDomains, sInternalPaths;
62struct FieldMapEntry :
public PortInfo {
72 using E =
typename T::ElementType;
73 using V = SmallVector<E>;
76 using const_iterator =
typename V::const_iterator;
78 template <
typename Container>
79 FieldIDSearch(
const Container &src) {
80 if constexpr (std::is_convertible_v<Container, Attribute>)
85 std::sort(vals.begin(), vals.end(), fieldComp);
88 std::pair<const_iterator, const_iterator> find(uint64_t low,
89 uint64_t high)
const {
90 return {std::lower_bound(vals.begin(), vals.end(), low, fieldCompInt2),
91 std::upper_bound(vals.begin(), vals.end(), high, fieldCompInt1)};
94 bool empty(uint64_t low, uint64_t high)
const {
95 auto [b, e] = find(low, high);
100 static constexpr auto fieldComp = [](
const E &lhs,
const E &rhs) {
101 return lhs.getFieldID() < rhs.getFieldID();
103 static constexpr auto fieldCompInt2 = [](
const E &lhs, uint64_t rhs) {
104 return lhs.getFieldID() < rhs;
106 static constexpr auto fieldCompInt1 = [](uint64_t lhs,
const E &rhs) {
107 return lhs < rhs.getFieldID();
115static hw::InnerSymAttr
117 const FieldIDSearch<hw::InnerSymAttr> &syms,
118 uint64_t low, uint64_t high) {
119 auto [b, e] = syms.find(low, high);
120 SmallVector<hw::InnerSymPropertiesAttr, 4> newSyms(b, e);
123 for (
auto &sym : newSyms)
124 sym = hw::InnerSymPropertiesAttr::get(
125 ctx, sym.getName(), sym.getFieldID() - low, sym.getSymVisibility());
126 return hw::InnerSymAttr::get(ctx, newSyms);
131 const FieldIDSearch<AnnotationSet> &annos, uint64_t low,
134 auto [b, e] = annos.find(low, high);
142 size_t portID,
const PortInfo &port,
bool isFlip,
143 Twine name,
FIRRTLType type, uint64_t fieldID,
144 const FieldIDSearch<hw::InnerSymAttr> &syms,
145 const FieldIDSearch<AnnotationSet> &annos) {
146 auto *ctx = type.getContext();
148 .
Case<BundleType>([&](BundleType bundle) -> LogicalResult {
151 if (conv != Convention::Scalarized && bundle.isPassive()) {
152 auto lastId = fieldID + bundle.getMaxFieldID();
154 {{StringAttr::get(ctx, name), type,
155 isFlip ? Direction::Out : Direction::In,
163 for (
auto [idx, elem] : llvm::enumerate(bundle.getElements())) {
165 mod, newPorts, conv, portID, port, isFlip ^ elem.isFlip,
166 name +
"_" + elem.
name.getValue(), elem.type,
167 fieldID + bundle.getFieldID(idx), syms, annos)))
169 if (!syms.empty(fieldID, fieldID))
170 return mod.emitError(
"Port [")
172 <<
"] should be subdivided, but cannot be because of "
174 << port.
sym.getSymIfExists(fieldID) <<
"] on a bundle";
175 if (!annos.empty(fieldID, fieldID)) {
176 auto err = mod.emitError(
"Port [")
178 <<
"] should be subdivided, but cannot be because of "
180 auto [b, e] = annos.find(fieldID, fieldID);
181 err << b->getClass() <<
"(" << b->getFieldID() <<
")";
184 err <<
", " << b->getClass() <<
"(" << b->getFieldID() <<
")";
185 err <<
"] on a bundle";
192 .Case<FVectorType>([&](FVectorType vector) -> LogicalResult {
193 if (conv != Convention::Scalarized &&
194 vector.getElementType().isPassive()) {
195 auto lastId = fieldID + vector.getMaxFieldID();
197 {{StringAttr::get(ctx, name), type,
198 isFlip ? Direction::Out : Direction::In,
206 for (
size_t i = 0, e = vector.getNumElements(); i < e; ++i) {
208 mod, newPorts, conv, portID, port, isFlip,
209 name +
"_" + Twine(i), vector.getElementType(),
210 fieldID + vector.getFieldID(i), syms, annos)))
212 if (!syms.empty(fieldID, fieldID))
213 return mod.emitError(
"Port [")
215 <<
"] should be subdivided, but cannot be because of "
217 << port.
sym.getSymIfExists(fieldID) <<
"] on a vector";
218 if (!annos.empty(fieldID, fieldID)) {
219 auto err = mod.emitError(
"Port [")
221 <<
"] should be subdivided, but cannot be because of "
223 auto [b, e] = annos.find(fieldID, fieldID);
224 err << b->getClass();
227 err <<
", " << b->getClass();
228 err <<
"] on a vector";
238 {{StringAttr::get(ctx, name), type,
239 isFlip ? Direction::Out : Direction::In,
253 for (
auto [idx, port] : llvm::enumerate(mod.getPorts())) {
255 mod, newPorts, conv, idx, port, port.direction == Direction::Out,
256 port.name.getValue(), type_cast<FIRRTLType>(port.type), 0,
257 FieldIDSearch<hw::InnerSymAttr>(port.sym),
258 FieldIDSearch<AnnotationSet>(port.annotations))))
267 ImplicitLocOpBuilder theBuilder(module.getLoc(), module.getContext());
270 if (
auto mod = dyn_cast<FModuleOp>(module.getOperation())) {
271 Block *body = mod.getBodyBlock();
272 theBuilder.setInsertionPointToStart(body);
273 auto oldNumArgs = body->getNumArguments();
278 SmallVector<Value> bounceWires(oldNumArgs);
279 for (
auto &p : newPorts) {
280 auto newArg = body->addArgument(p.type, p.loc);
283 if (p.fieldID != 0) {
284 auto &wire = bounceWires[p.portID];
286 wire = WireOp::create(theBuilder, module.getPortType(p.portID),
287 module.getPortNameAttr(p.portID),
288 NameKindEnum::InterestingName)
291 bounceWires[p.portID] = newArg;
296 for (
auto idx = 0U; idx < oldNumArgs; ++idx) {
297 if (!bounceWires[idx]) {
298 bounceWires[idx] = WireOp::create(theBuilder, module.getPortType(idx),
299 module.getPortNameAttr(idx))
302 body->getArgument(idx).replaceAllUsesWith(bounceWires[idx]);
306 body->eraseArguments(0, oldNumArgs);
309 for (
auto &p : newPorts) {
310 if (isa<BlockArgument>(bounceWires[p.portID]))
314 theBuilder, body->getArgument(p.resultID),
320 body->getArgument(p.resultID));
324 SmallVector<NamedAttribute, 8> newModuleAttrs;
327 for (
auto attr :
module->getAttrDictionary())
330 if (attr.getName() != "portNames" && attr.getName() != "portDirections" &&
331 attr.getName() != "portTypes" && attr.getName() != "portAnnotations" &&
332 attr.getName() != "portSymbols" && attr.getName() != "portLocations" &&
333 attr.getName() != "internalPaths")
334 newModuleAttrs.push_back(attr);
336 SmallVector<Direction> newPortDirections;
337 SmallVector<Attribute> newPortNames;
338 SmallVector<Attribute> newPortTypes;
339 SmallVector<Attribute> newPortSyms;
340 SmallVector<Attribute> newPortLocations;
341 SmallVector<Attribute, 8> newPortAnnotations;
342 SmallVector<Attribute> newPortDomains;
343 SmallVector<Attribute> newInternalPaths;
345 bool hasInternalPaths =
false;
346 auto internalPaths =
module->getAttrOfType<ArrayAttr>("internalPaths");
347 for (
auto p : newPorts) {
348 newPortTypes.push_back(TypeAttr::get(p.type));
349 newPortNames.push_back(p.name);
350 newPortDirections.push_back(p.direction);
351 newPortSyms.push_back(p.sym);
352 newPortLocations.push_back(p.loc);
353 newPortAnnotations.push_back(p.annotations.getArrayAttr());
354 newPortDomains.push_back(p.domains ? p.domains : cache.aEmpty);
356 auto internalPath = cast<InternalPathAttr>(internalPaths[p.portID]);
357 newInternalPaths.push_back(internalPath);
358 if (internalPath.getPath())
359 hasInternalPaths =
true;
363 newModuleAttrs.push_back(NamedAttribute(
364 cache.sPortDirections,
367 newModuleAttrs.push_back(
368 NamedAttribute(cache.sPortNames, theBuilder.getArrayAttr(newPortNames)));
370 newModuleAttrs.push_back(
371 NamedAttribute(cache.sPortTypes, theBuilder.getArrayAttr(newPortTypes)));
373 newModuleAttrs.push_back(NamedAttribute(
374 cache.sPortLocations, theBuilder.getArrayAttr(newPortLocations)));
376 newModuleAttrs.push_back(NamedAttribute(
377 cache.sPortAnnotations, theBuilder.getArrayAttr(newPortAnnotations)));
379 newModuleAttrs.push_back(NamedAttribute(
380 cache.sPortDomains, theBuilder.getArrayAttr(newPortDomains)));
382 assert(newInternalPaths.empty() ||
383 newInternalPaths.size() == newPorts.size());
384 if (hasInternalPaths) {
385 newModuleAttrs.emplace_back(cache.sInternalPaths,
386 theBuilder.getArrayAttr(newInternalPaths));
390 module->setAttrs(newModuleAttrs);
391 FModuleLike::fixupPortSymsArray(newPortSyms, theBuilder.getContext());
392 module.setPortSymbols(newPortSyms);
397 const DenseMap<StringAttr, PortConversion> &ports) {
398 mod->walk([&](InstanceOp inst) ->
void {
399 ImplicitLocOpBuilder theBuilder(inst.getLoc(), inst);
400 const auto &modPorts = ports.at(inst.getModuleNameAttr().getAttr());
403 SmallVector<PortInfo> instPorts;
404 for (
auto p : modPorts) {
408 instPorts.push_back(p);
410 auto annos = inst.getAnnotations();
411 auto newOp = InstanceOp::create(
412 theBuilder, instPorts, inst.getModuleName(), inst.getName(),
413 inst.getNameKind(), annos.getValue(), inst.getLayers(),
414 inst.getLowerToBind(), inst.getDoNotPrint(), inst.getInnerSymAttr());
416 auto oldDict = inst->getDiscardableAttrDictionary();
417 auto newDict = newOp->getDiscardableAttrDictionary();
418 auto oldNames = inst.getPortNamesAttr();
419 SmallVector<NamedAttribute> newAttrs;
420 for (
auto na : oldDict)
421 if (!newDict.contains(na.getName()))
422 newOp->setDiscardableAttr(na.getName(), na.getValue());
425 SmallVector<WireOp> bounce(inst.getNumResults());
426 for (
auto p : modPorts) {
428 if (p.fieldID == 0) {
429 inst.getResult(p.portID).replaceAllUsesWith(
430 newOp.getResult(p.resultID));
433 if (!bounce[p.portID]) {
434 bounce[p.portID] = WireOp::create(
435 theBuilder, inst.getResult(p.portID).getType(),
436 theBuilder.getStringAttr(
437 inst.getName() +
"." +
438 cast<StringAttr>(oldNames[p.portID]).getValue()));
439 inst.getResult(p.portID).replaceAllUsesWith(
440 bounce[p.portID].getResult());
444 emitConnect(theBuilder, newOp.getResult(p.resultID),
451 newOp.getResult(p.resultID));
455 for (
auto *use : llvm::make_early_inc_range(inst->getUsers())) {
456 assert(isa<MatchingConnectOp>(use) || isa<ConnectOp>(use));
469struct LowerSignaturesPass
470 :
public circt::firrtl::impl::LowerSignaturesBase<LowerSignaturesPass> {
471 void runOnOperation()
override;
476void LowerSignaturesPass::runOnOperation() {
479 AttrCache cache(&getContext());
481 DenseMap<StringAttr, PortConversion> portMap;
482 auto circuit = getOperation();
484 for (
auto mod : circuit.getOps<FModuleLike>()) {
486 portMap[mod.getNameAttr()])
488 return signalPassFailure();
490 parallelForEach(&getContext(), circuit.getOps<FModuleOp>(),
491 [&portMap](FModuleOp mod) { lowerModuleBody(mod, portMap); });
assert(baseType &&"element must be base type")
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)
static InstancePath empty
This class provides a read-only projection over the MLIR attributes that represent a set of annotatio...
MLIRContext * getContext() const
Return the MLIRContext corresponding to this AnnotationSet.
void addAnnotations(ArrayRef< Annotation > annotations)
Add more annotations to this annotation set.
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.
mlir::DenseBoolArrayAttr packAttribute(MLIRContext *context, ArrayRef< Direction > directions)
Return a DenseBoolArrayAttr containing the packed representation of an array of directions.
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.