CIRCT 23.0.0git
Loading...
Searching...
No Matches
LowerXMR.cpp
Go to the documentation of this file.
1//===- LowerXMR.cpp - FIRRTL Lower to XMR -----------------------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements FIRRTL XMR Lowering.
10//
11//===----------------------------------------------------------------------===//
12
22#include "mlir/IR/ImplicitLocOpBuilder.h"
23#include "mlir/Pass/Pass.h"
24#include "llvm/ADT/BitVector.h"
25#include "llvm/ADT/DenseMap.h"
26#include "llvm/ADT/EquivalenceClasses.h"
27#include "llvm/ADT/PostOrderIterator.h"
28#include "llvm/Support/Debug.h"
29
30#define DEBUG_TYPE "firrtl-lower-xmr"
31
32namespace circt {
33namespace firrtl {
34#define GEN_PASS_DEF_LOWERXMR
35#include "circt/Dialect/FIRRTL/Passes.h.inc"
36} // namespace firrtl
37} // namespace circt
38
39using namespace circt;
40using namespace firrtl;
41using hw::InnerRefAttr;
42
43/// The LowerXMRPass will replace every RefResolveOp with an XMR encoded within
44/// a verbatim expr op. This also removes every RefType port from the modules
45/// and corresponding instances. This is a dataflow analysis over a very
46/// constrained RefType. Domain of the dataflow analysis is the set of all
47/// RefSendOps. It computes an interprocedural reaching definitions (of
48/// RefSendOp) analysis. Essentially every RefType value must be mapped to one
49/// and only one RefSendOp. The analysis propagates the dataflow from every
50/// RefSendOp to every value of RefType across modules. The RefResolveOp is the
51/// final leaf into which the dataflow must reach.
52///
53/// Since there can be multiple readers, multiple RefResolveOps can be reachable
54/// from a single RefSendOp. To support multiply instantiated modules and
55/// multiple readers, it is essential to track the path to the RefSendOp, other
56/// than just the RefSendOp. For example, if there exists a wire `xmr_wire` in
57/// module `Foo`, the algorithm needs to support generating Top.Bar.Foo.xmr_wire
58/// and Top.Foo.xmr_wire and Top.Zoo.Foo.xmr_wire for different instance paths
59/// that exist in the circuit.
60
61namespace {
62struct XMRNode {
63 using NextNodeOnPath = std::optional<size_t>;
64 using SymOrIndexOp = PointerUnion<Attribute, Operation *>;
65 SymOrIndexOp info;
66 NextNodeOnPath next;
67};
68[[maybe_unused]] llvm::raw_ostream &operator<<(llvm::raw_ostream &os,
69 const XMRNode &node) {
70 os << "node(";
71 if (auto attr = dyn_cast<Attribute>(node.info))
72 os << "path=" << attr;
73 else {
74 auto subOp = cast<RefSubOp>(cast<Operation *>(node.info));
75 os << "index=" << subOp.getIndex() << " (-> " << subOp.getType() << ")";
76 }
77 os << ", next=" << node.next << ")";
78 return os;
79}
80
81/// Track information about operations being created in a module. This is used
82/// to generate more compact code and reuse operations where possible.
83class ModuleState {
84
85public:
86 ModuleState(FModuleOp &moduleOp) : body(moduleOp.getBodyBlock()) {}
87
88 /// Return the existing XMRRefOp for this type, symbol, and suffix for this
89 /// module. Otherwise, create a new one. The first XMRRefOp will be created
90 /// at the beginning of the module. Subsequent XMRRefOps will be created
91 /// immediately following the first one.
92 Value getOrCreateXMRRefOp(Type type, FlatSymbolRefAttr symbol,
93 StringAttr suffix, ImplicitLocOpBuilder &builder) {
94 // Return the saved XMRRefOp.
95 auto it = xmrRefCache.find({type, symbol, suffix});
96 if (it != xmrRefCache.end())
97 return it->getSecond();
98
99 // Create a new XMRRefOp.
100 OpBuilder::InsertionGuard guard(builder);
101 if (xmrRefPoint.isSet())
102 builder.restoreInsertionPoint(xmrRefPoint);
103 else
104 builder.setInsertionPointToStart(body);
105
106 Value xmr = XMRRefOp::create(builder, type, symbol, suffix);
107 xmrRefCache.insert({{type, symbol, suffix}, xmr});
108
109 xmrRefPoint = builder.saveInsertionPoint();
110 return xmr;
111 };
112
113private:
114 /// The module's body. This is used to set the insertion point for the first
115 /// created operation.
116 Block *body;
117
118 /// Map used to know if we created this XMRRefOp before.
119 DenseMap<std::tuple<Type, SymbolRefAttr, StringAttr>, Value> xmrRefCache;
120
121 /// The saved insertion point for XMRRefOps.
122 OpBuilder::InsertPoint xmrRefPoint;
123};
124} // end anonymous namespace
125
127
128 void runOnOperation() override {
129 // Populate a CircuitNamespace that can be used to generate unique
130 // circuit-level symbols.
131 CircuitNamespace ns(getOperation());
132 circuitNamespace = &ns;
133
135 &ns, OpBuilder::InsertPoint(getOperation().getBodyBlock(),
136 getOperation().getBodyBlock()->begin()));
137 hierPathCache = &pc;
138
139 llvm::EquivalenceClasses<Value> eq;
140 dataFlowClasses = &eq;
141
142 InstanceGraph &instanceGraph = getAnalysis<InstanceGraph>();
143 SmallVector<RefResolveOp> resolveOps;
144 SmallVector<RefSubOp> indexingOps;
145 SmallVector<Operation *> forceAndReleaseOps;
146 // The dataflow function, that propagates the reachable RefSendOp across
147 // RefType Ops.
148 auto transferFunc = [&](Operation *op) -> LogicalResult {
149 return TypeSwitch<Operation *, LogicalResult>(op)
150 .Case<RefSendOp>([&](RefSendOp send) {
151 // Get a reference to the actual signal to which the XMR will be
152 // generated.
153 Value xmrDef = send.getBase();
154 if (isZeroWidth(send.getType().getType())) {
155 markForRemoval(send);
156 return success();
157 }
158
159 if (auto verbExpr = xmrDef.getDefiningOp<VerbatimExprOp>())
160 if (verbExpr.getSymbolsAttr().empty() && verbExpr->hasOneUse()) {
161 // This represents the internal path into a module. For
162 // generating the correct XMR, no node can be created in this
163 // module. Create a null InnerRef and ensure the hierarchical
164 // path ends at the parent that instantiates this module.
165 auto inRef = InnerRefAttr();
166 auto ind = addReachingSendsEntry(send.getResult(), inRef);
167 xmrPathSuffix[ind] = verbExpr.getText();
168 markForRemoval(verbExpr);
169 markForRemoval(send);
170 return success();
171 }
172 // Get an InnerRefAttr to the value being sent.
173 auto *xmrDefOp = xmrDef.getDefiningOp();
174
175 // Add the symbol directly if the operation targets a specific
176 // result. This ensures that operations like InstanceOp and MemOp,
177 // which have inner symbols that target the operation itself (not a
178 // specific result), still get nodes created to distinguish which
179 // result is being referenced.
180 if (auto innerSymOp =
181 dyn_cast_or_null<hw::InnerSymbolOpInterface>(xmrDefOp))
182 if (innerSymOp.getTargetResultIndex()) {
183 addReachingSendsEntry(send.getResult(), getInnerRefTo(xmrDef));
184 markForRemoval(send);
185 return success();
186 }
187
188 // The operation cannot support an inner symbol, or it has
189 // multiple results and doesn't target a specific result, so
190 // create a node and replace all uses of the original value with
191 // the node (except the node itself).
192 ImplicitLocOpBuilder b(xmrDef.getLoc(), &getContext());
193 b.setInsertionPointAfterValue(xmrDef);
194 SmallString<32> opName;
195 auto nameKind = NameKindEnum::DroppableName;
196
197 if (auto [name, rootKnown] = getFieldName(
198 getFieldRefFromValue(xmrDef, /*lookThroughCasts=*/true),
199 /*nameSafe=*/true);
200 rootKnown) {
201 opName = name + "_probe";
202 nameKind = NameKindEnum::InterestingName;
203 } else if (xmrDefOp) {
204 // Inspect "name" directly for ops that aren't named by above.
205 // (e.g., firrtl.constant)
206 if (auto name = xmrDefOp->getAttrOfType<StringAttr>("name")) {
207 (Twine(name.strref()) + "_probe").toVector(opName);
208 nameKind = NameKindEnum::InterestingName;
209 }
210 }
211 auto node = NodeOp::create(b, xmrDef, opName, nameKind);
212 auto newValue = node.getResult();
213 // Replace all uses except the node itself and except when the value
214 // is the destination of a connect (operand 0). We need to preserve
215 // connect destinations to maintain proper flow semantics.
216 xmrDef.replaceUsesWithIf(newValue, [&](OpOperand &operand) {
217 if (operand.getOwner() == node.getOperation())
218 return false;
219 if (isa<FConnectLike>(operand.getOwner()) &&
220 operand.getOperandNumber() == 0)
221 return false;
222 return true;
223 });
224 xmrDef = newValue;
225
226 // Create a new entry for this RefSendOp. The path is currently
227 // local.
228 addReachingSendsEntry(send.getResult(), getInnerRefTo(xmrDef));
229 markForRemoval(send);
230 return success();
231 })
232 .Case<RWProbeOp>([&](RWProbeOp rwprobe) {
233 if (!isZeroWidth(rwprobe.getType().getType()))
234 addReachingSendsEntry(rwprobe.getResult(), rwprobe.getTarget());
235 markForRemoval(rwprobe);
236 return success();
237 })
238 .Case<MemOp>([&](MemOp mem) {
239 // MemOp can produce debug ports of RefType. Each debug port
240 // represents the RefType for the corresponding register of the
241 // memory. Since the memory is not yet generated the register name
242 // is assumed to be "Memory". Note that MemOp creates RefType
243 // without a RefSend.
244 for (const auto &res : llvm::enumerate(mem.getResults()))
245 if (isa<RefType>(mem.getResult(res.index()).getType())) {
246 auto inRef = getInnerRefTo(mem);
247 auto ind = addReachingSendsEntry(res.value(), inRef);
248 xmrPathSuffix[ind] = "Memory";
249 // Just node that all the debug ports of memory must be removed.
250 // So this does not record the port index.
251 refPortsToRemoveMap[mem].resize(1);
252 }
253 return success();
254 })
255 .Case<InstanceOp>(
256 [&](auto inst) { return handleInstanceOp(inst, instanceGraph); })
257 .Case<FConnectLike>([&](FConnectLike connect) {
258 // Ignore BaseType.
259 if (!isa<RefType>(connect.getSrc().getType()))
260 return success();
261 markForRemoval(connect);
262 if (isZeroWidth(
263 type_cast<RefType>(connect.getSrc().getType()).getType()))
264 return success();
265 // Merge the dataflow classes of destination into the source of the
266 // Connect. This handles two cases:
267 // 1. If the dataflow at the source is known, then the
268 // destination is also inferred. By merging the dataflow class of
269 // destination with source, every value reachable from the
270 // destination automatically infers a reaching RefSend.
271 // 2. If dataflow at source is unkown, then just record that both
272 // source and destination will have the same dataflow information.
273 // Later in the pass when the reaching RefSend is inferred at the
274 // leader of the dataflowClass, then we automatically infer the
275 // dataflow at this connect and every value reachable from the
276 // destination.
277 dataFlowClasses->unionSets(connect.getSrc(), connect.getDest());
278 return success();
279 })
280 .Case<RefSubOp>([&](RefSubOp op) -> LogicalResult {
281 markForRemoval(op);
282 if (isZeroWidth(op.getType().getType()))
283 return success();
284
285 // Enqueue for processing after visiting other operations.
286 indexingOps.push_back(op);
287 return success();
288 })
289 .Case<RefResolveOp>([&](RefResolveOp resolve) {
290 // Merge dataflow, under the same conditions as above for Connect.
291 // 1. If dataflow at the resolve.getRef is known, propagate that to
292 // the result. This is true for downward scoped XMRs, that is,
293 // RefSendOp must be visited before the corresponding RefResolveOp
294 // is visited.
295 // 2. Else, just record that both result and ref should have the
296 // same reaching RefSend. This condition is true for upward scoped
297 // XMRs. That is, RefResolveOp can be visited before the
298 // corresponding RefSendOp is recorded.
299
301 if (!isZeroWidth(resolve.getType()))
302 dataFlowClasses->unionSets(resolve.getRef(), resolve.getResult());
303 resolveOps.push_back(resolve);
304 return success();
305 })
306 .Case<RefCastOp>([&](RefCastOp op) {
307 markForRemoval(op);
308 if (!isZeroWidth(op.getType().getType()))
309 dataFlowClasses->unionSets(op.getInput(), op.getResult());
310 return success();
311 })
312 .Case<Forceable>([&](Forceable op) {
313 // Handle declarations containing refs as "data".
314 if (type_isa<RefType>(op.getDataRaw().getType())) {
315 markForRemoval(op);
316 return success();
317 }
318
319 // Otherwise, if forceable track the rwprobe result.
320 if (!op.isForceable() || op.getDataRef().use_empty() ||
321 isZeroWidth(op.getDataType()))
322 return success();
323
324 addReachingSendsEntry(op.getDataRef(), getInnerRefTo(op));
325 return success();
326 })
327 .Case<RefForceOp, RefForceInitialOp, RefReleaseOp,
328 RefReleaseInitialOp>([&](auto op) {
329 forceAndReleaseOps.push_back(op);
330 return success();
331 })
332 .Default([&](auto) { return success(); });
333 };
334
335 SmallVector<FModuleOp> publicModules;
336
337 // Traverse the modules in post order.
338 auto result = instanceGraph.walkPostOrder([&](auto &node) -> LogicalResult {
339 auto module = dyn_cast<FModuleOp>(*node.getModule());
340 if (!module)
341 return success();
342 LLVM_DEBUG(llvm::dbgs()
343 << "Traversing module:" << module.getModuleNameAttr() << "\n");
344
345 moduleStates.insert({module, ModuleState(module)});
346
347 if (module.isPublic())
348 publicModules.push_back(module);
349
350 auto result = module.walk([&](Operation *op) {
351 if (transferFunc(op).failed())
352 return WalkResult::interrupt();
353 return WalkResult::advance();
354 });
355
356 if (result.wasInterrupted())
357 return failure();
358
359 // Since we walk operations pre-order and not along dataflow edges,
360 // ref.sub may not be resolvable when we encounter them (they're not
361 // just unification). This can happen when refs go through an output
362 // port or input instance result and back into the design. Handle these
363 // by walking them, resolving what we can, until all are handled or
364 // nothing can be resolved.
365 while (!indexingOps.empty()) {
366 // Grab the set of unresolved ref.sub's.
367 decltype(indexingOps) worklist;
368 worklist.swap(indexingOps);
369
370 for (auto op : worklist) {
371 auto inputEntry =
372 getRemoteRefSend(op.getInput(), /*errorIfNotFound=*/false);
373 // If we can't resolve, add back and move on.
374 if (!inputEntry)
375 indexingOps.push_back(op);
376 else
377 addReachingSendsEntry(op.getResult(), op.getOperation(),
378 inputEntry);
379 }
380 // If nothing was resolved, give up.
381 if (worklist.size() == indexingOps.size()) {
382 auto op = worklist.front();
383 getRemoteRefSend(op.getInput());
384 op.emitError(
385 "indexing through probe of unknown origin (input probe?)")
386 .attachNote(op.getInput().getLoc())
387 .append("indexing through this reference");
388 return failure();
389 }
390 }
391
392 // Record all the RefType ports to be removed later.
393 size_t numPorts = module.getNumPorts();
394 for (size_t portNum = 0; portNum < numPorts; ++portNum)
395 if (isa<RefType>(module.getPortType(portNum)))
396 setPortToRemove(module, portNum, numPorts);
397
398 return success();
399 });
400 if (failed(result))
401 return signalPassFailure();
402
403 LLVM_DEBUG({
404 for (const auto &I :
405 *dataFlowClasses) { // Iterate over all of the equivalence sets.
406 if (!I->isLeader())
407 continue; // Ignore non-leader sets.
408 // Print members in this set.
409 llvm::interleave(dataFlowClasses->members(*I), llvm::dbgs(), "\n");
410 llvm::dbgs() << "\n dataflow at leader::" << I->getData() << "\n =>";
411 auto iter = dataflowAt.find(I->getData());
412 if (iter != dataflowAt.end()) {
413 for (auto init = refSendPathList[iter->getSecond()]; init.next;
414 init = refSendPathList[*init.next])
415 llvm::dbgs() << "\n " << init;
416 }
417 llvm::dbgs() << "\n Done\n"; // Finish set.
418 }
419 });
420 for (auto refResolve : resolveOps)
421 if (handleRefResolve(refResolve).failed())
422 return signalPassFailure();
423 for (auto *op : forceAndReleaseOps)
424 if (failed(handleForceReleaseOp(op)))
425 return signalPassFailure();
426 for (auto module : publicModules) {
427 if (failed(handlePublicModuleRefPorts(module)))
428 return signalPassFailure();
429 }
431
432 // Clean up
433 moduleNamespaces.clear();
434 visitedModules.clear();
435 dataflowAt.clear();
436 refSendPathList.clear();
437 dataFlowClasses = nullptr;
438 refPortsToRemoveMap.clear();
439 opsToRemove.clear();
440 xmrPathSuffix.clear();
441 circuitNamespace = nullptr;
442 hierPathCache = nullptr;
443 }
444
445 /// Generate the ABI ref_<module> prefix string into `prefix`.
446 void getRefABIPrefix(FModuleLike mod, SmallVectorImpl<char> &prefix) {
447 auto modName = mod.getModuleName();
448 if (auto ext = dyn_cast<FExtModuleOp>(*mod))
449 modName = ext.getExtModuleName();
450 (Twine("ref_") + modName).toVector(prefix);
451 }
452
453 /// Get full macro name as StringAttr for the specified ref port.
454 /// Uses existing 'prefix', optionally preprends the backtick character.
455 StringAttr getRefABIMacroForPort(FModuleLike mod, size_t portIndex,
456 const Twine &prefix, bool backTick = false) {
457 return StringAttr::get(&getContext(), Twine(backTick ? "`" : "") + prefix +
458 "_" + mod.getPortName(portIndex));
459 }
460
461 LogicalResult resolveReferencePath(mlir::TypedValue<RefType> refVal,
462 ImplicitLocOpBuilder builder,
463 mlir::FlatSymbolRefAttr &ref,
464 SmallString<128> &stringLeaf) {
465 assert(stringLeaf.empty());
466
467 auto remoteOpPath = getRemoteRefSend(refVal);
468 if (!remoteOpPath)
469 return failure();
470 SmallVector<Attribute> refSendPath;
471 SmallVector<RefSubOp> indexing;
472 size_t lastIndex;
473 while (remoteOpPath) {
474 lastIndex = *remoteOpPath;
475 auto entr = refSendPathList[*remoteOpPath];
476 if (entr.info)
477 TypeSwitch<XMRNode::SymOrIndexOp>(entr.info)
478 .Case<Attribute>([&](auto attr) {
479 // If the path is a singular verbatim expression, the attribute of
480 // the send path list entry will be null.
481 if (attr)
482 refSendPath.push_back(attr);
483 })
484 .Case<Operation *>(
485 [&](auto *op) { indexing.push_back(cast<RefSubOp>(op)); });
486 remoteOpPath = entr.next;
487 }
488 auto iter = xmrPathSuffix.find(lastIndex);
489
490 // If this xmr has a suffix string (internal path into a module, that is not
491 // yet generated).
492 if (iter != xmrPathSuffix.end()) {
493 if (!refSendPath.empty())
494 stringLeaf.append(".");
495 stringLeaf.append(iter->getSecond());
496 }
497
498 assert(!(refSendPath.empty() && stringLeaf.empty()) &&
499 "nothing to index through");
500
501 // All indexing done as the ref is plumbed around indexes through
502 // the target/referent, not the current point of the path which
503 // describes how to access the referent we're indexing through.
504 // Above we gathered all indexing operations, so now append them
505 // to the path (after any relevant `xmrPathSuffix`) to reach
506 // the target element.
507 // Generating these strings here (especially if ref is sent
508 // out from a different design) is fragile but should get this
509 // working well enough while sorting out how to do this better.
510 // Some discussion of this can be found here:
511 // https://github.com/llvm/circt/pull/5551#discussion_r1258908834
512 for (auto subOp : llvm::reverse(indexing)) {
513 TypeSwitch<FIRRTLBaseType>(subOp.getInput().getType().getType())
514 .Case<FVectorType, OpenVectorType>([&](auto vecType) {
515 (Twine("[") + Twine(subOp.getIndex()) + "]").toVector(stringLeaf);
516 })
517 .Case<BundleType, OpenBundleType>([&](auto bundleType) {
518 auto fieldName = bundleType.getElementName(subOp.getIndex());
519 stringLeaf.append({".", fieldName});
520 });
521 }
522
523 if (!refSendPath.empty())
524 // Compute the HierPathOp that stores the path.
525 ref = FlatSymbolRefAttr::get(
526 hierPathCache
527 ->getOrCreatePath(builder.getArrayAttr(refSendPath),
528 builder.getLoc())
529 .getSymNameAttr());
530
531 return success();
532 }
533
534 LogicalResult resolveReference(mlir::TypedValue<RefType> refVal,
535 ImplicitLocOpBuilder &builder,
536 FlatSymbolRefAttr &ref, StringAttr &xmrAttr) {
537 auto remoteOpPath = getRemoteRefSend(refVal);
538 if (!remoteOpPath)
539 return failure();
540
541 SmallString<128> xmrString;
542 if (failed(resolveReferencePath(refVal, builder, ref, xmrString)))
543 return failure();
544 xmrAttr =
545 xmrString.empty() ? StringAttr{} : builder.getStringAttr(xmrString);
546
547 return success();
548 }
549
550 // Replace the Force/Release's ref argument with a resolved XMRRef.
551 LogicalResult handleForceReleaseOp(Operation *op) {
552 return TypeSwitch<Operation *, LogicalResult>(op)
553 .Case<RefForceOp, RefForceInitialOp, RefReleaseOp, RefReleaseInitialOp>(
554 [&](auto op) {
555 // Drop if zero-width target.
556 auto destType = op.getDest().getType();
557 if (isZeroWidth(destType.getType())) {
558 op.erase();
559 return success();
560 }
561
562 ImplicitLocOpBuilder builder(op.getLoc(), op);
563 FlatSymbolRefAttr ref;
564 StringAttr str;
565 if (failed(resolveReference(op.getDest(), builder, ref, str)))
566 return failure();
567
568 Value xmr =
569 moduleStates.find(op->template getParentOfType<FModuleOp>())
570 ->getSecond()
571 .getOrCreateXMRRefOp(destType, ref, str, builder);
572 op.getDestMutable().assign(xmr);
573 return success();
574 })
575 .Default([](auto *op) {
576 return op->emitError("unexpected operation kind");
577 });
578 }
579
580 // Replace the RefResolveOp with verbatim op representing the XMR.
581 LogicalResult handleRefResolve(RefResolveOp resolve) {
582 auto resWidth = getBitWidth(resolve.getType());
583 if (resWidth.has_value() && *resWidth == 0) {
584 // Donot emit 0 width XMRs, replace it with constant 0.
585 ImplicitLocOpBuilder builder(resolve.getLoc(), resolve);
586 auto zeroUintType = UIntType::get(builder.getContext(), 0);
587 auto zeroC = builder.createOrFold<BitCastOp>(
588 resolve.getType(), ConstantOp::create(builder, zeroUintType,
589 getIntZerosAttr(zeroUintType)));
590 resolve.getResult().replaceAllUsesWith(zeroC);
591 return success();
592 }
593
594 FlatSymbolRefAttr ref;
595 StringAttr str;
596 ImplicitLocOpBuilder builder(resolve.getLoc(), resolve);
597 if (failed(resolveReference(resolve.getRef(), builder, ref, str)))
598 return failure();
599
600 Value result = XMRDerefOp::create(builder, resolve.getType(), ref, str);
601 resolve.getResult().replaceAllUsesWith(result);
602 return success();
603 }
604
605 void setPortToRemove(Operation *op, size_t index, size_t numPorts) {
606 if (refPortsToRemoveMap[op].size() < numPorts)
607 refPortsToRemoveMap[op].resize(numPorts);
608 refPortsToRemoveMap[op].set(index);
609 }
610
611 // Propagate the reachable RefSendOp across modules.
612 LogicalResult handleInstanceOp(InstanceOp inst,
613 InstanceGraph &instanceGraph) {
614 Operation *mod = inst.getReferencedModule(instanceGraph);
615 if (auto extRefMod = dyn_cast<FExtModuleOp>(mod)) {
616 auto numPorts = inst.getNumResults();
617 SmallString<128> circuitRefPrefix;
618
619 /// Get the resolution string for this ref-type port.
620 auto getPath = [&](size_t portNo) {
621 // Otherwise, we're using the ref ABI. Generate the prefix string
622 // and return the macro for the specified port.
623 if (circuitRefPrefix.empty())
624 getRefABIPrefix(extRefMod, circuitRefPrefix);
625
626 return getRefABIMacroForPort(extRefMod, portNo, circuitRefPrefix, true);
627 };
628
629 for (const auto &res : llvm::enumerate(inst.getResults())) {
630 if (!isa<RefType>(inst.getResult(res.index()).getType()))
631 continue;
632
633 auto inRef = getInnerRefTo(inst);
634 auto ind = addReachingSendsEntry(res.value(), inRef);
635
636 xmrPathSuffix[ind] = getPath(res.index());
637 // The instance result and module port must be marked for removal.
638 setPortToRemove(inst, res.index(), numPorts);
639 setPortToRemove(extRefMod, res.index(), numPorts);
640 }
641 return success();
642 }
643 auto refMod = dyn_cast<FModuleOp>(mod);
644 bool multiplyInstantiated = !visitedModules.insert(refMod).second;
645 for (size_t portNum = 0, numPorts = inst.getNumResults();
646 portNum < numPorts; ++portNum) {
647 auto instanceResult = inst.getResult(portNum);
648 if (!isa<RefType>(instanceResult.getType()))
649 continue;
650 if (!refMod)
651 return inst.emitOpError("cannot lower ext modules with RefType ports");
652 // Reference ports must be removed.
653 setPortToRemove(inst, portNum, numPorts);
654 // Drop the dead-instance-ports.
655 if (instanceResult.use_empty() ||
656 isZeroWidth(type_cast<RefType>(instanceResult.getType()).getType()))
657 continue;
658 auto refModuleArg = refMod.getArgument(portNum);
659 if (inst.getPortDirection(portNum) == Direction::Out) {
660 // For output instance ports, the dataflow is into this module.
661 // Get the remote RefSendOp, that flows through the module ports.
662 // If dataflow at remote module argument does not exist, error out.
663 auto remoteOpPath = getRemoteRefSend(refModuleArg);
664 if (!remoteOpPath)
665 return failure();
666 // Get the path to reaching refSend at the referenced module argument.
667 // Now append this instance to the path to the reaching refSend.
668 addReachingSendsEntry(instanceResult, getInnerRefTo(inst),
669 remoteOpPath);
670 } else {
671 // For input instance ports, the dataflow is into the referenced module.
672 // Input RefType port implies, generating an upward scoped XMR.
673 // No need to add the instance context, since downward reference must be
674 // through single instantiated modules.
675 if (multiplyInstantiated)
676 return refMod.emitOpError(
677 "multiply instantiated module with input RefType port '")
678 << refMod.getPortName(portNum) << "'";
679 dataFlowClasses->unionSets(
680 dataFlowClasses->getOrInsertLeaderValue(refModuleArg),
681 dataFlowClasses->getOrInsertLeaderValue(instanceResult));
682 }
683 }
684 return success();
685 }
686
687 LogicalResult handlePublicModuleRefPorts(FModuleOp module) {
688 auto *body = getOperation().getBodyBlock();
689
690 // Find all the output reference ports.
691 SmallString<128> circuitRefPrefix;
692 SmallVector<std::tuple<StringAttr, StringAttr, ArrayAttr>> ports;
693 auto declBuilder =
694 ImplicitLocOpBuilder::atBlockBegin(module.getLoc(), body);
695 for (size_t portIndex = 0, numPorts = module.getNumPorts();
696 portIndex != numPorts; ++portIndex) {
697 auto refType = type_dyn_cast<RefType>(module.getPortType(portIndex));
698 if (!refType || isZeroWidth(refType.getType()) ||
699 module.getPortDirection(portIndex) != Direction::Out)
700 continue;
701 auto portValue =
702 cast<mlir::TypedValue<RefType>>(module.getArgument(portIndex));
703 mlir::FlatSymbolRefAttr ref;
704 SmallString<128> stringLeaf;
705 if (failed(resolveReferencePath(portValue, declBuilder, ref, stringLeaf)))
706 return failure();
707
708 SmallString<128> formatString;
709 if (ref)
710 formatString += "{{0}}";
711 formatString += stringLeaf;
712
713 // Insert a macro with the format:
714 // ref_<module-name>_<ref-name> <path>
715 if (circuitRefPrefix.empty())
716 getRefABIPrefix(module, circuitRefPrefix);
717 auto macroName =
718 getRefABIMacroForPort(module, portIndex, circuitRefPrefix);
719 sv::MacroDeclOp::create(declBuilder, macroName, ArrayAttr(),
720 StringAttr());
721 ports.emplace_back(macroName, declBuilder.getStringAttr(formatString),
722 ref ? declBuilder.getArrayAttr({ref}) : ArrayAttr{});
723 }
724
725 // Create a file only if the module has at least one ref port.
726 if (ports.empty())
727 return success();
728
729 // The macros will be exported to a `ref_<module-name>.sv` file.
730 // In the IR, the file is inserted before the module.
731 auto fileBuilder = ImplicitLocOpBuilder(module.getLoc(), module);
732 emit::FileOp::create(fileBuilder, circuitRefPrefix + ".sv", [&] {
733 for (auto [macroName, formatString, symbols] : ports) {
734 sv::MacroDefOp::create(fileBuilder, FlatSymbolRefAttr::get(macroName),
735 formatString, symbols);
736 }
737 });
738
739 return success();
740 }
741
742 /// Get the cached namespace for a module.
744 return moduleNamespaces.try_emplace(module, module).first->second;
745 }
746
747 InnerRefAttr getInnerRefTo(Value val) {
748 if (auto arg = dyn_cast<BlockArgument>(val))
749 return ::getInnerRefTo(
750 cast<FModuleLike>(arg.getParentBlock()->getParentOp()),
751 arg.getArgNumber(),
752 [&](FModuleLike mod) -> hw::InnerSymbolNamespace & {
753 return getModuleNamespace(mod);
754 });
755 return getInnerRefTo(val.getDefiningOp());
756 }
757
758 InnerRefAttr getInnerRefTo(Operation *op) {
759 return ::getInnerRefTo(op,
760 [&](FModuleLike mod) -> hw::InnerSymbolNamespace & {
761 return getModuleNamespace(mod);
762 });
763 }
764
765 void markForRemoval(Operation *op) { opsToRemove.push_back(op); }
766
767 std::optional<size_t> getRemoteRefSend(Value val,
768 bool errorIfNotFound = true) {
769 auto iter = dataflowAt.find(dataFlowClasses->getOrInsertLeaderValue(val));
770 if (iter != dataflowAt.end())
771 return iter->getSecond();
772 if (!errorIfNotFound)
773 return std::nullopt;
774 // The referenced module must have already been analyzed, error out if the
775 // dataflow at the child module is not resolved.
776 if (BlockArgument arg = dyn_cast<BlockArgument>(val))
777 arg.getOwner()->getParentOp()->emitError(
778 "reference dataflow cannot be traced back to the remote read op "
779 "for module port '")
780 << dyn_cast<FModuleOp>(arg.getOwner()->getParentOp())
781 .getPortName(arg.getArgNumber())
782 << "'";
783 else
784 val.getDefiningOp()->emitOpError(
785 "reference dataflow cannot be traced back to the remote read op");
786 signalPassFailure();
787 return std::nullopt;
788 }
789
790 size_t
791 addReachingSendsEntry(Value atRefVal, XMRNode::SymOrIndexOp info,
792 std::optional<size_t> continueFrom = std::nullopt) {
793 auto leader = dataFlowClasses->getOrInsertLeaderValue(atRefVal);
794 auto indx = refSendPathList.size();
795 dataflowAt[leader] = indx;
796 refSendPathList.push_back({info, continueFrom});
797 return indx;
798 }
799
801 // Now erase all the Ops and ports of RefType.
802 // This needs to be done as the last step to ensure uses are erased before
803 // the def is erased.
804 for (Operation *op : llvm::reverse(opsToRemove))
805 op->erase();
806 for (auto iter : refPortsToRemoveMap)
807 if (auto mod = dyn_cast<FModuleOp>(iter.getFirst()))
808 mod.erasePorts(iter.getSecond());
809 else if (auto mod = dyn_cast<FExtModuleOp>(iter.getFirst()))
810 mod.erasePorts(iter.getSecond());
811 else if (auto inst = dyn_cast<InstanceOp>(iter.getFirst())) {
812 inst.cloneWithErasedPortsAndReplaceUses(iter.getSecond());
813 inst.erase();
814 } else if (auto mem = dyn_cast<MemOp>(iter.getFirst())) {
815 // Remove all debug ports of the memory.
816 ImplicitLocOpBuilder builder(mem.getLoc(), mem);
817 SmallVector<Attribute, 4> resultNames;
818 SmallVector<Type, 4> resultTypes;
819 SmallVector<Attribute, 4> portAnnotations;
820 SmallVector<Value, 4> oldResults;
821 for (const auto &res : llvm::enumerate(mem.getResults())) {
822 if (isa<RefType>(mem.getResult(res.index()).getType()))
823 continue;
824 resultNames.push_back(mem.getPortNameAttr(res.index()));
825 resultTypes.push_back(res.value().getType());
826 portAnnotations.push_back(mem.getPortAnnotation(res.index()));
827 oldResults.push_back(res.value());
828 }
829 auto newMem = MemOp::create(
830 builder, resultTypes, mem.getReadLatency(), mem.getWriteLatency(),
831 mem.getDepth(), RUWBehavior::Undefined,
832 builder.getArrayAttr(resultNames), mem.getNameAttr(),
833 mem.getNameKind(), mem.getAnnotations(),
834 builder.getArrayAttr(portAnnotations), mem.getInnerSymAttr(),
835 mem.getInitAttr(), mem.getPrefixAttr());
836 for (const auto &res : llvm::enumerate(oldResults))
837 res.value().replaceAllUsesWith(newMem.getResult(res.index()));
838 mem.erase();
839 }
840 opsToRemove.clear();
841 refPortsToRemoveMap.clear();
842 dataflowAt.clear();
843 refSendPathList.clear();
844 moduleStates.clear();
845 }
846
848
849private:
850 /// Cached module namespaces.
851 DenseMap<Operation *, hw::InnerSymbolNamespace> moduleNamespaces;
852
853 DenseSet<Operation *> visitedModules;
854 /// Map of a reference value to an entry into refSendPathList. Each entry in
855 /// refSendPathList represents the path to RefSend.
856 /// The path is required since there can be multiple paths to the RefSend and
857 /// we need to identify a unique path.
858 DenseMap<Value, size_t> dataflowAt;
859
860 /// refSendPathList is used to construct a path to the RefSendOp. Each entry
861 /// is an XMRNode, with an InnerRefAttr or indexing op, and a pointer to the
862 /// next node in the path. The InnerRefAttr can be to an InstanceOp or to the
863 /// XMR defining op, the index op records narrowing along path. All the nodes
864 /// representing an InstanceOp or indexing operation must have a valid
865 /// NextNodeOnPath. Only the node representing the final XMR defining op has
866 /// no NextNodeOnPath, which denotes a leaf node on the path.
867 SmallVector<XMRNode> refSendPathList;
868
869 llvm::EquivalenceClasses<Value> *dataFlowClasses;
870 // Instance and module ref ports that needs to be removed.
871 DenseMap<Operation *, llvm::BitVector> refPortsToRemoveMap;
872
873 /// RefResolve, RefSend, and Connects involving them that will be removed.
874 SmallVector<Operation *> opsToRemove;
875
876 /// Record the internal path to an external module or a memory.
877 DenseMap<size_t, SmallString<128>> xmrPathSuffix;
878
880
881 /// Utility to create HerPathOps at a predefined location in the circuit.
882 /// This handles caching and keeps the order consistent.
884
885 /// Per-module helpers for creating operations within modules.
886 DenseMap<FModuleOp, ModuleState> moduleStates;
887};
assert(baseType &&"element must be base type")
static mlir::Operation * resolve(Context &context, mlir::SymbolRefAttr sym)
static std::vector< mlir::Value > toVector(mlir::ValueRange range)
static Block * getBodyBlock(FModuleLike mod)
LogicalResult resolveReference(mlir::TypedValue< RefType > refVal, ImplicitLocOpBuilder &builder, FlatSymbolRefAttr &ref, StringAttr &xmrAttr)
Definition LowerXMR.cpp:534
DenseMap< Operation *, hw::InnerSymbolNamespace > moduleNamespaces
Cached module namespaces.
Definition LowerXMR.cpp:851
llvm::EquivalenceClasses< Value > * dataFlowClasses
Definition LowerXMR.cpp:869
DenseMap< size_t, SmallString< 128 > > xmrPathSuffix
Record the internal path to an external module or a memory.
Definition LowerXMR.cpp:877
InnerRefAttr getInnerRefTo(Value val)
Definition LowerXMR.cpp:747
size_t addReachingSendsEntry(Value atRefVal, XMRNode::SymOrIndexOp info, std::optional< size_t > continueFrom=std::nullopt)
Definition LowerXMR.cpp:791
DenseMap< FModuleOp, ModuleState > moduleStates
Per-module helpers for creating operations within modules.
Definition LowerXMR.cpp:886
LogicalResult resolveReferencePath(mlir::TypedValue< RefType > refVal, ImplicitLocOpBuilder builder, mlir::FlatSymbolRefAttr &ref, SmallString< 128 > &stringLeaf)
Definition LowerXMR.cpp:461
DenseMap< Value, size_t > dataflowAt
Map of a reference value to an entry into refSendPathList.
Definition LowerXMR.cpp:858
void setPortToRemove(Operation *op, size_t index, size_t numPorts)
Definition LowerXMR.cpp:605
hw::InnerSymbolNamespace & getModuleNamespace(FModuleLike module)
Get the cached namespace for a module.
Definition LowerXMR.cpp:743
void markForRemoval(Operation *op)
Definition LowerXMR.cpp:765
hw::HierPathCache * hierPathCache
Utility to create HerPathOps at a predefined location in the circuit.
Definition LowerXMR.cpp:883
void garbageCollect()
Definition LowerXMR.cpp:800
LogicalResult handlePublicModuleRefPorts(FModuleOp module)
Definition LowerXMR.cpp:687
void getRefABIPrefix(FModuleLike mod, SmallVectorImpl< char > &prefix)
Generate the ABI ref_<module> prefix string into prefix.
Definition LowerXMR.cpp:446
void runOnOperation() override
Definition LowerXMR.cpp:128
LogicalResult handleRefResolve(RefResolveOp resolve)
Definition LowerXMR.cpp:581
DenseMap< Operation *, llvm::BitVector > refPortsToRemoveMap
Definition LowerXMR.cpp:871
SmallVector< XMRNode > refSendPathList
refSendPathList is used to construct a path to the RefSendOp.
Definition LowerXMR.cpp:867
LogicalResult handleInstanceOp(InstanceOp inst, InstanceGraph &instanceGraph)
Definition LowerXMR.cpp:612
LogicalResult handleForceReleaseOp(Operation *op)
Definition LowerXMR.cpp:551
std::optional< size_t > getRemoteRefSend(Value val, bool errorIfNotFound=true)
Definition LowerXMR.cpp:767
DenseSet< Operation * > visitedModules
Definition LowerXMR.cpp:853
InnerRefAttr getInnerRefTo(Operation *op)
Definition LowerXMR.cpp:758
StringAttr getRefABIMacroForPort(FModuleLike mod, size_t portIndex, const Twine &prefix, bool backTick=false)
Get full macro name as StringAttr for the specified ref port.
Definition LowerXMR.cpp:455
CircuitNamespace * circuitNamespace
Definition LowerXMR.cpp:879
bool isZeroWidth(FIRRTLBaseType t)
Definition LowerXMR.cpp:847
SmallVector< Operation * > opsToRemove
RefResolve, RefSend, and Connects involving them that will be removed.
Definition LowerXMR.cpp:874
int32_t getBitWidthOrSentinel()
If this is an IntType, AnalogType, or sugar type for a single bit (Clock, Reset, etc) then return the...
This graph tracks modules and where they are instantiated.
decltype(auto) walkPostOrder(Fn &&fn)
Perform a post-order walk across the modules.
FieldRef getFieldRefFromValue(Value value, bool lookThroughCasts=false)
Get the FieldRef from a value.
hw::InnerRefAttr getInnerRefTo(const hw::InnerSymTarget &target, GetNamespaceCallback getNamespace)
Obtain an inner reference to the target (operation or port), adding an inner symbol as necessary.
llvm::raw_ostream & operator<<(llvm::raw_ostream &os, const InstanceInfo::LatticeValue &value)
std::pair< std::string, bool > getFieldName(const FieldRef &fieldRef, bool nameSafe=false)
Get a string identifier representing the FieldRef.
std::optional< int64_t > getBitWidth(FIRRTLBaseType type, bool ignoreFlip=false)
IntegerAttr getIntZerosAttr(Type type)
Utility for generating a constant zero attribute.
void info(Twine message)
Definition LSPUtils.cpp:20
The InstanceGraph op interface, see InstanceGraphInterface.td for more details.
The namespace of a CircuitOp, generally inhabited by modules.
Definition Namespace.h:24