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