CIRCT 24.0.0git
Loading...
Searching...
No Matches
HWLegalizeModules.cpp
Go to the documentation of this file.
1//===- HWLegalizeModulesPass.cpp - Lower unsupported IR features away -----===//
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 lowers away features in the SV/Comb/HW dialects that are
10// unsupported by some tools (e.g. multidimensional arrays) as specified by
11// LoweringOptions. This pass is run relatively late in the pipeline in
12// preparation for emission. Any passes run after this (e.g. PrettifyVerilog)
13// must be aware they cannot introduce new invalid constructs.
14//
15//===----------------------------------------------------------------------===//
16
24#include "mlir/IR/Builders.h"
25#include "mlir/Pass/Pass.h"
26
27namespace circt {
28namespace sv {
29#define GEN_PASS_DEF_HWLEGALIZEMODULES
30#include "circt/Dialect/SV/SVPasses.h.inc"
31} // namespace sv
32} // namespace circt
33
34using namespace circt;
35//===----------------------------------------------------------------------===//
36// HWLegalizeModulesPass
37//===----------------------------------------------------------------------===//
38
39namespace {
40struct HWLegalizeModulesPass
41 : public circt::sv::impl::HWLegalizeModulesBase<HWLegalizeModulesPass> {
42 void runOnOperation() override;
43
44private:
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,
50 Value array);
51 Value lowerLookupToCasez(Operation &op, Value input, Value index,
52 mlir::Type elementType,
53 SmallVector<Value> caseValues);
54 bool processUsers(Operation &op, Value value, ArrayRef<Value> mapping);
55 std::optional<std::pair<uint64_t, unsigned>>
56 tryExtractIndexAndBitWidth(Value value);
57 bool tryLoweringClockedAssertLike(Operation &op);
58
59 /// This is the current hw.module being processed.
60 hw::HWModuleOp thisHWModule;
61
62 bool anythingChanged;
63
64 /// This tells us what language features we're allowed to use in generated
65 /// Verilog.
66 LoweringOptions options;
67
68 /// This pass will be run on multiple hw.modules, this keeps track of the
69 /// contents of LoweringOptions so we don't have to reparse the
70 /// LoweringOptions for every hw.module.
71 StringAttr lastParsedOptions;
72};
73} // end anonymous namespace
74
75bool HWLegalizeModulesPass::tryLoweringPackedArrayOp(Operation &op) {
76 return TypeSwitch<Operation *, bool>(&op)
77 .Case<hw::AggregateConstantOp>([&](hw::AggregateConstantOp constOp) {
78 // Replace individual element uses (if any) with input fields.
79 SmallVector<Value> inputs;
80 OpBuilder builder(constOp);
81 for (auto field : llvm::reverse(constOp.getFields())) {
82 if (auto intAttr = dyn_cast<IntegerAttr>(field))
83 inputs.push_back(
84 hw::ConstantOp::create(builder, constOp.getLoc(), intAttr));
85 else
86 inputs.push_back(hw::AggregateConstantOp::create(
87 builder, constOp.getLoc(), constOp.getType(),
88 cast<ArrayAttr>(field)));
89 }
90 if (!processUsers(op, constOp.getResult(), inputs))
91 return false;
92
93 // Remove original op.
94 return true;
95 })
96 .Case<hw::ArrayConcatOp>([&](hw::ArrayConcatOp concatOp) {
97 // Redirect individual element uses (if any) to the input arguments.
98 SmallVector<Value> values;
99 OpBuilder builder(concatOp);
100 for (auto array : llvm::reverse(concatOp.getInputs())) {
101 auto ty = hw::type_cast<hw::ArrayType>(array.getType());
102 const auto indexValues = createIndexValuePairs<hw::ArrayGetOp>(
103 builder, concatOp.getLoc(), ty, array);
104 for (const auto &[_, value] : indexValues) {
105 values.push_back(value);
106 }
107 }
108 if (!processUsers(op, concatOp.getResult(), values))
109 return false;
110
111 // Remove original op.
112 return true;
113 })
114 .Case<hw::ArrayCreateOp>([&](hw::ArrayCreateOp createOp) {
115 // Replace individual element uses (if any) with input arguments.
116 SmallVector<Value> inputs(llvm::reverse(createOp.getInputs()));
117 if (!processUsers(op, createOp.getResult(), inputs))
118 return false;
119
120 // Remove original op.
121 return true;
122 })
123 .Case<hw::ArrayGetOp>([&](hw::ArrayGetOp getOp) {
124 // Skip index ops with constant index.
125 auto index = getOp.getIndex();
126 if (auto *definingOp = index.getDefiningOp())
127 if (isa<hw::ConstantOp>(definingOp))
128 return false;
129
130 // Generate case value element lookups.
131 auto ty = hw::type_cast<hw::ArrayType>(getOp.getInput().getType());
132 OpBuilder builder(getOp);
133 auto loc = op.getLoc();
134 const auto indexValues = createIndexValuePairs<hw::ArrayGetOp>(
135 builder, loc, ty, getOp.getInput());
136 SmallVector<Value> caseValues;
137 for (const auto &[_, value] : indexValues)
138 caseValues.push_back(value);
139
140 // Transform array index op into casez statement.
141 auto theWire = lowerLookupToCasez(op, getOp.getInput(), index,
142 ty.getElementType(), caseValues);
143
144 // Emit the read from the wire, replace uses and clean up.
145 builder.setInsertionPoint(getOp);
146 auto readWire =
147 sv::ReadInOutOp::create(builder, getOp.getLoc(), theWire);
148 getOp.getResult().replaceAllUsesWith(readWire);
149 return true;
150 })
151 .Case<sv::ArrayIndexInOutOp>([&](sv::ArrayIndexInOutOp indexOp) {
152 // Skip index ops with constant index.
153 auto index = indexOp.getIndex();
154 if (auto *definingOp = index.getDefiningOp())
155 if (isa<hw::ConstantOp>(definingOp))
156 return false;
157
158 // Skip index ops with unpacked arrays.
159 auto handle = indexOp.getInput().getType();
160 Type elementType = sv::getHandleElementType(handle);
161 if (hw::type_isa<hw::UnpackedArrayType>(elementType))
162 return false;
163
164 // Generate case value element lookups.
165 auto ty = hw::type_cast<hw::ArrayType>(elementType);
166 OpBuilder builder(&op);
167 auto loc = op.getLoc();
168 const auto indexValues = createIndexValuePairs<sv::ArrayIndexInOutOp>(
169 builder, loc, ty, indexOp.getInput());
170 SmallVector<Value> caseValues;
171 for (const auto &[_, element] : indexValues) {
172 auto readElement = sv::ReadInOutOp::create(builder, loc, element);
173 caseValues.push_back(readElement);
174 }
175
176 // Transform array index op into casez statement.
177 auto theWire = lowerLookupToCasez(op, indexOp.getInput(), index,
178 ty.getElementType(), caseValues);
179
180 // Replace uses and clean up.
181 indexOp.getResult().replaceAllUsesWith(theWire);
182 return true;
183 })
184 .Case<sv::PAssignOp>([&](sv::PAssignOp assignOp) {
185 // Transform array assignment into individual assignments for each array
186 // element.
187 auto destElementType =
188 sv::getHandleElementType(assignOp.getDest().getType());
189 auto ty = hw::type_dyn_cast<hw::ArrayType>(destElementType);
190 if (!ty)
191 return false;
192
193 OpBuilder builder(assignOp);
194 auto loc = op.getLoc();
195 const auto indexValues = createIndexValuePairs<hw::ArrayGetOp>(
196 builder, loc, ty, assignOp.getSrc());
197 for (const auto &[index, srcElement] : indexValues) {
198 auto dstElement = sv::ArrayIndexInOutOp::create(
199 builder, loc, assignOp.getDest(), index);
200 sv::PAssignOp::create(builder, loc, dstElement, srcElement);
201 }
202
203 // Remove original assignment.
204 return true;
205 })
206 .Case<sv::RegOp>([&](sv::RegOp regOp) {
207 // Transform array reg into individual regs for each array element.
208 auto ty = hw::type_dyn_cast<hw::ArrayType>(regOp.getElementType());
209 if (!ty)
210 return false;
211
212 OpBuilder builder(regOp);
213 auto name = StringAttr::get(regOp.getContext(), "name");
214 SmallVector<Value> elements;
215 for (size_t i = 0, e = ty.getNumElements(); i < e; i++) {
216 auto loc = op.getLoc();
217 auto element = sv::RegOp::create(builder, loc, ty.getElementType());
218 if (auto nameAttr = regOp->getAttrOfType<StringAttr>(name)) {
219 element.setNameAttr(
220 StringAttr::get(regOp.getContext(), nameAttr.getValue()));
221 }
222 elements.push_back(element);
223 }
224
225 // Fix users to refer to individual element regs.
226 if (!processUsers(op, regOp.getResult(), elements))
227 return false;
228
229 // Remove original reg.
230 return true;
231 })
232 .Case<comb::MuxOp>([&](comb::MuxOp muxOp) {
233 // Transform array mux into individual element muxes.
234 auto ty = hw::type_dyn_cast<hw::ArrayType>(muxOp.getType());
235 if (!ty)
236 return false;
237
238 OpBuilder builder(muxOp);
239
240 auto trueValues = createIndexValuePairs<hw::ArrayGetOp>(
241 builder, muxOp.getLoc(), ty, muxOp.getTrueValue());
242 auto falseValues = createIndexValuePairs<hw::ArrayGetOp>(
243 builder, muxOp.getLoc(), ty, muxOp.getFalseValue());
244
245 SmallVector<Value> muxedValues;
246
247 for (size_t i = 0, e = trueValues.size(); i < e; i++) {
248 const auto &[trueIndex, trueValue] = trueValues[i];
249 const auto &[falseIndex, falseValue] = falseValues[i];
250 muxedValues.push_back(
251 comb::MuxOp::create(builder, muxOp.getLoc(), muxOp.getCond(),
252 trueValue, falseValue, muxOp.getTwoState()));
253 }
254
255 if (!processUsers(op, muxOp.getResult(), muxedValues))
256 return false;
257
258 // Remove original mux.
259 return true;
260 })
261 .Default([&](auto op) { return false; });
262}
263
264template <typename ElementType>
265SmallVector<std::pair<Value, Value>>
266HWLegalizeModulesPass::createIndexValuePairs(OpBuilder &builder,
267 LocationAttr loc, hw::ArrayType ty,
268 Value array) {
269 SmallVector<std::pair<Value, Value>> result;
270 for (size_t i = 0, e = ty.getNumElements(); i < e; i++) {
271 auto index = builder.createOrFold<hw::ConstantOp>(
272 loc, APInt(llvm::Log2_64_Ceil(e), i));
273 auto element = ElementType::create(builder, loc, array, index);
274 result.emplace_back(index, element);
275 }
276 return result;
277}
278
279Value HWLegalizeModulesPass::lowerLookupToCasez(Operation &op, Value input,
280 Value index,
281 mlir::Type elementType,
282 SmallVector<Value> caseValues) {
283 // Create the wire for the result of the casez in the
284 // hw.module.
285 OpBuilder builder(&op);
286 auto theWire = sv::RegOp::create(builder, op.getLoc(), elementType,
287 builder.getStringAttr("casez_tmp"));
288 builder.setInsertionPoint(&op);
289
290 auto loc = input.getLoc();
291 // A casez is a procedural operation, so if we're in a
292 // non-procedural region we need to inject an always_comb
293 // block.
294 if (!op.getParentOp()->hasTrait<ProceduralRegion>()) {
295 auto alwaysComb = sv::AlwaysCombOp::create(builder, loc);
296 builder.setInsertionPointToEnd(alwaysComb.getBodyBlock());
297 }
298
299 // If we are missing elements in the array (it is non-power of
300 // two), then add a default 'X' value.
301 if (1ULL << index.getType().getIntOrFloatBitWidth() != caseValues.size()) {
302 caseValues.push_back(sv::ConstantXOp::create(builder, op.getLoc(),
303 op.getResult(0).getType()));
304 }
305
306 APInt caseValue(index.getType().getIntOrFloatBitWidth(), 0);
307 auto *context = builder.getContext();
308
309 // Create the casez itself.
310 sv::CaseOp::create(
311 builder, loc, CaseStmtType::CaseZStmt, index, caseValues.size(),
312 [&](size_t caseIdx) -> std::unique_ptr<sv::CasePattern> {
313 // Use a default pattern for the last value, even if we
314 // are complete. This avoids tools thinking they need to
315 // insert a latch due to potentially incomplete case
316 // coverage.
317 bool isDefault = caseIdx == caseValues.size() - 1;
318 Value theValue = caseValues[caseIdx];
319 std::unique_ptr<sv::CasePattern> thePattern;
320
321 if (isDefault)
322 thePattern = std::make_unique<sv::CaseDefaultPattern>(context);
323 else
324 thePattern = std::make_unique<sv::CaseBitPattern>(caseValue, context);
325 ++caseValue;
326 sv::BPAssignOp::create(builder, loc, theWire, theValue);
327 return thePattern;
328 });
329
330 return theWire;
331}
332
333bool HWLegalizeModulesPass::processUsers(Operation &op, Value value,
334 ArrayRef<Value> mapping) {
335 for (auto *user : llvm::make_early_inc_range(value.getUsers())) {
336 if (TypeSwitch<Operation *, bool>(user)
337 .Case<hw::ArrayGetOp>([&](hw::ArrayGetOp getOp) {
338 if (auto indexAndBitWidth =
339 tryExtractIndexAndBitWidth(getOp.getIndex())) {
340 getOp.replaceAllUsesWith(mapping[indexAndBitWidth->first]);
341 return true;
342 }
343
344 return false;
345 })
346 .Case<sv::ArrayIndexInOutOp>([&](sv::ArrayIndexInOutOp indexOp) {
347 if (auto indexAndBitWidth =
348 tryExtractIndexAndBitWidth(indexOp.getIndex())) {
349 indexOp.replaceAllUsesWith(mapping[indexAndBitWidth->first]);
350 return true;
351 }
352
353 return false;
354 })
355 .Default([](auto op) { return false; })) {
356 user->erase();
357 continue;
358 }
359
360 user->emitError("unsupported packed array expression");
361 signalPassFailure();
362 return false;
363 }
364
365 return true;
366}
367
368std::optional<std::pair<uint64_t, unsigned>>
369HWLegalizeModulesPass::tryExtractIndexAndBitWidth(Value value) {
370 if (auto constantOp = dyn_cast<hw::ConstantOp>(value.getDefiningOp())) {
371 auto index = constantOp.getValue();
372 return std::make_optional(
373 std::make_pair(index.getZExtValue(), index.getBitWidth()));
374 }
375 return std::nullopt;
376}
377
378namespace {
379template <typename Op>
380bool tryLoweringClockedAssertLike(Op &op) {
381 auto event = op.getEvent();
382 if (!event.has_value())
383 return false;
384
385 OpBuilder builder(op);
386
387 sv::AlwaysOp::create(builder, op->getLoc(), *event, op.getClock(), [&] {
388 Op::create(builder, op.getLoc(), op.getProperty(), op.getDisable(),
389 op.getLabelAttr());
390 });
391 return true;
392}
393} // namespace
394
395bool HWLegalizeModulesPass::tryLoweringClockedAssertLike(Operation &op) {
396 return TypeSwitch<Operation *, bool>(&op)
397 .Case<sv::AssertPropertyOp>(
398 ::tryLoweringClockedAssertLike<sv::AssertPropertyOp>)
399 .Case<sv::AssumePropertyOp>(
400 ::tryLoweringClockedAssertLike<sv::AssumePropertyOp>)
401 .Case<sv::CoverPropertyOp>(
402 ::tryLoweringClockedAssertLike<sv::CoverPropertyOp>)
403 .Default([&](auto op) { return false; });
404}
405
406void HWLegalizeModulesPass::processPostOrder(Block &body) {
407 if (body.empty())
408 return;
409
410 // Walk the block bottom-up, processing the region tree inside out.
411 Block::iterator it = std::prev(body.end());
412 while (it != body.end()) {
413 auto &op = *it;
414
415 // Advance the iterator, using the end iterator as a sentinel that we're at
416 // the top of the block.
417 if (it == body.begin())
418 it = body.end();
419 else
420 --it;
421
422 if (op.getNumRegions()) {
423 for (auto &region : op.getRegions())
424 for (auto &regionBlock : region.getBlocks())
425 processPostOrder(regionBlock);
426 }
427
428 if (options.disallowPackedArrays) {
429 // Try supported packed array op lowering.
430 if (tryLoweringPackedArrayOp(op)) {
431 it = --Block::iterator(op);
432 op.erase();
433 anythingChanged = true;
434 continue;
435 }
436
437 // Otherwise, if the IR produces a packed array and we aren't allowing
438 // multi-dimensional arrays, reject the IR as invalid.
439 for (auto value : op.getResults()) {
440 if (isa<hw::ArrayType>(value.getType())) {
441 op.emitError("unsupported packed array expression");
442 signalPassFailure();
443 }
444 }
445 }
446
447 if (options.disallowClockedAssertions) {
448 if (tryLoweringClockedAssertLike(op)) {
449 op.erase();
450 anythingChanged = true;
451 continue;
452 }
453 }
454 }
455}
456
457void HWLegalizeModulesPass::runOnOperation() {
458 thisHWModule = getOperation();
459
460 // Parse the lowering options if necessary.
461 auto optionsAttr = LoweringOptions::getAttributeFrom(
462 cast<ModuleOp>(thisHWModule->getParentOp()));
463 if (optionsAttr != lastParsedOptions) {
464 if (optionsAttr)
465 options = LoweringOptions(optionsAttr.getValue(), [&](Twine error) {
466 thisHWModule.emitError(error);
467 });
468 else
469 options = LoweringOptions();
470 lastParsedOptions = optionsAttr;
471 }
472
473 // Keeps track if anything changed during this pass, used to determine if
474 // the analyses were preserved.
475 anythingChanged = false;
476
477 // Walk the operations in post-order, transforming any that are interesting.
478 processPostOrder(*thisHWModule.getBodyBlock());
479
480 // If we did not change anything in the IR mark all analysis as preserved.
481 if (!anythingChanged)
482 markAllAnalysesPreserved();
483}
MlirType elementType
Definition CHIRRTL.cpp:29
static std::unique_ptr< Context > context
create(data_type, value)
Definition hw.py:433
create(value)
Definition sv.py:151
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...