CIRCT 22.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
227 /// Strip layer colors from the module's interface.
228 FailureOr<InnerRefMap> runOnModuleLike(FModuleLike moduleLike);
229
230 /// Extract layerblocks and strip probe colors from all ops under the module.
231 LogicalResult runOnModuleBody(FModuleOp moduleOp, InnerRefMap &innerRefMap);
232
233 /// Update the module's port types to remove any explicit layer requirements
234 /// from any probe types.
235 void removeLayersFromPorts(FModuleLike moduleLike);
236
237 /// Update the value's type to remove any layers from any probe types.
238 void removeLayersFromValue(Value value);
239
240 /// Lower an inline layerblock to an ifdef block.
241 void lowerInlineLayerBlock(LayerOp layer, LayerBlockOp layerBlock);
242
243 /// Build macro declarations and cache information about the layers.
244 void preprocessLayers(CircuitNamespace &ns, OpBuilder &b, LayerOp layer,
245 StringRef circuitName,
246 SmallVector<FlatSymbolRefAttr> &stack);
248
249 /// For each module, build a bindfile for each bound-layer, if needed.
251
252 /// Build the bindfile skeletons for each module. Set up a table which tells
253 /// us for each module/layer pair, where to insert the bind operations.
255
256 /// Build the bindfile skeleton for a module.
258 FModuleOp module);
259
260 /// Get the verilog name of an extmodule, which could be recorded in its
261 /// defname property.
262 StringRef getExtModuleName(FExtModuleOp extModule);
263
264 /// Record the supposed bindfiles for any known layers of the ext module.
266 FExtModuleOp extModule);
267
268 /// Build a bindfile skeleton for a particular module and layer.
270 OpBuilder &b, SymbolRefAttr layerName, LayerOp layer);
271
272 /// Entry point for the function.
273 void runOnOperation() override;
274
275 /// Indicates exclusive access to modify the circuitNamespace and the circuit.
276 llvm::sys::SmartMutex<true> *circuitMutex;
277
278 /// A map of layer blocks to "safe" global names which are fine to create in
279 /// the circuit namespace.
280 DenseMap<LayerBlockOp, LayerBlockGlobals> layerBlockGlobals;
281
282 /// A map from inline layers to their macro names.
283 DenseMap<LayerOp, FlatSymbolRefAttr> macroNames;
284
285 /// A mapping of symbol name to layer operation. This also serves as an
286 /// iterable list of all layers declared in a circuit. We use a map vector so
287 /// that the iteration order matches the order of declaration in the circuit.
288 /// This order is not required for correctness, it helps with legibility.
289 llvm::MapVector<SymbolRefAttr, LayerOp> symbolToLayer;
290
291 /// Utility for creating hw::HierPathOp.
293
294 /// A mapping from module*layer to bindfile name.
295 DenseMap<Operation *, DenseMap<LayerOp, BindFileInfo>> bindFiles;
296};
297
298/// Multi-process safe function to build a module in the circuit and return it.
299/// The name provided is only a namehint for the module---a unique name will be
300/// generated if there are conflicts with the namehint in the circuit-level
301/// namespace.
302FModuleOp LowerLayersPass::buildNewModule(OpBuilder &builder,
303 LayerBlockOp layerBlock) {
304 auto location = layerBlock.getLoc();
305 auto namehint = layerBlockGlobals.lookup(layerBlock).moduleName;
306 llvm::sys::SmartScopedLock<true> instrumentationLock(*circuitMutex);
307 FModuleOp newModule = FModuleOp::create(
308 builder, location, builder.getStringAttr(namehint),
309 ConventionAttr::get(builder.getContext(), Convention::Internal),
310 ArrayRef<PortInfo>{}, ArrayAttr{});
311 if (auto dir = getOutputFile(layerBlock.getLayerNameAttr())) {
312 assert(dir.isDirectory());
313 newModule->setAttr("output_file", dir);
314 }
315 SymbolTable::setSymbolVisibility(newModule, SymbolTable::Visibility::Private);
316 return newModule;
317}
318
320 auto type = dyn_cast<RefType>(value.getType());
321 if (!type || !type.getLayer())
322 return;
323 value.setType(type.removeLayer());
324}
325
326void LowerLayersPass::removeLayersFromPorts(FModuleLike moduleLike) {
327 auto oldTypeAttrs = moduleLike.getPortTypesAttr();
328 SmallVector<Attribute> newTypeAttrs;
329 newTypeAttrs.reserve(oldTypeAttrs.size());
330 bool changed = false;
331
332 for (auto typeAttr : oldTypeAttrs.getAsRange<TypeAttr>()) {
333 if (auto refType = dyn_cast<RefType>(typeAttr.getValue())) {
334 if (refType.getLayer()) {
335 typeAttr = TypeAttr::get(refType.removeLayer());
336 changed = true;
337 }
338 }
339 newTypeAttrs.push_back(typeAttr);
340 }
341
342 if (!changed)
343 return;
344
345 moduleLike.setPortTypesAttr(
346 ArrayAttr::get(moduleLike.getContext(), newTypeAttrs));
347
348 if (auto moduleOp = dyn_cast<FModuleOp>(moduleLike.getOperation())) {
349 for (auto arg : moduleOp.getBodyBlock()->getArguments())
351 }
352}
353
354FailureOr<InnerRefMap>
355LowerLayersPass::runOnModuleLike(FModuleLike moduleLike) {
356 LLVM_DEBUG({
357 llvm::dbgs() << "Module: " << moduleLike.getModuleName() << "\n";
358 llvm::dbgs() << " Examining Layer Blocks:\n";
359 });
360
361 // Strip away layers from the interface of the module-like op.
362 InnerRefMap innerRefMap;
363 auto result =
364 TypeSwitch<Operation *, LogicalResult>(moduleLike.getOperation())
365 .Case<FModuleOp>([&](auto op) {
366 op.setLayers({});
368 return runOnModuleBody(op, innerRefMap);
369 })
370 .Case<FExtModuleOp>([&](auto op) {
371 op.setKnownLayers({});
372 op.setLayers({});
374 return success();
375 })
376 .Case<FIntModuleOp, FMemModuleOp>([&](auto op) {
377 op.setLayers({});
379 return success();
380 })
381 .Case<ClassOp, ExtClassOp>([](auto) { return success(); })
382 .Default(
383 [](auto *op) { return op->emitError("unknown module-like op"); });
384
385 if (failed(result))
386 return failure();
387
388 return innerRefMap;
389}
390
392 LayerBlockOp layerBlock) {
393 if (!layerBlock.getBody()->empty()) {
394 OpBuilder builder(layerBlock);
395 auto macroName = macroNames[layer];
396 auto ifDef = builder.create<sv::IfDefOp>(layerBlock.getLoc(), macroName);
397 ifDef.getBodyRegion().takeBody(layerBlock.getBodyRegion());
398 }
399 layerBlock.erase();
400}
401
402LogicalResult LowerLayersPass::runOnModuleBody(FModuleOp moduleOp,
403 InnerRefMap &innerRefMap) {
404 hw::InnerSymbolNamespace ns(moduleOp);
405
406 // A cache of values to nameable ops that can be used
407 DenseMap<Value, Operation *> nodeCache;
408
409 // Get or create a node op for a value captured by a layer block.
410 auto getOrCreateNodeOp = [&](Value operand,
411 ImplicitLocOpBuilder &builder) -> Operation * {
412 // Use the cache hit.
413 auto *nodeOp = nodeCache.lookup(operand);
414 if (nodeOp)
415 return nodeOp;
416
417 // Create a new node. Put it in the cache and use it.
418 OpBuilder::InsertionGuard guard(builder);
419 builder.setInsertionPointAfterValue(operand);
420 SmallString<16> nameHint;
421 // Try to generate a "good" name hint to use for the node.
422 if (auto *definingOp = operand.getDefiningOp()) {
423 if (auto instanceOp = dyn_cast<InstanceOp>(definingOp)) {
424 nameHint.append(instanceOp.getName());
425 nameHint.push_back('_');
426 nameHint.append(
427 instanceOp.getPortName(cast<OpResult>(operand).getResultNumber()));
428 } else if (auto opName = definingOp->getAttrOfType<StringAttr>("name")) {
429 nameHint.append(opName);
430 }
431 }
432 return nodeOp = NodeOp::create(builder, operand.getLoc(), operand,
433 nameHint.empty() ? "_layer_probe"
434 : StringRef(nameHint));
435 };
436
437 // Determine the replacement for an operand within the current region. Keep a
438 // densemap of replacements around to avoid creating the same hardware
439 // multiple times.
440 DenseMap<Value, Value> replacements;
441 auto getReplacement = [&](Operation *user, Value value) -> Value {
442 auto it = replacements.find(value);
443 if (it != replacements.end())
444 return it->getSecond();
445
446 ImplicitLocOpBuilder localBuilder(value.getLoc(), &getContext());
447 Value replacement;
448
449 auto layerBlockOp = user->getParentOfType<LayerBlockOp>();
450 localBuilder.setInsertionPointToStart(layerBlockOp.getBody());
451
452 // If the operand is "special", e.g., it has no XMR representation, then we
453 // need to clone it.
454 //
455 // TODO: Change this to recursively clone. This will matter once FString
456 // operations have operands.
457 if (type_isa<FStringType>(value.getType())) {
458 localBuilder.setInsertionPoint(user);
459 replacement = localBuilder.clone(*value.getDefiningOp())->getResult(0);
460 replacements.insert({value, replacement});
461 return replacement;
462 }
463
464 // If the operand is an XMR ref, then we _have_ to clone it.
465 auto *definingOp = value.getDefiningOp();
466 if (isa_and_present<XMRRefOp>(definingOp)) {
467 replacement = localBuilder.clone(*definingOp)->getResult(0);
468 replacements.insert({value, replacement});
469 return replacement;
470 }
471
472 // Determine the replacement value for the captured operand. There are
473 // three cases that can occur:
474 //
475 // 1. Capturing something zero-width. Create a zero-width constant zero.
476 // 2. Capture an expression or instance port. Drop a node and XMR deref
477 // that.
478 // 3. Capture something that can handle an inner sym. XMR deref that.
479 //
480 // Note: (3) can be either an operation or a _module_ port.
481 auto baseType = type_cast<FIRRTLBaseType>(value.getType());
482 if (baseType && baseType.getBitWidthOrSentinel() == 0) {
483 OpBuilder::InsertionGuard guard(localBuilder);
484 auto zeroUIntType = UIntType::get(localBuilder.getContext(), 0);
485 replacement = localBuilder.createOrFold<BitCastOp>(
486 value.getType(), ConstantOp::create(localBuilder, zeroUIntType,
487 getIntZerosAttr(zeroUIntType)));
488 } else {
489 auto *definingOp = value.getDefiningOp();
490 hw::InnerRefAttr innerRef;
491 if (definingOp) {
492 // Always create a node. This is a trade-off between optimizations and
493 // dead code. By adding the node, this allows the original path to be
494 // better optimized, but will leave dead code in the design. If the
495 // node is not created, then the output is less optimized. Err on the
496 // side of dead code. This dead node _may_ be eventually inlined by
497 // `ExportVerilog`. However, this is not guaranteed.
498 definingOp = getOrCreateNodeOp(value, localBuilder);
499 innerRef = getInnerRefTo(
500 definingOp, [&](auto) -> hw::InnerSymbolNamespace & { return ns; });
501 } else {
502 auto portIdx = cast<BlockArgument>(value).getArgNumber();
503 innerRef = getInnerRefTo(
504 cast<FModuleLike>(*moduleOp), portIdx,
505 [&](auto) -> hw::InnerSymbolNamespace & { return ns; });
506 }
507
508 hw::HierPathOp hierPathOp;
509 {
510 // TODO: Move to before parallel region to avoid the lock.
511 auto insertPoint = OpBuilder::InsertPoint(moduleOp->getBlock(),
512 Block::iterator(moduleOp));
513 llvm::sys::SmartScopedLock<true> circuitLock(*circuitMutex);
514 hierPathOp = hierPathCache->getOrCreatePath(
515 localBuilder.getArrayAttr({innerRef}), localBuilder.getLoc(),
516 insertPoint, layerBlockGlobals.lookup(layerBlockOp).hierPathName);
517 hierPathOp.setVisibility(SymbolTable::Visibility::Private);
518 }
519
520 replacement = XMRDerefOp::create(localBuilder, value.getType(),
521 hierPathOp.getSymNameAttr());
522 }
523
524 replacements.insert({value, replacement});
525
526 return replacement;
527 };
528
529 // A map of instance ops to modules that this pass creates. This is used to
530 // check if this was an instance that we created and to do fast module
531 // dereferencing (avoiding a symbol table).
532 DenseMap<InstanceOp, FModuleOp> createdInstances;
533
534 // Check that the preconditions for this pass are met. Reject any ops which
535 // must have been removed before this runs.
536 auto opPreconditionCheck = [](Operation *op) -> LogicalResult {
537 // LowerXMR op removal postconditions.
538 if (isa<RefCastOp, RefDefineOp, RefResolveOp, RefSendOp, RefSubOp,
539 RWProbeOp>(op))
540 return op->emitOpError()
541 << "cannot be handled by the lower-layers pass. This should have "
542 "already been removed by the lower-xmr pass.";
543
544 return success();
545 };
546
547 // Post-order traversal that expands a layer block into its parent. Because of
548 // the pass precondition that this runs _after_ `LowerXMR`, not much has to
549 // happen here. All of the following do happen, though:
550 //
551 // 1. Any layer coloring is stripped.
552 // 2. Layers with Inline convention are converted to SV ifdefs.
553 // 3. Layers with Bind convention are converted to new modules and then
554 // instantiated at their original location. Any captured values are either
555 // moved, cloned, or converted to XMR deref ops.
556 // 4. Move instances created from earlier (3) conversions out of later (3)
557 // conversions. This is necessary to avoid a SystemVerilog-illegal
558 // bind-under-bind. (See Section 23.11 of 1800-2023.)
559 // 5. Keep track of special ops (ops with inner symbols or verbatims) which
560 // need to have something updated because of the new instance hierarchy
561 // being created.
562 //
563 // Remember, this is post-order, in-order. Child layer blocks are visited
564 // before parents. Any nested regions _within_ the layer block are also
565 // visited before the outer layer block.
566 auto result = moduleOp.walk<mlir::WalkOrder::PostOrder>([&](Operation *op) {
567 if (failed(opPreconditionCheck(op)))
568 return WalkResult::interrupt();
569
570 // Strip layer requirements from any op that might represent a probe.
571 for (auto result : op->getResults())
572 removeLayersFromValue(result);
573
574 // If the op is an instance, clear the enablelayers attribute.
575 if (auto instance = dyn_cast<InstanceOp>(op))
576 instance.setLayers({});
577
578 auto layerBlock = dyn_cast<LayerBlockOp>(op);
579 if (!layerBlock)
580 return WalkResult::advance();
581
582 // After this point, we are dealing with a layer block.
583 auto layer = symbolToLayer.lookup(layerBlock.getLayerName());
584
585 if (layer.getConvention() == LayerConvention::Inline) {
586 lowerInlineLayerBlock(layer, layerBlock);
587 return WalkResult::advance();
588 }
589
590 // After this point, we are dealing with a bind convention layer block.
591 assert(layer.getConvention() == LayerConvention::Bind);
592
593 // Clear the replacements so that none are re-used across layer blocks.
594 replacements.clear();
595 OpBuilder builder(moduleOp);
596 SmallVector<hw::InnerSymAttr> innerSyms;
597 SmallVector<sv::VerbatimOp> verbatims;
598 DenseSet<Operation *> spilledSubOps;
599 auto layerBlockWalkResult = layerBlock.walk([&](Operation *op) {
600 // Error if pass preconditions are not met.
601 if (failed(opPreconditionCheck(op)))
602 return WalkResult::interrupt();
603
604 // Specialized handling of subfields, subindexes, and subaccesses which
605 // need to be spilled and nodes that referred to spilled nodes. If these
606 // are kept in the module, then the XMR is going to be bidirectional. Fix
607 // this for subfield and subindex by moving these ops outside the
608 // layerblock. Try to fix this for subaccess and error if the move can't
609 // be made because the index is defined inside the layerblock. (This case
610 // is exceedingly rare given that subaccesses are almost always unexepcted
611 // when this pass runs.) Additionally, if any nodes are seen that are
612 // transparently referencing a spilled op, spill the node, too. The node
613 // provides an anchor for an inner symbol (which subfield, subindex, and
614 // subaccess do not).
615 auto fixSubOp = [&](auto subOp) {
616 auto input = subOp.getInput();
617
618 // If the input is defined in this layerblock, we are done.
619 if (isAncestorOfValueOwner(layerBlock, input))
620 return WalkResult::advance();
621
622 // Otherwise, capture the input operand, if possible.
623 if (firrtl::type_cast<FIRRTLBaseType>(input.getType()).isPassive()) {
624 subOp.getInputMutable().assign(getReplacement(subOp, input));
625 return WalkResult::advance();
626 }
627
628 // Otherwise, move the subfield op out of the layerblock.
629 op->moveBefore(layerBlock);
630 spilledSubOps.insert(op);
631 return WalkResult::advance();
632 };
633
634 if (auto subOp = dyn_cast<SubfieldOp>(op))
635 return fixSubOp(subOp);
636
637 if (auto subOp = dyn_cast<SubindexOp>(op))
638 return fixSubOp(subOp);
639
640 if (auto subOp = dyn_cast<SubaccessOp>(op)) {
641 auto input = subOp.getInput();
642 auto index = subOp.getIndex();
643
644 // If the input is defined in this layerblock, capture the index if
645 // needed, and we are done.
646 if (isAncestorOfValueOwner(layerBlock, input)) {
647 if (!isAncestorOfValueOwner(layerBlock, index)) {
648 subOp.getIndexMutable().assign(getReplacement(subOp, index));
649 }
650 return WalkResult::advance();
651 }
652
653 // Otherwise, capture the input operand, if possible.
654 if (firrtl::type_cast<FIRRTLBaseType>(input.getType()).isPassive()) {
655 subOp.getInputMutable().assign(getReplacement(subOp, input));
656 if (!isAncestorOfValueOwner(layerBlock, index))
657 subOp.getIndexMutable().assign(getReplacement(subOp, index));
658 return WalkResult::advance();
659 }
660
661 // Otherwise, move the subaccess op out of the layerblock, if possible.
662 if (!isAncestorOfValueOwner(layerBlock, index)) {
663 subOp->moveBefore(layerBlock);
664 spilledSubOps.insert(op);
665 return WalkResult::advance();
666 }
667
668 // When the input is not passive, but the index is defined inside this
669 // layerblock, we are out of options.
670 auto diag = op->emitOpError()
671 << "has a non-passive operand and captures a value defined "
672 "outside its enclosing bind-convention layerblock. The "
673 "'LowerLayers' pass cannot lower this as it would "
674 "create an output port on the resulting module.";
675 diag.attachNote(layerBlock.getLoc())
676 << "the layerblock is defined here";
677 return WalkResult::interrupt();
678 }
679
680 if (auto nodeOp = dyn_cast<NodeOp>(op)) {
681 auto *definingOp = nodeOp.getInput().getDefiningOp();
682 if (definingOp &&
683 spilledSubOps.contains(nodeOp.getInput().getDefiningOp())) {
684 op->moveBefore(layerBlock);
685 return WalkResult::advance();
686 }
687 }
688
689 // Record any operations inside the layer block which have inner symbols.
690 // Theses may have symbol users which need to be updated.
691 //
692 // Note: this needs to _not_ index spilled NodeOps above.
693 if (auto symOp = dyn_cast<hw::InnerSymbolOpInterface>(op))
694 if (auto innerSym = symOp.getInnerSymAttr())
695 innerSyms.push_back(innerSym);
696
697 // Handle instance ops that were created from nested layer blocks. These
698 // ops need to be moved outside the layer block to avoid nested binds.
699 // Nested binds are illegal in the SystemVerilog specification (and
700 // checked by FIRRTL verification).
701 //
702 // For each value defined in this layer block which drives a port of one
703 // of these instances, create an output reference type port on the
704 // to-be-created module and drive it with the value. Move the instance
705 // outside the layer block. We will hook it up later once we replace the
706 // layer block with an instance.
707 if (auto instOp = dyn_cast<InstanceOp>(op)) {
708 // Ignore instances which this pass did not create.
709 if (!createdInstances.contains(instOp))
710 return WalkResult::advance();
711
712 LLVM_DEBUG({
713 llvm::dbgs()
714 << " Found instance created from nested layer block:\n"
715 << " module: " << instOp.getModuleName() << "\n"
716 << " instance: " << instOp.getName() << "\n";
717 });
718 instOp->moveBefore(layerBlock);
719 return WalkResult::advance();
720 }
721
722 // Handle captures. For any captured operands, convert them to a suitable
723 // replacement value. The `getReplacement` function will automatically
724 // reuse values whenever possible.
725 for (size_t i = 0, e = op->getNumOperands(); i != e; ++i) {
726 auto operand = op->getOperand(i);
727
728 // If the operand is in this layer block, do nothing.
729 //
730 // Note: This check is what avoids handling ConnectOp destinations.
731 if (isAncestorOfValueOwner(layerBlock, operand))
732 continue;
733
734 op->setOperand(i, getReplacement(op, operand));
735 }
736
737 if (auto verbatim = dyn_cast<sv::VerbatimOp>(op))
738 verbatims.push_back(verbatim);
739
740 return WalkResult::advance();
741 });
742
743 if (layerBlockWalkResult.wasInterrupted())
744 return WalkResult::interrupt();
745
746 // Create the new module. This grabs a lock to modify the circuit.
747 FModuleOp newModule = buildNewModule(builder, layerBlock);
748 SymbolTable::setSymbolVisibility(newModule,
749 SymbolTable::Visibility::Private);
750 newModule.getBody().takeBody(layerBlock.getRegion());
751
752 LLVM_DEBUG({
753 llvm::dbgs() << " New Module: "
754 << layerBlockGlobals.lookup(layerBlock).moduleName << "\n";
755 });
756
757 // Replace the original layer block with an instance. Hook up the
758 // instance. Intentionally create instance with probe ports which do
759 // not have an associated layer. This is illegal IR that will be
760 // made legal by the end of the pass. This is done to avoid having
761 // to revisit and rewrite each instance everytime it is moved into a
762 // parent layer.
763 builder.setInsertionPointAfter(layerBlock);
764 auto instanceName = instanceNameForLayer(layerBlock.getLayerName());
765 auto innerSym =
766 hw::InnerSymAttr::get(builder.getStringAttr(ns.newName(instanceName)));
767
768 auto instanceOp = InstanceOp::create(
769 builder, layerBlock.getLoc(), /*moduleName=*/newModule,
770 /*name=*/
771 instanceName, NameKindEnum::DroppableName,
772 /*annotations=*/ArrayRef<Attribute>{},
773 /*portAnnotations=*/ArrayRef<Attribute>{}, /*lowerToBind=*/false,
774 /*doNotPrint=*/true, innerSym);
775
776 auto outputFile = outputFileForLayer(moduleOp.getModuleNameAttr(),
777 layerBlock.getLayerName());
778 instanceOp->setAttr("output_file", outputFile);
779
780 createdInstances.try_emplace(instanceOp, newModule);
781
782 // create the bind op.
783 {
784 auto builder = OpBuilder::atBlockEnd(bindFiles[moduleOp][layer].body);
785 BindOp::create(builder, layerBlock.getLoc(), moduleOp.getModuleNameAttr(),
786 instanceOp.getInnerSymAttr().getSymName());
787 }
788
789 LLVM_DEBUG(llvm::dbgs() << " moved inner refs:\n");
790 for (hw::InnerSymAttr innerSym : innerSyms) {
791 auto oldInnerRef = hw::InnerRefAttr::get(moduleOp.getModuleNameAttr(),
792 innerSym.getSymName());
793 auto splice = std::make_pair(instanceOp.getInnerSymAttr(),
794 newModule.getModuleNameAttr());
795 innerRefMap.insert({oldInnerRef, splice});
796 LLVM_DEBUG(llvm::dbgs() << " - ref: " << oldInnerRef << "\n"
797 << " splice: " << splice.first << ", "
798 << splice.second << "\n";);
799 }
800
801 // Update verbatims that target operations extracted alongside.
802 if (!verbatims.empty()) {
803 mlir::AttrTypeReplacer replacer;
804 replacer.addReplacement(
805 [&innerRefMap](hw::InnerRefAttr ref) -> std::optional<Attribute> {
806 auto it = innerRefMap.find(ref);
807 if (it != innerRefMap.end())
808 return hw::InnerRefAttr::get(it->second.second, ref.getName());
809 return std::nullopt;
810 });
811 for (auto verbatim : verbatims)
812 replacer.replaceElementsIn(verbatim);
813 }
814
815 layerBlock.erase();
816
817 return WalkResult::advance();
818 });
819 return success(!result.wasInterrupted());
820}
821
823 LayerOp layer, StringRef circuitName,
824 SmallVector<FlatSymbolRefAttr> &stack) {
825 stack.emplace_back(FlatSymbolRefAttr::get(layer.getSymNameAttr()));
826 ArrayRef stackRef(stack);
827 symbolToLayer.insert(
828 {SymbolRefAttr::get(stackRef.front().getAttr(), stackRef.drop_front()),
829 layer});
830 if (layer.getConvention() == LayerConvention::Inline) {
831 auto *ctx = &getContext();
832 auto macName = macroNameForLayer(circuitName, stack);
833 auto symName = ns.newName(macName);
834
835 auto symNameAttr = StringAttr::get(ctx, symName);
836 auto macNameAttr = StringAttr();
837 if (macName != symName)
838 macNameAttr = StringAttr::get(ctx, macName);
839
840 sv::MacroDeclOp::create(b, layer->getLoc(), symNameAttr, ArrayAttr(),
841 macNameAttr);
842 macroNames[layer] = FlatSymbolRefAttr::get(&getContext(), symNameAttr);
843 }
844 for (auto child : layer.getOps<LayerOp>())
845 preprocessLayers(ns, b, child, circuitName, stack);
846 stack.pop_back();
847}
848
850 auto circuit = getOperation();
851 auto circuitName = circuit.getName();
852 for (auto layer : circuit.getOps<LayerOp>()) {
853 OpBuilder b(layer);
854 SmallVector<FlatSymbolRefAttr> stack;
855 preprocessLayers(ns, b, layer, circuitName, stack);
856 }
857}
858
860 InstanceGraphNode *node, OpBuilder &b,
861 SymbolRefAttr layerName, LayerOp layer) {
862 assert(layer.getConvention() == LayerConvention::Bind);
863 auto module = node->getModule<FModuleOp>();
864 auto loc = module.getLoc();
865
866 // Compute the include guard macro name.
867 auto macroName = guardMacroNameForLayer(module.getModuleName(), layerName);
868 auto macroSymbol = ns.newName(macroName);
869 auto macroNameAttr = StringAttr::get(&getContext(), macroName);
870 auto macroSymbolAttr = StringAttr::get(&getContext(), macroSymbol);
871 auto macroSymbolRefAttr = FlatSymbolRefAttr::get(macroSymbolAttr);
872
873 // Compute the base name for the bind file.
874 auto bindFileName = fileNameForLayer(module.getName(), layerName);
875
876 // Build the full output path using the filename of the bindfile and the
877 // output directory of the layer, if any.
878 auto dir = layer->getAttrOfType<hw::OutputFileAttr>("output_file");
879 StringAttr filename = StringAttr::get(&getContext(), bindFileName);
880 StringAttr path;
881 if (dir)
882 path = StringAttr::get(&getContext(),
883 Twine(dir.getDirectory()) + bindFileName);
884 else
885 path = filename;
886
887 // Declare the macro for the include guard.
888 sv::MacroDeclOp::create(b, loc, macroSymbolAttr, ArrayAttr{}, macroNameAttr);
889
890 // Create the emit op.
891 auto bindFile = emit::FileOp::create(b, loc, path);
892 OpBuilder::InsertionGuard _(b);
893 b.setInsertionPointToEnd(bindFile.getBody());
894
895 // Create the #ifndef for the include guard.
896 auto includeGuard = sv::IfDefOp::create(b, loc, macroSymbolRefAttr);
897 b.createBlock(&includeGuard.getElseRegion());
898
899 // Create the #define for the include guard.
900 sv::MacroDefOp::create(b, loc, macroSymbolRefAttr);
901
902 // Create IR to enable any parent layers.
903 auto parent = layer->getParentOfType<LayerOp>();
904 while (parent) {
905 // If the parent is bound-in, we enable it by including the bindfile.
906 // The parent bindfile will enable all ancestors.
907 if (parent.getConvention() == LayerConvention::Bind) {
908 auto target = bindFiles[module][parent].filename;
909 sv::IncludeOp::create(b, loc, IncludeStyle::Local, target);
910 break;
911 }
912
913 // If the parent layer is inline, we can only assert that the parent is
914 // already enabled.
915 if (parent.getConvention() == LayerConvention::Inline) {
916 auto parentMacroSymbolRefAttr = macroNames[parent];
917 auto parentGuard = sv::IfDefOp::create(b, loc, parentMacroSymbolRefAttr);
918 OpBuilder::InsertionGuard guard(b);
919 b.createBlock(&parentGuard.getElseRegion());
920 auto message = StringAttr::get(&getContext(),
921 Twine(parent.getName()) + " not enabled");
922 sv::MacroErrorOp::create(b, loc, message);
923 parent = parent->getParentOfType<LayerOp>();
924 continue;
925 }
926
927 // Unknown Layer convention.
928 llvm_unreachable("unknown layer convention");
929 }
930
931 // Create IR to include bind files for child modules. If a module is
932 // instantiated more than once, we only need to include the bindfile once.
933 SmallPtrSet<Operation *, 8> seen;
934 for (auto *record : *node) {
935 auto *child = record->getTarget()->getModule().getOperation();
936 if (!std::get<bool>(seen.insert(child)))
937 continue;
938 auto files = bindFiles[child];
939 auto lookup = files.find(layer);
940 if (lookup != files.end())
941 sv::IncludeOp::create(b, loc, IncludeStyle::Local,
942 lookup->second.filename);
943 }
944
945 // Save the bind file information for later.
946 auto &info = bindFiles[module][layer];
947 info.filename = filename;
948 info.body = includeGuard.getElseBlock();
949}
950
952 InstanceGraphNode *node,
953 FModuleOp module) {
954
955 OpBuilder b(&getContext());
956 b.setInsertionPointAfter(module);
957
958 // Create a bind file only if the layer is used under the module.
959 llvm::SmallDenseSet<LayerOp> layersRequiringBindFiles;
960
961 // If the module is public, create a bind file for all layers.
962 if (module.isPublic() || emitAllBindFiles)
963 for (auto [_, layer] : symbolToLayer)
964 if (layer.getConvention() == LayerConvention::Bind)
965 layersRequiringBindFiles.insert(layer);
966
967 // Handle layers used directly in this module.
968 module->walk([&](LayerBlockOp layerBlock) {
969 auto layer = symbolToLayer[layerBlock.getLayerNameAttr()];
970 if (layer.getConvention() == LayerConvention::Inline)
971 return;
972
973 // Create a bindfile for any layer directly used in the module.
974 layersRequiringBindFiles.insert(layer);
975
976 // Determine names for all modules that will be created.
977 auto moduleName = module.getModuleName();
978 auto layerName = layerBlock.getLayerName();
979
980 // A name hint for the module created from this layerblock.
981 auto layerBlockModuleName = moduleNameForLayer(moduleName, layerName);
982
983 // A name hint for the hier-path-op which targets the bound-in instance of
984 // the module created from this layerblock.
985 auto layerBlockHierPathName = hierPathNameForLayer(moduleName, layerName);
986
987 LayerBlockGlobals globals;
988 globals.moduleName = ns.newName(layerBlockModuleName);
989 globals.hierPathName = ns.newName(layerBlockHierPathName);
990 layerBlockGlobals.insert({layerBlock, globals});
991 });
992
993 // Create a bindfile for layers used indirectly under this module.
994 for (auto *record : *node) {
995 auto *child = record->getTarget()->getModule().getOperation();
996 for (auto [layer, _] : bindFiles[child])
997 layersRequiringBindFiles.insert(layer);
998 }
999
1000 // Build the bindfiles for any layer seen under this module. The bindfiles are
1001 // emitted in the order which they are declared, for readability.
1002 for (auto [sym, layer] : symbolToLayer)
1003 if (layersRequiringBindFiles.contains(layer))
1004 buildBindFile(ns, node, b, sym, layer);
1005}
1006
1007StringRef LowerLayersPass::getExtModuleName(FExtModuleOp extModule) {
1008 if (auto name = extModule.getDefnameAttr())
1009 return name.getValue();
1010 return extModule.getName();
1011}
1012
1014 InstanceGraphNode *node,
1015 FExtModuleOp extModule) {
1016 // For each known layer of the extmodule, compute and record the bindfile
1017 // name. When a layer is known, its parent layers are implicitly known,
1018 // so compute bindfiles for parent layers too. Use a set to avoid
1019 // repeated work, which can happen if, for example, both a child layer and
1020 // a parent layer are explicitly declared to be known.
1021 auto known = extModule.getKnownLayersAttr().getAsRange<SymbolRefAttr>();
1022 if (known.empty())
1023 return;
1024
1025 auto moduleName = getExtModuleName(extModule);
1026 auto &files = bindFiles[extModule];
1027 SmallPtrSet<Operation *, 8> seen;
1028
1029 for (auto name : known) {
1030 auto layer = symbolToLayer[name];
1031 auto rootLayerName = name.getRootReference();
1032 auto nestedLayerNames = name.getNestedReferences();
1033 while (layer && std::get<bool>(seen.insert(layer))) {
1034 if (layer.getConvention() == LayerConvention::Bind) {
1035 BindFileInfo info;
1036 auto filename =
1037 fileNameForLayer(moduleName, rootLayerName, nestedLayerNames);
1038 info.filename = StringAttr::get(&getContext(), filename);
1039 info.body = nullptr;
1040 files.insert({layer, info});
1041 }
1042 layer = layer->getParentOfType<LayerOp>();
1043 if (!nestedLayerNames.empty())
1044 nestedLayerNames = nestedLayerNames.drop_back();
1045 }
1046 }
1047}
1048
1050 InstanceGraphNode *node) {
1051 auto *op = node->getModule().getOperation();
1052 if (!op)
1053 return;
1054
1055 if (auto module = dyn_cast<FModuleOp>(op))
1056 return preprocessModule(ns, node, module);
1057
1058 if (auto extModule = dyn_cast<FExtModuleOp>(op))
1059 return preprocessExtModule(ns, node, extModule);
1060}
1061
1062/// Create the bind file skeleton for each layer, for each module.
1064 InstanceGraph &ig) {
1065 DenseSet<InstanceGraphNode *> visited;
1066 for (auto *root : ig)
1067 for (auto *node : llvm::post_order_ext(root, visited))
1068 preprocessModuleLike(ns, node);
1069}
1070
1071/// Process a circuit to remove all layer blocks in each module and top-level
1072/// layer definition.
1074 LLVM_DEBUG(
1075 llvm::dbgs() << "==----- Running LowerLayers "
1076 "-------------------------------------------------===\n");
1077 CircuitOp circuitOp = getOperation();
1078
1079 // Initialize members which cannot be initialized automatically.
1080 llvm::sys::SmartMutex<true> mutex;
1081 circuitMutex = &mutex;
1082
1083 auto *ig = &getAnalysis<InstanceGraph>();
1084 CircuitNamespace ns(circuitOp);
1086 &ns, OpBuilder::InsertPoint(getOperation().getBodyBlock(),
1087 getOperation().getBodyBlock()->begin()));
1088 hierPathCache = &hpc;
1089
1090 preprocessLayers(ns);
1091 preprocessModules(ns, *ig);
1092
1093 auto mergeMaps = [](auto &&a, auto &&b) {
1094 if (failed(a))
1095 return std::forward<decltype(a)>(a);
1096 if (failed(b))
1097 return std::forward<decltype(b)>(b);
1098
1099 for (auto bb : *b)
1100 a->insert(bb);
1101 return std::forward<decltype(a)>(a);
1102 };
1103
1104 // Lower the layer blocks of each module.
1105 SmallVector<FModuleLike> modules(
1106 circuitOp.getBodyBlock()->getOps<FModuleLike>());
1107 auto failureOrInnerRefMap = transformReduce(
1108 circuitOp.getContext(), modules, FailureOr<InnerRefMap>(InnerRefMap{}),
1109 mergeMaps, [this](FModuleLike mod) -> FailureOr<InnerRefMap> {
1110 return runOnModuleLike(mod);
1111 });
1112 if (failed(failureOrInnerRefMap))
1113 return signalPassFailure();
1114 auto &innerRefMap = *failureOrInnerRefMap;
1115
1116 // Rewrite any hw::HierPathOps which have namepaths that contain rewritting
1117 // inner refs.
1118 //
1119 // TODO: This unnecessarily computes a new namepath for every hw::HierPathOp
1120 // even if that namepath is not used. It would be better to only build the
1121 // new namepath when a change is needed, e.g., by recording updates to the
1122 // namepath.
1123 for (hw::HierPathOp hierPathOp : circuitOp.getOps<hw::HierPathOp>()) {
1124 SmallVector<Attribute> newNamepath;
1125 bool modified = false;
1126 for (auto attr : hierPathOp.getNamepath()) {
1127 hw::InnerRefAttr innerRef = dyn_cast<hw::InnerRefAttr>(attr);
1128 if (!innerRef) {
1129 newNamepath.push_back(attr);
1130 continue;
1131 }
1132 auto it = innerRefMap.find(innerRef);
1133 if (it == innerRefMap.end()) {
1134 newNamepath.push_back(attr);
1135 continue;
1136 }
1137
1138 auto &[inst, mod] = it->getSecond();
1139 newNamepath.push_back(
1140 hw::InnerRefAttr::get(innerRef.getModule(), inst.getSymName()));
1141 newNamepath.push_back(hw::InnerRefAttr::get(mod, innerRef.getName()));
1142 modified = true;
1143 }
1144 if (modified)
1145 hierPathOp.setNamepathAttr(
1146 ArrayAttr::get(circuitOp.getContext(), newNamepath));
1147 }
1148
1149 // All layers definitions can now be deleted.
1150 for (auto layerOp :
1151 llvm::make_early_inc_range(circuitOp.getBodyBlock()->getOps<LayerOp>()))
1152 layerOp.erase();
1153
1154 // Cleanup state.
1155 circuitMutex = nullptr;
1156 layerBlockGlobals.clear();
1157 macroNames.clear();
1158 symbolToLayer.clear();
1159 hierPathCache = nullptr;
1160 bindFiles.clear();
1161}
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.
StringRef getExtModuleName(FExtModuleOp extModule)
Get the verilog name of an extmodule, which could be recorded in its defname property.
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.
hw::OutputFileAttr getOutputFile(SymbolRefAttr layerName)
hw::HierPathCache * hierPathCache
Utility for creating hw::HierPathOp.
FModuleOp buildNewModule(OpBuilder &builder, LayerBlockOp layerBlock)
Safely build a new module with a given namehint.
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.
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.
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.
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