CIRCT 23.0.0git
Loading...
Searching...
No Matches
LowerLayers.cpp
Go to the documentation of this file.
1//===- LowerLayers.cpp - Lower Layers by Convention -------------*- 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// This pass lowers FIRRTL layers based on their specified convention.
9//
10//===----------------------------------------------------------------------===//
11
21#include "circt/Support/Utils.h"
22#include "mlir/Pass/Pass.h"
23#include "llvm/ADT/PostOrderIterator.h"
24#include "llvm/ADT/SmallPtrSet.h"
25#include "llvm/Support/Debug.h"
26#include "llvm/Support/Mutex.h"
27
28#define DEBUG_TYPE "firrtl-lower-layers"
29
30namespace circt {
31namespace firrtl {
32#define GEN_PASS_DEF_LOWERLAYERS
33#include "circt/Dialect/FIRRTL/Passes.h.inc"
34} // namespace firrtl
35} // namespace circt
36
37using namespace circt;
38using namespace firrtl;
39
40namespace {
41
42/// Indicates the kind of reference that was captured.
43enum class ConnectKind {
44 /// A normal captured value. This is a read of a value outside the
45 /// layerblock.
46 NonRef,
47 /// A reference. This is a destination of a ref define.
48 Ref
49};
50
51struct ConnectInfo {
52 Value value;
53 ConnectKind kind;
54};
55
56/// The delimiters that should be used for a given generated name. These vary
57/// for modules and files, as well as by convention.
58enum class Delimiter { BindModule = '_', BindFile = '-', InlineMacro = '$' };
59
60/// This struct contains pre-allocated "safe" names that parallel regions can
61/// use to create names in the global namespace. This is allocated per-layer
62/// block.
63struct LayerBlockGlobals {
64 /// If the layer needs to create a module, use this name.
65 StringRef moduleName;
66
67 /// If the layer needs to create a hw::HierPathOp, use this name.
68 StringRef hierPathName;
69};
70
71} // namespace
72
73// A mapping of an old InnerRefAttr to the new inner symbol and module name that
74// need to be spliced into the old InnerRefAttr. This is used to fix
75// hierarchical path operations after layers are converted to modules.
77 DenseMap<hw::InnerRefAttr, std::pair<hw::InnerSymAttr, StringAttr>>;
78
79//===----------------------------------------------------------------------===//
80// Naming Helpers
81//===----------------------------------------------------------------------===//
82
83static void appendName(StringRef name, SmallString<32> &output,
84 bool toLower = false,
85 Delimiter delimiter = Delimiter::BindFile) {
86 if (name.empty())
87 return;
88 if (!output.empty())
89 output.push_back(static_cast<char>(delimiter));
90 output.append(name);
91 if (!toLower)
92 return;
93 auto i = output.size() - name.size();
94 output[i] = llvm::toLower(output[i]);
95}
96
97static void appendName(const ArrayRef<FlatSymbolRefAttr> &names,
98 SmallString<32> &output, bool toLower = false,
99 Delimiter delimiter = Delimiter::BindFile) {
100 for (auto name : names)
101 appendName(name.getValue(), output, toLower, delimiter);
102}
103
104static void appendName(SymbolRefAttr name, SmallString<32> &output,
105 bool toLower = false,
106 Delimiter delimiter = Delimiter::BindFile) {
107 appendName(name.getRootReference(), output, toLower, delimiter);
108 appendName(name.getNestedReferences(), output, toLower, delimiter);
109}
110
111/// For a layer `@A::@B::@C` in module Module,
112/// the generated module is called `Module_A_B_C`.
113static SmallString<32> moduleNameForLayer(StringRef moduleName,
114 SymbolRefAttr layerName) {
115 SmallString<32> result;
116 appendName(moduleName, result, /*toLower=*/false,
117 /*delimiter=*/Delimiter::BindModule);
118 appendName(layerName, result, /*toLower=*/false,
119 /*delimiter=*/Delimiter::BindModule);
120 return result;
121}
122
123static SmallString<32> hierPathNameForLayer(StringRef moduleName,
124 SymbolRefAttr layerName) {
125 SmallString<32> result("__lowerLayers_path");
126 appendName(moduleName, result, /*toLower=*/false,
127 /*delimiter=*/Delimiter::BindModule);
128 appendName(layerName, result, /*toLower=*/false,
129 /*delimiter=*/Delimiter::BindModule);
130 return result;
131}
132
133/// For a layerblock `@A::@B::@C`,
134/// the generated instance is called `a_b_c`.
135static SmallString<32> instanceNameForLayer(SymbolRefAttr layerName) {
136 SmallString<32> result;
137 appendName(layerName, result, /*toLower=*/true,
138 /*delimiter=*/Delimiter::BindModule);
139 return result;
140}
141
142static SmallString<32> fileNameForLayer(StringRef moduleName, StringAttr root,
143 ArrayRef<FlatSymbolRefAttr> nested) {
144 SmallString<32> result;
145 result.append("layers");
146 appendName(moduleName, result);
147 appendName(root, result);
148 appendName(nested, result);
149 result.append(".sv");
150 return result;
151}
152
153/// For all layerblocks `@A::@B::@C` in a module called Module,
154/// the output filename is `layers-Module-A-B-C.sv`.
155static SmallString<32> fileNameForLayer(StringRef moduleName,
156 SymbolRefAttr layerName) {
157 return fileNameForLayer(moduleName, layerName.getRootReference(),
158 layerName.getNestedReferences());
159}
160
161/// For all layerblocks `@A::@B::@C` in a module called Module,
162/// the include-guard macro is `layers_Module_A_B_C`.
163static SmallString<32> guardMacroNameForLayer(StringRef moduleName,
164 SymbolRefAttr layerName) {
165 SmallString<32> result;
166 result.append("layers");
167 appendName(moduleName, result, false, Delimiter::BindModule);
168 appendName(layerName, result, false, Delimiter::BindModule);
169 return result;
170}
171
172/// For a layerblock `@A::@B::@C`, the verilog macro is `A_B_C`.
173static SmallString<32>
174macroNameForLayer(StringRef circuitName,
175 ArrayRef<FlatSymbolRefAttr> layerName) {
176 SmallString<32> result("layer");
177 for (auto part : layerName)
178 appendName(part, result, /*toLower=*/false,
179 /*delimiter=*/Delimiter::InlineMacro);
180 return result;
181}
182
183//===----------------------------------------------------------------------===//
184// LowerLayersPass
185//===----------------------------------------------------------------------===//
186
187namespace {
188/// Information about each bind file we are emitting. During a prepass, we walk
189/// the modules to find layerblocks, creating an emit::FileOp for each bound
190/// layer used under each module. As we do this, we build a table of these info
191/// objects for quick lookup later.
192struct BindFileInfo {
193 /// The filename of the bind file _without_ a directory.
194 StringAttr filename;
195 /// Where to insert bind statements into the bind file.
196 Block *body;
197};
198} // namespace
199
201 : public circt::firrtl::impl::LowerLayersBase<LowerLayersPass> {
202 using Base::Base;
203
204 hw::OutputFileAttr getOutputFile(SymbolRefAttr layerName) {
205 auto layer = symbolToLayer.lookup(layerName);
206 if (!layer)
207 return nullptr;
208 return layer->getAttrOfType<hw::OutputFileAttr>("output_file");
209 }
210
211 hw::OutputFileAttr outputFileForLayer(StringRef moduleName,
212 SymbolRefAttr layerName) {
213 if (auto file = getOutputFile(layerName))
214 return hw::OutputFileAttr::getFromDirectoryAndFilename(
215 &getContext(), file.getDirectory(),
216 fileNameForLayer(moduleName, layerName),
217 /*excludeFromFileList=*/true);
218 return hw::OutputFileAttr::getFromFilename(
219 &getContext(), fileNameForLayer(moduleName, layerName),
220 /*excludeFromFileList=*/true);
221 }
222
223 /// Safely build a new module with a given namehint. This handles geting a
224 /// lock to modify the top-level circuit.
225 FModuleOp buildNewModule(OpBuilder &builder, LayerBlockOp layerBlock,
226 ArrayRef<PortInfo> ports);
227
228 /// Strip layer colors from the module's interface.
229 FailureOr<InnerRefMap> runOnModuleLike(FModuleLike moduleLike);
230
231 /// Extract layerblocks and strip probe colors from all ops under the module.
232 LogicalResult runOnModuleBody(FModuleOp moduleOp, InnerRefMap &innerRefMap);
233
234 /// Update the module's port types to remove any explicit layer requirements
235 /// from any probe types.
236 void removeLayersFromPorts(FModuleLike moduleLike);
237
238 /// Update the value's type to remove any layers from any probe types.
239 void removeLayersFromValue(Value value);
240
241 /// Lower an inline layerblock to an ifdef block.
242 void lowerInlineLayerBlock(LayerOp layer, LayerBlockOp layerBlock);
243
244 /// Build macro declarations and cache information about the layers.
245 void preprocessLayers(CircuitNamespace &ns, OpBuilder &b, LayerOp layer,
246 StringRef circuitName,
247 SmallVector<FlatSymbolRefAttr> &stack);
249
250 /// For each module, build a bindfile for each bound-layer, if needed.
252
253 /// Build the bindfile skeletons for each module. Set up a table which tells
254 /// us for each module/layer pair, where to insert the bind operations.
256
257 /// Build the bindfile skeleton for a module.
259 FModuleOp module);
260
261 /// Record the supposed bindfiles for any known layers of the ext module.
263 FExtModuleOp extModule);
264
265 /// Build a bindfile skeleton for a particular module and layer.
267 OpBuilder &b, SymbolRefAttr layerName, LayerOp layer);
268
269 /// Entry point for the function.
270 void runOnOperation() override;
271
272 /// Indicates exclusive access to modify the circuitNamespace and the circuit.
273 llvm::sys::SmartMutex<true> *circuitMutex;
274
275 /// A map of layer blocks to "safe" global names which are fine to create in
276 /// the circuit namespace.
277 DenseMap<LayerBlockOp, LayerBlockGlobals> layerBlockGlobals;
278
279 /// A map from inline layers to their macro names.
280 DenseMap<LayerOp, FlatSymbolRefAttr> macroNames;
281
282 /// A mapping of symbol name to layer operation. This also serves as an
283 /// iterable list of all layers declared in a circuit. We use a map vector so
284 /// that the iteration order matches the order of declaration in the circuit.
285 /// This order is not required for correctness, it helps with legibility.
286 llvm::MapVector<SymbolRefAttr, LayerOp> symbolToLayer;
287
288 /// Utility for creating hw::HierPathOp.
290
291 /// A mapping from module*layer to bindfile name.
292 DenseMap<Operation *, DenseMap<LayerOp, BindFileInfo>> bindFiles;
293};
294
295/// Multi-process safe function to build a module in the circuit and return it.
296/// The name provided is only a namehint for the module---a unique name will be
297/// generated if there are conflicts with the namehint in the circuit-level
298/// namespace.
299FModuleOp LowerLayersPass::buildNewModule(OpBuilder &builder,
300 LayerBlockOp layerBlock,
301 ArrayRef<PortInfo> ports) {
302 auto location = layerBlock.getLoc();
303 auto namehint = layerBlockGlobals.lookup(layerBlock).moduleName;
304 llvm::sys::SmartScopedLock<true> instrumentationLock(*circuitMutex);
305 FModuleOp newModule = FModuleOp::create(
306 builder, location, builder.getStringAttr(namehint),
307 ConventionAttr::get(builder.getContext(), Convention::Internal), ports,
308 ArrayAttr{});
309 if (auto dir = getOutputFile(layerBlock.getLayerNameAttr())) {
310 assert(dir.isDirectory());
311 newModule->setAttr("output_file", dir);
312 }
313 SymbolTable::setSymbolVisibility(newModule, SymbolTable::Visibility::Private);
314 return newModule;
315}
316
318 auto type = dyn_cast<RefType>(value.getType());
319 if (!type || !type.getLayer())
320 return;
321 value.setType(type.removeLayer());
322}
323
324void LowerLayersPass::removeLayersFromPorts(FModuleLike moduleLike) {
325 auto oldTypeAttrs = moduleLike.getPortTypesAttr();
326 SmallVector<Attribute> newTypeAttrs;
327 newTypeAttrs.reserve(oldTypeAttrs.size());
328 bool changed = false;
329
330 for (auto typeAttr : oldTypeAttrs.getAsRange<TypeAttr>()) {
331 if (auto refType = dyn_cast<RefType>(typeAttr.getValue())) {
332 if (refType.getLayer()) {
333 typeAttr = TypeAttr::get(refType.removeLayer());
334 changed = true;
335 }
336 }
337 newTypeAttrs.push_back(typeAttr);
338 }
339
340 if (!changed)
341 return;
342
343 moduleLike.setPortTypesAttr(
344 ArrayAttr::get(moduleLike.getContext(), newTypeAttrs));
345
346 if (auto moduleOp = dyn_cast<FModuleOp>(moduleLike.getOperation())) {
347 for (auto arg : moduleOp.getBodyBlock()->getArguments())
349 }
350}
351
352FailureOr<InnerRefMap>
353LowerLayersPass::runOnModuleLike(FModuleLike moduleLike) {
354 LLVM_DEBUG({
355 llvm::dbgs() << "Module: " << moduleLike.getModuleName() << "\n";
356 llvm::dbgs() << " Examining Layer Blocks:\n";
357 });
358
359 // Strip away layers from the interface of the module-like op.
360 InnerRefMap innerRefMap;
361 auto result =
362 TypeSwitch<Operation *, LogicalResult>(moduleLike.getOperation())
363 .Case<FModuleOp>([&](auto op) {
364 op.setLayers({});
366 return runOnModuleBody(op, innerRefMap);
367 })
368 .Case<FExtModuleOp>([&](auto op) {
369 op.setKnownLayers({});
370 op.setLayers({});
372 return success();
373 })
374 .Case<FIntModuleOp, FMemModuleOp>([&](auto op) {
375 op.setLayers({});
377 return success();
378 })
379 .Case<ClassOp, ExtClassOp>([](auto) { return success(); })
380 .Default(
381 [](auto *op) { return op->emitError("unknown module-like op"); });
382
383 if (failed(result))
384 return failure();
385
386 return innerRefMap;
387}
388
390 LayerBlockOp layerBlock) {
391 if (!layerBlock.getBody()->empty()) {
392 OpBuilder builder(layerBlock);
393 auto macroName = macroNames[layer];
394 auto ifDef = sv::IfDefOp::create(builder, layerBlock.getLoc(), macroName);
395 ifDef.getBodyRegion().takeBody(layerBlock.getBodyRegion());
396 }
397 layerBlock.erase();
398}
399
400LogicalResult LowerLayersPass::runOnModuleBody(FModuleOp moduleOp,
401 InnerRefMap &innerRefMap) {
402 hw::InnerSymbolNamespace ns(moduleOp);
403
404 // Get or create a node op for a value captured by a layer block.
405 auto getOrCreateNodeOp = [&](Value operand,
406 ImplicitLocOpBuilder &builder) -> NodeOp {
407 // Create a new node. Put it in the cache and use it.
408 OpBuilder::InsertionGuard guard(builder);
409 builder.setInsertionPointAfterValue(operand);
410 SmallString<16> nameHint;
411 // Try to generate a "good" name hint to use for the node.
412 if (auto *definingOp = operand.getDefiningOp()) {
413 if (auto instanceOp = dyn_cast<InstanceOp>(definingOp)) {
414 nameHint.append(instanceOp.getName());
415 nameHint.push_back('_');
416 nameHint.append(
417 instanceOp.getPortName(cast<OpResult>(operand).getResultNumber()));
418 } else if (auto opName = definingOp->getAttrOfType<StringAttr>("name")) {
419 nameHint.append(opName);
420 }
421 nameHint.append("_layer_probe");
422 }
423
424 return NodeOp::create(builder, operand.getLoc(), operand,
425 StringRef(nameHint));
426 };
427
428 // Determine the replacement for an operand within the current region. Keep a
429 // densemap of replacements around to avoid creating the same hardware
430 // multiple times.
431 DenseMap<Value, Value> replacements;
432 std::function<Value(Operation *, Value)> getReplacement =
433 [&](Operation *user, Value value) -> Value {
434 auto it = replacements.find(value);
435 if (it != replacements.end())
436 return it->getSecond();
437
438 ImplicitLocOpBuilder localBuilder(value.getLoc(), &getContext());
439 Value replacement;
440
441 auto layerBlockOp = user->getParentOfType<LayerBlockOp>();
442 localBuilder.setInsertionPointToStart(layerBlockOp.getBody());
443
444 // If the operand is "special", e.g., it has no XMR representation, then we
445 // need to clone it.
446 //
447 // TODO: Change this to recursively clone. This will matter once FString
448 // operations have operands.
449 if (type_isa<FStringType>(value.getType())) {
450 localBuilder.setInsertionPoint(user);
451 replacement = localBuilder.clone(*value.getDefiningOp())->getResult(0);
452 replacements.insert({value, replacement});
453 return replacement;
454 }
455
456 // If the operand is an XMR ref, then we _have_ to clone it.
457 auto *definingOp = value.getDefiningOp();
458 if (isa_and_present<XMRRefOp>(definingOp)) {
459 replacement = localBuilder.clone(*definingOp)->getResult(0);
460 replacements.insert({value, replacement});
461 return replacement;
462 }
463
464 // If the value is an instance input port, recurse on its driver instead.
465 // Instance input ports have special flow semantics (sink flow but can be
466 // read from). By recursing on the driver, we avoid creating a node for the
467 // instance port itself and instead directly XMR reference the driver,
468 // creating an intermediary node to dereference if the driver cannot support
469 // an inner symbol. This avoids creating intermediary nodes unless
470 // absolutely required while also avoiding dead code.
471 if (isa_and_present<InstanceOp, InstanceChoiceOp>(definingOp)) {
472 bool isInstanceInputPort =
473 TypeSwitch<Operation *, bool>(definingOp)
474 .Case<InstanceOp, InstanceChoiceOp>([&](auto instOp) {
475 for (auto [idx, result] : llvm::enumerate(instOp.getResults()))
476 if (result == value)
477 return instOp.getPortDirection(idx) == Direction::In;
478 return false;
479 })
480 .Default(false);
481
482 if (isInstanceInputPort) {
483 if (auto driver = getDriverFromConnect(value)) {
484 // Recurse on the driver to get its replacement. The connect stays
485 // as-is (driver -> instance port) in the original module.
486 replacement = getReplacement(user, driver);
487 replacements.insert({value, replacement});
488 return replacement;
489 }
490 }
491 }
492
493 // Determine the replacement value for the captured operand. There are
494 // three cases that can occur:
495 //
496 // 1. Capturing something zero-width. Create a zero-width constant zero.
497 // 2. Capture something that can handle an inner sym. Add the inner sym if
498 // it doesn't exist and XMRderef that.
499 // 3. Capture something that can't handle an inner sym. Add a node and XMR
500 // deref the node.
501 //
502 // The handling of (2) and (3) is diffuse in the code below due to needing
503 // to split things based on whether a value has a defining operation or not.
504 auto baseType = type_cast<FIRRTLBaseType>(value.getType());
505 if (baseType && baseType.getBitWidthOrSentinel() == 0) {
506 OpBuilder::InsertionGuard guard(localBuilder);
507 auto zeroUIntType = UIntType::get(localBuilder.getContext(), 0);
508 replacement = localBuilder.createOrFold<BitCastOp>(
509 value.getType(), ConstantOp::create(localBuilder, zeroUIntType,
510 getIntZerosAttr(zeroUIntType)));
511 } else {
512 hw::InnerRefAttr innerRef;
513 if (auto *definingOp = value.getDefiningOp()) {
514 // Check if the operation can support an inner symbol and targets a
515 // specific result.
516 auto innerSymOp = dyn_cast<hw::InnerSymbolOpInterface>(definingOp);
517 if (innerSymOp && innerSymOp.getTargetResultIndex()) {
518 // The operation can support an inner symbol, so add one directly.
519 innerRef = getInnerRefTo(
520 innerSymOp,
521 [&](auto) -> hw::InnerSymbolNamespace & { return ns; });
522 } else {
523 // The operation cannot support an inner symbol, or it has multiple
524 // results and doesn't target a specific result, so create a node
525 // and XMR deref the node.
526 auto node = getOrCreateNodeOp(value, localBuilder);
527 innerRef = getInnerRefTo(
528 node, [&](auto) -> hw::InnerSymbolNamespace & { return ns; });
529 auto newValue = node.getResult();
530 value.replaceAllUsesExcept(newValue, node);
531 value = newValue;
532 }
533 } else {
534 auto portIdx = cast<BlockArgument>(value).getArgNumber();
535 innerRef = getInnerRefTo(
536 cast<FModuleLike>(*moduleOp), portIdx,
537 [&](auto) -> hw::InnerSymbolNamespace & { return ns; });
538 }
539
540 hw::HierPathOp hierPathOp;
541 {
542 // TODO: Move to before parallel region to avoid the lock.
543 auto insertPoint = OpBuilder::InsertPoint(moduleOp->getBlock(),
544 Block::iterator(moduleOp));
545 llvm::sys::SmartScopedLock<true> circuitLock(*circuitMutex);
546 hierPathOp = hierPathCache->getOrCreatePath(
547 localBuilder.getArrayAttr({innerRef}), localBuilder.getLoc(),
548 insertPoint, layerBlockGlobals.lookup(layerBlockOp).hierPathName);
549 hierPathOp.setVisibility(SymbolTable::Visibility::Private);
550 }
551
552 replacement = XMRDerefOp::create(localBuilder, value.getType(),
553 hierPathOp.getSymNameAttr());
554 }
555
556 replacements.insert({value, replacement});
557
558 return replacement;
559 };
560
561 // A map of instance ops to modules that this pass creates. This is used to
562 // check if this was an instance that we created and to do fast module
563 // dereferencing (avoiding a symbol table).
564 DenseMap<Operation *, FModuleOp> createdInstances;
565
566 // Check that the preconditions for this pass are met. Reject any ops which
567 // must have been removed before this runs.
568 auto opPreconditionCheck = [](Operation *op) -> LogicalResult {
569 // LowerXMR op removal postconditions.
570 if (isa<RefCastOp, RefDefineOp, RefResolveOp, RefSendOp, RefSubOp,
571 RWProbeOp>(op))
572 return op->emitOpError()
573 << "cannot be handled by the lower-layers pass. This should have "
574 "already been removed by the lower-xmr pass.";
575
576 return success();
577 };
578
579 // Utility to determine the domain type of some value. This looks backwards
580 // through connections to find the source driver in the module and gets the
581 // domain type of that. This is necessary as intermediary wires do not track
582 // domain information.
583 //
584 // This cannot use `getModuleScopedDriver` because this can be called while
585 // `LayerBlockOp`s have temporarily gained block arguments while they are
586 // being migrated to modules. This is worked around by caching the known
587 // domain kinds of earlier-visited `WireOp`s to avoid needing to look through
588 // these non-`ModuleOp` block arguments.
589 //
590 // TODO: Simplify this once wires have domain kind information [1].
591 //
592 // [1]: https://github.com/llvm/circt/issues/9398
593 DenseMap<Operation *, Attribute> domainMap;
594 auto getDomain = [&domainMap](Value value,
595 Attribute &domain) -> LogicalResult {
596 SmallVector<Operation *> wires;
597
598 // Use iteration as this is recursive over the IR. `value` is changed for
599 // each iteration.
600 while (!domain) {
601 if (auto arg = dyn_cast<BlockArgument>(value)) {
602 domain = cast<FModuleLike>(arg.getOwner()->getParentOp())
603 .getDomainInfoAttrForPort(arg.getArgNumber());
604 continue;
605 }
606
607 auto result =
608 TypeSwitch<Operation *, LogicalResult>(value.getDefiningOp())
609 .Case<WireOp>([&](WireOp op) {
610 auto it = domainMap.find(op);
611 if (it != domainMap.end()) {
612 domain = it->getSecond();
613 return success();
614 }
615 for (auto *user : op->getUsers()) {
616 auto connect = dyn_cast<FConnectLike>(user);
617 if (!connect || connect.getDest() != value)
618 continue;
619 value = connect.getSrc();
620 wires.push_back(op);
621 return success();
622 }
623 emitError(value.getLoc())
624 << "unable to determine domain kind for source likely "
625 "indicating a "
626 "violation of static-single-connect";
627 return failure();
628 })
629 .Case<InstanceOp>([&](auto op) {
630 domain =
631 op.getPortDomain(cast<OpResult>(value).getResultNumber());
632 return success();
633 })
634 .Case<DomainCreateAnonOp>([&](auto op) {
635 domain = op.getDomainAttr();
636 return success();
637 })
638 .Default([&](auto op) {
639 op->emitOpError() << "unhandled domain source in 'LowerLayers";
640 return failure();
641 });
642 if (failed(result))
643 return failure();
644 }
645
646 // Update the `domainMap` with wire/domain information.
647 for (auto *wire : wires)
648 domainMap[wire] = domain;
649
650 return success();
651 };
652
653 // Post-order traversal that expands a layer block into its parent. Because of
654 // the pass precondition that this runs _after_ `LowerXMR`, not much has to
655 // happen here, other than for domain information. All of the following do
656 // happen, though:
657 //
658 // 1. Any layer coloring is stripped.
659 // 2. Layers with Inline convention are converted to SV ifdefs.
660 // 3. Layers with Bind convention are converted to new modules and then
661 // instantiated at their original location. Any captured values are either
662 // moved, cloned, or converted to XMR deref ops.
663 // 4. Move instances created from earlier (3) conversions out of later (3)
664 // conversions. This is necessary to avoid a SystemVerilog-illegal
665 // bind-under-bind. (See Section 23.11 of 1800-2023.)
666 // 5. Keep track of special ops (ops with inner symbols or verbatims) which
667 // need to have something updated because of the new instance hierarchy
668 // being created.
669 // 6. Any captured domain information result in input/output ports being
670 // created and these being hooked up when new modules are instantiated.
671 //
672 // Remember, this is post-order, in-order. Child layer blocks are visited
673 // before parents. Any nested regions _within_ the layer block are also
674 // visited before the outer layer block.
675 auto result = moduleOp.walk<mlir::WalkOrder::PostOrder>([&](Operation *op) {
676 if (failed(opPreconditionCheck(op)))
677 return WalkResult::interrupt();
678
679 // Strip layer requirements from any op that might represent a probe.
680 for (auto result : op->getResults())
681 removeLayersFromValue(result);
682
683 // If the op is an instance, clear the enablelayers attribute.
684 if (auto instance = dyn_cast<InstanceOp>(op))
685 instance.setLayers({});
686
687 auto layerBlock = dyn_cast<LayerBlockOp>(op);
688 if (!layerBlock)
689 return WalkResult::advance();
690
691 // After this point, we are dealing with a layer block.
692 auto layer = symbolToLayer.lookup(layerBlock.getLayerName());
693
694 if (layer.getConvention() == LayerConvention::Inline) {
695 lowerInlineLayerBlock(layer, layerBlock);
696 return WalkResult::advance();
697 }
698
699 // After this point, we are dealing with a bind convention layer block.
700 assert(layer.getConvention() == LayerConvention::Bind);
701
702 // Utilities and mutable state that results from creating ports. Due to the
703 // way in which this pass works and its phase ordering, the only types of
704 // ports that can be created are domain type ports.
705 SmallVector<PortInfo> ports;
706 SmallVector<Value> connectValues;
707 Namespace portNs;
708
709 // Create an input port for a domain-type operand. The source is not in the
710 // current layer block.
711 auto createInputPort = [&](Value src, Location loc) -> LogicalResult {
712 Attribute domain;
713 if (failed(getDomain(src, domain)))
714 return failure();
715
716 StringAttr name;
717 auto [nameHint, rootKnown] = getFieldName(FieldRef(src, 0), true);
718 if (rootKnown)
719 name = StringAttr::get(src.getContext(), portNs.newName(nameHint));
720 else
721 name = StringAttr::get(src.getContext(), portNs.newName("anonDomain"));
722 PortInfo port(
723 /*name=*/name,
724 /*type=*/src.getType(),
725 /*dir=*/Direction::In,
726 /*symName=*/{},
727 /*location=*/loc,
728 /*annos=*/{},
729 /*domains=*/domain);
730 ports.push_back(port);
731 connectValues.push_back(src);
732 BlockArgument replacement =
733 layerBlock.getBody()->addArgument(port.type, port.loc);
734 src.replaceUsesWithIf(replacement, [&](OpOperand &use) {
735 auto *user = use.getOwner();
736 if (!layerBlock->isAncestor(user))
737 return false;
738 // Replace if the connection source is the src and if the destination is
739 // _not_ in this layer block. If the destination is a spilled or
740 // to-be-spilled instance, then do not replace this connection as it
741 // will _later_ be spilled.
742 if (auto connectLike = dyn_cast<FConnectLike>(user)) {
743 auto *destDefiningOp = connectLike.getDest().getDefiningOp();
744 return connectLike.getSrc() == src &&
745 !createdInstances.contains(destDefiningOp);
746 }
747 return false;
748 });
749 return success();
750 };
751
752 // Set the location intelligently. Use the location of the capture if this
753 // is a port created for forwarding from a parent layer block to a nested
754 // layer block. Otherwise, use unknown.
755 auto getPortLoc = [&](Value port) -> Location {
756 Location loc = UnknownLoc::get(port.getContext());
757 if (auto *destOp = port.getDefiningOp())
758 if (auto instOp = dyn_cast<InstanceOp>(destOp)) {
759 auto modOpIt = createdInstances.find(instOp);
760 if (modOpIt != createdInstances.end()) {
761 auto portNum = cast<OpResult>(port).getResultNumber();
762 loc = modOpIt->getSecond().getPortLocation(portNum);
763 }
764 }
765 return loc;
766 };
767
768 // Source is in the current layer block. The destination is not in the
769 // current layer block.
770 auto createOutputPort = [&](Value src, Value dest) -> LogicalResult {
771 Attribute domain;
772 if (failed(getDomain(src, domain)))
773 return failure();
774
775 StringAttr name;
776 auto [nameHint, rootKnown] = getFieldName(FieldRef(src, 0), true);
777 if (rootKnown)
778 name = StringAttr::get(src.getContext(), portNs.newName(nameHint));
779 else
780 name = StringAttr::get(src.getContext(), portNs.newName("anonDomain"));
781 PortInfo port(
782 /*name=*/name,
783 /*type=*/src.getType(),
784 /*dir=*/Direction::Out,
785 /*symName=*/{},
786 /*location=*/getPortLoc(dest),
787 /*annos=*/{},
788 /*domains=*/domain);
789 ports.push_back(port);
790 connectValues.push_back(dest);
791 BlockArgument replacement =
792 layerBlock.getBody()->addArgument(port.type, port.loc);
793 dest.replaceUsesWithIf(replacement, [&](OpOperand &use) {
794 auto *user = use.getOwner();
795 if (!layerBlock->isAncestor(user))
796 return false;
797 // Replace connection destinations.
798 if (auto connectLike = dyn_cast<FConnectLike>(user))
799 return connectLike.getDest() == dest;
800 return false;
801 });
802 return success();
803 };
804
805 // Clear the replacements so that none are re-used across layer blocks.
806 replacements.clear();
807 OpBuilder builder(moduleOp);
808 SmallVector<hw::InnerSymAttr> innerSyms;
809 SmallVector<sv::VerbatimOp> verbatims;
810 DenseSet<Operation *> spilledSubOps;
811 auto layerBlockWalkResult = layerBlock.walk([&](Operation *op) {
812 // Error if pass preconditions are not met.
813 if (failed(opPreconditionCheck(op)))
814 return WalkResult::interrupt();
815
816 // Specialized handling of subfields, subindexes, and subaccesses which
817 // need to be spilled and nodes that referred to spilled nodes. If these
818 // are kept in the module, then the XMR is going to be bidirectional. Fix
819 // this for subfield and subindex by moving these ops outside the
820 // layerblock. Try to fix this for subaccess and error if the move can't
821 // be made because the index is defined inside the layerblock. (This case
822 // is exceedingly rare given that subaccesses are almost always unexepcted
823 // when this pass runs.) Additionally, if any nodes are seen that are
824 // transparently referencing a spilled op, spill the node, too. The node
825 // provides an anchor for an inner symbol (which subfield, subindex, and
826 // subaccess do not).
827 auto fixSubOp = [&](auto subOp) {
828 auto input = subOp.getInput();
829
830 // If the input is defined in this layerblock, we are done.
831 if (isAncestorOfValueOwner(layerBlock, input))
832 return WalkResult::advance();
833
834 // Otherwise, capture the input operand, if possible.
835 if (firrtl::type_cast<FIRRTLBaseType>(input.getType()).isPassive()) {
836 subOp.getInputMutable().assign(getReplacement(subOp, input));
837 return WalkResult::advance();
838 }
839
840 // Otherwise, move the subfield op out of the layerblock.
841 op->moveBefore(layerBlock);
842 spilledSubOps.insert(op);
843 return WalkResult::advance();
844 };
845
846 if (auto subOp = dyn_cast<SubfieldOp>(op))
847 return fixSubOp(subOp);
848
849 if (auto subOp = dyn_cast<SubindexOp>(op))
850 return fixSubOp(subOp);
851
852 if (auto subOp = dyn_cast<SubaccessOp>(op)) {
853 auto input = subOp.getInput();
854 auto index = subOp.getIndex();
855
856 // If the input is defined in this layerblock, capture the index if
857 // needed, and we are done.
858 if (isAncestorOfValueOwner(layerBlock, input)) {
859 if (!isAncestorOfValueOwner(layerBlock, index)) {
860 subOp.getIndexMutable().assign(getReplacement(subOp, index));
861 }
862 return WalkResult::advance();
863 }
864
865 // Otherwise, capture the input operand, if possible.
866 if (firrtl::type_cast<FIRRTLBaseType>(input.getType()).isPassive()) {
867 subOp.getInputMutable().assign(getReplacement(subOp, input));
868 if (!isAncestorOfValueOwner(layerBlock, index))
869 subOp.getIndexMutable().assign(getReplacement(subOp, index));
870 return WalkResult::advance();
871 }
872
873 // Otherwise, move the subaccess op out of the layerblock, if possible.
874 if (!isAncestorOfValueOwner(layerBlock, index)) {
875 subOp->moveBefore(layerBlock);
876 spilledSubOps.insert(op);
877 return WalkResult::advance();
878 }
879
880 // When the input is not passive, but the index is defined inside this
881 // layerblock, we are out of options.
882 auto diag = op->emitOpError()
883 << "has a non-passive operand and captures a value defined "
884 "outside its enclosing bind-convention layerblock. The "
885 "'LowerLayers' pass cannot lower this as it would "
886 "create an output port on the resulting module.";
887 diag.attachNote(layerBlock.getLoc())
888 << "the layerblock is defined here";
889 return WalkResult::interrupt();
890 }
891
892 if (auto nodeOp = dyn_cast<NodeOp>(op)) {
893 auto *definingOp = nodeOp.getInput().getDefiningOp();
894 if (definingOp &&
895 spilledSubOps.contains(nodeOp.getInput().getDefiningOp())) {
896 op->moveBefore(layerBlock);
897 return WalkResult::advance();
898 }
899 }
900
901 // Record any operations inside the layer block which have inner symbols.
902 // Theses may have symbol users which need to be updated.
903 //
904 // Note: this needs to _not_ index spilled NodeOps above.
905 if (auto symOp = dyn_cast<hw::InnerSymbolOpInterface>(op))
906 if (auto innerSym = symOp.getInnerSymAttr())
907 innerSyms.push_back(innerSym);
908
909 // Handle instance ops that were created from nested layer blocks. These
910 // ops need to be moved outside the layer block to avoid nested binds.
911 // Nested binds are illegal in the SystemVerilog specification (and
912 // checked by FIRRTL verification).
913 //
914 // For each value defined in this layer block which drives a port of one
915 // of these instances, create an output reference type port on the
916 // to-be-created module and drive it with the value. Move the instance
917 // outside the layer block. We will hook it up later once we replace the
918 // layer block with an instance.
919 if (auto instOp = dyn_cast<InstanceOp>(op)) {
920 // Ignore instances which this pass did not create.
921 if (!createdInstances.contains(instOp))
922 return WalkResult::advance();
923
924 LLVM_DEBUG({
925 llvm::dbgs()
926 << " Found instance created from nested layer block:\n"
927 << " module: " << instOp.getModuleName() << "\n"
928 << " instance: " << instOp.getName() << "\n";
929 });
930 instOp->moveBefore(layerBlock);
931 return WalkResult::advance();
932 }
933
934 // Handle domain define ops. The destination must be within the current
935 // layer block. The source may be outside it. These, unlike other XMR
936 // captures, need to create ports as there is no XMR representation for
937 // domains. When creating these, look through any intermediate wires as
938 // these need to know the domain kind when creating the port and wires do
939 // not presently have this.
940 //
941 // TODO: Stop looking through wires when wires support domain info [1].
942 //
943 // [1]: https://github.com/llvm/circt/issues/9398
944 if (auto domainDefineOp = dyn_cast<DomainDefineOp>(op)) {
945 auto src = domainDefineOp.getSrc();
946 auto dest = domainDefineOp.getDest();
947 auto srcInLayerBlock = isAncestorOfValueOwner(layerBlock, src);
948 auto destInLayerBlock = isAncestorOfValueOwner(layerBlock, dest);
949
950 if (srcInLayerBlock) {
951 // The source and destination are in the current block. Do nothing.
952 if (destInLayerBlock)
953 return WalkResult::advance();
954 // The source is in the current layer block, but the destination is
955 // outside it. This is not possible except in situations where we
956 // have moved an instance out of the layer block. I.e., this is due
957 // to a child layer (which has already been processed) capturing
958 // something from the current layer block.
959 return WalkResult(createOutputPort(src, dest));
960 }
961
962 // The source is _not_ in the current block. Create an input domain
963 // type port with the right kind. To find the right kind, we need to
964 // look through wires to the original source.
965 if (destInLayerBlock)
966 return WalkResult(createInputPort(src, domainDefineOp.getLoc()));
967
968 // The source and destination are outside the layer block. Bubble this
969 // up. Note: this code is only reachable for situations where a prior
970 // instance, created from a bind layer has been bubbled up. This flavor
971 // of construction is otherwise illegal.
972 domainDefineOp->moveBefore(layerBlock);
973 return WalkResult::advance();
974 }
975
976 // Handle captures. For any captured operands, convert them to a suitable
977 // replacement value. The `getReplacement` function will automatically
978 // reuse values whenever possible.
979 for (size_t i = 0, e = op->getNumOperands(); i != e; ++i) {
980 auto operand = op->getOperand(i);
981
982 // If the operand is in this layer block, do nothing.
983 //
984 // Note: This check is what avoids handling ConnectOp destinations.
985 if (isAncestorOfValueOwner(layerBlock, operand))
986 continue;
987
988 op->setOperand(i, getReplacement(op, operand));
989 }
990
991 if (auto verbatim = dyn_cast<sv::VerbatimOp>(op))
992 verbatims.push_back(verbatim);
993
994 return WalkResult::advance();
995 });
996
997 if (layerBlockWalkResult.wasInterrupted())
998 return WalkResult::interrupt();
999
1000 // If the layer block is empty, erase it instead of creating an empty
1001 // module. Note: empty leaf layer blocks will be erased by canonicalizers.
1002 // We don't expect to see these here. However, this handles the case of
1003 // empty intermediary layer blocks which are important in the layer block
1004 // representation, but can disappear when lowered to modules.
1005 if (llvm::all_of(layerBlock.getRegion().getBlocks(),
1006 [](auto &a) { return a.empty(); })) {
1007 assert(verbatims.empty());
1008 layerBlock.erase();
1009 return WalkResult::advance();
1010 }
1011
1012 // Create the new module. This grabs a lock to modify the circuit.
1013 FModuleOp newModule = buildNewModule(builder, layerBlock, ports);
1014 newModule.getBody().takeBody(layerBlock.getRegion());
1015 SymbolTable::setSymbolVisibility(newModule,
1016 SymbolTable::Visibility::Private);
1017
1018 LLVM_DEBUG({
1019 llvm::dbgs() << " New Module: "
1020 << layerBlockGlobals.lookup(layerBlock).moduleName << "\n";
1021 llvm::dbgs() << " ports:\n";
1022 for (size_t i = 0, e = ports.size(); i != e; ++i) {
1023 auto port = ports[i];
1024 auto value = connectValues[i];
1025 llvm::dbgs() << " - name: " << port.getName() << "\n"
1026 << " type: " << port.type << "\n"
1027 << " direction: " << port.direction << "\n"
1028 << " value: " << value << "\n";
1029 }
1030 });
1031
1032 // Replace the original layer block with an instance. Hook up the
1033 // instance. Intentionally create instance with probe ports which do
1034 // not have an associated layer. This is illegal IR that will be
1035 // made legal by the end of the pass. This is done to avoid having
1036 // to revisit and rewrite each instance everytime it is moved into a
1037 // parent layer.
1038 builder.setInsertionPointAfter(layerBlock);
1039 auto instanceName = instanceNameForLayer(layerBlock.getLayerName());
1040 auto innerSym =
1041 hw::InnerSymAttr::get(builder.getStringAttr(ns.newName(instanceName)));
1042
1043 auto instanceOp = InstanceOp::create(
1044 builder, layerBlock.getLoc(), /*moduleName=*/newModule,
1045 /*name=*/
1046 instanceName, NameKindEnum::DroppableName,
1047 /*annotations=*/ArrayRef<Attribute>{},
1048 /*portAnnotations=*/ArrayRef<Attribute>{}, /*lowerToBind=*/false,
1049 /*doNotPrint=*/true, innerSym);
1050 for (auto [lhs, rhs] : llvm::zip(instanceOp.getResults(), connectValues))
1051 if (instanceOp.getPortDirection(lhs.getResultNumber()) == Direction::In)
1052 DomainDefineOp::create(builder, builder.getUnknownLoc(), lhs, rhs);
1053 else {
1054 DomainDefineOp::create(builder, builder.getUnknownLoc(), rhs, lhs);
1055 }
1056
1057 auto outputFile = outputFileForLayer(moduleOp.getModuleNameAttr(),
1058 layerBlock.getLayerName());
1059 instanceOp->setAttr("output_file", outputFile);
1060
1061 createdInstances.try_emplace(instanceOp, newModule);
1062
1063 // create the bind op.
1064 {
1065 auto builder = OpBuilder::atBlockEnd(bindFiles[moduleOp][layer].body);
1066 BindOp::create(builder, layerBlock.getLoc(), moduleOp.getModuleNameAttr(),
1067 instanceOp.getInnerSymAttr().getSymName());
1068 }
1069
1070 LLVM_DEBUG(llvm::dbgs() << " moved inner refs:\n");
1071 for (hw::InnerSymAttr innerSym : innerSyms) {
1072 auto oldInnerRef = hw::InnerRefAttr::get(moduleOp.getModuleNameAttr(),
1073 innerSym.getSymName());
1074 auto splice = std::make_pair(instanceOp.getInnerSymAttr(),
1075 newModule.getModuleNameAttr());
1076 innerRefMap.insert({oldInnerRef, splice});
1077 LLVM_DEBUG(llvm::dbgs() << " - ref: " << oldInnerRef << "\n"
1078 << " splice: " << splice.first << ", "
1079 << splice.second << "\n";);
1080 }
1081
1082 // Update verbatims that target operations extracted alongside.
1083 if (!verbatims.empty()) {
1084 mlir::AttrTypeReplacer replacer;
1085 replacer.addReplacement(
1086 [&innerRefMap](hw::InnerRefAttr ref) -> std::optional<Attribute> {
1087 auto it = innerRefMap.find(ref);
1088 if (it != innerRefMap.end())
1089 return hw::InnerRefAttr::get(it->second.second, ref.getName());
1090 return std::nullopt;
1091 });
1092 for (auto verbatim : verbatims)
1093 replacer.replaceElementsIn(verbatim);
1094 }
1095
1096 layerBlock.erase();
1097
1098 return WalkResult::advance();
1099 });
1100 return success(!result.wasInterrupted());
1101}
1102
1104 LayerOp layer, StringRef circuitName,
1105 SmallVector<FlatSymbolRefAttr> &stack) {
1106 stack.emplace_back(FlatSymbolRefAttr::get(layer.getSymNameAttr()));
1107 ArrayRef stackRef(stack);
1108 symbolToLayer.insert(
1109 {SymbolRefAttr::get(stackRef.front().getAttr(), stackRef.drop_front()),
1110 layer});
1111 if (layer.getConvention() == LayerConvention::Inline) {
1112 auto *ctx = &getContext();
1113 auto macName = macroNameForLayer(circuitName, stack);
1114 auto symName = ns.newName(macName);
1115
1116 auto symNameAttr = StringAttr::get(ctx, symName);
1117 auto macNameAttr = StringAttr();
1118 if (macName != symName)
1119 macNameAttr = StringAttr::get(ctx, macName);
1120
1121 sv::MacroDeclOp::create(b, layer->getLoc(), symNameAttr, ArrayAttr(),
1122 macNameAttr);
1123 macroNames[layer] = FlatSymbolRefAttr::get(&getContext(), symNameAttr);
1124 }
1125 for (auto child : layer.getOps<LayerOp>())
1126 preprocessLayers(ns, b, child, circuitName, stack);
1127 stack.pop_back();
1128}
1129
1131 auto circuit = getOperation();
1132 auto circuitName = circuit.getName();
1133 for (auto layer : circuit.getOps<LayerOp>()) {
1134 OpBuilder b(layer);
1135 SmallVector<FlatSymbolRefAttr> stack;
1136 preprocessLayers(ns, b, layer, circuitName, stack);
1137 }
1138}
1139
1141 InstanceGraphNode *node, OpBuilder &b,
1142 SymbolRefAttr layerName, LayerOp layer) {
1143 assert(layer.getConvention() == LayerConvention::Bind);
1144 auto module = node->getModule<FModuleOp>();
1145 auto loc = module.getLoc();
1146
1147 // Compute the include guard macro name.
1148 auto macroName = guardMacroNameForLayer(module.getModuleName(), layerName);
1149 auto macroSymbol = ns.newName(macroName);
1150 auto macroNameAttr = StringAttr::get(&getContext(), macroName);
1151 auto macroSymbolAttr = StringAttr::get(&getContext(), macroSymbol);
1152 auto macroSymbolRefAttr = FlatSymbolRefAttr::get(macroSymbolAttr);
1153
1154 // Compute the base name for the bind file.
1155 auto bindFileName = fileNameForLayer(module.getName(), layerName);
1156
1157 // Build the full output path using the filename of the bindfile and the
1158 // output directory of the layer, if any.
1159 auto dir = layer->getAttrOfType<hw::OutputFileAttr>("output_file");
1160 StringAttr filename = StringAttr::get(&getContext(), bindFileName);
1161 StringAttr path;
1162 if (dir)
1163 path = StringAttr::get(&getContext(),
1164 Twine(dir.getDirectory()) + bindFileName);
1165 else
1166 path = filename;
1167
1168 // Declare the macro for the include guard.
1169 sv::MacroDeclOp::create(b, loc, macroSymbolAttr, ArrayAttr{}, macroNameAttr);
1170
1171 // Create the emit op.
1172 auto bindFile = emit::FileOp::create(b, loc, path);
1173 OpBuilder::InsertionGuard _(b);
1174 b.setInsertionPointToEnd(bindFile.getBody());
1175
1176 // Create the #ifndef for the include guard.
1177 auto includeGuard = sv::IfDefOp::create(b, loc, macroSymbolRefAttr);
1178 b.createBlock(&includeGuard.getElseRegion());
1179
1180 // Create the #define for the include guard.
1181 sv::MacroDefOp::create(b, loc, macroSymbolRefAttr);
1182
1183 // Create IR to enable any parent layers.
1184 auto parent = layer->getParentOfType<LayerOp>();
1185 while (parent) {
1186 // If the parent is bound-in, we enable it by including the bindfile.
1187 // The parent bindfile will enable all ancestors.
1188 if (parent.getConvention() == LayerConvention::Bind) {
1189 auto target = bindFiles[module][parent].filename;
1190 sv::IncludeOp::create(b, loc, IncludeStyle::Local, target);
1191 break;
1192 }
1193
1194 // If the parent layer is inline, we can only assert that the parent is
1195 // already enabled.
1196 if (parent.getConvention() == LayerConvention::Inline) {
1197 auto parentMacroSymbolRefAttr = macroNames[parent];
1198 auto parentGuard = sv::IfDefOp::create(b, loc, parentMacroSymbolRefAttr);
1199 OpBuilder::InsertionGuard guard(b);
1200 b.createBlock(&parentGuard.getElseRegion());
1201 auto message = StringAttr::get(&getContext(),
1202 Twine(parent.getName()) + " not enabled");
1203 sv::MacroErrorOp::create(b, loc, message);
1204 parent = parent->getParentOfType<LayerOp>();
1205 continue;
1206 }
1207
1208 // Unknown Layer convention.
1209 llvm_unreachable("unknown layer convention");
1210 }
1211
1212 // Create IR to include bind files for child modules. If a module is
1213 // instantiated more than once, we only need to include the bindfile once.
1214 SmallPtrSet<Operation *, 8> seen;
1215 for (auto *record : *node) {
1216 auto *child = record->getTarget()->getModule().getOperation();
1217 if (!std::get<bool>(seen.insert(child)))
1218 continue;
1219 auto files = bindFiles[child];
1220 auto lookup = files.find(layer);
1221 if (lookup != files.end())
1222 sv::IncludeOp::create(b, loc, IncludeStyle::Local,
1223 lookup->second.filename);
1224 }
1225
1226 // Save the bind file information for later.
1227 auto &info = bindFiles[module][layer];
1228 info.filename = filename;
1229 info.body = includeGuard.getElseBlock();
1230}
1231
1233 InstanceGraphNode *node,
1234 FModuleOp module) {
1235 OpBuilder b(&getContext());
1236 b.setInsertionPointAfter(module);
1237
1238 // Create a bind file only if the layer is used under the module.
1239 llvm::SmallDenseSet<LayerOp> layersRequiringBindFiles;
1240
1241 // If the module is public, create a bind file for all layers.
1242 if (module.isPublic() || emitAllBindFiles)
1243 for (auto [_, layer] : symbolToLayer)
1244 if (layer.getConvention() == LayerConvention::Bind)
1245 layersRequiringBindFiles.insert(layer);
1246
1247 // Handle layers used directly in this module.
1248 module->walk([&](LayerBlockOp layerBlock) {
1249 auto layer = symbolToLayer[layerBlock.getLayerNameAttr()];
1250 if (layer.getConvention() == LayerConvention::Inline)
1251 return;
1252
1253 // Create a bindfile for any layer directly used in the module.
1254 layersRequiringBindFiles.insert(layer);
1255
1256 // Determine names for all modules that will be created.
1257 auto moduleName = module.getModuleName();
1258 auto layerName = layerBlock.getLayerName();
1259
1260 // A name hint for the module created from this layerblock.
1261 auto layerBlockModuleName = moduleNameForLayer(moduleName, layerName);
1262
1263 // A name hint for the hier-path-op which targets the bound-in instance of
1264 // the module created from this layerblock.
1265 auto layerBlockHierPathName = hierPathNameForLayer(moduleName, layerName);
1266
1267 LayerBlockGlobals globals;
1268 globals.moduleName = ns.newName(layerBlockModuleName);
1269 globals.hierPathName = ns.newName(layerBlockHierPathName);
1270 layerBlockGlobals.insert({layerBlock, globals});
1271 });
1272
1273 // Create a bindfile for layers used indirectly under this module.
1274 for (auto *record : *node) {
1275 auto *child = record->getTarget()->getModule().getOperation();
1276 for (auto [layer, _] : bindFiles[child])
1277 layersRequiringBindFiles.insert(layer);
1278 }
1279
1280 // Build the bindfiles for any layer seen under this module. The bindfiles
1281 // are emitted in the order which they are declared, for readability.
1282 for (auto [sym, layer] : symbolToLayer)
1283 if (layersRequiringBindFiles.contains(layer))
1284 buildBindFile(ns, node, b, sym, layer);
1285}
1286
1288 InstanceGraphNode *node,
1289 FExtModuleOp extModule) {
1290 // For each known layer of the extmodule, compute and record the bindfile
1291 // name. When a layer is known, its parent layers are implicitly known,
1292 // so compute bindfiles for parent layers too. Use a set to avoid
1293 // repeated work, which can happen if, for example, both a child layer and
1294 // a parent layer are explicitly declared to be known.
1295 auto known = extModule.getKnownLayersAttr().getAsRange<SymbolRefAttr>();
1296 if (known.empty())
1297 return;
1298
1299 auto moduleName = extModule.getExtModuleName();
1300 auto &files = bindFiles[extModule];
1301 SmallPtrSet<Operation *, 8> seen;
1302
1303 for (auto name : known) {
1304 auto layer = symbolToLayer[name];
1305 auto rootLayerName = name.getRootReference();
1306 auto nestedLayerNames = name.getNestedReferences();
1307 while (layer && std::get<bool>(seen.insert(layer))) {
1308 if (layer.getConvention() == LayerConvention::Bind) {
1309 BindFileInfo info;
1310 auto filename =
1311 fileNameForLayer(moduleName, rootLayerName, nestedLayerNames);
1312 info.filename = StringAttr::get(&getContext(), filename);
1313 info.body = nullptr;
1314 files.insert({layer, info});
1315 }
1316 layer = layer->getParentOfType<LayerOp>();
1317 if (!nestedLayerNames.empty())
1318 nestedLayerNames = nestedLayerNames.drop_back();
1319 }
1320 }
1321}
1322
1324 InstanceGraphNode *node) {
1325 auto *op = node->getModule().getOperation();
1326 if (!op)
1327 return;
1328
1329 if (auto module = dyn_cast<FModuleOp>(op))
1330 return preprocessModule(ns, node, module);
1331
1332 if (auto extModule = dyn_cast<FExtModuleOp>(op))
1333 return preprocessExtModule(ns, node, extModule);
1334}
1335
1336/// Create the bind file skeleton for each layer, for each module.
1338 InstanceGraph &ig) {
1339 ig.walkPostOrder([&](auto &node) { preprocessModuleLike(ns, &node); });
1340}
1341
1342/// Process a circuit to remove all layer blocks in each module and top-level
1343/// layer definition.
1345 LLVM_DEBUG(
1346 llvm::dbgs() << "==----- Running LowerLayers "
1347 "-------------------------------------------------===\n");
1348 CircuitOp circuitOp = getOperation();
1349
1350 // Initialize members which cannot be initialized automatically.
1351 llvm::sys::SmartMutex<true> mutex;
1352 circuitMutex = &mutex;
1353
1354 auto *ig = &getAnalysis<InstanceGraph>();
1355 CircuitNamespace ns(circuitOp);
1357 &ns, OpBuilder::InsertPoint(getOperation().getBodyBlock(),
1358 getOperation().getBodyBlock()->begin()));
1359 hierPathCache = &hpc;
1360
1361 preprocessLayers(ns);
1362 preprocessModules(ns, *ig);
1363
1364 auto mergeMaps = [](auto &&a, auto &&b) {
1365 if (failed(a))
1366 return std::forward<decltype(a)>(a);
1367 if (failed(b))
1368 return std::forward<decltype(b)>(b);
1369
1370 for (auto bb : *b)
1371 a->insert(bb);
1372 return std::forward<decltype(a)>(a);
1373 };
1374
1375 // Lower the layer blocks of each module.
1376 SmallVector<FModuleLike> modules(
1377 circuitOp.getBodyBlock()->getOps<FModuleLike>());
1378 auto failureOrInnerRefMap = transformReduce(
1379 circuitOp.getContext(), modules, FailureOr<InnerRefMap>(InnerRefMap{}),
1380 mergeMaps, [this](FModuleLike mod) -> FailureOr<InnerRefMap> {
1381 return runOnModuleLike(mod);
1382 });
1383 if (failed(failureOrInnerRefMap))
1384 return signalPassFailure();
1385 auto &innerRefMap = *failureOrInnerRefMap;
1386
1387 // Rewrite any hw::HierPathOps which have namepaths that contain rewritting
1388 // inner refs.
1389 //
1390 // TODO: This unnecessarily computes a new namepath for every hw::HierPathOp
1391 // even if that namepath is not used. It would be better to only build the
1392 // new namepath when a change is needed, e.g., by recording updates to the
1393 // namepath.
1394 for (hw::HierPathOp hierPathOp : circuitOp.getOps<hw::HierPathOp>()) {
1395 SmallVector<Attribute> newNamepath;
1396 bool modified = false;
1397 for (auto attr : hierPathOp.getNamepath()) {
1398 hw::InnerRefAttr innerRef = dyn_cast<hw::InnerRefAttr>(attr);
1399 if (!innerRef) {
1400 newNamepath.push_back(attr);
1401 continue;
1402 }
1403 auto it = innerRefMap.find(innerRef);
1404 if (it == innerRefMap.end()) {
1405 newNamepath.push_back(attr);
1406 continue;
1407 }
1408
1409 auto &[inst, mod] = it->getSecond();
1410 newNamepath.push_back(
1411 hw::InnerRefAttr::get(innerRef.getModule(), inst.getSymName()));
1412 newNamepath.push_back(hw::InnerRefAttr::get(mod, innerRef.getName()));
1413 modified = true;
1414 }
1415 if (modified)
1416 hierPathOp.setNamepathAttr(
1417 ArrayAttr::get(circuitOp.getContext(), newNamepath));
1418 }
1419
1420 // All layers definitions can now be deleted.
1421 for (auto layerOp :
1422 llvm::make_early_inc_range(circuitOp.getBodyBlock()->getOps<LayerOp>()))
1423 layerOp.erase();
1424
1425 // Cleanup state.
1426 circuitMutex = nullptr;
1427 layerBlockGlobals.clear();
1428 macroNames.clear();
1429 symbolToLayer.clear();
1430 hierPathCache = nullptr;
1431 bindFiles.clear();
1432}
assert(baseType &&"element must be base type")
Delimiter
Definition HWOps.cpp:116
static SmallString< 32 > guardMacroNameForLayer(StringRef moduleName, SymbolRefAttr layerName)
For all layerblocks @A::@B::@C in a module called Module, the include-guard macro is layers_Module_A_...
static SmallString< 32 > instanceNameForLayer(SymbolRefAttr layerName)
For a layerblock @A::@B::@C, the generated instance is called a_b_c.
static void appendName(StringRef name, SmallString< 32 > &output, bool toLower=false, Delimiter delimiter=Delimiter::BindFile)
DenseMap< hw::InnerRefAttr, std::pair< hw::InnerSymAttr, StringAttr > > InnerRefMap
static SmallString< 32 > moduleNameForLayer(StringRef moduleName, SymbolRefAttr layerName)
For a layer @A::@B::@C in module Module, the generated module is called Module_A_B_C.
static SmallString< 32 > fileNameForLayer(StringRef moduleName, StringAttr root, ArrayRef< FlatSymbolRefAttr > nested)
static SmallString< 32 > macroNameForLayer(StringRef circuitName, ArrayRef< FlatSymbolRefAttr > layerName)
For a layerblock @A::@B::@C, the verilog macro is A_B_C.
static SmallString< 32 > hierPathNameForLayer(StringRef moduleName, SymbolRefAttr layerName)
static Block * getBodyBlock(FModuleLike mod)
void runOnOperation() override
Entry point for the function.
void removeLayersFromPorts(FModuleLike moduleLike)
Update the module's port types to remove any explicit layer requirements from any probe types.
FailureOr< InnerRefMap > runOnModuleLike(FModuleLike moduleLike)
Strip layer colors from the module's interface.
void preprocessModuleLike(CircuitNamespace &ns, InstanceGraphNode *node)
Build the bindfile skeletons for each module.
void preprocessModule(CircuitNamespace &ns, InstanceGraphNode *node, FModuleOp module)
Build the bindfile skeleton for a module.
DenseMap< LayerOp, FlatSymbolRefAttr > macroNames
A map from inline layers to their macro names.
hw::OutputFileAttr outputFileForLayer(StringRef moduleName, SymbolRefAttr layerName)
void preprocessExtModule(CircuitNamespace &ns, InstanceGraphNode *node, FExtModuleOp extModule)
Record the supposed bindfiles for any known layers of the ext module.
void lowerInlineLayerBlock(LayerOp layer, LayerBlockOp layerBlock)
Lower an inline layerblock to an ifdef block.
llvm::MapVector< SymbolRefAttr, LayerOp > symbolToLayer
A mapping of symbol name to layer operation.
void buildBindFile(CircuitNamespace &ns, InstanceGraphNode *node, OpBuilder &b, SymbolRefAttr layerName, LayerOp layer)
Build a bindfile skeleton for a particular module and layer.
void preprocessModules(CircuitNamespace &ns, InstanceGraph &ig)
For each module, build a bindfile for each bound-layer, if needed.
LogicalResult runOnModuleBody(FModuleOp moduleOp, InnerRefMap &innerRefMap)
Extract layerblocks and strip probe colors from all ops under the module.
FModuleOp buildNewModule(OpBuilder &builder, LayerBlockOp layerBlock, ArrayRef< PortInfo > ports)
Safely build a new module with a given namehint.
hw::OutputFileAttr getOutputFile(SymbolRefAttr layerName)
hw::HierPathCache * hierPathCache
Utility for creating hw::HierPathOp.
void removeLayersFromValue(Value value)
Update the value's type to remove any layers from any probe types.
void preprocessLayers(CircuitNamespace &ns, OpBuilder &b, LayerOp layer, StringRef circuitName, SmallVector< FlatSymbolRefAttr > &stack)
Build macro declarations and cache information about the layers.
DenseMap< Operation *, DenseMap< LayerOp, BindFileInfo > > bindFiles
A mapping from module*layer to bindfile name.
DenseMap< LayerBlockOp, LayerBlockGlobals > layerBlockGlobals
A map of layer blocks to "safe" global names which are fine to create in the circuit namespace.
llvm::sys::SmartMutex< true > * circuitMutex
Indicates exclusive access to modify the circuitNamespace and the circuit.
This class represents a reference to a specific field or element of an aggregate value.
Definition FieldRef.h:28
A namespace that is used to store existing names and generate new names in some scope within the IR.
Definition Namespace.h:30
StringRef newName(const Twine &name)
Return a unique name, derived from the input name, and add the new name to the internal namespace.
Definition Namespace.h:87
This graph tracks modules and where they are instantiated.
This is a Node in the InstanceGraph.
auto getModule()
Get the module that this node is tracking.
decltype(auto) walkPostOrder(Fn &&fn)
Perform a post-order walk across the modules.
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.
Value getDriverFromConnect(Value val)
Return the module-scoped driver of a value only looking through one connect.
std::pair< std::string, bool > getFieldName(const FieldRef &fieldRef, bool nameSafe=false)
Get a string identifier representing the FieldRef.
IntegerAttr getIntZerosAttr(Type type)
Utility for generating a constant zero attribute.
The InstanceGraph op interface, see InstanceGraphInterface.td for more details.
static ResultTy transformReduce(MLIRContext *context, IterTy begin, IterTy end, ResultTy init, ReduceFuncTy reduce, TransformFuncTy transform)
Wrapper for llvm::parallelTransformReduce that performs the transform_reduce serially when MLIR multi...
Definition Utils.h:40
bool isAncestorOfValueOwner(Operation *op, Value value)
Return true if a Value is created "underneath" an operation.
Definition Utils.h:27
The namespace of a CircuitOp, generally inhabited by modules.
Definition Namespace.h:24
This holds the name and type that describes the module's ports.