CIRCT 24.0.0git
Loading...
Searching...
No Matches
InferStateProperties.cpp
Go to the documentation of this file.
1//===- InferStateProperties.cpp -------------------------------------------===//
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
13#include "circt/Support/LLVM.h"
14#include "mlir/IR/SymbolTable.h"
15#include "mlir/Pass/Pass.h"
16
17#define DEBUG_TYPE "arc-infer-state-properties"
18
19namespace circt {
20namespace arc {
21#define GEN_PASS_DEF_INFERSTATEPROPERTIES
22#include "circt/Dialect/Arc/ArcPasses.h.inc"
23} // namespace arc
24} // namespace circt
25
26using namespace circt;
27using namespace arc;
28
29//===----------------------------------------------------------------------===//
30// Helpers
31//===----------------------------------------------------------------------===//
32
33static bool isConstZero(Value value) {
34 if (auto constOp = value.getDefiningOp<hw::ConstantOp>())
35 return constOp.getValue().isZero();
36
37 return false;
38}
39
40static bool isConstTrue(Value value) {
41 if (auto constOp = value.getDefiningOp<hw::ConstantOp>()) {
42 return constOp.getValue().getBitWidth() == 1 &&
43 constOp.getValue().isAllOnes();
44 }
45 return false;
46}
47
48//===----------------------------------------------------------------------===//
49// Reset and Enable property storages
50//===----------------------------------------------------------------------===//
51
52namespace {
53/// Contains all the information needed to pass a detected reset to the rewriter
54/// function.
55struct ResetInfo {
56 ResetInfo() = default;
57 ResetInfo(std::function<Value(OpBuilder &)> &&constructInput,
58 BlockArgument condition, bool isZeroReset)
59 : constructInput(constructInput), condition(condition),
60 isZeroReset(isZeroReset) {}
61
62 ResetInfo(Value input, BlockArgument condition, bool isZeroReset)
63 : ResetInfo([=](OpBuilder &) { return input; }, condition, isZeroReset) {}
64
65 std::function<Value(OpBuilder &)> constructInput;
66 BlockArgument condition;
67 bool isZeroReset;
68
69 operator bool() { return constructInput && condition; }
70};
71
72/// Contains all the information needed to pass a detected enable to the
73/// rewriter function.
74struct EnableInfo {
75 EnableInfo() = default;
76 EnableInfo(std::function<Value(OpBuilder &)> &&constructInput,
77 BlockArgument condition, BlockArgument selfArg, bool isDisable)
78 : constructInput(constructInput), condition(condition), selfArg(selfArg),
79 isDisable(isDisable) {}
80
81 EnableInfo(Value input, BlockArgument condition, BlockArgument selfArg,
82 bool isDisable)
83 : EnableInfo([=](OpBuilder &) { return input; }, condition, selfArg,
84 isDisable) {}
85
86 std::function<Value(OpBuilder &)> constructInput;
87 BlockArgument condition;
88 BlockArgument selfArg;
89 bool isDisable;
90
91 operator bool() { return constructInput && condition && selfArg; }
92};
93} // namespace
94
95//===----------------------------------------------------------------------===//
96// Rewriter functions
97//===----------------------------------------------------------------------===//
98
99/// Take an arc and a detected reset per output value and apply it to the arc if
100/// applicable (but does not change the state ops referring to the arc).
101static LogicalResult applyResetTransformation(arc::DefineOp arcOp,
102 ArrayRef<ResetInfo> resetInfos) {
103 auto outputOp = cast<arc::OutputOp>(arcOp.getBodyBlock().getTerminator());
104
105 assert(outputOp.getOutputs().size() == resetInfos.size() &&
106 "required to pass the same amount of resets as outputs of the arc");
107
108 for (auto info : resetInfos) {
109 if (!info)
110 return failure();
111
112 // We can only pull out the reset to the whole arc when all the output
113 // values have the same reset applied to them.
114 // TODO: split the arcs such that there is one for each reset kind, however,
115 // that requires a cost-model to not blow up binary-size too much
116 if (!resetInfos.empty() &&
117 (info.condition != resetInfos.back().condition ||
118 info.isZeroReset != resetInfos.back().isZeroReset))
119 return failure();
120
121 // TODO: arc.state operation only supports resets to zero at the moment.
122 if (!info.isZeroReset)
123 return failure();
124 }
125
126 if (resetInfos.empty())
127 return failure();
128
129 OpBuilder builder(outputOp);
130
131 for (size_t i = 0, e = outputOp.getOutputs().size(); i < e; ++i) {
132 auto *defOp = outputOp.getOperands()[i].getDefiningOp();
133 outputOp.getOperands()[i].replaceUsesWithIf(
134 resetInfos[i].constructInput(builder),
135 [](OpOperand &op) { return isa<arc::OutputOp>(op.getOwner()); });
136
137 if (defOp && defOp->getResult(0).use_empty())
138 defOp->erase();
139 }
140
141 return success();
142}
143
144/// Transform the given state operation to match the changes done to the arc in
145/// 'applyResetTransformation' without any additional checks.
146static void setResetOperandOfStateOp(arc::StateOp stateOp,
147 unsigned resetConditionIndex) {
148 Value resetCond = stateOp.getInputs()[resetConditionIndex];
149 ImplicitLocOpBuilder builder(stateOp.getLoc(), stateOp);
150
151 if (stateOp.getEnable())
152 resetCond = comb::AndOp::create(builder, stateOp.getEnable(), resetCond);
153
154 if (stateOp.getReset())
155 resetCond = comb::OrOp::create(builder, stateOp.getReset(), resetCond);
156
157 stateOp.getResetMutable().assign(resetCond);
158}
159
160/// Take an arc and a detected enable per output value and apply it to the given
161/// state if applicable (no changes required to the arc::DefineOp operation for
162/// enables).
163static LogicalResult
164applyEnableTransformation(arc::DefineOp arcOp, arc::StateOp stateOp,
165 ArrayRef<EnableInfo> enableInfos) {
166 auto outputOp = cast<arc::OutputOp>(arcOp.getBodyBlock().getTerminator());
167
168 assert(outputOp.getOutputs().size() == enableInfos.size() &&
169 "required to pass the same amount of enables as outputs of the arc");
170
171 for (auto info : enableInfos) {
172 if (!info)
173 return failure();
174
175 // Validate feedback zeros before creating operations or changing the state.
176 if (info.selfArg.hasOneUse() && hw::getBitWidth(info.selfArg.getType()) < 0)
177 return failure();
178
179 // We can only pull out the enable to the whole arc when all the output
180 // values have the same enable applied to them.
181 // TODO: split the arcs such that there is one for each enable kind,
182 // however, this requires a cost-model to not blow up binary-size too much.
183 if (!enableInfos.empty() &&
184 (info.condition != enableInfos.back().condition ||
185 info.isDisable != enableInfos.back().isDisable))
186 return failure();
187 }
188
189 if (enableInfos.empty())
190 return failure();
191
192 if (!enableInfos[0].condition.hasOneUse())
193 return failure();
194
195 ImplicitLocOpBuilder builder(stateOp.getLoc(), stateOp);
196 SmallVector<Value> inputs(stateOp.getInputs());
197
198 Value enableCond =
199 stateOp.getInputs()[enableInfos[0].condition.getArgNumber()];
200 Value one = hw::ConstantOp::create(builder, builder.getI1Type(), -1);
201 if (enableInfos[0].isDisable) {
202 inputs[enableInfos[0].condition.getArgNumber()] =
203 hw::ConstantOp::create(builder, builder.getI1Type(), 0);
204 enableCond = comb::XorOp::create(builder, enableCond, one);
205 } else {
206 inputs[enableInfos[0].condition.getArgNumber()] = one;
207 }
208
209 if (stateOp.getEnable())
210 enableCond = comb::AndOp::create(builder, stateOp.getEnable(), enableCond);
211
212 stateOp.getEnableMutable().assign(enableCond);
213
214 for (size_t i = 0, e = outputOp.getOutputs().size(); i < e; ++i) {
215 if (enableInfos[i].selfArg.hasOneUse()) {
216 // The feedback value may be an aggregate, but hw.constant only supports
217 // integers. Create an integer zero and bitcast it to the feedback type.
218 auto type = enableInfos[i].selfArg.getType();
219 Value zero = hw::ConstantOp::create(
220 builder, stateOp.getLoc(),
221 builder.getIntegerType(hw::getBitWidth(type)), 0);
222 if (zero.getType() != type)
223 zero = hw::BitcastOp::create(builder, type, zero);
224 inputs[enableInfos[i].selfArg.getArgNumber()] = zero;
225 }
226 }
227
228 stateOp.getInputsMutable().assign(inputs);
229 return success();
230}
231
232//===----------------------------------------------------------------------===//
233// Pattern detectors
234//===----------------------------------------------------------------------===//
235
236//===----------------------------------------------------------------------===//
237// Reset Patterns
238
239/// A reset represented with a single mux operation.
240/// out = mux(resetCondition, 0, arcArgument)
241/// ==>
242/// return arcArgument directly and add resetCondition to the StateOp
243static ResetInfo getIfMuxBasedReset(OpOperand &output) {
244 assert(isa<arc::OutputOp>(output.getOwner()) &&
245 "value has to be returned by the arc");
246
247 if (auto mux = output.get().getDefiningOp<comb::MuxOp>()) {
248 if (!isConstZero(mux.getTrueValue()))
249 return {};
250
251 if (!mux.getResult().hasOneUse())
252 return {};
253
254 if (auto condArg = dyn_cast<BlockArgument>(mux.getCond()))
255 return ResetInfo(mux.getFalseValue(), condArg, true);
256 }
257
258 return {};
259}
260
261/// A reset represented by an AND and XOR operation for i1 values only.
262/// out = and(X); X being a list containing all of
263/// {xor(resetCond, true), arcArgument}
264/// ==>
265/// out = and(X\xor(resetCond, true)) + add resetCond to StateOp
266static ResetInfo getIfAndBasedReset(OpOperand &output) {
267 assert(isa<arc::OutputOp>(output.getOwner()) &&
268 "value has to be returned by the arc");
269
270 if (auto andOp = output.get().getDefiningOp<comb::AndOp>()) {
271 if (!andOp.getResult().getType().isInteger(1))
272 return {};
273
274 if (!andOp.getResult().hasOneUse())
275 return {};
276
277 for (auto &operand : andOp->getOpOperands()) {
278 if (auto xorOp = operand.get().getDefiningOp<comb::XorOp>();
279 xorOp && xorOp->getNumOperands() == 2 &&
280 xorOp.getResult().hasOneUse()) {
281 if (auto condArg = dyn_cast<BlockArgument>(xorOp.getInputs()[0])) {
282 if (xorOp.getInputs().size() != 2 ||
283 !isConstTrue(xorOp.getInputs()[1]))
284 continue;
285
286 const unsigned condOutputNumber = operand.getOperandNumber();
287 auto inputConstructor = [=](OpBuilder &builder) -> Value {
288 if (andOp->getNumOperands() > 2) {
289 builder.setInsertionPoint(andOp);
290 auto copy = cast<comb::AndOp>(builder.clone(*andOp));
291 copy.getInputsMutable().erase(condOutputNumber);
292 return copy->getResult(0);
293 }
294
295 return andOp->getOperand(!condOutputNumber);
296 };
297
298 return ResetInfo(inputConstructor, condArg, true);
299 }
300 }
301 }
302 }
303
304 return {};
305}
306
307//===----------------------------------------------------------------------===//
308// Enable Patterns
309
310/// Just a helper function for the following two patterns.
311static EnableInfo checkOperandsForEnable(arc::StateOp stateOp, Value selfArg,
312 Value cond, unsigned outputNr,
313 bool isDisable) {
314 if (auto trueArg = dyn_cast<BlockArgument>(selfArg)) {
315 if (stateOp.getInputs()[trueArg.getArgNumber()] !=
316 stateOp.getResult(outputNr))
317 return {};
318
319 if (auto condArg = dyn_cast<BlockArgument>(cond))
320 return EnableInfo(selfArg, condArg, trueArg, isDisable);
321 }
322
323 return {};
324}
325
326/// An enable represented by a single mux operation.
327/// out = mux(enableCond, x, arcArgument) where x is the 'out' of the last cycle
328/// ==>
329/// out = arcArgument + set enableCond as enable operand to the StateOp
330static EnableInfo getIfMuxBasedEnable(OpOperand &output, StateOp stateOp) {
331 assert(isa<arc::OutputOp>(output.getOwner()) &&
332 "value has to be returned by the arc");
333
334 if (auto mux = output.get().getDefiningOp<comb::MuxOp>()) {
335 if (!mux.getResult().hasOneUse())
336 return {};
337
338 return checkOperandsForEnable(stateOp, mux.getFalseValue(), mux.getCond(),
339 output.getOperandNumber(), false);
340 }
341
342 return {};
343}
344
345/// A negated enable represented by a single mux operation.
346/// out = mux(enableCond, arcArgument, x) where x is the 'out' of the last cycle
347/// ==>
348/// out = arcArgument + set xor(enableCond, true) as enable operand to the
349/// StateOp
350static EnableInfo getIfMuxBasedDisable(OpOperand &output, StateOp stateOp) {
351 assert(isa<arc::OutputOp>(output.getOwner()) &&
352 "value has to be returned by the arc");
353
354 if (auto mux = output.get().getDefiningOp<comb::MuxOp>()) {
355 if (!mux.getResult().hasOneUse())
356 return {};
357
358 return checkOperandsForEnable(stateOp, mux.getTrueValue(), mux.getCond(),
359 output.getOperandNumber(), true);
360 }
361
362 return {};
363}
364
365//===----------------------------------------------------------------------===//
366// Combine all the patterns
367//===----------------------------------------------------------------------===//
368
369/// Combine all the reset patterns to one.
370ResetInfo computeResetInfoFromPattern(OpOperand &output) {
371 auto resetInfo = getIfMuxBasedReset(output);
372
373 if (!resetInfo)
374 resetInfo = getIfAndBasedReset(output);
375
376 return resetInfo;
377}
378
379/// Combine all the enable patterns to one.
380EnableInfo computeEnableInfoFromPattern(OpOperand &output, StateOp stateOp) {
381 auto enableInfo = getIfMuxBasedEnable(output, stateOp);
382
383 if (!enableInfo)
384 enableInfo = getIfMuxBasedDisable(output, stateOp);
385
386 return enableInfo;
387}
388
389//===----------------------------------------------------------------------===//
390// DetectResets pass
391//===----------------------------------------------------------------------===//
392
393namespace {
394struct InferStatePropertiesPass
395 : public impl::InferStatePropertiesBase<InferStatePropertiesPass> {
396 using InferStatePropertiesBase::InferStatePropertiesBase;
397
398 void runOnOperation() override;
399 void runOnStateOp(arc::StateOp stateOp, arc::DefineOp arc,
400 DenseMap<arc::DefineOp, unsigned> &resetConditionMap,
401 const mlir::SymbolUserMap &symbolUsers);
402};
403} // namespace
404
405void InferStatePropertiesPass::runOnOperation() {
406 SymbolTableCollection symbolTable;
407 mlir::SymbolUserMap symbolUsers(symbolTable, getOperation());
408
409 DenseMap<arc::DefineOp, unsigned> resetConditionMap;
410 getOperation()->walk([&](arc::StateOp stateOp) {
411 auto arc =
412 cast<arc::DefineOp>(cast<mlir::CallOpInterface>(stateOp.getOperation())
413 .resolveCallableInTable(&symbolTable));
414 runOnStateOp(stateOp, arc, resetConditionMap, symbolUsers);
415 });
416}
417
418void InferStatePropertiesPass::runOnStateOp(
419 arc::StateOp stateOp, arc::DefineOp arc,
420 DenseMap<arc::DefineOp, unsigned> &resetConditionMap,
421 const mlir::SymbolUserMap &symbolUsers) {
422
423 auto outputOp = cast<arc::OutputOp>(arc.getBodyBlock().getTerminator());
424 static constexpr unsigned visitedNoChange = -1;
425
426 if (detectResets) {
427 // Check for reset patterns, we only have to do this once per arc::DefineOp
428 // and store the result for later arc::StateOps referring to the same arc.
429 bool seen = resetConditionMap.count(arc);
430
431 // The reset is pulled out by rewriting the arc::DefineOp in place, and only
432 // the arc::StateOps are updated to compensate. Any other user (e.g., an
433 // arc::CallOp sharing the arc after deduplication) would silently compute a
434 // different function, so leave such arcs untouched.
435 if (!seen && !llvm::all_of(symbolUsers.getUsers(arc), [](Operation *user) {
436 return isa<arc::StateOp>(user);
437 })) {
438 resetConditionMap[arc] = visitedNoChange;
439 seen = true;
440 }
441
442 if (!seen) {
443 SmallVector<ResetInfo> resetInfos;
444 int numResets = 0;
445 for (auto &output : outputOp->getOpOperands()) {
446 auto resetInfo = computeResetInfoFromPattern(output);
447 resetInfos.push_back(resetInfo);
448 if (resetInfo)
449 ++numResets;
450 }
451
452 // Rewrite the arc::DefineOp if valid
453 auto result = applyResetTransformation(arc, resetInfos);
454 if ((succeeded(result) && resetInfos[0]))
455 resetConditionMap[arc] = resetInfos[0].condition.getArgNumber();
456 else
457 resetConditionMap[arc] = visitedNoChange;
458
459 if (failed(result))
460 missedResets += numResets;
461 }
462
463 // Apply resets to the state operation.
464 if (resetConditionMap[arc] != visitedNoChange) {
465 setResetOperandOfStateOp(stateOp, resetConditionMap[arc]);
466 ++addedResets;
467 }
468 }
469
470 if (detectEnables) {
471 // Check for enable patterns.
472 SmallVector<EnableInfo> enableInfos;
473 int numEnables = 0;
474 for (OpOperand &output : outputOp->getOpOperands()) {
475 auto enableInfo = computeEnableInfoFromPattern(output, stateOp);
476 enableInfos.push_back(enableInfo);
477 if (enableInfo)
478 ++numEnables;
479 }
480
481 // Apply enable patterns.
482 if (!failed(applyEnableTransformation(arc, stateOp, enableInfos)))
483 ++addedEnables;
484 else
485 missedEnables += numEnables;
486 }
487}
assert(baseType &&"element must be base type")
static bool isConstTrue(Value value)
static EnableInfo checkOperandsForEnable(arc::StateOp stateOp, Value selfArg, Value cond, unsigned outputNr, bool isDisable)
Just a helper function for the following two patterns.
static EnableInfo getIfMuxBasedDisable(OpOperand &output, StateOp stateOp)
A negated enable represented by a single mux operation.
static ResetInfo getIfAndBasedReset(OpOperand &output)
A reset represented by an AND and XOR operation for i1 values only.
static LogicalResult applyEnableTransformation(arc::DefineOp arcOp, arc::StateOp stateOp, ArrayRef< EnableInfo > enableInfos)
Take an arc and a detected enable per output value and apply it to the given state if applicable (no ...
static bool isConstZero(Value value)
static LogicalResult applyResetTransformation(arc::DefineOp arcOp, ArrayRef< ResetInfo > resetInfos)
Take an arc and a detected reset per output value and apply it to the arc if applicable (but does not...
EnableInfo computeEnableInfoFromPattern(OpOperand &output, StateOp stateOp)
Combine all the enable patterns to one.
static void setResetOperandOfStateOp(arc::StateOp stateOp, unsigned resetConditionIndex)
Transform the given state operation to match the changes done to the arc in 'applyResetTransformation...
ResetInfo computeResetInfoFromPattern(OpOperand &output)
Combine all the reset patterns to one.
static EnableInfo getIfMuxBasedEnable(OpOperand &output, StateOp stateOp)
An enable represented by a single mux operation.
static ResetInfo getIfMuxBasedReset(OpOperand &output)
A reset represented with a single mux operation.
false return failure()
Parse an optional keyword or string and set instance into 'result'.
return success()
create(data_type, value)
Definition hw.py:444
create(data_type, value)
Definition hw.py:433
Definition arc.py:1
int64_t getBitWidth(mlir::Type type)
Return the hardware bit width of a type.
Definition HWTypes.cpp:122
The InstanceGraph op interface, see InstanceGraphInterface.td for more details.