30 #include "mlir/IR/ImplicitLocOpBuilder.h"
31 #include "mlir/IR/Threading.h"
32 #include "llvm/ADT/APSInt.h"
33 #include "llvm/ADT/BitVector.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/Parallel.h"
37 #define DEBUG_TYPE "firrtl-lower-signatures"
39 using namespace circt;
40 using namespace firrtl;
48 AttrCache(MLIRContext *context) {
57 AttrCache(
const AttrCache &) =
default;
59 StringAttr nameAttr, sPortDirections, sPortNames, sPortTypes, sPortLocations,
60 sPortAnnotations, sInternalPaths;
63 struct FieldMapEntry :
public PortInfo {
73 using E =
typename T::ElementType;
74 using V = SmallVector<E>;
77 using const_iterator =
typename V::const_iterator;
79 template <
typename Container>
80 FieldIDSearch(
const Container &src) {
81 if constexpr (std::is_convertible_v<Container, Attribute>)
86 std::sort(vals.begin(), vals.end(), fieldComp);
89 std::pair<const_iterator, const_iterator> find(uint64_t low,
90 uint64_t high)
const {
91 return {std::lower_bound(vals.begin(), vals.end(), low, fieldCompInt2),
92 std::upper_bound(vals.begin(), vals.end(), high, fieldCompInt1)};
95 bool empty(uint64_t low, uint64_t high)
const {
96 auto [b, e] = find(low, high);
101 static constexpr
auto fieldComp = [](
const E &lhs,
const E &rhs) {
102 return lhs.getFieldID() < rhs.getFieldID();
104 static constexpr
auto fieldCompInt2 = [](
const E &lhs, uint64_t rhs) {
105 return lhs.getFieldID() < rhs;
107 static constexpr
auto fieldCompInt1 = [](uint64_t lhs,
const E &rhs) {
108 return lhs < rhs.getFieldID();
116 static hw::InnerSymAttr
118 const FieldIDSearch<hw::InnerSymAttr> &syms,
119 uint64_t low, uint64_t high) {
120 auto [b, e] = syms.find(low, high);
121 SmallVector<hw::InnerSymPropertiesAttr, 4> newSyms(b, e);
124 for (
auto &sym : newSyms)
126 ctx, sym.getName(), sym.getFieldID() - low, sym.getSymVisibility());
132 const FieldIDSearch<AnnotationSet> &annos, uint64_t low,
135 auto [b, e] = annos.find(low, high);
143 size_t portID,
const PortInfo &port,
bool isFlip,
144 Twine name,
FIRRTLType type, uint64_t fieldID,
145 const FieldIDSearch<hw::InnerSymAttr> &syms,
146 const FieldIDSearch<AnnotationSet> &annos) {
147 auto *ctx = type.getContext();
149 .
Case<BundleType>([&](BundleType bundle) -> LogicalResult {
152 if (conv != Convention::Scalarized && bundle.isPassive()) {
153 auto lastId = fieldID + bundle.getMaxFieldID();
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();
205 for (
size_t i = 0, e = vector.getNumElements(); i < e; ++i) {
207 mod, newPorts, conv, portID, port, isFlip,
208 name +
"_" + Twine(i), vector.getElementType(),
209 fieldID + vector.getFieldID(i), syms, annos)))
211 if (!syms.empty(fieldID, fieldID))
212 return mod.emitError(
"Port [")
214 <<
"] should be subdivided, but cannot be because of "
216 << port.
sym.getSymIfExists(fieldID) <<
"] on a vector";
217 if (!annos.empty(fieldID, fieldID)) {
218 auto err = mod.emitError(
"Port [")
220 <<
"] should be subdivided, but cannot be because of "
222 auto [b, e] = annos.find(fieldID, fieldID);
223 err << b->getClass();
226 err <<
", " << b->getClass();
227 err <<
"] on a vector";
234 .Case<FEnumType>([&](FEnumType fenum) {
return failure(); })
253 for (
auto [idx, port] : llvm::enumerate(mod.getPorts())) {
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];
287 .create<WireOp>(module.getPortType(p.portID),
288 module.getPortNameAttr(p.portID),
289 NameKindEnum::InterestingName)
292 bounceWires[p.portID] = newArg;
297 for (
auto idx = 0U; idx < oldNumArgs; ++idx) {
298 if (!bounceWires[idx]) {
299 bounceWires[idx] = theBuilder
300 .create<WireOp>(module.getPortType(idx),
301 module.getPortNameAttr(idx))
304 body->getArgument(idx).replaceAllUsesWith(bounceWires[idx]);
308 body->eraseArguments(0, oldNumArgs);
311 for (
auto &p : newPorts) {
312 if (isa<BlockArgument>(bounceWires[p.portID]))
316 theBuilder, body->getArgument(p.resultID),
322 body->getArgument(p.resultID));
326 SmallVector<NamedAttribute, 8> newModuleAttrs;
329 for (
auto attr : module->getAttrDictionary())
332 if (attr.getName() !=
"portNames" && attr.getName() !=
"portDirections" &&
333 attr.getName() !=
"portTypes" && attr.getName() !=
"portAnnotations" &&
334 attr.getName() !=
"portSyms" && attr.getName() !=
"portLocations" &&
335 attr.getName() !=
"internalPaths")
336 newModuleAttrs.push_back(attr);
338 SmallVector<Direction> newPortDirections;
339 SmallVector<Attribute> newPortNames;
340 SmallVector<Attribute> newPortTypes;
341 SmallVector<Attribute> newPortSyms;
342 SmallVector<Attribute> newPortLocations;
343 SmallVector<Attribute, 8> newPortAnnotations;
344 SmallVector<Attribute> newInternalPaths;
346 bool hasInternalPaths =
false;
347 auto internalPaths = module->getAttrOfType<ArrayAttr>(
"internalPaths");
348 for (
auto p : newPorts) {
350 newPortNames.push_back(p.name);
351 newPortDirections.push_back(p.direction);
352 newPortSyms.push_back(p.sym);
353 newPortLocations.push_back(p.loc);
354 newPortAnnotations.push_back(p.annotations.getArrayAttr());
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 assert(newInternalPaths.empty() ||
380 newInternalPaths.size() == newPorts.size());
381 if (hasInternalPaths) {
382 newModuleAttrs.emplace_back(cache.sInternalPaths,
383 theBuilder.getArrayAttr(newInternalPaths));
387 module->setAttrs(newModuleAttrs);
388 module.setPortSymbols(newPortSyms);
393 const DenseMap<StringAttr, PortConversion> &ports) {
394 mod->walk([&](InstanceOp inst) ->
void {
395 ImplicitLocOpBuilder theBuilder(inst.getLoc(), inst);
396 const auto &modPorts = ports.at(inst.getModuleNameAttr().getAttr());
399 SmallVector<PortInfo> instPorts;
400 for (
auto p : modPorts) {
404 instPorts.push_back(p);
406 auto annos = inst.getAnnotations();
407 auto newOp = theBuilder.create<InstanceOp>(
408 instPorts, inst.getModuleName(), inst.getName(), inst.getNameKind(),
409 annos.getValue(), inst.getLayers(), inst.getLowerToBind(),
410 inst.getInnerSymAttr());
412 auto oldDict = inst->getDiscardableAttrDictionary();
413 auto newDict = newOp->getDiscardableAttrDictionary();
414 auto oldNames = inst.getPortNamesAttr();
415 SmallVector<NamedAttribute> newAttrs;
416 for (
auto na : oldDict)
417 if (!newDict.contains(na.getName()))
418 newOp->setDiscardableAttr(na.getName(), na.getValue());
421 SmallVector<WireOp> bounce(inst.getNumResults());
422 for (
auto p : modPorts) {
424 if (p.fieldID == 0) {
425 inst.getResult(p.portID).replaceAllUsesWith(
426 newOp.getResult(p.resultID));
429 if (!bounce[p.portID]) {
430 bounce[p.portID] = theBuilder.create<WireOp>(
431 inst.getResult(p.portID).getType(),
432 theBuilder.getStringAttr(
433 inst.getName() +
"." +
434 cast<StringAttr>(oldNames[p.portID]).getValue()));
435 inst.getResult(p.portID).replaceAllUsesWith(
436 bounce[p.portID].getResult());
440 emitConnect(theBuilder, newOp.getResult(p.resultID),
447 newOp.getResult(p.resultID));
451 for (
auto *use : llvm::make_early_inc_range(inst->getUsers())) {
452 assert(isa<StrictConnectOp>(use) || isa<ConnectOp>(use));
465 struct LowerSignaturesPass :
public LowerSignaturesBase<LowerSignaturesPass> {
466 void runOnOperation()
override;
471 void LowerSignaturesPass::runOnOperation() {
474 AttrCache cache(&getContext());
476 DenseMap<StringAttr, PortConversion> portMap;
477 auto circuit = getOperation();
479 for (
auto mod : circuit.getOps<FModuleLike>()) {
481 portMap[mod.getNameAttr()])
483 return signalPassFailure();
485 parallelForEach(&getContext(), circuit.getOps<FModuleOp>(),
486 [&portMap](FModuleOp mod) { lowerModuleBody(mod, portMap); });
491 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.