CIRCT 24.0.0git
Loading...
Searching...
No Matches
IMConstProp.cpp
Go to the documentation of this file.
1//===- IMConstProp.cpp - Intermodule ConstProp and DCE ----------*- 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//
9// This implements SCCP:
10// https://www.cs.wustl.edu/~cytron/531Pages/f11/Resources/Papers/cprop.pdf
11//
12//===----------------------------------------------------------------------===//
13
20#include "circt/Support/APInt.h"
21#include "mlir/IR/Iterators.h"
22#include "mlir/IR/Threading.h"
23#include "mlir/Pass/Pass.h"
24#include "llvm/ADT/APSInt.h"
25#include "llvm/ADT/TinyPtrVector.h"
26#include "llvm/Support/Debug.h"
27#include "llvm/Support/ScopedPrinter.h"
28
29namespace circt {
30namespace firrtl {
31#define GEN_PASS_DEF_IMCONSTPROP
32#include "circt/Dialect/FIRRTL/Passes.h.inc"
33} // namespace firrtl
34} // namespace circt
35
36using namespace circt;
37using namespace firrtl;
38
39#define DEBUG_TYPE "IMCP"
40
41/// Return true if this is a wire or register.
42static bool isWireOrReg(Operation *op) {
43 return isa<WireOp, RegResetOp, RegOp>(op);
44}
45
46/// Return true if this is an aggregate indexer.
47static bool isAggregate(Operation *op) {
48 return isa<SubindexOp, SubaccessOp, SubfieldOp, OpenSubfieldOp,
49 OpenSubindexOp, RefSubOp>(op);
50}
51
52// Return true if this forwards input to output.
53// Implies has appropriate visit method that propagates changes.
54static bool isNodeLike(Operation *op) {
55 return isa<NodeOp, RefResolveOp, RefSendOp>(op);
56}
57
58/// Return true if this is a wire or register we're allowed to delete.
59static bool isDeletableWireOrRegOrNode(Operation *op) {
60 if (!isWireOrReg(op) && !isa<NodeOp>(op))
61 return false;
62
63 // Always allow deleting wires of probe-type.
64 if (type_isa<RefType>(op->getResult(0).getType()))
65 return true;
66
67 // Otherwise, don't delete if has anything keeping it around or unknown.
68 return AnnotationSet(op).empty() && !hasDontTouch(op) &&
69 hasDroppableName(op) && !cast<Forceable>(op).isForceable();
70}
71
72//===----------------------------------------------------------------------===//
73// Pass Infrastructure
74//===----------------------------------------------------------------------===//
75
76namespace {
77/// This class represents a single lattice value. A lattive value corresponds to
78/// the various different states that a value in the SCCP dataflow analysis can
79/// take. See 'Kind' below for more details on the different states a value can
80/// take.
81class LatticeValue {
82 enum Kind {
83 /// A value with a yet-to-be-determined value. This state may be changed to
84 /// anything, it hasn't been processed by IMConstProp.
85 Unknown,
86
87 /// A value that is known to be a constant. This state may be changed to
88 /// overdefined.
89 Constant,
90
91 /// A value that cannot statically be determined to be a constant. This
92 /// state cannot be changed.
93 Overdefined
94 };
95
96public:
97 /// Initialize a lattice value with "Unknown".
98 /*implicit*/ LatticeValue() : valueAndTag(nullptr, Kind::Unknown) {}
99 /// Initialize a lattice value with a constant.
100 /*implicit*/ LatticeValue(IntegerAttr attr)
101 : valueAndTag(attr, Kind::Constant) {}
102 /*implicit*/ LatticeValue(StringAttr attr)
103 : valueAndTag(attr, Kind::Constant) {}
104
105 static LatticeValue getOverdefined() {
106 LatticeValue result;
107 result.markOverdefined();
108 return result;
109 }
110
111 bool isUnknown() const { return valueAndTag.getInt() == Kind::Unknown; }
112 bool isConstant() const { return valueAndTag.getInt() == Kind::Constant; }
113 bool isOverdefined() const {
114 return valueAndTag.getInt() == Kind::Overdefined;
115 }
116
117 /// Mark the lattice value as overdefined.
118 void markOverdefined() {
119 valueAndTag.setPointerAndInt(nullptr, Kind::Overdefined);
120 }
121
122 /// Mark the lattice value as constant.
123 void markConstant(IntegerAttr value) {
124 valueAndTag.setPointerAndInt(value, Kind::Constant);
125 }
126
127 /// If this lattice is constant or invalid value, return the attribute.
128 /// Returns nullptr otherwise.
129 Attribute getValue() const { return valueAndTag.getPointer(); }
130
131 /// If this is in the constant state, return the attribute.
132 Attribute getConstant() const {
134 return getValue();
135 }
136
137 /// Merge in the value of the 'rhs' lattice into this one. Returns true if the
138 /// lattice value changed.
139 bool mergeIn(LatticeValue rhs) {
140 // If we are already overdefined, or rhs is unknown, there is nothing to do.
141 if (isOverdefined() || rhs.isUnknown())
142 return false;
143
144 // If we are unknown, just take the value of rhs.
145 if (isUnknown()) {
146 valueAndTag = rhs.valueAndTag;
147 return true;
148 }
149
150 // Otherwise, if this value doesn't match rhs go straight to overdefined.
151 // This happens when we merge "3" and "4" from two different instance sites
152 // for example.
153 if (valueAndTag != rhs.valueAndTag) {
154 markOverdefined();
155 return true;
156 }
157 return false;
158 }
159
160 bool operator==(const LatticeValue &other) const {
161 return valueAndTag == other.valueAndTag;
162 }
163 bool operator!=(const LatticeValue &other) const {
164 return valueAndTag != other.valueAndTag;
165 }
166
167private:
168 /// The attribute value if this is a constant and the tag for the element
169 /// kind. The attribute is an IntegerAttr (or BoolAttr) or StringAttr.
170 llvm::PointerIntPair<Attribute, 2, Kind> valueAndTag;
171};
172} // end anonymous namespace
173
174LLVM_ATTRIBUTE_USED
175static llvm::raw_ostream &operator<<(llvm::raw_ostream &os,
176 const LatticeValue &lattice) {
177 if (lattice.isUnknown())
178 return os << "<Unknown>";
179 if (lattice.isOverdefined())
180 return os << "<Overdefined>";
181 return os << "<" << lattice.getConstant() << ">";
182}
183
184namespace {
185struct IMConstPropPass
186 : public circt::firrtl::impl::IMConstPropBase<IMConstPropPass> {
187
188 void runOnOperation() override;
189 void rewriteModuleBody(FModuleOp module);
190
191 /// Returns true if the given block is executable.
192 bool isBlockExecutable(Block *block) const {
193 return executableBlocks.count(block);
194 }
195
196 bool isOverdefined(FieldRef value) const {
197 auto it = latticeValues.find(value);
198 return it != latticeValues.end() && it->second.isOverdefined();
199 }
200
201 // Mark the given value as overdefined. If the value is an aggregate,
202 // we mark all ground elements as overdefined.
203 void markOverdefined(Value value) {
204 FieldRef fieldRef = getOrCacheFieldRefFromValue(value);
205 auto firrtlType = type_dyn_cast<FIRRTLType>(value.getType());
206 if (!firrtlType || type_isa<PropertyType, DomainType>(firrtlType)) {
207 markOverdefined(fieldRef);
208 return;
209 }
210
211 walkGroundTypes(firrtlType, [&](uint64_t fieldID, auto, auto) {
212 markOverdefined(fieldRef.getSubField(fieldID));
213 });
214 }
215
216 /// Mark the given value as overdefined. This means that we cannot refine a
217 /// specific constant for this value.
218 void markOverdefined(FieldRef value) {
219 auto &entry = latticeValues[value];
220 if (!entry.isOverdefined()) {
221 LLVM_DEBUG({
222 logger.getOStream()
223 << "Setting overdefined : (" << getFieldName(value).first << ")\n";
224 });
225 entry.markOverdefined();
226 changedLatticeValueWorklist.push_back(value);
227 }
228 }
229
230 /// Merge information from the 'from' lattice value into value. If it
231 /// changes, then users of the value are added to the worklist for
232 /// revisitation.
233 void mergeLatticeValue(FieldRef value, LatticeValue &valueEntry,
234 LatticeValue source) {
235 if (valueEntry.mergeIn(source)) {
236 LLVM_DEBUG({
237 logger.getOStream()
238 << "Changed to " << valueEntry << " : (" << value << ")\n";
239 });
240 changedLatticeValueWorklist.push_back(value);
241 }
242 }
243
244 void mergeLatticeValue(FieldRef value, LatticeValue source) {
245 // Don't even do a map lookup if from has no info in it.
246 if (source.isUnknown())
247 return;
248 mergeLatticeValue(value, latticeValues[value], source);
249 }
250
251 void mergeLatticeValue(FieldRef result, FieldRef from) {
252 // If 'from' hasn't been computed yet, then it is unknown, don't do
253 // anything.
254 auto it = latticeValues.find(from);
255 if (it == latticeValues.end())
256 return;
257 mergeLatticeValue(result, it->second);
258 }
259
260 void mergeLatticeValue(Value result, Value from) {
261 FieldRef fieldRefFrom = getOrCacheFieldRefFromValue(from);
262 FieldRef fieldRefResult = getOrCacheFieldRefFromValue(result);
263 if (!type_isa<FIRRTLType>(result.getType()))
264 return mergeLatticeValue(fieldRefResult, fieldRefFrom);
265 // Special-handle PropertyType's, walkGroundType's doesn't support.
266 if (type_isa<PropertyType, DomainType>(result.getType()))
267 return mergeLatticeValue(fieldRefResult, fieldRefFrom);
268 walkGroundTypes(type_cast<FIRRTLType>(result.getType()),
269 [&](uint64_t fieldID, auto, auto) {
270 mergeLatticeValue(fieldRefResult.getSubField(fieldID),
271 fieldRefFrom.getSubField(fieldID));
272 });
273 }
274
275 /// setLatticeValue - This is used when a new LatticeValue is computed for
276 /// the result of the specified value that replaces any previous knowledge,
277 /// e.g. because a fold() function on an op returned a new thing. This should
278 /// not be used on operations that have multiple contributors to it, e.g.
279 /// wires or ports.
280 void setLatticeValue(FieldRef value, LatticeValue source) {
281 // Don't even do a map lookup if from has no info in it.
282 if (source.isUnknown())
283 return;
284
285 // If we've changed this value then revisit all the users.
286 auto &valueEntry = latticeValues[value];
287 if (valueEntry != source) {
288 changedLatticeValueWorklist.push_back(value);
289 valueEntry = source;
290 }
291 }
292
293 // This function returns a field ref of the given value. This function caches
294 // the result to avoid extra IR traversal if the value is an aggregate
295 // element.
296 FieldRef getOrCacheFieldRefFromValue(Value value) {
297 if (!value.getDefiningOp() || !isAggregate(value.getDefiningOp()))
298 return FieldRef(value, 0);
299 auto &fieldRef = valueToFieldRef[value];
300 if (fieldRef)
301 return fieldRef;
302 return fieldRef = getFieldRefFromValue(value);
303 }
304
305 /// Return the lattice value for the specified SSA value, extended to the
306 /// width of the specified destType. If allowTruncation is true, then this
307 /// allows truncating the lattice value to the specified type.
308 LatticeValue getExtendedLatticeValue(FieldRef value, FIRRTLType destType,
309 bool allowTruncation = false);
310
311 /// Mark the given block as executable.
312 void markBlockExecutable(Block *block);
313 void markWireOp(WireOp wireOrReg);
314 void markMemOp(MemOp mem);
315 void markDPICallIntrinsicOp(DPICallIntrinsicOp dpi);
316
317 void markInvalidValueOp(InvalidValueOp invalid);
318 void markAggregateConstantOp(AggregateConstantOp constant);
319 void markInstanceLike(FInstanceLike instance);
320 void markInstanceTarget(FInstanceLike instance, Operation *op);
321 template <typename OpTy>
322 void markConstantValueOp(OpTy op);
323
324 void visitConnectLike(FConnectLike connect, FieldRef changedFieldRef);
325 void visitRefSend(RefSendOp send, FieldRef changedFieldRef);
326 void visitRefResolve(RefResolveOp resolve, FieldRef changedFieldRef);
327 void mergeOnlyChangedLatticeValue(Value dest, Value src,
328 FieldRef changedFieldRef);
329 void visitNode(NodeOp node, FieldRef changedFieldRef);
330 void visitOperation(Operation *op, FieldRef changedFieldRef);
331
332private:
333 /// This is the current instance graph for the Circuit.
334 InstanceGraph *instanceGraph = nullptr;
335
336 /// This keeps track of the current state of each tracked value.
337 DenseMap<FieldRef, LatticeValue> latticeValues;
338
339 /// The set of blocks that are known to execute, or are intrinsically live.
340 SmallPtrSet<Block *, 16> executableBlocks;
341
342 /// A worklist of values whose LatticeValue recently changed, indicating the
343 /// users need to be reprocessed.
344 SmallVector<FieldRef, 64> changedLatticeValueWorklist;
345
346 // A map to give operations to be reprocessed.
347 DenseMap<FieldRef, llvm::TinyPtrVector<Operation *>> fieldRefToUsers;
348
349 // A map to cache results of getFieldRefFromValue since it's costly traverse
350 // the IR.
351 llvm::DenseMap<Value, FieldRef> valueToFieldRef;
352
353 /// This keeps track of users the instance results that correspond to output
354 /// ports.
355 DenseMap<BlockArgument, llvm::TinyPtrVector<Value>>
356 resultPortToInstanceResultMapping;
357
358#ifndef NDEBUG
359 /// A logger used to emit information during the application process.
360 llvm::ScopedPrinter logger{llvm::dbgs()};
361#endif
362};
363} // end anonymous namespace
364
365// TODO: handle annotations: [[OptimizableExtModuleAnnotation]]
366void IMConstPropPass::runOnOperation() {
367 auto circuit = getOperation();
368 LLVM_DEBUG(
369 { logger.startLine() << "IMConstProp : " << circuit.getName() << "\n"; });
370
371 instanceGraph = &getAnalysis<InstanceGraph>();
372
373 // Mark input ports as overdefined where appropriate.
374 for (auto &op : circuit.getOps()) {
375 // Inputs of public modules are overdefined.
376 if (auto module = dyn_cast<FModuleOp>(op)) {
377 if (module.isPublic()) {
378 markBlockExecutable(module.getBodyBlock());
379 for (auto port : module.getBodyBlock()->getArguments())
380 markOverdefined(port);
381 }
382 continue;
383 }
384
385 // Otherwise we check whether the top-level operation contains any
386 // references to modules. Symbol uses in NLAs are ignored.
387 if (isa<hw::HierPathOp>(op))
388 continue;
389
390 // Inputs of modules referenced by unknown operations are overdefined, since
391 // we don't know how those operations affect the input port values. This
392 // handles things like `firrtl.formal`, which may may assign symbolic values
393 // to input ports of a private module.
394 auto symbolUses = SymbolTable::getSymbolUses(&op);
395 if (!symbolUses)
396 continue;
397 for (const auto &use : *symbolUses) {
398 if (auto symRef = dyn_cast<FlatSymbolRefAttr>(use.getSymbolRef())) {
399 if (auto *igNode = instanceGraph->lookupOrNull(symRef.getAttr())) {
400 if (auto module = dyn_cast<FModuleOp>(*igNode->getModule())) {
401 LLVM_DEBUG(llvm::dbgs()
402 << "Unknown use of " << module.getModuleNameAttr()
403 << " in " << op.getName()
404 << ", marking inputs as overdefined\n");
405 markBlockExecutable(module.getBodyBlock());
406 for (auto port : module.getBodyBlock()->getArguments())
407 markOverdefined(port);
408 }
409 }
410 }
411 }
412 }
413
414 // If a value changed lattice state then reprocess any of its users.
415 while (!changedLatticeValueWorklist.empty()) {
416 FieldRef changedFieldRef = changedLatticeValueWorklist.pop_back_val();
417 for (Operation *user : fieldRefToUsers[changedFieldRef]) {
418 if (isBlockExecutable(user->getBlock()))
419 visitOperation(user, changedFieldRef);
420 }
421 }
422
423 // Rewrite any constants in the modules.
424 mlir::parallelForEach(circuit.getContext(),
425 circuit.getBodyBlock()->getOps<FModuleOp>(),
426 [&](auto op) { rewriteModuleBody(op); });
427
428 // Clean up our state for next time.
429 instanceGraph = nullptr;
430 latticeValues.clear();
431 executableBlocks.clear();
432 assert(changedLatticeValueWorklist.empty());
433 fieldRefToUsers.clear();
434 valueToFieldRef.clear();
435 resultPortToInstanceResultMapping.clear();
436}
437
438/// Return the lattice value for the specified SSA value, extended to the width
439/// of the specified destType. If allowTruncation is true, then this allows
440/// truncating the lattice value to the specified type.
441LatticeValue IMConstPropPass::getExtendedLatticeValue(FieldRef value,
442 FIRRTLType destType,
443 bool allowTruncation) {
444 // If 'value' hasn't been computed yet, then it is unknown.
445 auto it = latticeValues.find(value);
446 if (it == latticeValues.end())
447 return LatticeValue();
448
449 auto result = it->second;
450 // Unknown/overdefined stay whatever they are.
451 if (result.isUnknown() || result.isOverdefined())
452 return result;
453
454 // No extOrTrunc for property types. Return what we have.
455 if (isa<PropertyType, DomainType>(destType))
456 return result;
457
458 auto constant = result.getConstant();
459
460 // If not property, only support integers.
461 auto intAttr = dyn_cast<IntegerAttr>(constant);
462 assert(intAttr && "unsupported lattice attribute kind");
463 if (!intAttr)
464 return result;
465
466 // No extOrTrunc necessary for bools.
467 if (auto boolAttr = dyn_cast<BoolAttr>(intAttr))
468 return result;
469
470 // Non-base (or non-ref) types are overdefined.
471 auto baseType = getBaseType(destType);
472 if (!baseType)
473 return LatticeValue::getOverdefined();
474
475 // If destType is wider than the source constant type, extend it.
476 auto resultConstant = intAttr.getAPSInt();
477 auto destWidth = baseType.getBitWidthOrSentinel();
478 if (destWidth == -1) // We don't support unknown width FIRRTL.
479 return LatticeValue::getOverdefined();
480 if (resultConstant.getBitWidth() == (unsigned)destWidth)
481 return result; // Already the right width, we're done.
482
483 // Otherwise, extend the constant using the signedness of the source.
484 resultConstant = extOrTruncZeroWidth(resultConstant, destWidth);
485 return LatticeValue(IntegerAttr::get(destType.getContext(), resultConstant));
486}
487
488// NOLINTBEGIN(misc-no-recursion)
489/// Mark a block executable if it isn't already. This does an initial scan of
490/// the block, processing nullary operations like wires, instances, and
491/// constants that only get processed once.
492void IMConstPropPass::markBlockExecutable(Block *block) {
493 if (!executableBlocks.insert(block).second)
494 return; // Already executable.
495
496 // Mark block arguments, which are module ports, with don't touch as
497 // overdefined.
498 for (auto ba : block->getArguments())
499 if (hasDontTouch(ba))
500 markOverdefined(ba);
501
502 for (auto &op : *block) {
503 // Handle each of the special operations in the firrtl dialect.
504 TypeSwitch<Operation *>(&op)
505 .Case<RegOp, RegResetOp>(
506 [&](auto reg) { markOverdefined(op.getResult(0)); })
507 .Case<WireOp>([&](auto wire) { markWireOp(wire); })
508 .Case<ConstantOp, SpecialConstantOp, StringConstantOp,
509 FIntegerConstantOp, BoolConstantOp>(
510 [&](auto constOp) { markConstantValueOp(constOp); })
511 .Case<AggregateConstantOp>(
512 [&](auto aggConstOp) { markAggregateConstantOp(aggConstOp); })
513 .Case<InvalidValueOp>(
514 [&](auto invalid) { markInvalidValueOp(invalid); })
515 .Case<FInstanceLike>([&](auto instance) { markInstanceLike(instance); })
516 .Case<FObjectLike>([&](auto obj) { markOverdefined(obj.getResult()); })
517 .Case<MemOp>([&](auto mem) { markMemOp(mem); })
518 .Case<LayerBlockOp>(
519 [&](auto layer) { markBlockExecutable(layer.getBody(0)); })
520 .Case<DPICallIntrinsicOp>(
521 [&](auto dpi) { markDPICallIntrinsicOp(dpi); })
522 .Default([&](auto _) {
523 if (isa<mlir::UnrealizedConversionCastOp, VerbatimExprOp,
524 VerbatimWireOp, SubaccessOp>(op) ||
525 op.getNumOperands() == 0) {
526 // Mark operations whose results cannot be tracked as overdefined.
527 // Mark unhandled operations with no operand as well since otherwise
528 // they will remain unknown states until the end.
529 for (auto result : op.getResults())
530 markOverdefined(result);
531 } else if (
532 // Operations that are handled when propagating values, or chasing
533 // indexing.
534 !isAggregate(&op) && !isNodeLike(&op) && op.getNumResults() > 0) {
535 // If an unknown operation has an aggregate operand, mark results as
536 // overdefined since we cannot track the dataflow. Similarly if the
537 // operations create aggregate values, we mark them overdefined.
538
539 // TODO: We should handle aggregate operations such as
540 // vector_create, bundle_create or vector operations.
541
542 bool hasAggregateOperand =
543 llvm::any_of(op.getOperandTypes(), [](Type type) {
544 return type_isa<FVectorType, BundleType>(type);
545 });
546
547 for (auto result : op.getResults())
548 if (hasAggregateOperand ||
549 type_isa<FVectorType, BundleType>(result.getType()))
550 markOverdefined(result);
551 }
552 });
553
554 // This tracks a dependency from field refs to operations which need
555 // to be added to worklist when lattice values change.
556 if (!isAggregate(&op)) {
557 for (auto operand : op.getOperands()) {
558 auto fieldRef = getOrCacheFieldRefFromValue(operand);
559 auto firrtlType = type_dyn_cast<FIRRTLType>(operand.getType());
560 if (!firrtlType)
561 continue;
562 // Special-handle PropertyType's, walkGroundTypes doesn't support.
563 if (type_isa<PropertyType, DomainType>(firrtlType)) {
564 fieldRefToUsers[fieldRef].push_back(&op);
565 continue;
566 }
567 walkGroundTypes(firrtlType, [&](uint64_t fieldID, auto type, auto) {
568 fieldRefToUsers[fieldRef.getSubField(fieldID)].push_back(&op);
569 });
570 }
571 }
572 }
573}
574// NOLINTEND(misc-no-recursion)
575
576void IMConstPropPass::markWireOp(WireOp wire) {
577 auto type = type_dyn_cast<FIRRTLType>(wire.getResult().getType());
578 if (!type || hasDontTouch(wire.getResult()) || wire.isForceable()) {
579 for (auto result : wire.getResults())
580 markOverdefined(result);
581 return;
582 }
583
584 // Otherwise, this starts out as unknown and is upgraded by connects.
585}
586
587void IMConstPropPass::markMemOp(MemOp mem) {
588 for (auto result : mem.getResults())
589 markOverdefined(result);
590}
591
592void IMConstPropPass::markDPICallIntrinsicOp(DPICallIntrinsicOp dpi) {
593 if (auto result = dpi.getResult())
594 markOverdefined(result);
595}
596
597template <typename OpTy>
598void IMConstPropPass::markConstantValueOp(OpTy op) {
599 mergeLatticeValue(getOrCacheFieldRefFromValue(op),
600 LatticeValue(op.getValueAttr()));
601}
602
603void IMConstPropPass::markAggregateConstantOp(AggregateConstantOp constant) {
604 walkGroundTypes(constant.getType(), [&](uint64_t fieldID, auto, auto) {
605 mergeLatticeValue(FieldRef(constant, fieldID),
606 LatticeValue(cast<IntegerAttr>(
607 constant.getAttributeFromFieldID(fieldID))));
608 });
609}
610
611void IMConstPropPass::markInvalidValueOp(InvalidValueOp invalid) {
612 markOverdefined(invalid.getResult());
613}
614
615/// Instance-like ops have no operands, so they are visited exactly once their
616/// enclosing block is marked live. This sets up the def-use edge for ports.
617void IMConstPropPass::markInstanceLike(FInstanceLike instance) {
618 for (auto moduleName :
619 instance.getReferencedModuleNamesAttr().getAsRange<StringAttr>()) {
620 auto *node = instanceGraph->lookup(moduleName);
621 Operation *op = node->getModule().getOperation();
622 markInstanceTarget(instance, op);
623 }
624}
625
626/// Set up propagation between instance-like op and once possible target
627/// module.
628void IMConstPropPass::markInstanceTarget(FInstanceLike instance,
629 Operation *op) {
630 // If this is an extmodule, just remember that any results and inouts are
631 // overdefined.
632 if (!isa<FModuleOp>(op)) {
633 auto module = dyn_cast<FModuleLike>(op);
634 for (size_t resultNo = 0, e = instance.getNumPorts(); resultNo != e;
635 ++resultNo) {
636 auto portVal = instance->getResult(resultNo);
637 // If this is an input to the extmodule, we can ignore it.
638 if (module.getPortDirection(resultNo) == Direction::In)
639 continue;
640
641 // Otherwise this is a result from it or an inout, mark it as overdefined.
642 markOverdefined(portVal);
643 }
644 return;
645 }
646 // Otherwise this is a defined module.
647 auto fModule = cast<FModuleOp>(op);
648 markBlockExecutable(fModule.getBodyBlock());
649
650 // Ok, it is a normal internal module reference. Populate
651 // resultPortToInstanceResultMapping, and forward any already-computed values.
652 for (size_t resultNo = 0, e = instance.getNumPorts(); resultNo != e;
653 ++resultNo) {
654 auto instancePortVal = instance->getResult(resultNo);
655 // If this is an input to the instance, it will
656 // get handled when any connects to it are processed.
657 if (fModule.getPortDirection(resultNo) == Direction::In)
658 continue;
659
660 // Otherwise we have a result from the instance. We need to forward results
661 // from the body to this instance result's SSA value, so remember it.
662 BlockArgument modulePortVal = fModule.getArgument(resultNo);
663
664 resultPortToInstanceResultMapping[modulePortVal].push_back(instancePortVal);
665
666 // If there is already a value known for modulePortVal make sure to forward
667 // it here.
668 mergeLatticeValue(instancePortVal, modulePortVal);
669 }
670}
671
672static std::optional<uint64_t>
673getFieldIDOffset(FieldRef changedFieldRef, Type connectionType,
674 FieldRef connectedValueFieldRef) {
675 assert(!type_isa<RefType>(connectionType));
676 if (changedFieldRef.getValue() != connectedValueFieldRef.getValue())
677 return {};
678 if (changedFieldRef.getFieldID() >= connectedValueFieldRef.getFieldID() &&
679 changedFieldRef.getFieldID() <=
680 hw::FieldIdImpl::getMaxFieldID(connectionType) +
681 connectedValueFieldRef.getFieldID())
682 return changedFieldRef.getFieldID() - connectedValueFieldRef.getFieldID();
683 return {};
684}
685
686void IMConstPropPass::mergeOnlyChangedLatticeValue(Value dest, Value src,
687 FieldRef changedFieldRef) {
688
689 // Operate on inner type for refs.
690 auto destType = dest.getType();
691 if (auto refType = type_dyn_cast<RefType>(destType))
692 destType = refType.getType();
693
694 if (!isa<FIRRTLType>(destType)) {
695 // If the dest is not FIRRTL type, conservatively mark
696 // all of them overdefined.
697 markOverdefined(src);
698 return markOverdefined(dest);
699 }
700
701 auto fieldRefSrc = getOrCacheFieldRefFromValue(src);
702 auto fieldRefDest = getOrCacheFieldRefFromValue(dest);
703
704 // If a changed field ref is included the source value, find an offset in the
705 // connection.
706 if (auto srcOffset = getFieldIDOffset(changedFieldRef, destType, fieldRefSrc))
707 mergeLatticeValue(fieldRefDest.getSubField(*srcOffset),
708 fieldRefSrc.getSubField(*srcOffset));
709
710 // If a changed field ref is included the dest value, find an offset in the
711 // connection.
712 if (auto destOffset =
713 getFieldIDOffset(changedFieldRef, destType, fieldRefDest))
714 mergeLatticeValue(fieldRefDest.getSubField(*destOffset),
715 fieldRefSrc.getSubField(*destOffset));
716}
717
718void IMConstPropPass::visitConnectLike(FConnectLike connect,
719 FieldRef changedFieldRef) {
720 // Operate on inner type for refs.
721 auto destType = connect.getDest().getType();
722 if (auto refType = type_dyn_cast<RefType>(destType))
723 destType = refType.getType();
724
725 // Mark foreign types as overdefined.
726 if (!isa<FIRRTLType>(destType)) {
727 markOverdefined(connect.getSrc());
728 return markOverdefined(connect.getDest());
729 }
730
731 auto fieldRefSrc = getOrCacheFieldRefFromValue(connect.getSrc());
732 auto fieldRefDest = getOrCacheFieldRefFromValue(connect.getDest());
733 if (auto subaccess = fieldRefDest.getValue().getDefiningOp<SubaccessOp>()) {
734 // If the destination is subaccess, we give up to precisely track
735 // lattice values and mark entire aggregate as overdefined. This code
736 // should be dead unless we stop lowering of subaccess in LowerTypes.
737 Value parent = subaccess.getInput();
738 while (parent.getDefiningOp() &&
739 parent.getDefiningOp()->getNumOperands() > 0)
740 parent = parent.getDefiningOp()->getOperand(0);
741 return markOverdefined(parent);
742 }
743
744 auto propagateElementLattice = [&](uint64_t fieldID, FIRRTLType destType) {
745 auto fieldRefDestConnected = fieldRefDest.getSubField(fieldID);
747 firrtl::type_cast<FIRRTLBaseType>(destType).isGround());
748
749 // Handle implicit extensions.
750 auto srcValue =
751 getExtendedLatticeValue(fieldRefSrc.getSubField(fieldID), destType);
752 if (srcValue.isUnknown())
753 return;
754
755 // Driving result ports propagates the value to each instance using the
756 // module.
757 if (auto blockArg = dyn_cast<BlockArgument>(fieldRefDest.getValue())) {
758 for (auto userOfResultPort : resultPortToInstanceResultMapping[blockArg])
759 mergeLatticeValue(
760 FieldRef(userOfResultPort, fieldRefDestConnected.getFieldID()),
761 srcValue);
762 // Output ports are wire-like and may have users.
763 return mergeLatticeValue(fieldRefDestConnected, srcValue);
764 }
765
766 auto dest = cast<mlir::OpResult>(fieldRefDest.getValue());
767
768 // For wires and registers, we drive the value of the wire itself, which
769 // automatically propagates to users.
770 if (isWireOrReg(dest.getOwner()))
771 return mergeLatticeValue(fieldRefDestConnected, srcValue);
772
773 // Driving an instance argument port drives the corresponding argument
774 // of the referenced module.
775 if (auto instance = dest.getDefiningOp<FInstanceLike>()) {
776 // Update the dest, when its an instance op.
777 mergeLatticeValue(fieldRefDestConnected, srcValue);
778
779 for (auto moduleName :
780 instance.getReferencedModuleNamesAttr().getAsRange<StringAttr>()) {
781 auto *node = instanceGraph->lookup(moduleName);
782 auto mod = dyn_cast<FModuleOp>(node->getModule().getOperation());
783 if (!mod)
784 continue;
785
786 BlockArgument modulePortVal = mod.getArgument(dest.getResultNumber());
787 mergeLatticeValue(
788 FieldRef(modulePortVal, fieldRefDestConnected.getFieldID()),
789 srcValue);
790 }
791 return;
792 }
793
794 // Skip unsupported ops that are already marked as overdefined.
795 if (isa_and_nonnull<MemOp, ObjectSubfieldOp>(dest.getDefiningOp()))
796 return;
797
798 connect.emitError("connectlike operation unhandled by IMConstProp")
799 .attachNote(connect.getDest().getLoc())
800 << "connect destination is here";
801 };
802
803 if (auto srcOffset = getFieldIDOffset(changedFieldRef, destType, fieldRefSrc))
804 propagateElementLattice(
805 *srcOffset,
807 hw::FieldIdImpl::getFinalTypeByFieldID(destType, *srcOffset)));
808
809 if (auto relativeDest =
810 getFieldIDOffset(changedFieldRef, destType, fieldRefDest))
811 propagateElementLattice(
812 *relativeDest,
814 hw::FieldIdImpl::getFinalTypeByFieldID(destType, *relativeDest)));
815}
816
817void IMConstPropPass::visitRefSend(RefSendOp send, FieldRef changedFieldRef) {
818 // Send connects the base value (source) to the result (dest).
819 return mergeOnlyChangedLatticeValue(send.getResult(), send.getBase(),
820 changedFieldRef);
821}
822
823void IMConstPropPass::visitRefResolve(RefResolveOp resolve,
824 FieldRef changedFieldRef) {
825 // Resolve connects the ref value (source) to result (dest).
826 // If writes are ever supported, this will need to work differently!
827 return mergeOnlyChangedLatticeValue(resolve.getResult(), resolve.getRef(),
828 changedFieldRef);
829}
830
831void IMConstPropPass::visitNode(NodeOp node, FieldRef changedFieldRef) {
832 if (hasDontTouch(node.getResult()) || node.isForceable()) {
833 for (auto result : node.getResults())
834 markOverdefined(result);
835 return;
836 }
837
838 return mergeOnlyChangedLatticeValue(node.getResult(), node.getInput(),
839 changedFieldRef);
840}
841
842/// This method is invoked when an operand of the specified op changes its
843/// lattice value state and when the block containing the operation is first
844/// noticed as being alive.
845///
846/// This should update the lattice value state for any result values.
847///
848void IMConstPropPass::visitOperation(Operation *op, FieldRef changedField) {
849 // If this is a operation with special handling, handle it specially.
850 if (auto connectLikeOp = dyn_cast<FConnectLike>(op))
851 return visitConnectLike(connectLikeOp, changedField);
852 if (auto sendOp = dyn_cast<RefSendOp>(op))
853 return visitRefSend(sendOp, changedField);
854 if (auto resolveOp = dyn_cast<RefResolveOp>(op))
855 return visitRefResolve(resolveOp, changedField);
856 if (auto nodeOp = dyn_cast<NodeOp>(op))
857 return visitNode(nodeOp, changedField);
858
859 // The clock operand of regop changing doesn't change its result value. All
860 // other registers are over-defined. Aggregate operations also doesn't change
861 // its result value.
862 if (isa<RegOp, RegResetOp>(op) || isAggregate(op))
863 return;
864 // TODO: Handle 'when' operations.
865
866 // If all of the results of this operation are already overdefined (or if
867 // there are no results) then bail out early: we've converged.
868 auto isOverdefinedFn = [&](Value value) {
869 return isOverdefined(getOrCacheFieldRefFromValue(value));
870 };
871 if (llvm::all_of(op->getResults(), isOverdefinedFn))
872 return;
873
874 // To prevent regressions, mark values as overdefined when they are defined
875 // by operations with a large number of operands.
876 if (op->getNumOperands() > 128) {
877 for (auto value : op->getResults())
878 markOverdefined(value);
879 return;
880 }
881
882 // Collect all of the constant operands feeding into this operation. If any
883 // are not ready to be resolved, bail out and wait for them to resolve.
884 SmallVector<Attribute, 8> operandConstants;
885 operandConstants.reserve(op->getNumOperands());
886 bool hasUnknown = false;
887 for (Value operand : op->getOperands()) {
888
889 auto &operandLattice = latticeValues[getOrCacheFieldRefFromValue(operand)];
890
891 // If the operand is an unknown value, then we generally don't want to
892 // process it - we want to wait until the value is resolved to by the SCCP
893 // algorithm.
894 if (operandLattice.isUnknown())
895 hasUnknown = true;
896
897 // Otherwise, it must be constant, invalid, or overdefined. Translate them
898 // into attributes that the fold hook can look at.
899 if (operandLattice.isConstant())
900 operandConstants.push_back(operandLattice.getValue());
901 else
902 operandConstants.push_back({});
903 }
904
905 // Simulate the result of folding this operation to a constant. If folding
906 // fails mark the results as overdefined.
907 SmallVector<OpFoldResult, 8> foldResults;
908 foldResults.reserve(op->getNumResults());
909 if (failed(op->fold(operandConstants, foldResults))) {
910 LLVM_DEBUG({
911 logger.startLine() << "Folding Failed operation : '" << op->getName()
912 << "\n";
913 op->dump();
914 });
915 // If we had unknown arguments, hold off on overdefining
916 if (!hasUnknown)
917 for (auto value : op->getResults())
918 markOverdefined(value);
919 return;
920 }
921
922 LLVM_DEBUG({
923 logger.getOStream() << "\n";
924 logger.startLine() << "Folding operation : '" << op->getName() << "\n";
925 op->dump();
926 logger.getOStream() << "( ";
927 for (auto cst : operandConstants)
928 if (!cst)
929 logger.getOStream() << "{} ";
930 else
931 logger.getOStream() << cst << " ";
932 logger.unindent();
933 logger.getOStream() << ") -> { ";
934 logger.indent();
935 for (auto &r : foldResults) {
936 logger.getOStream() << r << " ";
937 }
938 logger.unindent();
939 logger.getOStream() << "}\n";
940 });
941
942 // If the folding was in-place, keep going. This is surprising, but since
943 // only folder that will do in-place updates is the commutative folder, we
944 // aren't going to stop. We don't update the results, since they didn't
945 // change, the op just got shuffled around.
946 if (foldResults.empty())
947 return visitOperation(op, changedField);
948
949 // Merge the fold results into the lattice for this operation.
950 assert(foldResults.size() == op->getNumResults() && "invalid result size");
951 for (unsigned i = 0, e = foldResults.size(); i != e; ++i) {
952 // Merge in the result of the fold, either a constant or a value.
953 LatticeValue resultLattice;
954 OpFoldResult foldResult = foldResults[i];
955 if (Attribute foldAttr = dyn_cast<Attribute>(foldResult)) {
956 if (auto intAttr = dyn_cast<IntegerAttr>(foldAttr))
957 resultLattice = LatticeValue(intAttr);
958 else if (auto strAttr = dyn_cast<StringAttr>(foldAttr))
959 resultLattice = LatticeValue(strAttr);
960 else // Treat unsupported constants as overdefined.
961 resultLattice = LatticeValue::getOverdefined();
962 } else { // Folding to an operand results in its value.
963 resultLattice =
964 latticeValues[getOrCacheFieldRefFromValue(cast<Value>(foldResult))];
965 }
966
967 mergeLatticeValue(getOrCacheFieldRefFromValue(op->getResult(i)),
968 resultLattice);
969 }
970}
971
972void IMConstPropPass::rewriteModuleBody(FModuleOp module) {
973 auto *body = module.getBodyBlock();
974 // If a module is unreachable, just ignore it.
975 if (!executableBlocks.count(body))
976 return;
977
978 auto builder = OpBuilder::atBlockBegin(body);
979
980 // Separate the constants we insert from the instructions we are folding and
981 // processing. Leave these as-is until we're done.
982 auto cursor = firrtl::ConstantOp::create(builder, module.getLoc(), APSInt(1));
983 builder.setInsertionPoint(cursor);
984
985 // Unique constants per <Const,Type> pair, inserted at entry
986 DenseMap<std::pair<Attribute, Type>, Operation *> constPool;
987
988 std::function<Value(Attribute, Type, Location)> getConst =
989 [&](Attribute constantValue, Type type, Location loc) -> Value {
990 auto constIt = constPool.find({constantValue, type});
991 if (constIt != constPool.end()) {
992 auto *cst = constIt->second;
993 // Add location to the constant
994 cst->setLoc(builder.getFusedLoc({cst->getLoc(), loc}));
995 return cst->getResult(0);
996 }
997 OpBuilder::InsertionGuard x(builder);
998 builder.setInsertionPoint(cursor);
999
1000 // Materialize reftype "constants" by materializing the constant
1001 // and probing it.
1002 Operation *cst;
1003 if (auto refType = type_dyn_cast<RefType>(type)) {
1004 assert(!type_cast<RefType>(type).getForceable() &&
1005 "Attempting to materialize rwprobe of constant, shouldn't happen");
1006 auto inner = getConst(constantValue, refType.getType(), loc);
1007 assert(inner);
1008 cst = RefSendOp::create(builder, loc, inner);
1009 } else
1010 cst = module->getDialect()->materializeConstant(builder, constantValue,
1011 type, loc);
1012 assert(cst && "all FIRRTL constants can be materialized");
1013 constPool.insert({{constantValue, type}, cst});
1014 return cst->getResult(0);
1015 };
1016
1017 // If the lattice value for the specified value is a constant update it and
1018 // return true. Otherwise return false.
1019 auto replaceValueIfPossible = [&](Value value) -> bool {
1020 // Lambda to replace all uses of this value a replacement, unless this is
1021 // the destination of a connect. We leave connects alone to avoid upsetting
1022 // flow, i.e., to avoid trying to connect to a constant.
1023 auto replaceIfNotConnect = [&value](Value replacement) {
1024 value.replaceUsesWithIf(replacement, [](OpOperand &operand) {
1025 return !isa<FConnectLike>(operand.getOwner()) ||
1026 operand.getOperandNumber() != 0;
1027 });
1028 };
1029
1030 // TODO: Replace entire aggregate.
1031 auto it = latticeValues.find(getFieldRefFromValue(value));
1032 if (it == latticeValues.end() || it->second.isOverdefined() ||
1033 it->second.isUnknown())
1034 return false;
1035
1036 // Cannot materialize constants for certain types.
1037 // TODO: Let materializeConstant tell us what it supports instead of this.
1038 // Presently it asserts on unsupported combinations, so check this here.
1040 value.getType()))
1041 return false;
1042
1043 auto cstValue =
1044 getConst(it->second.getValue(), value.getType(), value.getLoc());
1045
1046 replaceIfNotConnect(cstValue);
1047 return true;
1048 };
1049
1050 // Constant propagate any ports that are always constant.
1051 for (auto &port : body->getArguments())
1052 replaceValueIfPossible(port);
1053
1054 // Walk the IR bottom-up when folding. We often fold entire chains of
1055 // operations into constants, which make the intermediate nodes dead. Going
1056 // bottom up eliminates the users of the intermediate ops, allowing us to
1057 // aggressively delete them.
1058 //
1059 // TODO: Handle WhenOps correctly.
1060 bool aboveCursor = false;
1061 module.walk<mlir::WalkOrder::PostOrder, mlir::ReverseIterator>(
1062 [&](Operation *op) {
1063 auto dropIfDead = [&](Operation *op, const Twine &debugPrefix) {
1064 if (op->use_empty() &&
1065 (wouldOpBeTriviallyDead(op) || isDeletableWireOrRegOrNode(op))) {
1066 LLVM_DEBUG({
1067 logger.getOStream() << debugPrefix << " : " << *op << "\n";
1068 });
1069 ++numErasedOp;
1070 op->erase();
1071 return true;
1072 }
1073 return false;
1074 };
1075
1076 if (aboveCursor) {
1077 // Drop dead constants we materialized.
1078 dropIfDead(op, "Trivially dead materialized constant");
1079 return WalkResult::advance();
1080 }
1081 // Stop once hit the generated constants.
1082 if (op == cursor) {
1083 cursor.erase();
1084 aboveCursor = true;
1085 return WalkResult::advance();
1086 }
1087
1088 // Connects to values that we found to be constant can be dropped.
1089 if (auto connect = dyn_cast<FConnectLike>(op)) {
1090 if (auto *destOp = connect.getDest().getDefiningOp()) {
1091 auto fieldRef = getOrCacheFieldRefFromValue(connect.getDest());
1092 // Don't remove a field-level connection even if the src value is
1093 // constant. If other elements of the aggregate value are not
1094 // constant, the aggregate value cannot be replaced. We can forward
1095 // the constant to its users, so IMDCE (or SV/HW canonicalizer)
1096 // should remove the aggregate if entire aggregate is dead.
1097 auto type = type_dyn_cast<FIRRTLType>(connect.getDest().getType());
1098 if (!type)
1099 return WalkResult::advance();
1100 auto baseType = type_dyn_cast<FIRRTLBaseType>(type);
1101 if (baseType && !baseType.isGround())
1102 return WalkResult::advance();
1103 if (isDeletableWireOrRegOrNode(destOp) &&
1104 !isOverdefined(fieldRef)) {
1105 connect.erase();
1106 ++numErasedOp;
1107 }
1108 }
1109 return WalkResult::advance();
1110 }
1111
1112 // We only fold single-result ops and instances in practice, because
1113 // they are the expressions.
1114 if (op->getNumResults() != 1 && !isa<InstanceOp>(op))
1115 return WalkResult::advance();
1116
1117 // If this operation is already dead, then go ahead and remove it.
1118 if (dropIfDead(op, "Trivially dead"))
1119 return WalkResult::advance();
1120
1121 // Don't "fold" constants (into equivalent), also because they
1122 // may have name hints we'd like to preserve.
1123 if (op->hasTrait<mlir::OpTrait::ConstantLike>())
1124 return WalkResult::advance();
1125
1126 // If the op had any constants folded, replace them.
1127 builder.setInsertionPoint(op);
1128 bool foldedAny = false;
1129 for (auto result : op->getResults())
1130 foldedAny |= replaceValueIfPossible(result);
1131
1132 if (foldedAny)
1133 ++numFoldedOp;
1134
1135 // If the operation folded to a constant then we can probably nuke it.
1136 if (foldedAny && dropIfDead(op, "Made dead"))
1137 return WalkResult::advance();
1138
1139 return WalkResult::advance();
1140 });
1141}
assert(baseType &&"element must be base type")
static mlir::Operation * resolve(Context &context, mlir::SymbolRefAttr sym)
static std::optional< APSInt > getConstant(Attribute operand)
Determine the value of a constant operand for the sake of constant folding.
static bool isNodeLike(Operation *op)
static bool isWireOrReg(Operation *op)
Return true if this is a wire or register.
static bool isAggregate(Operation *op)
Return true if this is an aggregate indexer.
static std::optional< uint64_t > getFieldIDOffset(FieldRef changedFieldRef, Type connectionType, FieldRef connectedValueFieldRef)
static bool isDeletableWireOrRegOrNode(Operation *op)
Return true if this is a wire or register we're allowed to delete.
This class represents a reference to a specific field or element of an aggregate value.
Definition FieldRef.h:28
FieldRef getSubField(unsigned subFieldID) const
Get a reference to a subfield.
Definition FieldRef.h:64
unsigned getFieldID() const
Get the field ID of this FieldRef, which is a unique identifier mapped to a specific field in a bundl...
Definition FieldRef.h:61
Value getValue() const
Get the Value which created this location.
Definition FieldRef.h:39
Location getLoc() const
Get the location associated with the value of this field ref.
Definition FieldRef.h:69
This class provides a read-only projection over the MLIR attributes that represent a set of annotatio...
connect(destination, source)
Definition support.py:39
BaseTy type_cast(Type type)
FIRRTLBaseType getBaseType(Type type)
If it is a base type, return it as is.
FieldRef getFieldRefFromValue(Value value, bool lookThroughCasts=false)
Get the FieldRef from a value.
void walkGroundTypes(FIRRTLType firrtlType, llvm::function_ref< void(uint64_t, FIRRTLBaseType, bool)> fn)
Walk leaf ground types in the firrtlType and apply the function fn.
bool isConstant(Operation *op)
Return true if the specified operation has a constant value.
bool hasDontTouch(Value value)
Check whether a block argument ("port") or the operation defining a value has a DontTouch annotation,...
llvm::raw_ostream & operator<<(llvm::raw_ostream &os, const InstanceInfo::LatticeValue &value)
bool hasDroppableName(Operation *op)
Return true if the name is droppable.
std::pair< std::string, bool > getFieldName(const FieldRef &fieldRef, bool nameSafe=false)
Get a string identifier representing the FieldRef.
BaseTy type_dyn_cast(Type type)
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.
::mlir::Type getFinalTypeByFieldID(Type type, uint64_t fieldID)
uint64_t getMaxFieldID(Type)
static bool operator==(const ModulePort &a, const ModulePort &b)
Definition HWTypes.h:64
The InstanceGraph op interface, see InstanceGraphInterface.td for more details.
APSInt extOrTruncZeroWidth(APSInt value, unsigned width)
A safe version of APSInt::extOrTrunc that will NOT assert on zero-width signed APSInts.
Definition APInt.cpp:22
bool operator!=(uint64_t a, const FVInt &b)
Definition FVInt.h:685
reg(value, clock, reset=None, reset_value=None, name=None, sym_name=None)
Definition seq.py:21