CIRCT 24.0.0git
Loading...
Searching...
No Matches
IMDeadCodeElim.cpp
Go to the documentation of this file.
1//===- IMDeadCodeElim.cpp - Intermodule Dead Code Elimination ---*- 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
14#include "circt/Support/Debug.h"
15#include "mlir/IR/Iterators.h"
16#include "mlir/IR/Threading.h"
17#include "mlir/Interfaces/SideEffectInterfaces.h"
18#include "mlir/Pass/Pass.h"
19#include "llvm/ADT/BitVector.h"
20#include "llvm/ADT/DenseMapInfoVariant.h"
21#include "llvm/ADT/PostOrderIterator.h"
22#include "llvm/Support/Debug.h"
23
24#define DEBUG_TYPE "firrtl-imdeadcodeelim"
25
26namespace circt {
27namespace firrtl {
28#define GEN_PASS_DEF_IMDEADCODEELIM
29#include "circt/Dialect/FIRRTL/Passes.h.inc"
30} // namespace firrtl
31} // namespace circt
32
33using namespace circt;
34using namespace firrtl;
35
36// Return true if this op has side-effects except for alloc and read.
37static bool hasUnknownSideEffect(Operation *op) {
38 return !(mlir::isMemoryEffectFree(op) ||
39 mlir::hasSingleEffect<mlir::MemoryEffects::Allocate>(op) ||
40 mlir::hasSingleEffect<mlir::MemoryEffects::Read>(op));
41}
42
43/// Return true if this is a wire or a register or a node.
44static bool isDeclaration(Operation *op) {
45 return isa<WireOp, RegResetOp, RegOp, NodeOp, MemOp>(op);
46}
47
48/// Return true if this is a wire or register we're allowed to delete.
49static bool isDeletableDeclaration(Operation *op) {
50 if (auto name = dyn_cast<FNamableOp>(op))
51 if (!name.hasDroppableName())
52 return false;
53 return !hasDontTouch(op) && AnnotationSet(op).empty();
54}
55
56namespace {
57struct IMDeadCodeElimPass
58 : public circt::firrtl::impl::IMDeadCodeElimBase<IMDeadCodeElimPass> {
59 using Base::Base;
60
61 void runOnOperation() override;
62
63 void rewriteModuleSignature(FModuleOp module);
64 void rewriteModuleBody(FModuleOp module);
65 void eraseEmptyModule(FModuleOp module);
66 void forwardConstantOutputPort(FModuleOp module);
67
68 /// Return true if the value is known alive.
69 bool isKnownAlive(Value value) const {
70 assert(value && "null should not be used");
71 return liveElements.count(value);
72 }
73
74 /// Return true if the value is assumed dead.
75 bool isAssumedDead(Value value) const { return !isKnownAlive(value); }
76 bool isAssumedDead(Operation *op) const {
77 return llvm::none_of(op->getResults(),
78 [&](Value value) { return isKnownAlive(value); });
79 }
80
81 /// Return true if the block is alive.
82 bool isBlockExecutable(Block *block) const {
83 return executableBlocks.count(block);
84 }
85
86 void visitUser(Operation *op);
87 void visitValue(Value value);
88
89 void visitConnect(FConnectLike connect);
90 void visitSubelement(Operation *op);
91 void markBlockExecutable(Block *block);
92 void markBlockUndeletable(Operation *op) {
93 markAlive(op->getParentOfType<FModuleOp>());
94 }
95
96 void markDeclaration(Operation *op);
97 void markFInstanceLikeOp(FInstanceLike instanceLike);
98 void markUnknownSideEffectOp(Operation *op);
99 void visitFInstanceLikeOp(FInstanceLike instanceLike);
100 void visitHierPathOp(hw::HierPathOp hierpath);
101 void visitModuleOp(FModuleOp module);
102
103private:
104 /// The set of blocks that are known to execute, or are intrinsically alive.
105 DenseSet<Block *> executableBlocks;
106
107 InstanceGraph *instanceGraph;
108
109 // The type with which we associate liveness.
110 using ElementType =
111 std::variant<Value, FModuleOp, FInstanceLike, hw::HierPathOp>;
112
113 void markAlive(ElementType element) {
114 if (!liveElements.insert(element).second)
115 return;
116 worklist.push_back(element);
117 }
118
119 /// A worklist of values whose liveness recently changed, indicating
120 /// the users need to be reprocessed.
121 SmallVector<ElementType, 64> worklist;
122 llvm::DenseSet<ElementType> liveElements;
123
124 /// A map from instances to hierpaths whose last path is the associated
125 /// instance.
126 DenseMap<InstanceOp, SmallVector<hw::HierPathOp>> instanceToHierPaths;
127
128 /// A cache for a (inner)symbol lookp.
129 circt::hw::InnerRefNamespace *innerRefNamespace;
130 mlir::SymbolTable *symbolTable;
131};
132} // namespace
133
134void IMDeadCodeElimPass::visitFInstanceLikeOp(FInstanceLike instanceLike) {
135 auto instance = dyn_cast<InstanceOp>(*instanceLike);
136
137 // This is already marked as alive in the initialization.
138 if (!instance)
139 return;
140
141 markBlockUndeletable(instance);
142
143 auto module = instance.getReferencedModule<FModuleOp>(*instanceGraph);
144
145 if (!module)
146 return;
147
148 // NOTE: Don't call `markAlive(module)` here as liveness of instance doesn't
149 // imply the global liveness of the module.
150
151 // Propgate liveness through hierpath.
152 for (auto hierPath : instanceToHierPaths[instance])
153 markAlive(hierPath);
154
155 // Input ports get alive only when the instance is alive.
156 for (auto &blockArg : module.getBody().getArguments()) {
157 auto portNo = blockArg.getArgNumber();
158 if (module.getPortDirection(portNo) == Direction::In &&
159 isKnownAlive(module.getArgument(portNo)))
160 markAlive(instance.getResult(portNo));
161 }
162}
163
164void IMDeadCodeElimPass::visitModuleOp(FModuleOp module) {
165 // If the module needs to be alive, so are its instances and instance choices.
166 for (auto *use : instanceGraph->lookup(module)->uses()) {
167 if (auto instance = use->getInstance<FInstanceLike>())
168 markAlive(instance);
169 }
170}
171
172void IMDeadCodeElimPass::visitHierPathOp(hw::HierPathOp hierPathOp) {
173 // If the hierpath is alive, mark all instances on the path alive.
174 for (auto path : hierPathOp.getNamepathAttr())
175 if (auto innerRef = dyn_cast<hw::InnerRefAttr>(path)) {
176 auto *op = innerRefNamespace->lookupOp(innerRef);
177 if (auto instance = dyn_cast_or_null<InstanceOp>(op))
178 markAlive(instance);
179 }
180}
181
182void IMDeadCodeElimPass::markDeclaration(Operation *op) {
183 assert(isDeclaration(op) && "only a declaration is expected");
184 if (!isDeletableDeclaration(op)) {
185 for (auto result : op->getResults())
186 markAlive(result);
187 markBlockUndeletable(op);
188 }
189}
190
191void IMDeadCodeElimPass::markUnknownSideEffectOp(Operation *op) {
192 // For operations with side effects, pessimistically mark results and
193 // operands as alive.
194 for (auto result : op->getResults())
195 markAlive(result);
196 for (auto operand : op->getOperands())
197 markAlive(operand);
198 markBlockUndeletable(op);
199
200 // Recursively mark any blocks contained within these operations as
201 // executable.
202 for (auto &region : op->getRegions())
203 for (auto &block : region.getBlocks())
204 markBlockExecutable(&block);
205}
206
207void IMDeadCodeElimPass::visitUser(Operation *op) {
208 LLVM_DEBUG(llvm::dbgs() << "Visit: " << *op << "\n");
209 if (auto connectOp = dyn_cast<FConnectLike>(op))
210 return visitConnect(connectOp);
211 if (isa<SubfieldOp, SubindexOp, SubaccessOp, ObjectSubfieldOp>(op))
212 return visitSubelement(op);
213}
214
215void IMDeadCodeElimPass::markFInstanceLikeOp(FInstanceLike instanceLike) {
216 if (auto instance = dyn_cast<InstanceOp>(*instanceLike)) {
217 // Get the module being referenced.
218 Operation *op = instance.getReferencedModule(*instanceGraph);
219
220 // If this is an extmodule, just remember that any inputs and inouts are
221 // alive.
222 if (!isa<FModuleOp>(op)) {
223 auto module = dyn_cast<FModuleLike>(op);
224 for (auto resultNo : llvm::seq(0u, instance.getNumResults())) {
225 // If this is an output to the extmodule, we can ignore it.
226 if (module.getPortDirection(resultNo) == Direction::Out)
227 continue;
228
229 // Otherwise this is an input from it or an inout, mark it as alive.
230 markAlive(instance.getResult(resultNo));
231 }
232 markAlive(instance);
233
234 return;
235 }
236
237 // Otherwise this is a defined module.
238 auto fModule = cast<FModuleOp>(op);
239 markBlockExecutable(fModule.getBodyBlock());
240 return;
241 }
242
243 // Conservatively mark everything.
244
245 markAlive(instanceLike);
246 markBlockUndeletable(instanceLike);
247
248 // Mark all results (ports) as alive.
249 for (auto result : instanceLike->getResults())
250 markAlive(result);
251
252 // Mark all possible target modules as executable.
253 for (auto moduleName : instanceLike.getReferencedModuleNamesAttr()) {
254 auto *node = instanceGraph->lookup(cast<StringAttr>(moduleName));
255 if (!node)
256 continue;
257
258 if (auto fModule = dyn_cast<FModuleOp>(*node->getModule())) {
259 markBlockExecutable(fModule.getBodyBlock());
260 for (auto result : fModule.getBodyBlock()->getArguments())
261 markAlive(result);
262 }
263 }
264}
265
266void IMDeadCodeElimPass::markBlockExecutable(Block *block) {
267 if (!executableBlocks.insert(block).second)
268 return; // Already executable.
269
270 auto fmodule = dyn_cast<FModuleOp>(block->getParentOp());
271 if (fmodule && (fmodule.isPublic() || removePortsOnly))
272 markAlive(fmodule);
273
274 // Mark ports with don't touch as alive.
275 for (auto blockArg : block->getArguments())
276 if (hasDontTouch(blockArg)) {
277 markAlive(blockArg);
278 if (fmodule)
279 markAlive(fmodule);
280 }
281
282 for (auto &op : *block) {
283 if (auto instance = dyn_cast<FInstanceLike>(op)) {
284 markFInstanceLikeOp(instance);
285 continue;
286 }
287
288 // Skip connects in both modes.
289 if (isa<FConnectLike>(op))
290 continue;
291
292 if (removePortsOnly) {
293 // In port-only mode, all non-instance, non-connect ops are alive.
294 markUnknownSideEffectOp(&op);
295 continue;
296 }
297
298 // Full IMDCE mode: handle declarations and side effects.
299 if (isDeclaration(&op))
300 markDeclaration(&op);
301 else if (hasUnknownSideEffect(&op))
302 markUnknownSideEffectOp(&op);
303
304 // TODO: Handle attach etc.
305 }
306}
307
308void IMDeadCodeElimPass::forwardConstantOutputPort(FModuleOp module) {
309 // This tracks constant values of output ports. std::nullopt represents an
310 // invalid value.
311 SmallVector<std::pair<unsigned, std::optional<APSInt>>>
312 constantPortIndicesAndValues;
313 auto ports = module.getPorts();
314 auto *instanceGraphNode = instanceGraph->lookup(module);
315
316 for (const auto &e : llvm::enumerate(ports)) {
317 unsigned index = e.index();
318 auto port = e.value();
319 auto arg = module.getArgument(index);
320
321 // If the port has don't touch, don't propagate the constant value.
322 if (!port.isOutput() || hasDontTouch(arg))
323 continue;
324
325 // Remember the index and constant value connected to an output port.
326 if (auto connect = getSingleConnectUserOf(arg)) {
327 if (auto constant = connect.getSrc().getDefiningOp<ConstantOp>())
328 constantPortIndicesAndValues.push_back({index, constant.getValue()});
329 else if (connect.getSrc().getDefiningOp<InvalidValueOp>())
330 constantPortIndicesAndValues.push_back({index, std::nullopt});
331 }
332 }
333
334 // If there is no constant or invalid port, abort.
335 if (constantPortIndicesAndValues.empty())
336 return;
337
338 // Rewrite all uses.
339 for (auto *use : instanceGraphNode->uses()) {
340 auto instance = use->getInstance<InstanceOp>();
341 // Only constprop for instance ops.
342 if (!instance)
343 continue;
344 ImplicitLocOpBuilder builder(instance.getLoc(), instance);
345 for (auto [index, constant] : constantPortIndicesAndValues) {
346 auto result = instance.getResult(index);
347 assert(ports[index].isOutput() && "must be an output port");
348
349 // Replace the port with the constant or invalid value.
350 Value replacement;
351 if (constant)
352 replacement = ConstantOp::create(builder, *constant);
353 else
354 replacement = InvalidValueOp::create(builder, result.getType());
355 result.replaceAllUsesWith(replacement);
356 }
357 }
358}
359
360void IMDeadCodeElimPass::runOnOperation() {
362
363 auto circuits = getOperation().getOps<CircuitOp>();
364 if (circuits.empty())
365 return;
366
367 auto circuit = *circuits.begin();
368
369 if (!llvm::hasSingleElement(circuits)) {
370 mlir::emitError(circuit.getLoc(),
371 "cannot process multiple circuit operations")
372 .attachNote((*std::next(circuits.begin())).getLoc())
373 << "second circuit here";
374 return signalPassFailure();
375 }
376
377 instanceGraph = &getChildAnalysis<InstanceGraph>(circuit);
378 symbolTable = &getChildAnalysis<SymbolTable>(circuit);
379 auto &istc = getChildAnalysis<hw::InnerSymbolTableCollection>(circuit);
380
381 circt::hw::InnerRefNamespace theInnerRefNamespace{*symbolTable, istc};
382 innerRefNamespace = &theInnerRefNamespace;
383
384 // Walk attributes and find unknown uses of inner symbols or hierpaths.
385 getOperation().walk([&](Operation *op) {
386 if (isa<FModuleOp>(op)) // Port or module annotations are ok to ignore.
387 return;
388
389 if (auto hierPath = dyn_cast<hw::HierPathOp>(op)) {
390 auto namePath = hierPath.getNamepath().getValue();
391 // If the hierpath is public or ill-formed, the verifier should have
392 // caught the error. Conservatively mark the symbol as alive.
393 if (hierPath.isPublic() || namePath.size() <= 1 ||
394 isa<hw::InnerRefAttr>(namePath.back()))
395 return markAlive(hierPath);
396
397 if (auto instance =
398 dyn_cast_or_null<firrtl::InstanceOp>(innerRefNamespace->lookupOp(
399 cast<hw::InnerRefAttr>(namePath.drop_back().back()))))
400 instanceToHierPaths[instance].push_back(hierPath);
401 return;
402 }
403
404 // If there is an unknown symbol or inner symbol use, mark all of them
405 // alive.
406 op->getAttrDictionary().walk([&](Attribute attr) {
407 if (auto innerRef = dyn_cast<hw::InnerRefAttr>(attr)) {
408 // Mark instances alive that are targeted by an inner ref.
409 if (auto instance = dyn_cast_or_null<firrtl::InstanceOp>(
410 innerRefNamespace->lookupOp(innerRef)))
411 markAlive(instance);
412 return;
413 }
414
415 if (auto symbolRef = dyn_cast<FlatSymbolRefAttr>(attr)) {
416 auto *symbol = symbolTable->lookup(symbolRef.getAttr());
417 if (!symbol)
418 return;
419
420 // Mark referenced hierarchical paths alive.
421 if (auto hierPath = dyn_cast<hw::HierPathOp>(symbol))
422 markAlive(hierPath);
423
424 // Mark modules referenced by unknown ops alive.
425 if (auto module = dyn_cast<FModuleOp>(symbol)) {
426 if (!isa<firrtl::InstanceOp>(op)) {
427 LLVM_DEBUG(llvm::dbgs()
428 << "Unknown use of " << module.getModuleNameAttr()
429 << " in " << op->getName() << "\n");
430 markAlive(module);
431 markBlockExecutable(module.getBodyBlock());
432 }
433 }
434
435 return;
436 }
437 });
438 });
439
440 // Create a vector of modules in the post order of instance graph.
441 // FIXME: We copy the list of modules into a vector first to avoid iterator
442 // invalidation while we mutate the instance graph. See issue 3387.
443 SmallVector<FModuleOp, 0> modules(llvm::make_filter_range(
444 llvm::map_range(
445 llvm::post_order(instanceGraph),
446 [](auto *node) { return dyn_cast<FModuleOp>(*node->getModule()); }),
447 [](auto module) { return module; }));
448
449 // Forward constant output ports to caller sides so that we can eliminate
450 // constant outputs.
451 for (auto module : modules)
452 forwardConstantOutputPort(module);
453
454 for (auto module : circuit.getBodyBlock()->getOps<FModuleOp>()) {
455 bool isPublic = module.isPublic();
456 if (isPublic || removePortsOnly) {
457 markBlockExecutable(module.getBodyBlock());
458 // Mark the ports of public modules as alive.
459 if (isPublic)
460 for (auto port : module.getBodyBlock()->getArguments())
461 markAlive(port);
462 }
463
464 // Walk annotations and populate a map from hierpath to attached annotation
465 // targets. `portId` is `-1` for module annotations.
466 auto visitAnnotation = [&](int portId, Annotation anno) -> bool {
467 auto hierPathSym = anno.getMember<FlatSymbolRefAttr>("circt.nonlocal");
468 hw::HierPathOp hierPathOp;
469 if (hierPathSym)
470 hierPathOp =
471 symbolTable->template lookup<hw::HierPathOp>(hierPathSym.getAttr());
472
473 if (hierPathOp)
474 markAlive(hierPathOp);
475 if (portId >= 0)
476 markAlive(module.getArgument(portId));
477 markAlive(module);
478 return false;
479 };
480
481 AnnotationSet::removePortAnnotations(module, visitAnnotation);
483 module, std::bind(visitAnnotation, -1, std::placeholders::_1));
484 }
485
486 // If an element changed liveness then propagate liveness through it.
487 while (!worklist.empty()) {
488 auto v = worklist.pop_back_val();
489 if (auto *value = std::get_if<Value>(&v))
490 visitValue(*value);
491 else if (auto *instance = std::get_if<FInstanceLike>(&v))
492 visitFInstanceLikeOp(*instance);
493 else if (auto *hierpath = std::get_if<hw::HierPathOp>(&v))
494 visitHierPathOp(*hierpath);
495 else if (auto *module = std::get_if<FModuleOp>(&v))
496 visitModuleOp(*module);
497 }
498
499 // Rewrite module signatures or delete unreachable modules.
500 for (auto module : llvm::make_early_inc_range(
501 circuit.getBodyBlock()->getOps<FModuleOp>())) {
502 if (isBlockExecutable(module.getBodyBlock()))
503 rewriteModuleSignature(module);
504 else {
505 // If the module is unreachable from the toplevel, just delete it.
506 // Note that post-order traversal on the instance graph never visit
507 // unreachable modules so it's safe to erase the module even though
508 // `modules` seems to be capturing module pointers.
509 module.erase();
510 }
511 }
512
513 // Rewrite module bodies parallelly.
514 mlir::parallelForEach(circuit.getContext(),
515 circuit.getBodyBlock()->getOps<FModuleOp>(),
516 [&](auto op) { rewriteModuleBody(op); });
517
518 // Clean up hierpaths.
519 for (auto op : llvm::make_early_inc_range(
520 circuit.getBodyBlock()->getOps<hw::HierPathOp>()))
521 if (!liveElements.count(op))
522 op.erase();
523
524 if (!removePortsOnly)
525 for (auto module : modules)
526 eraseEmptyModule(module);
527
528 // Clean up data structures.
529 executableBlocks.clear();
530 liveElements.clear();
531 instanceToHierPaths.clear();
532}
533
534void IMDeadCodeElimPass::visitValue(Value value) {
535 assert(isKnownAlive(value) && "only alive values reach here");
536
537 // Propagate liveness through users.
538 for (Operation *user : value.getUsers())
539 visitUser(user);
540
541 if (auto blockArg = dyn_cast<BlockArgument>(value)) {
542 if (auto module =
543 dyn_cast<FModuleOp>(blockArg.getParentBlock()->getParentOp())) {
544 auto portDirection = module.getPortDirection(blockArg.getArgNumber());
545 // If the port is input, it's necessary to mark corresponding input ports
546 // of instances as alive. We don't have to propagate the liveness of
547 // output ports.
548 if (portDirection == Direction::In) {
549 for (auto *instRec : instanceGraph->lookup(module)->uses()) {
550 // If this is not an instance, it must be marked overdefined already.
551 if (auto instance = instRec->getInstance<InstanceOp>()) {
552 if (liveElements.contains(instance))
553 markAlive(instance.getResult(blockArg.getArgNumber()));
554 }
555 }
556 }
557
558 // Any domain ports associated with non-domain ports are also alive.
559 if (!type_isa<DomainType>(blockArg.getType()))
560 for (auto domain : cast<ArrayAttr>(
561 module.getDomainInfoAttrForPort(blockArg.getArgNumber())))
562 markAlive(module.getArgument(
563 cast<IntegerAttr>(domain).getValue().getZExtValue()));
564 return;
565 }
566 }
567
568 // Marking an instance port as alive propagates to the corresponding port of
569 // the module.
570 if (auto instance = value.getDefiningOp<InstanceOp>()) {
571 auto instanceResult = cast<mlir::OpResult>(value);
572 // Update the src, when it's an instance op.
573 auto module = instance.getReferencedModule<FModuleOp>(*instanceGraph);
574
575 // Propagate liveness only when a port is output.
576 if (!module || module.getPortDirection(instanceResult.getResultNumber()) ==
577 Direction::In)
578 return;
579
580 markAlive(instance);
581
582 BlockArgument modulePortVal =
583 module.getArgument(instanceResult.getResultNumber());
584 return markAlive(modulePortVal);
585 }
586
587 // If a port of a memory is alive, all other ports are.
588 if (auto mem = value.getDefiningOp<MemOp>()) {
589 for (auto port : mem->getResults())
590 markAlive(port);
591 return;
592 }
593
594 // If the value is defined by an operation, mark its operands alive and any
595 // nested blocks executable.
596 if (auto *op = value.getDefiningOp()) {
597 for (auto operand : op->getOperands())
598 markAlive(operand);
599 for (auto &region : op->getRegions())
600 for (auto &block : region)
601 markBlockExecutable(&block);
602 }
603
604 // If either result of a forceable declaration is alive, they both are.
605 if (auto fop = value.getDefiningOp<Forceable>();
606 fop && fop.isForceable() &&
607 (fop.getData() == value || fop.getDataRef() == value)) {
608 markAlive(fop.getData());
609 markAlive(fop.getDataRef());
610 }
611}
612
613void IMDeadCodeElimPass::visitConnect(FConnectLike connect) {
614 // If the dest is alive, mark the source value as alive.
615 if (isKnownAlive(connect.getDest()))
616 markAlive(connect.getSrc());
617}
618
619void IMDeadCodeElimPass::visitSubelement(Operation *op) {
620 if (isKnownAlive(op->getOperand(0)))
621 markAlive(op->getResult(0));
622}
623
624void IMDeadCodeElimPass::rewriteModuleBody(FModuleOp module) {
625 assert(isBlockExecutable(module.getBodyBlock()) &&
626 "unreachable modules must be already deleted");
627
628 auto removeDeadNonLocalAnnotations = [&](int _, Annotation anno) -> bool {
629 auto hierPathSym = anno.getMember<FlatSymbolRefAttr>("circt.nonlocal");
630 if (!hierPathSym)
631 return false;
632 auto hierPathOp =
633 symbolTable->template lookup<hw::HierPathOp>(hierPathSym.getAttr());
634 return !liveElements.count(hierPathOp);
635 };
636
637 AnnotationSet::removePortAnnotations(module, removeDeadNonLocalAnnotations);
639 module,
640 std::bind(removeDeadNonLocalAnnotations, -1, std::placeholders::_1));
641
642 // Walk the IR bottom-up when deleting operations.
643 module.walk<mlir::WalkOrder::PostOrder, mlir::ReverseIterator>(
644 [&](Operation *op) {
645 // Connects to values that we found to be dead can be dropped.
646 LLVM_DEBUG(llvm::dbgs() << "Visit: " << *op << "\n");
647 if (auto connect = dyn_cast<FConnectLike>(op)) {
648 if (isAssumedDead(connect.getDest())) {
649 LLVM_DEBUG(llvm::dbgs() << "DEAD: " << connect << "\n";);
650 connect.erase();
651 ++numErasedOps;
652 }
653 return;
654 }
655
656 // Delete dead wires, regs, nodes and alloc/read ops.
657 if ((isDeclaration(op) || !hasUnknownSideEffect(op)) &&
658 isAssumedDead(op)) {
659 LLVM_DEBUG(llvm::dbgs() << "DEAD: " << *op << "\n";);
660 assert(op->use_empty() && "users should be already removed");
661 op->erase();
662 ++numErasedOps;
663 return;
664 }
665
666 // Remove non-sideeffect op using `isOpTriviallyDead`.
667 if (mlir::isOpTriviallyDead(op)) {
668 op->erase();
669 ++numErasedOps;
670 }
671 });
672}
673
674void IMDeadCodeElimPass::rewriteModuleSignature(FModuleOp module) {
675 assert(isBlockExecutable(module.getBodyBlock()) &&
676 "unreachable modules must be already deleted");
677 InstanceGraphNode *instanceGraphNode = instanceGraph->lookup(module);
678 LLVM_DEBUG(llvm::dbgs() << "Prune ports of module: " << module.getName()
679 << "\n");
680
681 auto replaceInstanceResultWithWire =
682 [&](ImplicitLocOpBuilder &builder, unsigned index, InstanceOp instance) {
683 auto result = instance.getResult(index);
684 if (isAssumedDead(result)) {
685 // If the result is dead, replace the result with an unrealized
686 // conversion cast which works as a dummy placeholder.
687 auto wire =
688 mlir::UnrealizedConversionCastOp::create(
689 builder, ArrayRef<Type>{result.getType()}, ArrayRef<Value>{})
690 ->getResult(0);
691 result.replaceAllUsesWith(wire);
692 return;
693 }
694
695 Value wire = WireOp::create(builder, result.getType()).getResult();
696 result.replaceAllUsesWith(wire);
697 // If a module port is dead but its instance result is alive, the port
698 // is used as a temporary wire so make sure that a replaced wire is
699 // putted into `liveSet`.
700 liveElements.erase(result);
701 liveElements.insert(wire);
702 };
703
704 // First, delete dead instances.
705 for (auto *use : llvm::make_early_inc_range(instanceGraphNode->uses())) {
706 auto instanceLike = use->getInstance<FInstanceLike>();
707 if (instanceLike && !liveElements.count(instanceLike)) {
708 auto instance = cast<InstanceOp>(instanceLike);
709 // Replace old instance results with dummy wires.
710 ImplicitLocOpBuilder builder(instance.getLoc(), instance);
711 for (auto index : llvm::seq(0u, instance.getNumResults()))
712 replaceInstanceResultWithWire(builder, index, instance);
713 // Make sure that we update the instance graph.
714 use->erase();
715 instance.erase();
716 }
717 }
718
719 // Ports of public modules cannot be modified.
720 if (module.isPublic())
721 return;
722
723 unsigned numOldPorts = module.getNumPorts();
724 llvm::BitVector deadPortIndexes(numOldPorts);
725
726 ImplicitLocOpBuilder builder(module.getLoc(), module.getContext());
727 builder.setInsertionPointToStart(module.getBodyBlock());
728 auto oldPorts = module.getPorts();
729
730 for (auto index : llvm::seq(0u, numOldPorts)) {
731 auto argument = module.getArgument(index);
732 assert((!hasDontTouch(argument) || isKnownAlive(argument)) &&
733 "If the port has don't touch, it should be known alive");
734
735 // If the port has dontTouch, skip.
736 if (hasDontTouch(argument))
737 continue;
738
739 if (isKnownAlive(argument)) {
740
741 // If an output port is only used internally in the module, then we can
742 // remove the port and replace it with a wire.
743 if (module.getPortDirection(index) == Direction::In)
744 continue;
745
746 // Check if the output port is demanded by any instance. If not, then it
747 // is only demanded internally to the module.
748 if (llvm::any_of(instanceGraph->lookup(module)->uses(),
749 [&](InstanceRecord *record) {
750 return isKnownAlive(
751 record->getInstance().getOperation()->getResult(
752 index));
753 }))
754 continue;
755
756 // Ok, this port is used only within its defined module. So we can replace
757 // the port with a wire.
758 auto wire = WireOp::create(builder, argument.getType()).getResult();
759
760 // Since `liveSet` contains the port, we have to erase it from the set.
761 liveElements.erase(argument);
762 liveElements.insert(wire);
763 argument.replaceAllUsesWith(wire);
764 deadPortIndexes.set(index);
765 continue;
766 }
767
768 // Replace the port with a dummy wire. This wire should be erased within
769 // `rewriteModuleBody`.
770 Value wire =
771 mlir::UnrealizedConversionCastOp::create(
772 builder, ArrayRef<Type>{argument.getType()}, ArrayRef<Value>{})
773 ->getResult(0);
774
775 argument.replaceAllUsesWith(wire);
776 assert(isAssumedDead(wire) && "dummy wire must be dead");
777 deadPortIndexes.set(index);
778 }
779
780 // If there is nothing to remove, abort.
781 if (deadPortIndexes.none())
782 return;
783
784 // Erase arguments of the old module from liveSet to prevent from creating
785 // dangling pointers.
786 for (auto arg : module.getArguments())
787 liveElements.erase(arg);
788
789 // Delete ports from the module.
790 module.erasePorts(deadPortIndexes);
791
792 // Add arguments of the new module to liveSet.
793 for (auto arg : module.getArguments())
794 liveElements.insert(arg);
795
796 // Rewrite all uses.
797 for (auto *use : llvm::make_early_inc_range(instanceGraphNode->uses())) {
798 auto instance = use->getInstance<InstanceOp>();
799 if (!instance) {
800 assert(!use->getInstance<FInstanceLike>() &&
801 "if this is not an instance, it must be marked overdefined");
802 continue;
803 }
804
805 ImplicitLocOpBuilder builder(instance.getLoc(), instance);
806 // Replace old instance results with dummy wires.
807 for (auto index : deadPortIndexes.set_bits())
808 replaceInstanceResultWithWire(builder, index, instance);
809
810 // Since we will rewrite instance op, it is necessary to remove old
811 // instance results from liveSet.
812 for (auto oldResult : instance.getResults())
813 liveElements.erase(oldResult);
814
815 // Create a new instance op without dead ports.
816 auto newInstance =
817 instance.cloneWithErasedPortsAndReplaceUses(deadPortIndexes);
818
819 // Mark new results as alive.
820 for (auto newResult : newInstance->getResults())
821 liveElements.insert(newResult);
822
823 instanceGraph->replaceInstance(instance, newInstance);
824 if (liveElements.contains(instance)) {
825 liveElements.erase(instance);
826 liveElements.insert(newInstance);
827 }
828 // Remove old one.
829 instance.erase();
830 }
831
832 numRemovedPorts += deadPortIndexes.count();
833}
834
835void IMDeadCodeElimPass::eraseEmptyModule(FModuleOp module) {
836 // If the module is not empty, just skip.
837 if (!module.getBodyBlock()->empty())
838 return;
839
840 // We cannot delete public modules so generate a warning.
841 if (module.isPublic()) {
842 mlir::emitWarning(module.getLoc())
843 << "module `" << module.getName()
844 << "` is empty but cannot be removed because the module is public";
845 return;
846 }
847
848 if (!module.getAnnotations().empty()) {
849 module.emitWarning() << "module `" << module.getName()
850 << "` is empty but cannot be removed "
851 "because the module has annotations "
852 << module.getAnnotations();
853 return;
854 }
855
856 if (!module.getBodyBlock()->args_empty()) {
857 auto diag = module.emitWarning()
858 << "module `" << module.getName()
859 << "` is empty but cannot be removed because the "
860 "module has ports ";
861 llvm::interleaveComma(module.getPortNames(), diag);
862 diag << " are referenced by name or dontTouched";
863 return;
864 }
865
866 // Ok, the module is empty. Delete instances unless they have symbols.
867 LLVM_DEBUG(llvm::dbgs() << "Erase " << module.getName() << "\n");
868
869 InstanceGraphNode *instanceGraphNode =
870 instanceGraph->lookup(module.getModuleNameAttr());
871
872 SmallVector<Location> instancesWithSymbols;
873 for (auto *use : llvm::make_early_inc_range(instanceGraphNode->uses())) {
874 auto instance = use->getInstance<InstanceOp>();
875 if (!instance)
876 continue;
877 if (instance.getInnerSym()) {
878 instancesWithSymbols.push_back(instance.getLoc());
879 continue;
880 }
881 use->erase();
882 instance.erase();
883 }
884
885 // If there is an instance with a symbol, we don't delete the module itself.
886 if (!instancesWithSymbols.empty()) {
887 auto diag = module.emitWarning()
888 << "module `" << module.getName()
889 << "` is empty but cannot be removed because an instance is "
890 "referenced by name";
891 diag.attachNote(FusedLoc::get(&getContext(), instancesWithSymbols))
892 << "these are instances with symbols";
893 return;
894 }
895
896 // We cannot delete alive modules.
897 if (liveElements.contains(module))
898 return;
899
900 instanceGraph->erase(instanceGraphNode);
901 module.erase();
902 ++numErasedModules;
903}
assert(baseType &&"element must be base type")
static bool isDeletableDeclaration(Operation *op)
Return true if this is a wire or register we're allowed to delete.
static bool hasUnknownSideEffect(Operation *op)
static bool isDeclaration(Operation *op)
Return true if this is a wire or a register or a node.
#define CIRCT_DEBUG_SCOPED_PASS_LOGGER(PASS)
Definition Debug.h:70
This class provides a read-only projection over the MLIR attributes that represent a set of annotatio...
bool removeAnnotations(llvm::function_ref< bool(Annotation)> predicate)
Remove all annotations from this annotation set for which predicate returns true.
static bool removePortAnnotations(Operation *module, llvm::function_ref< bool(unsigned, Annotation)> predicate)
Remove all port annotations from a module or extmodule for which predicate returns true.
llvm::iterator_range< UseIterator > uses()
virtual void replaceInstance(InstanceOpInterface inst, InstanceOpInterface newInst)
Replaces an instance of a module with another instance.
virtual void erase(InstanceGraphNode *node)
Remove this module from the instance graph.
InstanceGraphNode * lookup(ModuleOpInterface op)
Look up an InstanceGraphNode for a module.
connect(destination, source)
Definition support.py:39
bool hasDontTouch(Value value)
Check whether a block argument ("port") or the operation defining a value has a DontTouch annotation,...
igraph::InstanceRecord InstanceRecord
MatchingConnectOp getSingleConnectUserOf(Value value)
Scan all the uses of the specified value, checking to see if there is exactly one connect that has th...
igraph::InstanceGraphNode InstanceGraphNode
bool type_isa(Type type)
std::map< std::string, std::set< std::string > > InstanceGraph
Iterates over the handshake::FuncOp's in the program to build an instance graph.
The InstanceGraph op interface, see InstanceGraphInterface.td for more details.
Operation * lookupOp(hw::InnerRefAttr inner) const
Resolve the InnerRef to its target within this namespace, returning empty target if no such name exis...