24#include "mlir/IR/Builders.h"
25#include "mlir/Pass/Pass.h"
29#define GEN_PASS_DEF_HWLEGALIZEMODULES
30#include "circt/Dialect/SV/SVPasses.h.inc"
40struct HWLegalizeModulesPass
41 :
public circt::sv::impl::HWLegalizeModulesBase<HWLegalizeModulesPass> {
42 void runOnOperation()
override;
45 void processPostOrder(
Block &block);
46 bool tryLoweringPackedArrayOp(Operation &op);
47 template <
typename ElementType>
48 SmallVector<std::pair<Value, Value>>
49 createIndexValuePairs(OpBuilder &builder, LocationAttr loc, hw::ArrayType ty,
51 Value lowerLookupToCasez(Operation &op, Value input, Value index,
53 SmallVector<Value> caseValues);
54 bool processUsers(Operation &op, Value value, ArrayRef<Value> mapping);
55 template <
typename DeclOp>
56 bool lowerArrayVar(DeclOp declOp);
57 std::optional<std::pair<uint64_t, unsigned>>
58 tryExtractIndexAndBitWidth(Value value);
59 bool tryLoweringClockedAssertLike(Operation &op);
62 hw::HWModuleOp thisHWModule;
68 LoweringOptions options;
73 StringAttr lastParsedOptions;
79template <
typename DeclOp>
80bool HWLegalizeModulesPass::lowerArrayVar(DeclOp declOp) {
81 auto ty = hw::type_dyn_cast<hw::ArrayType>(declOp.getElementType());
85 OpBuilder builder(declOp);
86 auto name = StringAttr::get(declOp.getContext(),
"name");
87 SmallVector<Value> elements;
88 for (
size_t i = 0, e = ty.getNumElements(); i < e; i++) {
89 auto loc = declOp.getLoc();
90 auto element = DeclOp::create(builder, loc, ty.getElementType());
91 if (
auto nameAttr = declOp->template getAttrOfType<StringAttr>(name)) {
93 StringAttr::get(declOp.getContext(), nameAttr.getValue()));
95 elements.push_back(element);
99 return processUsers(*declOp, declOp.getResult(), elements);
102bool HWLegalizeModulesPass::tryLoweringPackedArrayOp(Operation &op) {
103 return TypeSwitch<Operation *, bool>(&op)
104 .Case<hw::AggregateConstantOp>([&](hw::AggregateConstantOp constOp) {
106 SmallVector<Value> inputs;
107 OpBuilder builder(constOp);
108 for (
auto field : llvm::reverse(constOp.getFields())) {
109 if (
auto intAttr = dyn_cast<IntegerAttr>(field))
113 inputs.push_back(hw::AggregateConstantOp::create(
114 builder, constOp.getLoc(), constOp.getType(),
115 cast<ArrayAttr>(field)));
117 if (!processUsers(op, constOp.getResult(), inputs))
123 .Case<hw::ArrayConcatOp>([&](hw::ArrayConcatOp concatOp) {
125 SmallVector<Value> values;
126 OpBuilder builder(concatOp);
127 for (
auto array : llvm::reverse(concatOp.getInputs())) {
128 auto ty = hw::type_cast<hw::ArrayType>(array.getType());
129 const auto indexValues = createIndexValuePairs<hw::ArrayGetOp>(
130 builder, concatOp.getLoc(), ty, array);
131 for (
const auto &[_, value] : indexValues) {
132 values.push_back(value);
135 if (!processUsers(op, concatOp.getResult(), values))
141 .Case<hw::ArrayCreateOp>([&](hw::ArrayCreateOp createOp) {
143 SmallVector<Value> inputs(llvm::reverse(createOp.getInputs()));
144 if (!processUsers(op, createOp.getResult(), inputs))
150 .Case<hw::ArrayGetOp>([&](hw::ArrayGetOp getOp) {
152 auto index = getOp.getIndex();
153 if (
auto *definingOp = index.getDefiningOp())
154 if (isa<hw::ConstantOp>(definingOp))
158 auto ty = hw::type_cast<hw::ArrayType>(getOp.getInput().getType());
159 OpBuilder builder(getOp);
160 auto loc = op.getLoc();
161 const auto indexValues = createIndexValuePairs<hw::ArrayGetOp>(
162 builder, loc, ty, getOp.getInput());
163 SmallVector<Value> caseValues;
164 for (
const auto &[_, value] : indexValues)
165 caseValues.push_back(value);
168 auto theWire = lowerLookupToCasez(op, getOp.getInput(), index,
169 ty.getElementType(), caseValues);
172 builder.setInsertionPoint(getOp);
175 getOp.getResult().replaceAllUsesWith(readWire);
178 .Case<sv::ArrayIndexInOutOp>([&](sv::ArrayIndexInOutOp indexOp) {
180 auto index = indexOp.getIndex();
181 if (
auto *definingOp = index.getDefiningOp())
182 if (isa<hw::ConstantOp>(definingOp))
186 auto handle = indexOp.getInput().getType();
187 Type
elementType = sv::getHandleElementType(handle);
188 if (hw::type_isa<hw::UnpackedArrayType>(
elementType))
192 auto ty = hw::type_cast<hw::ArrayType>(
elementType);
193 OpBuilder builder(&op);
194 auto loc = op.getLoc();
195 const auto indexValues = createIndexValuePairs<sv::ArrayIndexInOutOp>(
196 builder, loc, ty, indexOp.getInput());
197 SmallVector<Value> caseValues;
198 for (
const auto &[_, element] : indexValues) {
200 caseValues.push_back(readElement);
204 auto theWire = lowerLookupToCasez(op, indexOp.getInput(), index,
205 ty.getElementType(), caseValues);
208 indexOp.getResult().replaceAllUsesWith(theWire);
211 .Case<sv::PAssignOp>([&](sv::PAssignOp assignOp) {
214 auto destElementType =
215 sv::getHandleElementType(assignOp.getDest().getType());
216 auto ty = hw::type_dyn_cast<hw::ArrayType>(destElementType);
220 OpBuilder builder(assignOp);
221 auto loc = op.getLoc();
222 const auto indexValues = createIndexValuePairs<hw::ArrayGetOp>(
223 builder, loc, ty, assignOp.getSrc());
224 for (
const auto &[index, srcElement] : indexValues) {
225 auto dstElement = sv::ArrayIndexInOutOp::create(
226 builder, loc, assignOp.getDest(), index);
227 sv::PAssignOp::create(builder, loc, dstElement, srcElement);
233 .Case<sv::VarOp, sv::RegOp>([&](
auto op) {
return lowerArrayVar(op); })
234 .Case<comb::MuxOp>([&](comb::MuxOp muxOp) {
236 auto ty = hw::type_dyn_cast<hw::ArrayType>(muxOp.getType());
240 OpBuilder builder(muxOp);
242 auto trueValues = createIndexValuePairs<hw::ArrayGetOp>(
243 builder, muxOp.getLoc(), ty, muxOp.getTrueValue());
244 auto falseValues = createIndexValuePairs<hw::ArrayGetOp>(
245 builder, muxOp.getLoc(), ty, muxOp.getFalseValue());
247 SmallVector<Value> muxedValues;
249 for (
size_t i = 0, e = trueValues.size(); i < e; i++) {
250 const auto &[trueIndex, trueValue] = trueValues[i];
251 const auto &[falseIndex, falseValue] = falseValues[i];
252 muxedValues.push_back(
253 comb::MuxOp::create(builder, muxOp.getLoc(), muxOp.getCond(),
254 trueValue, falseValue, muxOp.getTwoState()));
257 if (!processUsers(op, muxOp.getResult(), muxedValues))
263 .Default([&](
auto op) {
return false; });
266template <
typename ElementType>
267SmallVector<std::pair<Value, Value>>
268HWLegalizeModulesPass::createIndexValuePairs(OpBuilder &builder,
269 LocationAttr loc, hw::ArrayType ty,
271 SmallVector<std::pair<Value, Value>> result;
272 for (
size_t i = 0, e = ty.getNumElements(); i < e; i++) {
273 auto index = builder.createOrFold<hw::ConstantOp>(
274 loc, APInt(llvm::Log2_64_Ceil(e), i));
275 auto element = ElementType::create(builder, loc, array, index);
276 result.emplace_back(index, element);
281Value HWLegalizeModulesPass::lowerLookupToCasez(Operation &op, Value input,
284 SmallVector<Value> caseValues) {
287 OpBuilder builder(&op);
289 builder.getStringAttr(
"casez_tmp"));
290 builder.setInsertionPoint(&op);
292 auto loc = input.getLoc();
296 if (!op.getParentOp()->hasTrait<ProceduralRegion>()) {
297 auto alwaysComb = sv::AlwaysCombOp::create(builder, loc);
298 builder.setInsertionPointToEnd(alwaysComb.getBodyBlock());
303 if (1ULL << index.getType().getIntOrFloatBitWidth() != caseValues.size()) {
304 caseValues.push_back(sv::ConstantXOp::create(builder, op.getLoc(),
305 op.getResult(0).getType()));
308 APInt caseValue(index.getType().getIntOrFloatBitWidth(), 0);
309 auto *
context = builder.getContext();
313 builder, loc, CaseStmtType::CaseZStmt, index, caseValues.size(),
314 [&](
size_t caseIdx) -> std::unique_ptr<sv::CasePattern> {
319 bool isDefault = caseIdx == caseValues.size() - 1;
320 Value theValue = caseValues[caseIdx];
321 std::unique_ptr<sv::CasePattern> thePattern;
324 thePattern = std::make_unique<sv::CaseDefaultPattern>(context);
326 thePattern = std::make_unique<sv::CaseBitPattern>(caseValue, context);
328 sv::BPAssignOp::create(builder, loc, theWire, theValue);
335bool HWLegalizeModulesPass::processUsers(Operation &op, Value value,
336 ArrayRef<Value> mapping) {
337 for (
auto *user : llvm::make_early_inc_range(value.getUsers())) {
338 if (TypeSwitch<Operation *, bool>(user)
339 .Case<hw::ArrayGetOp>([&](hw::ArrayGetOp getOp) {
340 if (
auto indexAndBitWidth =
341 tryExtractIndexAndBitWidth(getOp.getIndex())) {
342 getOp.replaceAllUsesWith(mapping[indexAndBitWidth->first]);
348 .Case<sv::ArrayIndexInOutOp>([&](sv::ArrayIndexInOutOp indexOp) {
349 if (
auto indexAndBitWidth =
350 tryExtractIndexAndBitWidth(indexOp.getIndex())) {
351 indexOp.replaceAllUsesWith(mapping[indexAndBitWidth->first]);
357 .Default([](
auto op) {
return false; })) {
362 user->emitError(
"unsupported packed array expression");
370std::optional<std::pair<uint64_t, unsigned>>
371HWLegalizeModulesPass::tryExtractIndexAndBitWidth(Value value) {
372 if (
auto constantOp = dyn_cast<hw::ConstantOp>(value.getDefiningOp())) {
373 auto index = constantOp.getValue();
374 return std::make_optional(
375 std::make_pair(index.getZExtValue(), index.getBitWidth()));
381template <
typename Op>
382bool tryLoweringClockedAssertLike(Op &op) {
383 auto event = op.getEvent();
384 if (!event.has_value())
387 OpBuilder builder(op);
389 sv::AlwaysOp::create(builder, op->getLoc(), *event, op.getClock(), [&] {
390 Op::create(builder, op.getLoc(), op.getProperty(), op.getDisable(),
397bool HWLegalizeModulesPass::tryLoweringClockedAssertLike(Operation &op) {
398 return TypeSwitch<Operation *, bool>(&op)
399 .Case<sv::AssertPropertyOp>(
400 ::tryLoweringClockedAssertLike<sv::AssertPropertyOp>)
401 .Case<sv::AssumePropertyOp>(
402 ::tryLoweringClockedAssertLike<sv::AssumePropertyOp>)
403 .Case<sv::CoverPropertyOp>(
404 ::tryLoweringClockedAssertLike<sv::CoverPropertyOp>)
405 .Default([&](
auto op) {
return false; });
408void HWLegalizeModulesPass::processPostOrder(Block &body) {
413 Block::iterator it = std::prev(body.end());
414 while (it != body.end()) {
419 if (it == body.begin())
424 if (op.getNumRegions()) {
425 for (
auto ®ion : op.getRegions())
426 for (
auto ®ionBlock : region.getBlocks())
427 processPostOrder(regionBlock);
432 if (tryLoweringPackedArrayOp(op)) {
433 it = --Block::iterator(op);
435 anythingChanged =
true;
441 for (
auto value : op.getResults()) {
442 if (isa<hw::ArrayType>(value.getType())) {
443 op.emitError(
"unsupported packed array expression");
450 if (tryLoweringClockedAssertLike(op)) {
452 anythingChanged =
true;
459void HWLegalizeModulesPass::runOnOperation() {
460 thisHWModule = getOperation();
464 cast<ModuleOp>(thisHWModule->getParentOp()));
465 if (optionsAttr != lastParsedOptions) {
467 options = LoweringOptions(optionsAttr.getValue(), [&](Twine error) {
468 thisHWModule.emitError(error);
471 options = LoweringOptions();
472 lastParsedOptions = optionsAttr;
477 anythingChanged =
false;
480 processPostOrder(*thisHWModule.getBodyBlock());
483 if (!anythingChanged)
484 markAllAnalysesPreserved();
static std::unique_ptr< Context > context
create(data_type, name=None, sym_name=None)
The InstanceGraph op interface, see InstanceGraphInterface.td for more details.
bool disallowPackedArrays
If true, eliminate packed arrays for tools that don't support them (e.g.
static mlir::StringAttr getAttributeFrom(mlir::ModuleOp module)
Return the value of the circt.loweringOptions in the specified module if present, or a null attribute...
bool disallowClockedAssertions