CIRCT 23.0.0git
Loading...
Searching...
No Matches
StructuralHash.cpp
Go to the documentation of this file.
1//===----------------------------------------------------------------------===//
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 pass performs structural hashing for Synth dialect operations.
10// Unlike MLIR's general CSE pass, this is domain-specific to AIG
11// operations, allowing it to reorder operands based on their
12// structural properties and take inversion flags into account for
13// canonicalization.
14//
15//===----------------------------------------------------------------------===//
16
21#include "mlir/Analysis/TopologicalSortUtils.h"
22#include "mlir/IR/BuiltinAttributes.h"
23#include "mlir/IR/Operation.h"
24#include "mlir/IR/Visitors.h"
25#include "mlir/Support/LLVM.h"
26#include "mlir/Transforms/RegionUtils.h"
27#include "llvm/ADT/DenseMap.h"
28#include "llvm/ADT/DenseMapInfo.h"
29#include "llvm/ADT/PointerIntPair.h"
30#include "llvm/ADT/TypeSwitch.h"
31#include "llvm/Support/DebugLog.h"
32#include "llvm/Support/LogicalResult.h"
33
34#define DEBUG_TYPE "synth-structural-hash"
35
36namespace circt {
37namespace synth {
38#define GEN_PASS_DEF_STRUCTURALHASH
39#include "circt/Dialect/Synth/Transforms/SynthPasses.h.inc"
40} // namespace synth
41} // namespace circt
42
43using namespace circt;
44using namespace circt::synth;
45
46/// A struct that represents the key used for structural hashing. It contains
47/// the operation name and a sorted vector of pointer-integer pairs, which
48/// represent the inputs to the operation and their inversion status.
49/// This key is used to identify structurally equivalent operations for CSE.
51 OperationName opName;
52 llvm::SmallVector<llvm::PointerIntPair<Value, 1>, 3> operandPairs;
53
54 /// Constructor.
55 StructuralHashKey(OperationName name,
56 llvm::SmallVector<llvm::PointerIntPair<Value, 1>, 3> inps)
57 : opName(name), operandPairs(std::move(inps)) {}
58};
59
60// DenseMapInfo specialization for StructuralHashKey
61template <>
67
72
73 static unsigned getHashValue(const StructuralHashKey &key) {
74 auto hash = hash_value(key.opName);
75 for (const auto &operand : key.operandPairs)
76 hash = llvm::hash_combine(hash, operand.getOpaqueValue());
77 return static_cast<unsigned>(hash);
78 }
79
80 static bool isEqual(const StructuralHashKey &lhs,
81 const StructuralHashKey &rhs) {
83 lhs.operandPairs == rhs.operandPairs;
84 }
85};
86
87namespace {
88/// Pass definition.
89struct StructuralHashPass
90 : public impl::StructuralHashBase<StructuralHashPass> {
91 void runOnOperation() override;
92};
93} // namespace
94
95namespace {
96/// The main driver class that implements the structural hashing algorithm.
97/// This class manages the state for value numbering, inversion tracking,
98/// and the hash table for CSE. It processes operations in topological order
99/// and performs operand reordering and inversion propagation for
100/// canonicalization.
101class StructuralHashDriver {
102public:
103 StructuralHashDriver() = default;
104 void visitOp(BooleanLogicOpInterface op);
105 void visitUnaryOp(BooleanLogicOpInterface op);
106 void visitVariadicOp(BooleanLogicOpInterface op);
107 uint64_t getNumber(Value v);
108
109 /// Runs the structural hashing pass on the given operation.
110 /// Performs topological sorting, assigns value numbers to arguments,
111 /// processes target operations, and cleans up unused operations.
112 llvm::LogicalResult run(Operation *op);
113
114private:
115 /// Maps values to unique numbers for deterministic operand sorting.
116 DenseMap<Value, uint64_t> valueNumber;
117 uint64_t constantCounter = 0;
118
119 /// Hash table mapping structural keys to canonical operations for CSE.
120 DenseMap<StructuralHashKey, BooleanLogicOpInterface> hashTable;
121
122 /// Maps inverted values to their non-inverted equivalents for propagation.
123 /// For example, if we have:
124 /// ```
125 /// %b = synth.aig.and_inv not %a
126 /// %c = synth.aig.and_inv not %b
127 /// ```
128 /// Then `inversion[%b] = %a`, and when visiting `%c`, we can query
129 /// `inversion[%b]` to directly obtain `%a`.
130 DenseMap<Value, Value> inversion;
131};
132} // namespace
133
134void StructuralHashDriver::visitOp(BooleanLogicOpInterface op) {
135 /// Dispatches to the appropriate visitor based on the number of operands.
136 /// For unary operations, calls visitUnaryOp; for variadic operations,
137 /// calls visitVariadicOp.
138 if (op.getInputs().size() == 1) {
139 visitUnaryOp(op);
140 return;
141 }
142 visitVariadicOp(op);
143}
144
145/// Handles unary operations (single operand).
146/// If not inverted, replaces the operation with its operand.
147/// If inverted, attempts to propagate inversion through the inversion map
148/// or records the inversion for later propagation.
149void StructuralHashDriver::visitUnaryOp(BooleanLogicOpInterface logicOp) {
150 Operation *op = logicOp.getOperation();
151 auto [input, inverted] = logicOp.getInputPair(0);
152 if (!inverted) {
153 op->replaceAllUsesWith(ArrayRef<Value>{input});
154 op->erase();
155 return;
156 }
157 auto it = inversion.find(input);
158 if (it != inversion.end()) {
159 // Found, replace the operand with the mapped value
160 op->replaceAllUsesWith(ArrayRef<Value>{it->second});
161 op->erase();
162 } else {
163 // Not found, insert into the map
164 inversion[logicOp.getResult()] = input;
165 }
166}
167
168/// Computes a structural hash key, sorts operands for canonicalization,
169/// and performs CSE by checking the hash table for equivalent operations.
170void StructuralHashDriver::visitVariadicOp(BooleanLogicOpInterface logicOp) {
171 Operation *op = logicOp.getOperation();
172 auto inversions = logicOp.getInverted();
173
174 // Compute the structural hash key for the operation.
175 StructuralHashKey key(op->getName(), {});
176 for (auto [input, inverted] : llvm::zip(op->getOperands(), inversions)) {
177 bool isInverted = inverted;
178 // Check if we can propagate inversion through the inversion map
179 auto it = inversion.find(input);
180 if (it != inversion.end()) {
181 // Found, use the mapped value and flip the inversion status
182 input = it->second;
183 isInverted = !isInverted;
184 }
185
186 key.operandPairs.push_back(
187 llvm::PointerIntPair<Value, 1>(input, isInverted));
188 // Ensure the operand has a number assigned, otherwise sorting might be
189 // non-deterministic.
190 (void)getNumber(input);
191 }
192
193 // Canonicalize operand order only when the operation semantics permit
194 // reordering full (input, inverted) pairs.
195 if (logicOp.areInputsPermutationInvariant()) {
196 llvm::sort(key.operandPairs, [&](auto a, auto b) {
197 size_t aNum = getNumber(a.getPointer());
198 size_t bNum = getNumber(b.getPointer());
199 if (aNum != bNum)
200 return aNum < bNum;
201 return a.getInt() < b.getInt();
202 });
203 }
204
205 // Insert the key into the hash table.
206 auto [it, inserted] = hashTable.try_emplace(key, logicOp);
207 if (inserted) {
208 // New entry, keep the operation and sort its operands.
209 op->setOperands(llvm::to_vector<3>(llvm::map_range(
210 key.operandPairs, [](auto p) { return p.getPointer(); })));
211 SmallVector<bool, 3> newInversion(
212 llvm::map_range(key.operandPairs, [](auto p) { return p.getInt(); }));
213 logicOp.setInverted(newInversion);
214 // Assign a number to the result for future sorting.
215 (void)getNumber(logicOp.getResult());
216 } else {
217 LDBG() << "Structural Hash: Replacing " << *op << " with " << *(it->second)
218 << "\n";
219 // Existing entry, replace all uses and erase the operation.
220 // Propagate namehints.
221 auto name = circt::chooseName(op, it->second);
222 if (name && !it->second->hasAttr("sv.namehint"))
223 it->second->setAttr("sv.namehint", name);
224 op->replaceAllUsesWith(it->second);
225 op->erase();
226 }
227}
228
229/// Assigns or retrieves a unique number for a value. Used for deterministic
230/// operand sorting.
231uint64_t StructuralHashDriver::getNumber(Value v) {
232 auto it = valueNumber.find(v);
233 if (it != valueNumber.end())
234 return it->second;
235
236 // Assign a new number. Constants get high numbers to make constants are
237 // pushed to the back.
238 if (auto *op = v.getDefiningOp();
239 op && op->hasTrait<mlir::OpTrait::ConstantLike>()) {
240 auto [it, inserted] = valueNumber.try_emplace(
241 v, std::numeric_limits<uint64_t>::max() - constantCounter++);
242 return it->second;
243 }
244
245 return valueNumber.try_emplace(v, valueNumber.size() - constantCounter)
246 .first->second;
247}
248
249llvm::LogicalResult StructuralHashDriver::run(Operation *moduleOp) {
250 auto isOperationReady = [&](Value value, Operation *op) -> bool {
251 // Other than target ops, all other ops are always ready.
252 return !isa<BooleanLogicOpInterface>(op);
253 };
254
255 if (moduleOp->getNumRegions() != 1 ||
256 moduleOp->getRegion(0).getBlocks().size() != 1)
257 return llvm::success();
258
259 Block &block = moduleOp->getRegion(0).front();
260 if (!mlir::sortTopologically(&block, isOperationReady))
261 return failure();
262
263 for (auto arg : block.getArguments())
264 (void)getNumber(arg);
265
266 // Process target ops.
267 // NOTE: Don't use walk here since the pass currently doesn't handle nested
268 // regions.
269 for (auto op :
270 llvm::make_early_inc_range(block.getOps<BooleanLogicOpInterface>())) {
271 visitOp(op);
272 }
273
274 // Run DCE to remove dangling ops.
275 mlir::PatternRewriter rewriter(moduleOp->getContext());
276 (void)mlir::runRegionDCE(rewriter, moduleOp->getRegions());
277 return mlir::success();
278}
279
280void StructuralHashPass::runOnOperation() {
281 auto *topOp = getOperation();
282 StructuralHashDriver driver;
283 if (failed(driver.run(topOp)))
284 return signalPassFailure();
285}
The InstanceGraph op interface, see InstanceGraphInterface.td for more details.
StringRef chooseName(StringRef a, StringRef b)
Choose a good name for an item from two options.
Definition Naming.cpp:47
int run(Type[Generator] generator=CppGenerator, cmdline_args=sys.argv)
Definition codegen.py:879
llvm::hash_code hash_value(const DenseSet< T > &set)
Definition synth.py:1
A struct that represents the key used for structural hashing.
StructuralHashKey(OperationName name, llvm::SmallVector< llvm::PointerIntPair< Value, 1 >, 3 > inps)
Constructor.
llvm::SmallVector< llvm::PointerIntPair< Value, 1 >, 3 > operandPairs
OperationName opName
static StructuralHashKey getTombstoneKey()
static bool isEqual(const StructuralHashKey &lhs, const StructuralHashKey &rhs)
static StructuralHashKey getEmptyKey()
static unsigned getHashValue(const StructuralHashKey &key)