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 auto getReplacement = [&](Operation *user, Value value) -> Value {
433 auto it = replacements.find(value);
434 if (it != replacements.end())
435 return it->getSecond();
436
437 ImplicitLocOpBuilder localBuilder(value.getLoc(), &getContext());
438 Value replacement;
439
440 auto layerBlockOp = user->getParentOfType<LayerBlockOp>();
441 localBuilder.setInsertionPointToStart(layerBlockOp.getBody());
442
443 // If the operand is "special", e.g., it has no XMR representation, then we
444 // need to clone it.
445 //
446 // TODO: Change this to recursively clone. This will matter once FString
447 // operations have operands.
448 if (type_isa<FStringType>(value.getType())) {
449 localBuilder.setInsertionPoint(user);
450 replacement = localBuilder.clone(*value.getDefiningOp())->getResult(0);
451 replacements.insert({value, replacement});
452 return replacement;
453 }
454
455 // If the operand is an XMR ref, then we _have_ to clone it.
456 auto *definingOp = value.getDefiningOp();
457 if (isa_and_present<XMRRefOp>(definingOp)) {
458 replacement = localBuilder.clone(*definingOp)->getResult(0);
459 replacements.insert({value, replacement});
460 return replacement;
461 }
462
463 // Determine the replacement value for the captured operand. There are
464 // three cases that can occur:
465 //
466 // 1. Capturing something zero-width. Create a zero-width constant zero.
467 // 2. Capture something that can handle an inner sym. Add the inner sym if
468 // it doesn't exist and XMRderef that.
469 // 3. Capture something that can't handle an inner sym. Add a node, RAUW,
470 // and XMR deref the node.
471 //
472 // The handling of (2) and (3) is diffuse in the code below due to needing
473 // to split things based on whether a value has a defining operation or not.
474 auto baseType = type_cast<FIRRTLBaseType>(value.getType());
475 if (baseType && baseType.getBitWidthOrSentinel() == 0) {
476 OpBuilder::InsertionGuard guard(localBuilder);
477 auto zeroUIntType = UIntType::get(localBuilder.getContext(), 0);
478 replacement = localBuilder.createOrFold<BitCastOp>(
479 value.getType(), ConstantOp::create(localBuilder, zeroUIntType,
480 getIntZerosAttr(zeroUIntType)));
481 } else {
482 hw::InnerRefAttr innerRef;
483 if (auto *definingOp = value.getDefiningOp()) {
484 // Check if the operation can support an inner symbol and targets a
485 // specific result.
486 auto innerSymOp = dyn_cast<hw::InnerSymbolOpInterface>(definingOp);
487 if (innerSymOp && innerSymOp.getTargetResultIndex()) {
488 // The operation can support an inner symbol, so add one directly.
489 innerRef = getInnerRefTo(
490 innerSymOp,
491 [&](auto) -> hw::InnerSymbolNamespace & { return ns; });
492 } else {
493 // The operation cannot support an inner symbol, or it has multiple
494 // results and doesn't target a specific result, so create a node
495 // and replace all uses of the original value with the node (except
496 // the node itself).
497 auto node = getOrCreateNodeOp(value, localBuilder);
498 innerRef = getInnerRefTo(
499 node, [&](auto) -> hw::InnerSymbolNamespace & { return ns; });
500 auto newValue = node.getResult();
501 value.replaceAllUsesExcept(newValue, node);
502 value = newValue;
503 }
504 } else {
505 auto portIdx = cast<BlockArgument>(value).getArgNumber();
506 innerRef = getInnerRefTo(
507 cast<FModuleLike>(*moduleOp), portIdx,
508 [&](auto) -> hw::InnerSymbolNamespace & { return ns; });
509 }
510
511 hw::HierPathOp hierPathOp;
512 {
513 // TODO: Move to before parallel region to avoid the lock.
514 auto insertPoint = OpBuilder::InsertPoint(moduleOp->getBlock(),
515 Block::iterator(moduleOp));
516 llvm::sys::SmartScopedLock<true> circuitLock(*circuitMutex);
517 hierPathOp = hierPathCache->getOrCreatePath(
518 localBuilder.getArrayAttr({innerRef}), localBuilder.getLoc(),
519 insertPoint, layerBlockGlobals.lookup(layerBlockOp).hierPathName);
520 hierPathOp.setVisibility(SymbolTable::Visibility::Private);
521 }
522
523 replacement = XMRDerefOp::create(localBuilder, value.getType(),
524 hierPathOp.getSymNameAttr());
525 }
526
527 replacements.insert({value, replacement});
528
529 return replacement;
530 };
531
532 // A map of instance ops to modules that this pass creates. This is used to
533 // check if this was an instance that we created and to do fast module
534 // dereferencing (avoiding a symbol table).
535 DenseMap<Operation *, FModuleOp> createdInstances;
536
537 // Check that the preconditions for this pass are met. Reject any ops which
538 // must have been removed before this runs.
539 auto opPreconditionCheck = [](Operation *op) -> LogicalResult {
540 // LowerXMR op removal postconditions.
541 if (isa<RefCastOp, RefDefineOp, RefResolveOp, RefSendOp, RefSubOp,
542 RWProbeOp>(op))
543 return op->emitOpError()
544 << "cannot be handled by the lower-layers pass. This should have "
545 "already been removed by the lower-xmr pass.";
546
547 return success();
548 };
549
550 // Utility to determine the domain type of some value. This looks backwards
551 // through connections to find the source driver in the module and gets the
552 // domain type of that. This is necessary as intermediary wires do not track
553 // domain information.
554 //
555 // This cannot use `getModuleScopedDriver` because this can be called while
556 // `LayerBlockOp`s have temporarily gained block arguments while they are
557 // being migrated to modules. This is worked around by caching the known
558 // domain kinds of earlier-visited `WireOp`s to avoid needing to look through
559 // these non-`ModuleOp` block arguments.
560 //
561 // TODO: Simplify this once wires have domain kind information [1].
562 //
563 // [1]: https://github.com/llvm/circt/issues/9398
564 DenseMap<Operation *, Attribute> domainMap;
565 auto getDomain = [&domainMap](Value value,
566 Attribute &domain) -> LogicalResult {
567 SmallVector<Operation *> wires;
568
569 // Use iteration as this is recursive over the IR. `value` is changed for
570 // each iteration.
571 while (!domain) {
572 if (auto arg = dyn_cast<BlockArgument>(value)) {
573 domain = cast<FModuleLike>(arg.getOwner()->getParentOp())
574 .getDomainInfoAttrForPort(arg.getArgNumber());
575 continue;
576 }
577
578 auto result =
579 TypeSwitch<Operation *, LogicalResult>(value.getDefiningOp())
580 .Case<WireOp>([&](WireOp op) {
581 auto it = domainMap.find(op);
582 if (it != domainMap.end()) {
583 domain = it->getSecond();
584 return success();
585 }
586 for (auto *user : op->getUsers()) {
587 auto connect = dyn_cast<FConnectLike>(user);
588 if (!connect || connect.getDest() != value)
589 continue;
590 value = connect.getSrc();
591 wires.push_back(op);
592 return success();
593 }
594 emitError(value.getLoc())
595 << "unable to determine domain kind for source likely "
596 "indicating a "
597 "violation of static-single-connect";
598 return failure();
599 })
600 .Case<InstanceOp>([&](auto op) {
601 domain =
602 op.getPortDomain(cast<OpResult>(value).getResultNumber());
603 return success();
604 })
605 .Case<DomainCreateAnonOp>([&](auto op) {
606 domain = op.getDomainAttr();
607 return success();
608 })
609 .Default([&](auto op) {
610 op->emitOpError() << "unhandled domain source in 'LowerLayers";
611 return failure();
612 });
613 if (failed(result))
614 return failure();
615 }
616
617 // Update the `domainMap` with wire/domain information.
618 for (auto *wire : wires)
619 domainMap[wire] = domain;
620
621 return success();
622 };
623
624 // Post-order traversal that expands a layer block into its parent. Because of
625 // the pass precondition that this runs _after_ `LowerXMR`, not much has to
626 // happen here, other than for domain information. All of the following do
627 // happen, though:
628 //
629 // 1. Any layer coloring is stripped.
630 // 2. Layers with Inline convention are converted to SV ifdefs.
631 // 3. Layers with Bind convention are converted to new modules and then
632 // instantiated at their original location. Any captured values are either
633 // moved, cloned, or converted to XMR deref ops.
634 // 4. Move instances created from earlier (3) conversions out of later (3)
635 // conversions. This is necessary to avoid a SystemVerilog-illegal
636 // bind-under-bind. (See Section 23.11 of 1800-2023.)
637 // 5. Keep track of special ops (ops with inner symbols or verbatims) which
638 // need to have something updated because of the new instance hierarchy
639 // being created.
640 // 6. Any captured domain information result in input/output ports being
641 // created and these being hooked up when new modules are instantiated.
642 //
643 // Remember, this is post-order, in-order. Child layer blocks are visited
644 // before parents. Any nested regions _within_ the layer block are also
645 // visited before the outer layer block.
646 auto result = moduleOp.walk<mlir::WalkOrder::PostOrder>([&](Operation *op) {
647 if (failed(opPreconditionCheck(op)))
648 return WalkResult::interrupt();
649
650 // Strip layer requirements from any op that might represent a probe.
651 for (auto result : op->getResults())
652 removeLayersFromValue(result);
653
654 // If the op is an instance, clear the enablelayers attribute.
655 if (auto instance = dyn_cast<InstanceOp>(op))
656 instance.setLayers({});
657
658 auto layerBlock = dyn_cast<LayerBlockOp>(op);
659 if (!layerBlock)
660 return WalkResult::advance();
661
662 // After this point, we are dealing with a layer block.
663 auto layer = symbolToLayer.lookup(layerBlock.getLayerName());
664
665 if (layer.getConvention() == LayerConvention::Inline) {
666 lowerInlineLayerBlock(layer, layerBlock);
667 return WalkResult::advance();
668 }
669
670 // After this point, we are dealing with a bind convention layer block.
671 assert(layer.getConvention() == LayerConvention::Bind);
672
673 // Utilities and mutable state that results from creating ports. Due to the
674 // way in which this pass works and its phase ordering, the only types of
675 // ports that can be created are domain type ports.
676 SmallVector<PortInfo> ports;
677 SmallVector<Value> connectValues;
678 Namespace portNs;
679
680 // Create an input port for a domain-type operand. The source is not in the
681 // current layer block.
682 auto createInputPort = [&](Value src, Location loc) -> LogicalResult {
683 Attribute domain;
684 if (failed(getDomain(src, domain)))
685 return failure();
686
687 StringAttr name;
688 auto [nameHint, rootKnown] = getFieldName(FieldRef(src, 0), true);
689 if (rootKnown)
690 name = StringAttr::get(src.getContext(), portNs.newName(nameHint));
691 else
692 name = StringAttr::get(src.getContext(), portNs.newName("anonDomain"));
693 PortInfo port(
694 /*name=*/name,
695 /*type=*/src.getType(),
696 /*dir=*/Direction::In,
697 /*symName=*/{},
698 /*location=*/loc,
699 /*annos=*/{},
700 /*domains=*/domain);
701 ports.push_back(port);
702 connectValues.push_back(src);
703 BlockArgument replacement =
704 layerBlock.getBody()->addArgument(port.type, port.loc);
705 src.replaceUsesWithIf(replacement, [&](OpOperand &use) {
706 auto *user = use.getOwner();
707 if (!layerBlock->isAncestor(user))
708 return false;
709 // Replace if the connection source is the src and if the destination is
710 // _not_ in this layer block. If the destination is a spilled or
711 // to-be-spilled instance, then do not replace this connection as it
712 // will _later_ be spilled.
713 if (auto connectLike = dyn_cast<FConnectLike>(user)) {
714 auto *destDefiningOp = connectLike.getDest().getDefiningOp();
715 return connectLike.getSrc() == src &&
716 !createdInstances.contains(destDefiningOp);
717 }
718 return false;
719 });
720 return success();
721 };
722
723 // Set the location intelligently. Use the location of the capture if this
724 // is a port created for forwarding from a parent layer block to a nested
725 // layer block. Otherwise, use unknown.
726 auto getPortLoc = [&](Value port) -> Location {
727 Location loc = UnknownLoc::get(port.getContext());
728 if (auto *destOp = port.getDefiningOp())
729 if (auto instOp = dyn_cast<InstanceOp>(destOp)) {
730 auto modOpIt = createdInstances.find(instOp);
731 if (modOpIt != createdInstances.end()) {
732 auto portNum = cast<OpResult>(port).getResultNumber();
733 loc = modOpIt->getSecond().getPortLocation(portNum);
734 }
735 }
736 return loc;
737 };
738
739 // Source is in the current layer block. The destination is not in the
740 // current layer block.
741 auto createOutputPort = [&](Value src, Value dest) -> LogicalResult {
742 Attribute domain;
743 if (failed(getDomain(src, domain)))
744 return failure();
745
746 StringAttr name;
747 auto [nameHint, rootKnown] = getFieldName(FieldRef(src, 0), true);
748 if (rootKnown)
749 name = StringAttr::get(src.getContext(), portNs.newName(nameHint));
750 else
751 name = StringAttr::get(src.getContext(), portNs.newName("anonDomain"));
752 PortInfo port(
753 /*name=*/name,
754 /*type=*/src.getType(),
755 /*dir=*/Direction::Out,
756 /*symName=*/{},
757 /*location=*/getPortLoc(dest),
758 /*annos=*/{},
759 /*domains=*/domain);
760 ports.push_back(port);
761 connectValues.push_back(dest);
762 BlockArgument replacement =
763 layerBlock.getBody()->addArgument(port.type, port.loc);
764 dest.replaceUsesWithIf(replacement, [&](OpOperand &use) {
765 auto *user = use.getOwner();
766 if (!layerBlock->isAncestor(user))
767 return false;
768 // Replace connection destinations.
769 if (auto connectLike = dyn_cast<FConnectLike>(user))
770 return connectLike.getDest() == dest;
771 return false;
772 });
773 return success();
774 };
775
776 // Clear the replacements so that none are re-used across layer blocks.
777 replacements.clear();
778 OpBuilder builder(moduleOp);
779 SmallVector<hw::InnerSymAttr> innerSyms;
780 SmallVector<sv::VerbatimOp> verbatims;
781 DenseSet<Operation *> spilledSubOps;
782 auto layerBlockWalkResult = layerBlock.walk([&](Operation *op) {
783 // Error if pass preconditions are not met.
784 if (failed(opPreconditionCheck(op)))
785 return WalkResult::interrupt();
786
787 // Specialized handling of subfields, subindexes, and subaccesses which
788 // need to be spilled and nodes that referred to spilled nodes. If these
789 // are kept in the module, then the XMR is going to be bidirectional. Fix
790 // this for subfield and subindex by moving these ops outside the
791 // layerblock. Try to fix this for subaccess and error if the move can't
792 // be made because the index is defined inside the layerblock. (This case
793 // is exceedingly rare given that subaccesses are almost always unexepcted
794 // when this pass runs.) Additionally, if any nodes are seen that are
795 // transparently referencing a spilled op, spill the node, too. The node
796 // provides an anchor for an inner symbol (which subfield, subindex, and
797 // subaccess do not).
798 auto fixSubOp = [&](auto subOp) {
799 auto input = subOp.getInput();
800
801 // If the input is defined in this layerblock, we are done.
802 if (isAncestorOfValueOwner(layerBlock, input))
803 return WalkResult::advance();
804
805 // Otherwise, capture the input operand, if possible.
806 if (firrtl::type_cast<FIRRTLBaseType>(input.getType()).isPassive()) {
807 subOp.getInputMutable().assign(getReplacement(subOp, input));
808 return WalkResult::advance();
809 }
810
811 // Otherwise, move the subfield op out of the layerblock.
812 op->moveBefore(layerBlock);
813 spilledSubOps.insert(op);
814 return WalkResult::advance();
815 };
816
817 if (auto subOp = dyn_cast<SubfieldOp>(op))
818 return fixSubOp(subOp);
819
820 if (auto subOp = dyn_cast<SubindexOp>(op))
821 return fixSubOp(subOp);
822
823 if (auto subOp = dyn_cast<SubaccessOp>(op)) {
824 auto input = subOp.getInput();
825 auto index = subOp.getIndex();
826
827 // If the input is defined in this layerblock, capture the index if
828 // needed, and we are done.
829 if (isAncestorOfValueOwner(layerBlock, input)) {
830 if (!isAncestorOfValueOwner(layerBlock, index)) {
831 subOp.getIndexMutable().assign(getReplacement(subOp, index));
832 }
833 return WalkResult::advance();
834 }
835
836 // Otherwise, capture the input operand, if possible.
837 if (firrtl::type_cast<FIRRTLBaseType>(input.getType()).isPassive()) {
838 subOp.getInputMutable().assign(getReplacement(subOp, input));
839 if (!isAncestorOfValueOwner(layerBlock, index))
840 subOp.getIndexMutable().assign(getReplacement(subOp, index));
841 return WalkResult::advance();
842 }
843
844 // Otherwise, move the subaccess op out of the layerblock, if possible.
845 if (!isAncestorOfValueOwner(layerBlock, index)) {
846 subOp->moveBefore(layerBlock);
847 spilledSubOps.insert(op);
848 return WalkResult::advance();
849 }
850
851 // When the input is not passive, but the index is defined inside this
852 // layerblock, we are out of options.
853 auto diag = op->emitOpError()
854 << "has a non-passive operand and captures a value defined "
855 "outside its enclosing bind-convention layerblock. The "
856 "'LowerLayers' pass cannot lower this as it would "
857 "create an output port on the resulting module.";
858 diag.attachNote(layerBlock.getLoc())
859 << "the layerblock is defined here";
860 return WalkResult::interrupt();
861 }
862
863 if (auto nodeOp = dyn_cast<NodeOp>(op)) {
864 auto *definingOp = nodeOp.getInput().getDefiningOp();
865 if (definingOp &&
866 spilledSubOps.contains(nodeOp.getInput().getDefiningOp())) {
867 op->moveBefore(layerBlock);
868 return WalkResult::advance();
869 }
870 }
871
872 // Record any operations inside the layer block which have inner symbols.
873 // Theses may have symbol users which need to be updated.
874 //
875 // Note: this needs to _not_ index spilled NodeOps above.
876 if (auto symOp = dyn_cast<hw::InnerSymbolOpInterface>(op))
877 if (auto innerSym = symOp.getInnerSymAttr())
878 innerSyms.push_back(innerSym);
879
880 // Handle instance ops that were created from nested layer blocks. These
881 // ops need to be moved outside the layer block to avoid nested binds.
882 // Nested binds are illegal in the SystemVerilog specification (and
883 // checked by FIRRTL verification).
884 //
885 // For each value defined in this layer block which drives a port of one
886 // of these instances, create an output reference type port on the
887 // to-be-created module and drive it with the value. Move the instance
888 // outside the layer block. We will hook it up later once we replace the
889 // layer block with an instance.
890 if (auto instOp = dyn_cast<InstanceOp>(op)) {
891 // Ignore instances which this pass did not create.
892 if (!createdInstances.contains(instOp))
893 return WalkResult::advance();
894
895 LLVM_DEBUG({
896 llvm::dbgs()
897 << " Found instance created from nested layer block:\n"
898 << " module: " << instOp.getModuleName() << "\n"
899 << " instance: " << instOp.getName() << "\n";
900 });
901 instOp->moveBefore(layerBlock);
902 return WalkResult::advance();
903 }
904
905 // Handle domain define ops. The destination must be within the current
906 // layer block. The source may be outside it. These, unlike other XMR
907 // captures, need to create ports as there is no XMR representation for
908 // domains. When creating these, look through any intermediate wires as
909 // these need to know the domain kind when creating the port and wires do
910 // not presently have this.
911 //
912 // TODO: Stop looking through wires when wires support domain info [1].
913 //
914 // [1]: https://github.com/llvm/circt/issues/9398
915 if (auto domainDefineOp = dyn_cast<DomainDefineOp>(op)) {
916 auto src = domainDefineOp.getSrc();
917 auto dest = domainDefineOp.getDest();
918 auto srcInLayerBlock = isAncestorOfValueOwner(layerBlock, src);
919 auto destInLayerBlock = isAncestorOfValueOwner(layerBlock, dest);
920
921 if (srcInLayerBlock) {
922 // The source and destination are in the current block. Do nothing.
923 if (destInLayerBlock)
924 return WalkResult::advance();
925 // The source is in the current layer block, but the destination is
926 // outside it. This is not possible except in situations where we
927 // have moved an instance out of the layer block. I.e., this is due
928 // to a child layer (which has already been processed) capturing
929 // something from the current layer block.
930 return WalkResult(createOutputPort(src, dest));
931 }
932
933 // The source is _not_ in the current block. Create an input domain
934 // type port with the right kind. To find the right kind, we need to
935 // look through wires to the original source.
936 if (destInLayerBlock)
937 return WalkResult(createInputPort(src, domainDefineOp.getLoc()));
938
939 // The source and destination are outside the layer block. Bubble this
940 // up. Note: this code is only reachable for situations where a prior
941 // instance, created from a bind layer has been bubbled up. This flavor
942 // of construction is otherwise illegal.
943 domainDefineOp->moveBefore(layerBlock);
944 return WalkResult::advance();
945 }
946
947 // Handle captures. For any captured operands, convert them to a suitable
948 // replacement value. The `getReplacement` function will automatically
949 // reuse values whenever possible.
950 for (size_t i = 0, e = op->getNumOperands(); i != e; ++i) {
951 auto operand = op->getOperand(i);
952
953 // If the operand is in this layer block, do nothing.
954 //
955 // Note: This check is what avoids handling ConnectOp destinations.
956 if (isAncestorOfValueOwner(layerBlock, operand))
957 continue;
958
959 op->setOperand(i, getReplacement(op, operand));
960 }
961
962 if (auto verbatim = dyn_cast<sv::VerbatimOp>(op))
963 verbatims.push_back(verbatim);
964
965 return WalkResult::advance();
966 });
967
968 if (layerBlockWalkResult.wasInterrupted())
969 return WalkResult::interrupt();
970
971 // If the layer block is empty, erase it instead of creating an empty
972 // module. Note: empty leaf layer blocks will be erased by canonicalizers.
973 // We don't expect to see these here. However, this handles the case of
974 // empty intermediary layer blocks which are important in the layer block
975 // representation, but can disappear when lowered to modules.
976 if (llvm::all_of(layerBlock.getRegion().getBlocks(),
977 [](auto &a) { return a.empty(); })) {
978 assert(verbatims.empty());
979 layerBlock.erase();
980 return WalkResult::advance();
981 }
982
983 // Create the new module. This grabs a lock to modify the circuit.
984 FModuleOp newModule = buildNewModule(builder, layerBlock, ports);
985 newModule.getBody().takeBody(layerBlock.getRegion());
986 SymbolTable::setSymbolVisibility(newModule,
987 SymbolTable::Visibility::Private);
988
989 LLVM_DEBUG({
990 llvm::dbgs() << " New Module: "
991 << layerBlockGlobals.lookup(layerBlock).moduleName << "\n";
992 llvm::dbgs() << " ports:\n";
993 for (size_t i = 0, e = ports.size(); i != e; ++i) {
994 auto port = ports[i];
995 auto value = connectValues[i];
996 llvm::dbgs() << " - name: " << port.getName() << "\n"
997 << " type: " << port.type << "\n"
998 << " direction: " << port.direction << "\n"
999 << " value: " << value << "\n";
1000 }
1001 });
1002
1003 // Replace the original layer block with an instance. Hook up the
1004 // instance. Intentionally create instance with probe ports which do
1005 // not have an associated layer. This is illegal IR that will be
1006 // made legal by the end of the pass. This is done to avoid having
1007 // to revisit and rewrite each instance everytime it is moved into a
1008 // parent layer.
1009 builder.setInsertionPointAfter(layerBlock);
1010 auto instanceName = instanceNameForLayer(layerBlock.getLayerName());
1011 auto innerSym =
1012 hw::InnerSymAttr::get(builder.getStringAttr(ns.newName(instanceName)));
1013
1014 auto instanceOp = InstanceOp::create(
1015 builder, layerBlock.getLoc(), /*moduleName=*/newModule,
1016 /*name=*/
1017 instanceName, NameKindEnum::DroppableName,
1018 /*annotations=*/ArrayRef<Attribute>{},
1019 /*portAnnotations=*/ArrayRef<Attribute>{}, /*lowerToBind=*/false,
1020 /*doNotPrint=*/true, innerSym);
1021 for (auto [lhs, rhs] : llvm::zip(instanceOp.getResults(), connectValues))
1022 if (instanceOp.getPortDirection(lhs.getResultNumber()) == Direction::In)
1023 DomainDefineOp::create(builder, builder.getUnknownLoc(), lhs, rhs);
1024 else {
1025 DomainDefineOp::create(builder, builder.getUnknownLoc(), rhs, lhs);
1026 }
1027
1028 auto outputFile = outputFileForLayer(moduleOp.getModuleNameAttr(),
1029 layerBlock.getLayerName());
1030 instanceOp->setAttr("output_file", outputFile);
1031
1032 createdInstances.try_emplace(instanceOp, newModule);
1033
1034 // create the bind op.
1035 {
1036 auto builder = OpBuilder::atBlockEnd(bindFiles[moduleOp][layer].body);
1037 BindOp::create(builder, layerBlock.getLoc(), moduleOp.getModuleNameAttr(),
1038 instanceOp.getInnerSymAttr().getSymName());
1039 }
1040
1041 LLVM_DEBUG(llvm::dbgs() << " moved inner refs:\n");
1042 for (hw::InnerSymAttr innerSym : innerSyms) {
1043 auto oldInnerRef = hw::InnerRefAttr::get(moduleOp.getModuleNameAttr(),
1044 innerSym.getSymName());
1045 auto splice = std::make_pair(instanceOp.getInnerSymAttr(),
1046 newModule.getModuleNameAttr());
1047 innerRefMap.insert({oldInnerRef, splice});
1048 LLVM_DEBUG(llvm::dbgs() << " - ref: " << oldInnerRef << "\n"
1049 << " splice: " << splice.first << ", "
1050 << splice.second << "\n";);
1051 }
1052
1053 // Update verbatims that target operations extracted alongside.
1054 if (!verbatims.empty()) {
1055 mlir::AttrTypeReplacer replacer;
1056 replacer.addReplacement(
1057 [&innerRefMap](hw::InnerRefAttr ref) -> std::optional<Attribute> {
1058 auto it = innerRefMap.find(ref);
1059 if (it != innerRefMap.end())
1060 return hw::InnerRefAttr::get(it->second.second, ref.getName());
1061 return std::nullopt;
1062 });
1063 for (auto verbatim : verbatims)
1064 replacer.replaceElementsIn(verbatim);
1065 }
1066
1067 layerBlock.erase();
1068
1069 return WalkResult::advance();
1070 });
1071 return success(!result.wasInterrupted());
1072}
1073
1075 LayerOp layer, StringRef circuitName,
1076 SmallVector<FlatSymbolRefAttr> &stack) {
1077 stack.emplace_back(FlatSymbolRefAttr::get(layer.getSymNameAttr()));
1078 ArrayRef stackRef(stack);
1079 symbolToLayer.insert(
1080 {SymbolRefAttr::get(stackRef.front().getAttr(), stackRef.drop_front()),
1081 layer});
1082 if (layer.getConvention() == LayerConvention::Inline) {
1083 auto *ctx = &getContext();
1084 auto macName = macroNameForLayer(circuitName, stack);
1085 auto symName = ns.newName(macName);
1086
1087 auto symNameAttr = StringAttr::get(ctx, symName);
1088 auto macNameAttr = StringAttr();
1089 if (macName != symName)
1090 macNameAttr = StringAttr::get(ctx, macName);
1091
1092 sv::MacroDeclOp::create(b, layer->getLoc(), symNameAttr, ArrayAttr(),
1093 macNameAttr);
1094 macroNames[layer] = FlatSymbolRefAttr::get(&getContext(), symNameAttr);
1095 }
1096 for (auto child : layer.getOps<LayerOp>())
1097 preprocessLayers(ns, b, child, circuitName, stack);
1098 stack.pop_back();
1099}
1100
1102 auto circuit = getOperation();
1103 auto circuitName = circuit.getName();
1104 for (auto layer : circuit.getOps<LayerOp>()) {
1105 OpBuilder b(layer);
1106 SmallVector<FlatSymbolRefAttr> stack;
1107 preprocessLayers(ns, b, layer, circuitName, stack);
1108 }
1109}
1110
1112 InstanceGraphNode *node, OpBuilder &b,
1113 SymbolRefAttr layerName, LayerOp layer) {
1114 assert(layer.getConvention() == LayerConvention::Bind);
1115 auto module = node->getModule<FModuleOp>();
1116 auto loc = module.getLoc();
1117
1118 // Compute the include guard macro name.
1119 auto macroName = guardMacroNameForLayer(module.getModuleName(), layerName);
1120 auto macroSymbol = ns.newName(macroName);
1121 auto macroNameAttr = StringAttr::get(&getContext(), macroName);
1122 auto macroSymbolAttr = StringAttr::get(&getContext(), macroSymbol);
1123 auto macroSymbolRefAttr = FlatSymbolRefAttr::get(macroSymbolAttr);
1124
1125 // Compute the base name for the bind file.
1126 auto bindFileName = fileNameForLayer(module.getName(), layerName);
1127
1128 // Build the full output path using the filename of the bindfile and the
1129 // output directory of the layer, if any.
1130 auto dir = layer->getAttrOfType<hw::OutputFileAttr>("output_file");
1131 StringAttr filename = StringAttr::get(&getContext(), bindFileName);
1132 StringAttr path;
1133 if (dir)
1134 path = StringAttr::get(&getContext(),
1135 Twine(dir.getDirectory()) + bindFileName);
1136 else
1137 path = filename;
1138
1139 // Declare the macro for the include guard.
1140 sv::MacroDeclOp::create(b, loc, macroSymbolAttr, ArrayAttr{}, macroNameAttr);
1141
1142 // Create the emit op.
1143 auto bindFile = emit::FileOp::create(b, loc, path);
1144 OpBuilder::InsertionGuard _(b);
1145 b.setInsertionPointToEnd(bindFile.getBody());
1146
1147 // Create the #ifndef for the include guard.
1148 auto includeGuard = sv::IfDefOp::create(b, loc, macroSymbolRefAttr);
1149 b.createBlock(&includeGuard.getElseRegion());
1150
1151 // Create the #define for the include guard.
1152 sv::MacroDefOp::create(b, loc, macroSymbolRefAttr);
1153
1154 // Create IR to enable any parent layers.
1155 auto parent = layer->getParentOfType<LayerOp>();
1156 while (parent) {
1157 // If the parent is bound-in, we enable it by including the bindfile.
1158 // The parent bindfile will enable all ancestors.
1159 if (parent.getConvention() == LayerConvention::Bind) {
1160 auto target = bindFiles[module][parent].filename;
1161 sv::IncludeOp::create(b, loc, IncludeStyle::Local, target);
1162 break;
1163 }
1164
1165 // If the parent layer is inline, we can only assert that the parent is
1166 // already enabled.
1167 if (parent.getConvention() == LayerConvention::Inline) {
1168 auto parentMacroSymbolRefAttr = macroNames[parent];
1169 auto parentGuard = sv::IfDefOp::create(b, loc, parentMacroSymbolRefAttr);
1170 OpBuilder::InsertionGuard guard(b);
1171 b.createBlock(&parentGuard.getElseRegion());
1172 auto message = StringAttr::get(&getContext(),
1173 Twine(parent.getName()) + " not enabled");
1174 sv::MacroErrorOp::create(b, loc, message);
1175 parent = parent->getParentOfType<LayerOp>();
1176 continue;
1177 }
1178
1179 // Unknown Layer convention.
1180 llvm_unreachable("unknown layer convention");
1181 }
1182
1183 // Create IR to include bind files for child modules. If a module is
1184 // instantiated more than once, we only need to include the bindfile once.
1185 SmallPtrSet<Operation *, 8> seen;
1186 for (auto *record : *node) {
1187 auto *child = record->getTarget()->getModule().getOperation();
1188 if (!std::get<bool>(seen.insert(child)))
1189 continue;
1190 auto files = bindFiles[child];
1191 auto lookup = files.find(layer);
1192 if (lookup != files.end())
1193 sv::IncludeOp::create(b, loc, IncludeStyle::Local,
1194 lookup->second.filename);
1195 }
1196
1197 // Save the bind file information for later.
1198 auto &info = bindFiles[module][layer];
1199 info.filename = filename;
1200 info.body = includeGuard.getElseBlock();
1201}
1202
1204 InstanceGraphNode *node,
1205 FModuleOp module) {
1206 OpBuilder b(&getContext());
1207 b.setInsertionPointAfter(module);
1208
1209 // Create a bind file only if the layer is used under the module.
1210 llvm::SmallDenseSet<LayerOp> layersRequiringBindFiles;
1211
1212 // If the module is public, create a bind file for all layers.
1213 if (module.isPublic() || emitAllBindFiles)
1214 for (auto [_, layer] : symbolToLayer)
1215 if (layer.getConvention() == LayerConvention::Bind)
1216 layersRequiringBindFiles.insert(layer);
1217
1218 // Handle layers used directly in this module.
1219 module->walk([&](LayerBlockOp layerBlock) {
1220 auto layer = symbolToLayer[layerBlock.getLayerNameAttr()];
1221 if (layer.getConvention() == LayerConvention::Inline)
1222 return;
1223
1224 // Create a bindfile for any layer directly used in the module.
1225 layersRequiringBindFiles.insert(layer);
1226
1227 // Determine names for all modules that will be created.
1228 auto moduleName = module.getModuleName();
1229 auto layerName = layerBlock.getLayerName();
1230
1231 // A name hint for the module created from this layerblock.
1232 auto layerBlockModuleName = moduleNameForLayer(moduleName, layerName);
1233
1234 // A name hint for the hier-path-op which targets the bound-in instance of
1235 // the module created from this layerblock.
1236 auto layerBlockHierPathName = hierPathNameForLayer(moduleName, layerName);
1237
1238 LayerBlockGlobals globals;
1239 globals.moduleName = ns.newName(layerBlockModuleName);
1240 globals.hierPathName = ns.newName(layerBlockHierPathName);
1241 layerBlockGlobals.insert({layerBlock, globals});
1242 });
1243
1244 // Create a bindfile for layers used indirectly under this module.
1245 for (auto *record : *node) {
1246 auto *child = record->getTarget()->getModule().getOperation();
1247 for (auto [layer, _] : bindFiles[child])
1248 layersRequiringBindFiles.insert(layer);
1249 }
1250
1251 // Build the bindfiles for any layer seen under this module. The bindfiles
1252 // are emitted in the order which they are declared, for readability.
1253 for (auto [sym, layer] : symbolToLayer)
1254 if (layersRequiringBindFiles.contains(layer))
1255 buildBindFile(ns, node, b, sym, layer);
1256}
1257
1259 InstanceGraphNode *node,
1260 FExtModuleOp extModule) {
1261 // For each known layer of the extmodule, compute and record the bindfile
1262 // name. When a layer is known, its parent layers are implicitly known,
1263 // so compute bindfiles for parent layers too. Use a set to avoid
1264 // repeated work, which can happen if, for example, both a child layer and
1265 // a parent layer are explicitly declared to be known.
1266 auto known = extModule.getKnownLayersAttr().getAsRange<SymbolRefAttr>();
1267 if (known.empty())
1268 return;
1269
1270 auto moduleName = extModule.getExtModuleName();
1271 auto &files = bindFiles[extModule];
1272 SmallPtrSet<Operation *, 8> seen;
1273
1274 for (auto name : known) {
1275 auto layer = symbolToLayer[name];
1276 auto rootLayerName = name.getRootReference();
1277 auto nestedLayerNames = name.getNestedReferences();
1278 while (layer && std::get<bool>(seen.insert(layer))) {
1279 if (layer.getConvention() == LayerConvention::Bind) {
1280 BindFileInfo info;
1281 auto filename =
1282 fileNameForLayer(moduleName, rootLayerName, nestedLayerNames);
1283 info.filename = StringAttr::get(&getContext(), filename);
1284 info.body = nullptr;
1285 files.insert({layer, info});
1286 }
1287 layer = layer->getParentOfType<LayerOp>();
1288 if (!nestedLayerNames.empty())
1289 nestedLayerNames = nestedLayerNames.drop_back();
1290 }
1291 }
1292}
1293
1295 InstanceGraphNode *node) {
1296 auto *op = node->getModule().getOperation();
1297 if (!op)
1298 return;
1299
1300 if (auto module = dyn_cast<FModuleOp>(op))
1301 return preprocessModule(ns, node, module);
1302
1303 if (auto extModule = dyn_cast<FExtModuleOp>(op))
1304 return preprocessExtModule(ns, node, extModule);
1305}
1306
1307/// Create the bind file skeleton for each layer, for each module.
1309 InstanceGraph &ig) {
1310 ig.walkPostOrder([&](auto &node) { preprocessModuleLike(ns, &node); });
1311}
1312
1313/// Process a circuit to remove all layer blocks in each module and top-level
1314/// layer definition.
1316 LLVM_DEBUG(
1317 llvm::dbgs() << "==----- Running LowerLayers "
1318 "-------------------------------------------------===\n");
1319 CircuitOp circuitOp = getOperation();
1320
1321 // Initialize members which cannot be initialized automatically.
1322 llvm::sys::SmartMutex<true> mutex;
1323 circuitMutex = &mutex;
1324
1325 auto *ig = &getAnalysis<InstanceGraph>();
1326 CircuitNamespace ns(circuitOp);
1328 &ns, OpBuilder::InsertPoint(getOperation().getBodyBlock(),
1329 getOperation().getBodyBlock()->begin()));
1330 hierPathCache = &hpc;
1331
1332 preprocessLayers(ns);
1333 preprocessModules(ns, *ig);
1334
1335 auto mergeMaps = [](auto &&a, auto &&b) {
1336 if (failed(a))
1337 return std::forward<decltype(a)>(a);
1338 if (failed(b))
1339 return std::forward<decltype(b)>(b);
1340
1341 for (auto bb : *b)
1342 a->insert(bb);
1343 return std::forward<decltype(a)>(a);
1344 };
1345
1346 // Lower the layer blocks of each module.
1347 SmallVector<FModuleLike> modules(
1348 circuitOp.getBodyBlock()->getOps<FModuleLike>());
1349 auto failureOrInnerRefMap = transformReduce(
1350 circuitOp.getContext(), modules, FailureOr<InnerRefMap>(InnerRefMap{}),
1351 mergeMaps, [this](FModuleLike mod) -> FailureOr<InnerRefMap> {
1352 return runOnModuleLike(mod);
1353 });
1354 if (failed(failureOrInnerRefMap))
1355 return signalPassFailure();
1356 auto &innerRefMap = *failureOrInnerRefMap;
1357
1358 // Rewrite any hw::HierPathOps which have namepaths that contain rewritting
1359 // inner refs.
1360 //
1361 // TODO: This unnecessarily computes a new namepath for every hw::HierPathOp
1362 // even if that namepath is not used. It would be better to only build the
1363 // new namepath when a change is needed, e.g., by recording updates to the
1364 // namepath.
1365 for (hw::HierPathOp hierPathOp : circuitOp.getOps<hw::HierPathOp>()) {
1366 SmallVector<Attribute> newNamepath;
1367 bool modified = false;
1368 for (auto attr : hierPathOp.getNamepath()) {
1369 hw::InnerRefAttr innerRef = dyn_cast<hw::InnerRefAttr>(attr);
1370 if (!innerRef) {
1371 newNamepath.push_back(attr);
1372 continue;
1373 }
1374 auto it = innerRefMap.find(innerRef);
1375 if (it == innerRefMap.end()) {
1376 newNamepath.push_back(attr);
1377 continue;
1378 }
1379
1380 auto &[inst, mod] = it->getSecond();
1381 newNamepath.push_back(
1382 hw::InnerRefAttr::get(innerRef.getModule(), inst.getSymName()));
1383 newNamepath.push_back(hw::InnerRefAttr::get(mod, innerRef.getName()));
1384 modified = true;
1385 }
1386 if (modified)
1387 hierPathOp.setNamepathAttr(
1388 ArrayAttr::get(circuitOp.getContext(), newNamepath));
1389 }
1390
1391 // All layers definitions can now be deleted.
1392 for (auto layerOp :
1393 llvm::make_early_inc_range(circuitOp.getBodyBlock()->getOps<LayerOp>()))
1394 layerOp.erase();
1395
1396 // Cleanup state.
1397 circuitMutex = nullptr;
1398 layerBlockGlobals.clear();
1399 macroNames.clear();
1400 symbolToLayer.clear();
1401 hierPathCache = nullptr;
1402 bindFiles.clear();
1403}
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.
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.