CIRCT 24.0.0git
Loading...
Searching...
No Matches
PrepareForEmission.cpp
Go to the documentation of this file.
1//===- PrepareForEmission.cpp - IR Prepass for Emitter --------------------===//
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 file implements the "prepare" pass that walks the IR before the emitter
10// gets involved. This allows us to do some transformations that would be
11// awkward to implement inline in the emitter.
12//
13// NOTE: This file covers the preparation phase of `ExportVerilog` which mainly
14// legalizes the IR and makes adjustments necessary for emission. This is the
15// place to mutate the IR if emission needs it. The IR cannot be modified during
16// emission itself, which happens in parallel.
17//
18//===----------------------------------------------------------------------===//
19
29#include "mlir/IR/ImplicitLocOpBuilder.h"
30#include "mlir/Interfaces/CallInterfaces.h"
31#include "mlir/Pass/Pass.h"
32#include "llvm/ADT/DenseSet.h"
33#include "llvm/ADT/SmallPtrSet.h"
34#include "llvm/ADT/TypeSwitch.h"
35#include "llvm/Support/CommandLine.h"
36#include "llvm/Support/Debug.h"
37
38#define DEBUG_TYPE "prepare-for-emission"
39
40namespace circt {
41#define GEN_PASS_DEF_PREPAREFOREMISSION
42#include "circt/Conversion/Passes.h.inc"
43} // namespace circt
44
45using namespace circt;
46using namespace comb;
47using namespace hw;
48using namespace sv;
49using namespace ExportVerilog;
50
51// Check if the value is from read of a handle (net, var, inout) or is a port. A
53 if (isa<BlockArgument>(v))
54 return true;
55 auto *vOp = v.getDefiningOp();
56 if (!vOp)
57 return false;
58 if (sv::getHandleElementType(v.getType()))
59 return true;
60 auto read = dyn_cast<ReadInOutOp>(vOp);
61 if (!read)
62 return false;
63 auto *readSrc = read.getInput().getDefiningOp();
64 if (!readSrc)
65 return false;
66 return isa<sv::WireOp, RegOp, LogicOp, VarOp, XMROp, XMRRefOp>(readSrc);
67}
68
69// Check if the value is deemed worth spilling into a wire.
70static bool shouldSpillWire(Operation &op, const LoweringOptions &options) {
71 if (!isVerilogExpression(&op))
72 return false;
73
74 // Spill temporary wires if it is not possible to inline.
75 return !ExportVerilog::isExpressionEmittedInline(&op, options);
76}
77
78static StringAttr getArgName(Operation *op, size_t idx) {
79 if (auto inst = dyn_cast<HWInstanceLike>(op))
80 return inst.getInputName(idx);
81 return {};
82}
83
84// Given an instance, make sure all inputs are driven from wires or ports.
85static void spillWiresForInstanceInputs(HWInstanceLike op) {
86 Block *block = op->getParentOfType<HWModuleOp>().getBodyBlock();
87 auto builder = ImplicitLocOpBuilder::atBlockBegin(op.getLoc(), block);
88
89 SmallString<32> nameTmp{"_", op.getInstanceName(), "_"};
90 auto namePrefixSize = nameTmp.size();
91
92 for (size_t opNum = 0, e = op->getNumOperands(); opNum != e; ++opNum) {
93 auto src = op->getOperand(opNum);
94
95 if (isSimpleReadOrPort(src))
96 continue;
97
98 nameTmp.resize(namePrefixSize);
99 if (auto n = getArgName(op, opNum))
100 nameTmp += n.getValue().str();
101 else
102 nameTmp += std::to_string(opNum);
103
104 auto newWire =
105 sv::WireOp::create(builder, sv::NetType::get(src.getType()), nameTmp);
106 auto newWireRead = ReadInOutOp::create(builder, newWire);
107 auto connect = AssignOp::create(builder, newWire, src);
108 newWireRead->moveBefore(op);
109 connect->moveBefore(op);
110 op->setOperand(opNum, newWireRead);
111 }
112}
113
114// Introduces a wire to replace an output port SSA wire. If the operation
115// is in a procedural region, it creates a temporary logic, otherwise it
116// places a wire. The connecting op is inserted in the op's region.
117static void replacePortWithWire(ImplicitLocOpBuilder &builder, Operation *op,
118 Value result, StringRef name) {
119
120 bool isProcedural = op->getParentOp()->hasTrait<ProceduralRegion>();
121
122 Value newTarget;
123 if (isProcedural) {
124 newTarget = sv::VarOp::create(builder, result.getType(),
125 builder.getStringAttr(name));
126 } else {
127 newTarget =
128 sv::WireOp::create(builder, sv::NetType::get(result.getType()), name);
129 }
130
131 while (!result.use_empty()) {
132 auto newRead = sv::ReadInOutOp::create(builder, newTarget);
133 OpOperand &use = *result.getUses().begin();
134 use.set(newRead);
135 newRead->moveBefore(use.getOwner());
136 }
137
138 Operation *connect;
139 if (isProcedural) {
140 connect = sv::BPAssignOp::create(builder, newTarget, result);
141 } else {
142 connect = sv::AssignOp::create(builder, newTarget, result);
143 }
144 connect->moveAfter(op);
145}
146
147static StringAttr getResName(Operation *op, size_t idx) {
148 if (auto inst = dyn_cast<HWInstanceLike>(op))
149 return inst.getOutputName(idx);
150 return {};
151}
152
153// Ensure that each output of an instance are used only by a wire
154static void lowerInstanceResults(HWInstanceLike op) {
155 Block *block = op->getParentOfType<HWModuleOp>().getBodyBlock();
156 auto builder = ImplicitLocOpBuilder::atBlockBegin(op.getLoc(), block);
157
158 SmallString<32> nameTmp{"_", op.getInstanceName(), "_"};
159 auto namePrefixSize = nameTmp.size();
160
161 for (size_t resNum = 0, e = op->getNumResults(); resNum != e; ++resNum) {
162 auto result = op->getResult(resNum);
163
164 // If the result doesn't have a user, the connection won't be emitted by
165 // Emitter, so there's no need to create a wire for it. However, if the
166 // result is a zero bit value, the normal emission code path should be used,
167 // as zero bit values require special handling by the emitter.
168 if (result.use_empty() && !ExportVerilog::isZeroBitType(result.getType()))
169 continue;
170
171 if (result.hasOneUse()) {
172 OpOperand &use = *result.getUses().begin();
173 if (dyn_cast_or_null<OutputOp>(use.getOwner()))
174 continue;
175 if (auto assign = dyn_cast_or_null<AssignOp>(use.getOwner());
176 assign && assign->getBlock() == op->getBlock()) {
177 // Move assign op after instance to resolve cyclic dependencies.
178 assign->moveAfter(op);
179 continue;
180 }
181 }
182
183 nameTmp.resize(namePrefixSize);
184 if (auto n = getResName(op, resNum))
185 nameTmp += n.getValue().str();
186 else
187 nameTmp += std::to_string(resNum);
188 Value newWire = sv::WireOp::create(
189 builder, sv::NetType::get(result.getType()), nameTmp);
190
191 while (!result.use_empty()) {
192 auto newWireRead = ReadInOutOp::create(builder, newWire);
193 OpOperand &use = *result.getUses().begin();
194 use.set(newWireRead);
195 newWireRead->moveBefore(use.getOwner());
196 }
197
198 auto connect = AssignOp::create(builder, newWire, result);
199 connect->moveAfter(op);
200 }
201}
202
203// Ensure that each output of a function call is used only by a wire or reg.
204static void lowerFunctionCallResults(Operation *op) {
205 Block *block = op->getParentOfType<HWModuleLike>().getBodyBlock();
206 auto builder = ImplicitLocOpBuilder::atBlockBegin(op->getLoc(), block);
207 auto callee = op->getAttrOfType<FlatSymbolRefAttr>("callee");
208 assert(callee);
209 SmallString<32> nameTmp{"_", callee.getValue(), "_"};
210
211 auto namePrefixSize = nameTmp.size();
212
213 for (auto [i, result] : llvm::enumerate(op->getResults())) {
214 if (result.hasOneUse()) {
215 Operation *user = *result.getUsers().begin();
216 if (isa<BPAssignOp, AssignOp>(user)) {
217 // Move assign op after instance to resolve cyclic dependencies.
218 user->moveAfter(op);
219 continue;
220 }
221 }
222
223 nameTmp.resize(namePrefixSize);
224 // TODO: Use a result name as suffix.
225 nameTmp += std::to_string(i);
226 replacePortWithWire(builder, op, result, nameTmp);
227 }
228}
229
230/// Emit an explicit wire or logic to assign operation's result. This function
231/// is used to create a temporary to legalize a verilog expression or to
232/// resolve use-before-def in a graph region. If `emitWireAtBlockBegin` is true,
233/// a temporary wire will be created at the beginning of the block. Otherwise,
234/// a wire is created just after op's position so that we can inline the
235/// assignment into its wire declaration.
236static void lowerUsersToTemporaryWire(Operation &op,
237 bool emitWireAtBlockBegin = false) {
238 Block *block = op.getBlock();
239 auto builder = ImplicitLocOpBuilder::atBlockBegin(op.getLoc(), block);
240 bool isProceduralRegion = op.getParentOp()->hasTrait<ProceduralRegion>();
241
242 auto createWireForResult = [&](Value result, StringAttr name) {
243 Value newWire;
244 Type wireElementType = result.getType();
245 bool isResultInOut = false;
246
247 // If the result already is an InOut, make sure to not wrap it again
248 if (auto inoutType = hw::type_dyn_cast<hw::InOutType>(result.getType())) {
249 wireElementType = inoutType.getElementType();
250 isResultInOut = true;
251 } else if (auto handleElementType =
252 sv::getHandleElementType(result.getType())) {
253 wireElementType = handleElementType;
254 isResultInOut = true;
255 }
256
257 // If the op is in a procedural region, use logic op.
258 if (isProceduralRegion)
259 newWire = sv::VarOp::create(builder, wireElementType, name);
260 else
261 newWire =
262 sv::WireOp::create(builder, sv::NetType::get(wireElementType), name);
263
264 // Replace all uses with newWire. Wrap in ReadInOutOp if required.
265 while (!result.use_empty()) {
266 OpOperand &use = *result.getUses().begin();
267 if (isResultInOut) {
268 use.set(newWire);
269 } else {
270 auto newWireRead = ReadInOutOp::create(builder, newWire);
271 use.set(newWireRead);
272 newWireRead->moveBefore(use.getOwner());
273 }
274 }
275
276 // Assign the original result to the temporary wire.
277 Operation *connect;
278 ReadInOutOp resultRead;
279
280 if (isResultInOut)
281 resultRead = ReadInOutOp::create(builder, result);
282
283 if (isProceduralRegion)
284 connect = BPAssignOp::create(
285 builder, newWire, isResultInOut ? resultRead.getResult() : result);
286 else
287 connect = AssignOp::create(
288 builder, newWire, isResultInOut ? resultRead.getResult() : result);
289
290 connect->moveAfter(&op);
291 if (resultRead)
292 resultRead->moveBefore(connect);
293
294 // Move the temporary to the appropriate place.
295 if (!emitWireAtBlockBegin) {
296 // `emitWireAtBlockBegin` is intendend to be used for resovling cyclic
297 // dependencies. So when `emitWireAtBlockBegin` is true, we keep the
298 // position of the wire. Otherwise, we move the wire to immediately after
299 // the expression so that the wire and assignment are next to each other.
300 // This ordering will be used by the heurstic to inline assignments.
301 newWire.getDefiningOp()->moveAfter(&op);
302 }
303 };
304
305 // If the op has a single result, infer a meaningful name from the
306 // value.
307 if (op.getNumResults() == 1) {
308 auto namehint = inferStructuralNameForTemporary(op.getResult(0));
309 op.removeAttr("sv.namehint");
310 createWireForResult(op.getResult(0), namehint);
311 return;
312 }
313
314 // If the op has multiple results, create wires for each result.
315 for (auto result : op.getResults())
316 createWireForResult(result, StringAttr());
317}
318
319// Given a side effect free "always inline" operation, make sure that it
320// exists in the same block as its users and that it has one use for each one.
321static void lowerAlwaysInlineOperation(Operation *op,
322 const LoweringOptions &options) {
323 assert(op->getNumResults() == 1 &&
324 "only support 'always inline' ops with one result");
325
326 // Moving/cloning an op should pull along its operand tree with it if they are
327 // always inline. This happens when an array index has a constant operand for
328 // example. If the operand is not always inline, then evaluate it to see if
329 // it should be spilled to a wire.
330 auto recursivelyHandleOperands = [&](Operation *op) {
331 for (auto operand : op->getOperands()) {
332 if (auto *operandOp = operand.getDefiningOp()) {
333 if (isExpressionAlwaysInline(operandOp))
334 lowerAlwaysInlineOperation(operandOp, options);
335 else if (shouldSpillWire(*operandOp, options))
336 lowerUsersToTemporaryWire(*operandOp);
337 }
338 }
339 };
340
341 // If an operation is an assignment that immediately follows the declaration
342 // of its wire, return that wire. Otherwise return the original op. This
343 // ensures that the declaration and assignment don't get split apart by
344 // inlined operations, which allows `ExportVerilog` to trivially emit the
345 // expression inline in the declaration.
346 auto skipToWireImmediatelyBefore = [](Operation *user) {
347 if (!isa<BPAssignOp, AssignOp>(user))
348 return user;
349 auto *wireOp = user->getOperand(0).getDefiningOp();
350 if (wireOp && wireOp->getNextNode() == user)
351 return wireOp;
352 return user;
353 };
354
355 // If this operation has multiple uses, duplicate it into N-1 of them in
356 // turn.
357 while (!op->hasOneUse()) {
358 OpOperand &use = *op->getUses().begin();
359 Operation *user = skipToWireImmediatelyBefore(use.getOwner());
360
361 // Clone the op before the user.
362 auto *newOp = op->clone();
363 user->getBlock()->getOperations().insert(Block::iterator(user), newOp);
364 // Change the user to use the new op.
365 use.set(newOp->getResult(0));
366
367 // If any of the operations of the moved op are always inline, recursively
368 // handle them too.
369 recursivelyHandleOperands(newOp);
370 }
371
372 // Finally, ensures the op is in the same block as its user so it can be
373 // inlined.
374 Operation *user = skipToWireImmediatelyBefore(*op->getUsers().begin());
375 op->moveBefore(user);
376
377 // If any of the operations of the moved op are always inline, recursively
378 // move/clone them too.
379 recursivelyHandleOperands(op);
380 return;
381}
382
383// Find a nearest insertion point where logic op can be declared.
384// Logic ops are emitted as "automatic logic" in procedural regions, but
385// they must be declared at beginning of blocks.
386static std::pair<Block *, Block::iterator>
388 // We have to skip `ifdef.procedural` because it is a just macro.
389 if (isa<IfDefProceduralOp>(op->getParentOp()))
390 return findLogicOpInsertionPoint(op->getParentOp());
391 return {op->getBlock(), op->getBlock()->begin()};
392}
393
394/// Lower a variadic fully-associative operation into an expression tree. This
395/// enables long-line splitting to work with them.
396/// NOLINTNEXTLINE(misc-no-recursion)
397static Value lowerFullyAssociativeOp(Operation &op, OperandRange operands,
398 SmallVector<Operation *> &newOps) {
399 // save the top level name
400 auto name = op.getAttr("sv.namehint");
401 if (name)
402 op.removeAttr("sv.namehint");
403 Value lhs, rhs;
404 switch (operands.size()) {
405 case 0:
406 assert(0 && "cannot be called with empty operand range");
407 break;
408 case 1:
409 return operands[0];
410 case 2:
411 lhs = operands[0];
412 rhs = operands[1];
413 break;
414 default:
415 auto firstHalf = operands.size() / 2;
416 lhs = lowerFullyAssociativeOp(op, operands.take_front(firstHalf), newOps);
417 rhs = lowerFullyAssociativeOp(op, operands.drop_front(firstHalf), newOps);
418 break;
419 }
420
421 OperationState state(op.getLoc(), op.getName());
422 state.addOperands(ValueRange{lhs, rhs});
423 state.addTypes(op.getResult(0).getType());
424 auto *newOp = Operation::create(state);
425 op.getBlock()->getOperations().insert(Block::iterator(&op), newOp);
426 newOps.push_back(newOp);
427 if (name)
428 newOp->setAttr("sv.namehint", name);
429 if (auto twoState = op.getAttr("twoState"))
430 newOp->setAttr("twoState", twoState);
431 return newOp->getResult(0);
432}
433
434/// Transform "a + -cst" ==> "a - cst" for prettier output. This returns the
435/// first operation emitted.
437 hw::ConstantOp rhsCst) {
438 ImplicitLocOpBuilder builder(add.getLoc(), add);
439
440 // Get the positive constant.
441 auto negCst = hw::ConstantOp::create(builder, -rhsCst.getValue());
442 auto sub = comb::SubOp::create(builder, add.getOperand(0), negCst,
443 add.getTwoState());
444 add.getResult().replaceAllUsesWith(sub);
445 add.erase();
446 if (rhsCst.use_empty())
447 rhsCst.erase();
448 return negCst;
449}
450
451// Transforms a hw.struct_explode operation into a set of hw.struct_extract
452// operations, and returns the first op generated.
453static Operation *lowerStructExplodeOp(hw::StructExplodeOp op) {
454 Operation *firstOp = nullptr;
455 ImplicitLocOpBuilder builder(op.getLoc(), op);
456 StructType structType = cast<StructType>(op.getInput().getType());
457 for (auto [res, field] :
458 llvm::zip(op.getResults(), structType.getElements())) {
459 auto extract =
460 hw::StructExtractOp::create(builder, op.getInput(), field.name);
461 if (!firstOp)
462 firstOp = extract;
463 res.replaceAllUsesWith(extract);
464 }
465 op.erase();
466 return firstOp;
467}
468
469/// Given an operation in a procedural region, scan up the region tree to find
470/// the first operation in a graph region (typically an always or initial op).
471///
472/// By looking for a graph region, we will stop at graph-region #ifdef's that
473/// may enclose this operation.
474static Operation *findParentInNonProceduralRegion(Operation *op) {
475 Operation *parentOp = op->getParentOp();
476 assert(parentOp->hasTrait<ProceduralRegion>() &&
477 "we should only be hoisting from procedural");
478 while (parentOp->getParentOp()->hasTrait<ProceduralRegion>())
479 parentOp = parentOp->getParentOp();
480 return parentOp;
481}
482
483/// This function is invoked on side effecting Verilog expressions when we're in
484/// 'disallowLocalVariables' mode for old Verilog clients. This ensures that
485/// any side effecting expressions are only used by a single BPAssign to a
486/// sv.var or sv.logic operation. This ensures that the verilog emitter doesn't
487/// have to worry about spilling them.
488///
489/// This returns true if the op was rewritten, false otherwise.
490static bool rewriteSideEffectingExpr(Operation *op) {
491 assert(op->getNumResults() == 1 && "isn't a verilog expression");
492
493 // Check to see if this is already rewritten.
494 if (op->hasOneUse()) {
495 if (auto assign = dyn_cast<BPAssignOp>(*op->user_begin()))
496 return false;
497 }
498
499 // Otherwise, we have to transform it. Insert a reg at the top level, make
500 // everything using the side effecting expression read the reg, then assign to
501 // it after the side effecting operation.
502 Value opValue = op->getResult(0);
503
504 // Scan to the top of the region tree to find out where to insert the reg.
505 Operation *parentOp = findParentInNonProceduralRegion(op);
506 OpBuilder builder(parentOp);
507 auto reg = VarOp::create(builder, op->getLoc(), opValue.getType());
508
509 // Everything using the expr now uses a read_inout of the reg.
510 auto value = ReadInOutOp::create(builder, op->getLoc(), reg);
511 opValue.replaceAllUsesWith(value);
512
513 // We assign the side effect expr to the reg immediately after that expression
514 // is computed.
515 builder.setInsertionPointAfter(op);
516 BPAssignOp::create(builder, op->getLoc(), reg, opValue);
517 return true;
518}
519
520/// This function is called for non-side-effecting Verilog expressions when
521/// we're in 'disallowLocalVariables' mode for old Verilog clients. It hoists
522/// non-constant expressions out to the top level so they don't turn into local
523/// variable declarations.
524static bool hoistNonSideEffectExpr(Operation *op) {
525 // Never hoist "always inline" expressions except for inout stuffs - they will
526 // never generate a temporary and in fact must always be emitted inline.
527 if (isExpressionAlwaysInline(op) &&
528 !(isa<sv::ReadInOutOp>(op) ||
529 sv::getHandleElementType(op->getResult(0).getType())))
530 return false;
531
532 // Scan to the top of the region tree to find out where to move the op.
533 Operation *parentOp = findParentInNonProceduralRegion(op);
534
535 // We can typically hoist all the way out to the top level in one step, but
536 // there may be intermediate operands that aren't hoistable. If so, just
537 // hoist one level.
538 bool cantHoist = false;
539 if (llvm::any_of(op->getOperands(), [&](Value operand) -> bool {
540 // The operand value dominates the original operation, but may be
541 // defined in one of the procedural regions between the operation and
542 // the top level of the module. We can tell this quite efficiently by
543 // looking for ops in a procedural region - because procedural regions
544 // live in graph regions but not visa-versa.
545 if (BlockArgument block = dyn_cast<BlockArgument>(operand)) {
546 // References to ports are always ok.
547 if (isa<hw::HWModuleOp>(block.getParentBlock()->getParentOp()))
548 return false;
549
550 cantHoist = true;
551 return true;
552 }
553 Operation *operandOp = operand.getDefiningOp();
554
555 if (operandOp->getParentOp()->hasTrait<ProceduralRegion>()) {
556 cantHoist |= operandOp->getBlock() == op->getBlock();
557 return true;
558 }
559 return false;
560 })) {
561
562 // If the operand is in the same block as the expression then we can't hoist
563 // this out at all.
564 if (cantHoist)
565 return false;
566
567 // Otherwise, we can hoist it, but not all the way out in one step. Just
568 // hoist one level out.
569 parentOp = op->getParentOp();
570 }
571
572 op->moveBefore(parentOp);
573 return true;
574}
575
576/// Check whether an op is a declaration that can be moved.
577static bool isMovableDeclaration(Operation *op) {
578 if (op->getNumResults() != 1 ||
579 !(sv::getHandleElementType(op->getResult(0).getType()) ||
580 isa<sv::InterfaceType>(op->getResult(0).getType())))
581 return false;
582
583 // If all operands (e.g. init value) are constant, it is safe to move
584 return llvm::all_of(op->getOperands(), [](Value operand) -> bool {
585 auto *defOp = operand.getDefiningOp();
586 return !!defOp && isConstantExpression(defOp);
587 });
588}
589
590//===----------------------------------------------------------------------===//
591// EmittedExpressionStateManager
592//===----------------------------------------------------------------------===//
593
595 size_t size = 0;
599 void mergeState(const EmittedExpressionState &state) { size += state.size; }
600};
601
602/// This class handles information about AST structures of each expressions.
604 : public hw::TypeOpVisitor<EmittedExpressionStateManager,
605 EmittedExpressionState>,
606 public comb::CombinationalVisitor<EmittedExpressionStateManager,
607 EmittedExpressionState>,
608 public sv::Visitor<EmittedExpressionStateManager,
609 EmittedExpressionState> {
610public:
613
614 // Get or caluculate an emitted expression state.
616
617 bool dispatchHeuristic(Operation &op);
618
619 // Return true if the operation is worth spilling based on the expression
620 // state of the op.
621 bool shouldSpillWireBasedOnState(Operation &op);
622
623private:
626 friend class CombinationalVisitor<EmittedExpressionStateManager,
630 LLVM_DEBUG(op->emitWarning() << "unhandled by EmittedExpressionState");
631 if (op->getNumOperands() == 0)
633 return mergeOperandsStates(op);
634 }
636 return dispatchTypeOpVisitor(op);
637 }
639 return visitUnhandledExpr(op);
640 }
642 return dispatchSVVisitor(op);
643 }
645 return visitUnhandledExpr(op);
646 }
648 return visitUnhandledExpr(op);
649 }
650
651 using CombinationalVisitor::visitComb;
652 using Visitor::visitSV;
653
655
656 // A helper function to accumulate states.
658
659 // This caches the expression states in the module scope.
660 DenseMap<Value, EmittedExpressionState> expressionStates;
661};
662
665 auto it = expressionStates.find(v);
666 if (it != expressionStates.end())
667 return it->second;
668
669 // Ports.
670 if (auto blockArg = dyn_cast<BlockArgument>(v))
672
674 dispatchCombinationalVisitor(v.getDefiningOp());
675 expressionStates.insert({v, state});
676 return state;
677}
678
682 for (auto operand : op->getOperands())
683 state.mergeState(getExpressionState(operand));
684
685 return state;
686}
687
688/// If exactly one use of this op is an assign, replace the other uses with a
689/// read from the assigned wire or reg. This assumes the preconditions for doing
690/// so are met: op must be an expression in a non-procedural region.
691static bool reuseExistingInOut(Operation *op, const LoweringOptions &options) {
692 // Try to collect a single assign and all the other uses of op.
693 sv::AssignOp assign;
694 SmallVector<OpOperand *> uses;
695
696 // Look at each use.
697 for (OpOperand &use : op->getUses()) {
698 // If it's an assign, try to save it.
699 if (auto assignUse = dyn_cast<AssignOp>(use.getOwner())) {
700 // If there are multiple assigns, bail out.
701 if (assign)
702 return false;
703
704 // If the assign is not at the top level, it might be conditionally
705 // executed. So bail out.
706 if (!isa<HWModuleOp>(assignUse->getParentOp()))
707 return false;
708
709 // Remember this assign for later.
710 assign = assignUse;
711 continue;
712 }
713
714 // If not an assign, remember this use for later.
715 uses.push_back(&use);
716 }
717
718 // If we didn't find anything, bail out.
719 if (!assign || uses.empty())
720 return false;
721
722 if (auto *cop = assign.getSrc().getDefiningOp())
723 if (isa<ConstantOp>(cop))
724 return false;
725
726 // Replace all saved uses with a read from the assigned destination.
727 ImplicitLocOpBuilder builder(assign.getDest().getLoc(), op->getContext());
728 for (OpOperand *use : uses) {
729 builder.setInsertionPoint(use->getOwner());
730 auto read = ReadInOutOp::create(builder, assign.getDest());
731 use->set(read);
732 }
733 if (auto *destOp = assign.getDest().getDefiningOp())
734 if (isExpressionAlwaysInline(destOp))
735 lowerAlwaysInlineOperation(destOp, options);
736 return true;
737}
738
740 // TODO: Consider using virtual functions.
741 if (options.isWireSpillingHeuristicEnabled(
743 if (auto hint = op.getAttrOfType<StringAttr>("sv.namehint")) {
744 // Spill wires if the name doesn't have a prefix "_".
745 if (!hint.getValue().starts_with("_"))
746 return true;
747 // If the name has prefix "_", spill if the size is greater than the
748 // threshould.
749 if (getExpressionState(op.getResult(0)).size >=
750 options.wireSpillingNamehintTermLimit)
751 return true;
752 }
753
754 return false;
755}
756
757/// Return true if it is beneficial to spill the operation under the specified
758/// spilling heuristic.
760 // Don't spill wires for inout operations and simple expressions such as read
761 // or constant.
762 if (op.getNumResults() == 0 ||
763 sv::getHandleElementType(op.getResult(0).getType()) ||
764 isa<ReadInOutOp, ConstantOp>(op))
765 return false;
766
767 // If the operation is only used by an assignment, the op is already spilled
768 // to a wire.
769 if (op.hasOneUse()) {
770 auto *singleUser = *op.getUsers().begin();
771 if (isa<hw::OutputOp, sv::AssignOp, sv::BPAssignOp, hw::InstanceOp>(
772 singleUser))
773 return false;
774
775 // If the single user is bitcast, we check the same property for the bitcast
776 // op since bitcast op is no-op in system verilog.
777 if (singleUser->hasOneUse() && isa<hw::BitcastOp>(singleUser) &&
778 isa<hw::OutputOp, sv::AssignOp, sv::BPAssignOp>(
779 *singleUser->getUsers().begin()))
780 return false;
781 }
782
783 // If the term size is greater than `maximumNumberOfTermsPerExpression`,
784 // we have to spill the wire.
785 if (options.maximumNumberOfTermsPerExpression <
786 getExpressionState(op.getResult(0)).size)
787 return true;
788 return dispatchHeuristic(op);
789}
790
791/// After the legalization, we are able to know accurate verilog AST structures.
792/// So this function walks and prettifies verilog IR with a heuristic method
793/// specified by `options.wireSpillingHeuristic` based on the structures.
794/// Also move the declarations to the top of the block when
795/// `disallowDeclAssignments` is set.
797 Block &block, const LoweringOptions &options,
798 EmittedExpressionStateManager &expressionStateManager) {
799 // TODO: Handle procedural regions as well.
800 if (block.getParentOp()->hasTrait<ProceduralRegion>())
801 return;
802
803 for (auto &op : llvm::make_early_inc_range(block)) {
804 if (!isVerilogExpression(&op))
805 continue;
806 if (expressionStateManager.shouldSpillWireBasedOnState(op)) {
808 continue;
809 }
810 }
811
812 // Recursively process nested regions, and move declarations to the top of the
813 // block when `disallowDeclAssignments` is set.
814 Operation *insertionPoint = block.empty() ? nullptr : &block.front();
815 for (auto &op : llvm::make_early_inc_range(block)) {
816 // If the operations has regions, visit each of the region bodies.
817 for (auto &region : op.getRegions()) {
818 if (!region.empty())
819 prettifyAfterLegalization(region.front(), options,
820 expressionStateManager);
821 }
822
823 if (options.disallowDeclAssignments && isMovableDeclaration(&op)) {
824 op.moveBefore(insertionPoint);
825 insertionPoint = op.getNextNode();
826 }
827 }
828}
829
831 hw::WireOp wireOp;
832 Block::iterator declarePoint;
833 Block::iterator assignPoint;
834};
835
836/// Determine the insertion location of declaration and assignment ops for
837/// `hw::WireOp`s in a block. This function tries to place the declaration point
838/// as late as possible, right before the very first use of the wire. It also
839/// tries to place the assign point as early as possible, right after the
840/// assigned value becomes available.
841static void buildWireLowerings(Block &block,
842 SmallVectorImpl<WireLowering> &wireLowerings) {
843 for (auto hwWireOp : block.getOps<hw::WireOp>()) {
844 // Find the earliest point in the block at which the input operand is
845 // available. The assign operation will have to go after that to not create
846 // a use-before-def situation. In a block without a terminator, this may be
847 // the end of the block.
848 Block::iterator assignPoint = block.begin();
849 if (auto *defOp = hwWireOp.getInput().getDefiningOp())
850 if (defOp && defOp->getBlock() == &block)
851 assignPoint = ++Block::iterator(defOp);
852
853 // Find the earliest use of the wire within the block. The wire declaration
854 // will have to go somewhere before this point to not create a
855 // use-before-def situation.
856 Block::iterator declarePoint = assignPoint;
857 for (auto *user : hwWireOp->getUsers()) {
858 while (user->getBlock() != &block)
859 user = user->getParentOp();
860 if (declarePoint == block.end() || user->isBeforeInBlock(&*declarePoint))
861 declarePoint = Block::iterator(user);
862 }
863
864 wireLowerings.push_back({hwWireOp, declarePoint, assignPoint});
865 }
866}
867
868/// Materialize the SV wire declaration and assignment operations in the
869/// locations previously determined by a call to `buildWireLowerings`. This
870/// replaces all `hw::WireOp`s with their appropriate SV counterpart.
871static void applyWireLowerings(Block &block,
872 ArrayRef<WireLowering> wireLowerings) {
873 bool isProceduralRegion = block.getParentOp()->hasTrait<ProceduralRegion>();
874
875 for (auto [hwWireOp, declarePoint, assignPoint] : wireLowerings) {
876 // Create the declaration.
877 ImplicitLocOpBuilder builder(hwWireOp.getLoc(), &block, declarePoint);
878 Value decl;
879 if (isProceduralRegion) {
880 decl =
881 sv::VarOp::create(builder, hwWireOp.getType(), hwWireOp.getNameAttr(),
882 hwWireOp.getInnerSymAttr());
883 } else {
884 decl = sv::WireOp::create(builder, sv::NetType::get(hwWireOp.getType()),
885 hwWireOp.getNameAttr(),
886 hwWireOp.getInnerSymAttr());
887 }
888
889 // Carry attributes over to the lowered operation.
890 auto defaultAttrNames = hwWireOp.getAttributeNames();
891 for (auto namedAttr : hwWireOp->getAttrs())
892 if (!llvm::is_contained(defaultAttrNames, namedAttr.getName()))
893 decl.getDefiningOp()->setAttr(namedAttr.getName(),
894 namedAttr.getValue());
895
896 // Create the assignment. If it is supposed to be at a different point than
897 // the declaration, reposition the builder there. Otherwise we'll just build
898 // the assignment immediately after the declaration.
899 if (assignPoint != declarePoint)
900 builder.setInsertionPoint(&block, assignPoint);
901 if (isProceduralRegion)
902 BPAssignOp::create(builder, decl, hwWireOp.getInput());
903 else
904 AssignOp::create(builder, decl, hwWireOp.getInput());
905
906 // Create the read. If we have created the assignment at a different point
907 // than the declaration, reposition the builder to immediately after the
908 // declaration. Otherwise we'll just build the read immediately after the
909 // assignment.
910 if (assignPoint != declarePoint)
911 builder.setInsertionPointAfterValue(decl);
912 auto readOp = sv::ReadInOutOp::create(builder, decl);
913
914 // Replace the HW wire.
915 hwWireOp.replaceAllUsesWith(readOp.getResult());
916 }
917
918 for (auto [hwWireOp, declarePoint, assignPoint] : wireLowerings)
919 hwWireOp.erase();
920}
921
922/// For each module we emit, do a prepass over the structure, pre-lowering and
923/// otherwise rewriting operations we don't want to emit.
924static LogicalResult legalizeHWModule(Block &block,
925 const LoweringOptions &options) {
926
927 // First step, check any nested blocks that exist in this region. This walk
928 // can pull things out to our level of the hierarchy.
929 for (auto &op : block) {
930 // If the operations has regions, prepare each of the region bodies.
931 for (auto &region : op.getRegions()) {
932 if (!region.empty())
933 if (failed(legalizeHWModule(region.front(), options)))
934 return failure();
935 }
936 }
937
938 // Lower HW wires into SV wires in the appropriate spots. Try to put the
939 // declaration close to the first use in the block, and the assignment right
940 // after the assigned value becomes available.
941 {
942 SmallVector<WireLowering> wireLowerings;
943 buildWireLowerings(block, wireLowerings);
944 applyWireLowerings(block, wireLowerings);
945 }
946
947 // Next, walk all of the operations at this level.
948
949 // True if these operations are in a procedural region.
950 bool isProceduralRegion = block.getParentOp()->hasTrait<ProceduralRegion>();
951
952 // This tracks "always inline" operation already visited in the iterations to
953 // avoid processing same operations infinitely.
954 DenseSet<Operation *> visitedAlwaysInlineOperations;
955
956 // Debug operations to be moved to the end of the block such that they don't
957 // create unnecessary spill wires.
958 SmallVector<Operation *> debugOpsToMoveToEnd;
959
960 for (Block::iterator opIterator = block.begin(), e = block.end();
961 opIterator != e;) {
962 auto &op = *opIterator++;
963
964 if (!isa<CombDialect, SVDialect, HWDialect, ltl::LTLDialect,
965 verif::VerifDialect, debug::DebugDialect>(op.getDialect())) {
966 auto d = op.emitError() << "dialect \"" << op.getDialect()->getNamespace()
967 << "\" not supported for direct Verilog emission";
968 d.attachNote() << "ExportVerilog cannot emit this operation; it needs "
969 "to be lowered before running ExportVerilog";
970 return failure();
971 }
972
973 // Do not reorder LTL expressions, which are always emitted inline.
974 if (isa<ltl::LTLDialect>(op.getDialect()))
975 continue;
976
977 // Move debug operations to the end of the block.
978 if (isa<debug::DebugDialect>(op.getDialect())) {
979 debugOpsToMoveToEnd.push_back(&op);
980 continue;
981 }
982
983 // Name legalization should have happened in a different pass for these sv
984 // elements and we don't want to change their name through re-legalization
985 // (e.g. letting a temporary take the name of an unvisited wire). Adding
986 // them now ensures any temporary generated will not use one of the names
987 // previously declared.
988 if (auto inst = dyn_cast<HWInstanceLike>(op)) {
989 // Anchor return values to wires early
991 // Anchor ports of instances when `disallowExpressionInliningInPorts` is
992 // enabled.
995 }
996
997 if (auto call = dyn_cast<mlir::CallOpInterface>(op))
999
1000 // If a reg or logic is located in a procedural region, we have to move the
1001 // op declaration to a valid program point.
1002 if (isProceduralRegion && isa<LogicOp, RegOp, sv::VarOp>(op)) {
1003 if (options.disallowLocalVariables) {
1004 // When `disallowLocalVariables` is enabled, "automatic logic" is
1005 // prohibited so hoist the op to a non-procedural region.
1006 auto *parentOp = findParentInNonProceduralRegion(&op);
1007 op.moveBefore(parentOp);
1008 }
1009 }
1010
1011 // If the target doesn't support local variables, hoist all the expressions
1012 // out to the nearest non-procedural region.
1013 if (options.disallowLocalVariables && isVerilogExpression(&op) &&
1014 isProceduralRegion) {
1015
1016 // Force any side-effecting expressions in nested regions into a sv.var
1017 // if we aren't allowing local variable declarations. The Verilog emitter
1018 // doesn't want to have to have to know how to synthesize a reg in the
1019 // case they have to be spilled for whatever reason.
1020 if (!mlir::isMemoryEffectFree(&op)) {
1021 if (rewriteSideEffectingExpr(&op))
1022 continue;
1023 }
1024
1025 // Hoist other expressions out to the parent region.
1026 //
1027 // NOTE: This effectively disables inlining of expressions into if
1028 // conditions, $fwrite statements, and instance inputs. We could be
1029 // smarter in ExportVerilog itself, but we'd have to teach it to put
1030 // spilled expressions (due to line length, multiple-uses, and
1031 // non-inlinable expressions) in the outer scope.
1032 if (hoistNonSideEffectExpr(&op))
1033 continue;
1034 }
1035
1036 // Duplicate "always inline" expression for each of their users and move
1037 // them to be next to their users.
1038 if (isExpressionAlwaysInline(&op)) {
1039 // Nuke use-less operations.
1040 if (op.use_empty()) {
1041 op.erase();
1042 continue;
1043 }
1044 // Process the op only when the op is never processed from the top-level
1045 // loop.
1046 if (visitedAlwaysInlineOperations.insert(&op).second)
1047 lowerAlwaysInlineOperation(&op, options);
1048
1049 continue;
1050 }
1051
1052 if (auto aggregateConstantOp = dyn_cast<hw::AggregateConstantOp>(op);
1053 options.disallowPackedStructAssignments && aggregateConstantOp) {
1054 if (hw::StructType structType =
1055 type_dyn_cast<hw::StructType>(aggregateConstantOp.getType())) {
1056 // Create hw struct create op and apply the legalization again.
1057 SmallVector<Value> operands;
1058 ImplicitLocOpBuilder builder(op.getLoc(), op.getContext());
1059 builder.setInsertionPointAfter(&op);
1060 for (auto [value, field] :
1061 llvm::zip(aggregateConstantOp.getFieldsAttr(),
1062 structType.getElements())) {
1063 if (auto arrayAttr = dyn_cast<mlir::ArrayAttr>(value))
1064 operands.push_back(hw::AggregateConstantOp::create(
1065 builder, field.type, arrayAttr));
1066 else
1067 operands.push_back(hw::ConstantOp::create(
1068 builder, field.type, cast<mlir::IntegerAttr>(value)));
1069 }
1070
1071 auto structCreate =
1072 hw::StructCreateOp::create(builder, structType, operands);
1073 aggregateConstantOp.getResult().replaceAllUsesWith(structCreate);
1074 // Reset the iterator.
1075 opIterator = std::next(op.getIterator());
1076
1077 op.erase();
1078 continue;
1079 }
1080 }
1081
1082 if (auto structCreateOp = dyn_cast<hw::StructCreateOp>(op);
1083 options.disallowPackedStructAssignments && structCreateOp) {
1084 // Force packed struct assignment to be a wire + assignments to each
1085 // field.
1086 Value wireOp;
1087 ImplicitLocOpBuilder builder(op.getLoc(), &op);
1088 hw::StructType structType =
1089 cast<hw::StructType>(structCreateOp.getResult().getType());
1090 bool procedural = op.getParentOp()->hasTrait<ProceduralRegion>();
1091 if (procedural)
1092 wireOp = sv::VarOp::create(builder, structType);
1093 else
1094 wireOp = sv::WireOp::create(builder, sv::NetType::get(structType));
1095
1096 for (auto [input, field] :
1097 llvm::zip(structCreateOp.getInput(), structType.getElements())) {
1098 auto target =
1099 sv::StructFieldInOutOp::create(builder, wireOp, field.name);
1100 if (procedural)
1101 BPAssignOp::create(builder, target, input);
1102 else
1103 AssignOp::create(builder, target, input);
1104 }
1105 // Have to create a separate read for each use to keep things legal.
1106 for (auto &use :
1107 llvm::make_early_inc_range(structCreateOp.getResult().getUses()))
1108 use.set(ReadInOutOp::create(builder, wireOp));
1109
1110 structCreateOp.erase();
1111 continue;
1112 }
1113
1114 // Lower `hw.array_inject` to a temporary variable that contains a copy of
1115 // the input array, with the injected index overwritten.
1116 if (auto arrayInjectOp = dyn_cast<hw::ArrayInjectOp>(op)) {
1117 bool procedural = op.getParentOp()->hasTrait<ProceduralRegion>();
1118 ImplicitLocOpBuilder builder(op.getLoc(), &op);
1119 Value decl;
1120 if (procedural)
1121 decl = sv::VarOp::create(builder, arrayInjectOp.getType());
1122 else
1123 decl = sv::VarOp::create(builder, arrayInjectOp.getType());
1124 for (auto &use : llvm::make_early_inc_range(arrayInjectOp->getUses()))
1125 use.set(ReadInOutOp::create(builder, decl));
1126
1127 // Make sure we have a procedural region where we can first copy the input
1128 // array into `decl`, and then overwrite a single index.
1129 if (!procedural) {
1130 auto alwaysOp = sv::AlwaysCombOp::create(builder);
1131 builder.setInsertionPointToStart(alwaysOp.getBodyBlock());
1132 }
1133
1134 // Copy the input array into `decl`.
1135 sv::BPAssignOp::create(builder, decl, arrayInjectOp.getInput());
1136
1137 // Overwrite the injected value.
1138 auto target = sv::ArrayIndexInOutOp::create(builder, decl,
1139 arrayInjectOp.getIndex());
1140 sv::BPAssignOp::create(builder, target, arrayInjectOp.getElement());
1141
1142 arrayInjectOp.erase();
1143 continue;
1144 }
1145
1146 // Force array index expressions to be a simple name when the
1147 // `mitigateVivadoArrayIndexConstPropBug` option is set.
1149 isa<ArraySliceOp, ArrayGetOp, ArrayIndexInOutOp,
1150 IndexedPartSelectInOutOp, IndexedPartSelectOp>(&op)) {
1151
1152 // Check if the index expression is already a wire.
1153 Value wireOp;
1154 Value readOp;
1155 if (auto maybeReadOp =
1156 op.getOperand(1).getDefiningOp<sv::ReadInOutOp>()) {
1157 if (isa_and_nonnull<sv::WireOp, LogicOp, sv::VarOp>(
1158 maybeReadOp.getInput().getDefiningOp())) {
1159 wireOp = maybeReadOp.getInput();
1160 readOp = maybeReadOp;
1161 }
1162 }
1163
1164 // Insert a wire and read if necessary.
1165 ImplicitLocOpBuilder builder(op.getLoc(), &op);
1166 if (!wireOp) {
1167 auto type = op.getOperand(1).getType();
1168 const auto *name = "_GEN_ARRAY_IDX";
1169 if (op.getParentOp()->hasTrait<ProceduralRegion>()) {
1170 wireOp =
1171 sv::VarOp::create(builder, type, builder.getStringAttr(name));
1172 BPAssignOp::create(builder, wireOp, op.getOperand(1));
1173 } else {
1174 wireOp = sv::WireOp::create(builder, sv::NetType::get(type), name);
1175 AssignOp::create(builder, wireOp, op.getOperand(1));
1176 }
1177 readOp = ReadInOutOp::create(builder, wireOp);
1178 }
1179 op.setOperand(1, readOp);
1180
1181 // Add a `(* keep = "true" *)` SV attribute to the wire.
1182 sv::addSVAttributes(wireOp.getDefiningOp(),
1183 SVAttributeAttr::get(wireOp.getContext(), "keep",
1184 R"("true")",
1185 /*emitAsComment=*/false));
1186 continue;
1187 }
1188
1189 // If this expression is deemed worth spilling into a wire, do it here.
1190 if (shouldSpillWire(op, options)) {
1191 // We first check that it is possible to reuse existing wires as a spilled
1192 // wire. Otherwise, create a new wire op.
1193 if (isProceduralRegion || !reuseExistingInOut(&op, options)) {
1194 if (options.disallowLocalVariables) {
1195 // If we're not in a procedural region, or we are, but we can hoist
1196 // out of it, we are good to generate a wire.
1197 if (!isProceduralRegion ||
1198 (isProceduralRegion && hoistNonSideEffectExpr(&op))) {
1199 // If op is moved to a non-procedural region, create a temporary
1200 // wire.
1201 if (!op.getParentOp()->hasTrait<ProceduralRegion>())
1203
1204 // If we're in a procedural region, we move on to the next op in the
1205 // block. The expression splitting and canonicalization below will
1206 // happen after we recurse back up. If we're not in a procedural
1207 // region, the expression can continue being worked on.
1208 if (isProceduralRegion)
1209 continue;
1210 }
1211 } else {
1212 // If `disallowLocalVariables` is not enabled, we can spill the
1213 // expression to automatic logic declarations even when the op is in a
1214 // procedural region.
1216 }
1217 }
1218 }
1219
1220 // Lower variadic fully-associative operations with more than two operands
1221 // into balanced operand trees so we can split long lines across multiple
1222 // statements. Variadic and full-associative operations with only one
1223 // operand are replaced with its operand.
1224 // TODO: This is checking the Commutative property, which doesn't seem
1225 // right in general. MLIR doesn't have a "fully associative" property.
1226 if (op.getNumOperands() != 2 && op.getNumResults() == 1 &&
1227 op.hasTrait<mlir::OpTrait::IsCommutative>() &&
1228 mlir::isMemoryEffectFree(&op) && op.getNumRegions() == 0 &&
1229 op.getNumSuccessors() == 0 &&
1230 llvm::all_of(op.getAttrs(), [](NamedAttribute attr) {
1231 return attr.getNameDialect() != nullptr ||
1232 attr.getName() == "twoState";
1233 })) {
1234 // Lower this operation to a balanced binary tree of the same operation.
1235 SmallVector<Operation *> newOps;
1236 auto result = lowerFullyAssociativeOp(op, op.getOperands(), newOps);
1237 op.getResult(0).replaceAllUsesWith(result);
1238 op.erase();
1239
1240 // Make sure we revisit the newly inserted operations.
1241 if (!newOps.empty())
1242 opIterator = Block::iterator(newOps.front());
1243 continue;
1244 }
1245
1246 // Turn a + -cst ==> a - cst
1247 if (auto addOp = dyn_cast<comb::AddOp>(op)) {
1248 if (auto cst = addOp.getOperand(1).getDefiningOp<hw::ConstantOp>()) {
1249 assert(addOp.getNumOperands() == 2 && "commutative lowering is done");
1250 if (cst.getValue().isNegative()) {
1251 Operation *firstOp = rewriteAddWithNegativeConstant(addOp, cst);
1252 opIterator = Block::iterator(firstOp);
1253 continue;
1254 }
1255 }
1256 }
1257
1258 // Lower hw.struct_explode ops into a set of hw.struct_extract ops which
1259 // have well-defined SV emission semantics.
1260 if (auto structExplodeOp = dyn_cast<hw::StructExplodeOp>(op)) {
1261 Operation *firstOp = lowerStructExplodeOp(structExplodeOp);
1262 opIterator = Block::iterator(firstOp);
1263 continue;
1264 }
1265
1266 // Try to anticipate expressions that ExportVerilog may spill to a temporary
1267 // inout, and re-use an existing inout when possible. This is legal when op
1268 // is an expression in a non-procedural region.
1269 if (!isProceduralRegion && isVerilogExpression(&op))
1270 (void)reuseExistingInOut(&op, options);
1271 }
1272
1273 // Move debug operations to the end of the block.
1274 auto debugBuilder = OpBuilder::atBlockEnd(&block);
1275 if (!block.empty() && block.back().mightHaveTrait<OpTrait::IsTerminator>())
1276 debugBuilder.setInsertionPoint(&block.back());
1277 for (auto *op : debugOpsToMoveToEnd) {
1278 op->remove();
1279 debugBuilder.insert(op);
1280 }
1281
1282 if (isProceduralRegion) {
1283 // If there is no operation, there is nothing to do.
1284 if (block.empty())
1285 return success();
1286
1287 // In a procedural region, logic operations needs to be top of blocks so
1288 // mvoe logic operations to valid program points.
1289
1290 // This keeps tracks of an insertion point of logic op.
1291 std::pair<Block *, Block::iterator> logicOpInsertionPoint =
1292 findLogicOpInsertionPoint(&block.front());
1293 for (auto &op : llvm::make_early_inc_range(block)) {
1294 if (isa<LogicOp, VarOp>(op)) {
1295 // If the logic op is already located at the given point, increment the
1296 // iterator to keep the order of logic operations in the block.
1297 if (logicOpInsertionPoint.second == op.getIterator()) {
1298 ++logicOpInsertionPoint.second;
1299 continue;
1300 }
1301 // Otherwise, move the op to the insertion point.
1302 op.moveBefore(logicOpInsertionPoint.first,
1303 logicOpInsertionPoint.second);
1304 }
1305 }
1306 return success();
1307 }
1308
1309 // Now that all the basic ops are settled, check for any use-before def issues
1310 // in graph regions. Lower these into explicit wires to keep the emitter
1311 // simple.
1312
1313 SmallPtrSet<Operation *, 32> seenOperations;
1314
1315 for (auto &op : llvm::make_early_inc_range(block)) {
1316 // Do not reorder LTL expressions, which are always emitted inline. Ignore
1317 // debug operations which are not emitted as Verilog.
1318 if (isa<ltl::LTLDialect, debug::DebugDialect>(op.getDialect()))
1319 continue;
1320
1321 // Check the users of any expressions to see if they are
1322 // lexically below the operation itself. If so, it is being used out
1323 // of order.
1324 bool haveAnyOutOfOrderUses = false;
1325 for (auto *userOp : op.getUsers()) {
1326 // If the user is in a suboperation like an always block, then zip up
1327 // to the operation that uses it.
1328 while (&block != &userOp->getParentRegion()->front())
1329 userOp = userOp->getParentOp();
1330
1331 if (seenOperations.count(userOp)) {
1332 haveAnyOutOfOrderUses = true;
1333 break;
1334 }
1335 }
1336
1337 // Remember that we've seen this operation.
1338 seenOperations.insert(&op);
1339
1340 // If all the uses of the operation are below this, then we're ok.
1341 if (!haveAnyOutOfOrderUses)
1342 continue;
1343
1344 // If this is a reg/wire declaration, then we move it to the top of the
1345 // block. We can't abstract the inout result.
1346 if (isMovableDeclaration(&op)) {
1347 op.moveBefore(&block.front());
1348 continue;
1349 }
1350
1351 // If this is a constant, then we move it to the top of the block.
1352 if (isConstantExpression(&op)) {
1353 op.moveBefore(&block.front());
1354 continue;
1355 }
1356
1357 // If this is a an operation reading from a declaration, move it up,
1358 // along with the corresponding declaration.
1359 if (auto readInOut = dyn_cast<ReadInOutOp>(op)) {
1360 auto *def = readInOut.getInput().getDefiningOp();
1361 if (isMovableDeclaration(def)) {
1362 op.moveBefore(&block.front());
1363 def->moveBefore(&block.front());
1364 continue;
1365 }
1366 }
1367
1368 // Otherwise, we need to lower this to a wire to resolve this.
1370 /*emitWireAtBlockBegin=*/true);
1371 }
1372 return success();
1373}
1374
1375static void fixUpEmptyModules(hw::HWEmittableModuleLike module) {
1376 auto outputOp = dyn_cast<hw::OutputOp>(module.getBodyBlock()->begin());
1377 if (!outputOp || outputOp->getNumOperands() > 0)
1378 return; // Not empty so no need to fix up.
1379 OpBuilder builder(module->getContext());
1380 builder.setInsertionPoint(outputOp);
1381 auto constant = hw::ConstantOp::create(builder, module.getLoc(),
1382 builder.getBoolAttr(true));
1383 auto wire = sv::WireOp::create(builder, module.getLoc(),
1384 sv::NetType::get(builder.getI1Type()));
1385 sv::setSVAttributes(wire,
1386 sv::SVAttributeAttr::get(
1387 builder.getContext(),
1388 "This wire is added to avoid emitting empty modules. "
1389 "See `fixUpEmptyModules` lowering option in CIRCT.",
1390 /*emitAsComment=*/true));
1391 sv::AssignOp::create(builder, module.getLoc(), wire, constant);
1392}
1393
1394// NOLINTNEXTLINE(misc-no-recursion)
1395LogicalResult ExportVerilog::prepareHWModule(hw::HWEmittableModuleLike module,
1396 const LoweringOptions &options) {
1397 // If the module body is empty, just skip it.
1398 if (!module.getBodyBlock())
1399 return success();
1400
1401 // Zero-valued logic pruning.
1402 pruneZeroValuedLogic(module);
1403
1404 // Fix up empty modules if necessary.
1405 if (options.fixUpEmptyModules)
1406 fixUpEmptyModules(module);
1407
1408 // Legalization.
1409 if (failed(legalizeHWModule(*module.getBodyBlock(), options)))
1410 return failure();
1411
1412 EmittedExpressionStateManager expressionStateManager(options);
1413 // Spill wires to prettify verilog outputs.
1414 prettifyAfterLegalization(*module.getBodyBlock(), options,
1415 expressionStateManager);
1416
1417 return success();
1418}
1419
1420namespace {
1421
1422struct PrepareForEmissionPass
1423 : public circt::impl::PrepareForEmissionBase<PrepareForEmissionPass> {
1424
1425 bool canScheduleOn(mlir::RegisteredOperationName opName) const final {
1426 return opName.hasInterface<hw::HWEmittableModuleLike>();
1427 }
1428
1429 void runOnOperation() override {
1430 auto module = cast<hw::HWEmittableModuleLike>(getOperation());
1431 LoweringOptions options(cast<mlir::ModuleOp>(module->getParentOp()));
1432 if (failed(prepareHWModule(module, options)))
1433 signalPassFailure();
1434 }
1435};
1436
1437} // end anonymous namespace
assert(baseType &&"element must be base type")
false return failure()
Parse an optional keyword or string and set instance into 'result'.
if(parseOptionalKeywordOrOptionalString(parser, result.rawName, found)) return failure()
return success()
static Operation * lowerStructExplodeOp(hw::StructExplodeOp op)
static Operation * findParentInNonProceduralRegion(Operation *op)
Given an operation in a procedural region, scan up the region tree to find the first operation in a g...
static Operation * rewriteAddWithNegativeConstant(comb::AddOp add, hw::ConstantOp rhsCst)
Transform "a + -cst" ==> "a - cst" for prettier output.
static void fixUpEmptyModules(hw::HWEmittableModuleLike module)
static void lowerUsersToTemporaryWire(Operation &op, bool emitWireAtBlockBegin=false)
Emit an explicit wire or logic to assign operation's result.
static StringAttr getResName(Operation *op, size_t idx)
static void prettifyAfterLegalization(Block &block, const LoweringOptions &options, EmittedExpressionStateManager &expressionStateManager)
After the legalization, we are able to know accurate verilog AST structures.
static bool rewriteSideEffectingExpr(Operation *op)
This function is invoked on side effecting Verilog expressions when we're in 'disallowLocalVariables'...
static void buildWireLowerings(Block &block, SmallVectorImpl< WireLowering > &wireLowerings)
Determine the insertion location of declaration and assignment ops for hw::WireOps in a block.
static StringAttr getArgName(Operation *op, size_t idx)
static void lowerFunctionCallResults(Operation *op)
static void spillWiresForInstanceInputs(HWInstanceLike op)
static void lowerInstanceResults(HWInstanceLike op)
static bool hoistNonSideEffectExpr(Operation *op)
This function is called for non-side-effecting Verilog expressions when we're in 'disallowLocalVariab...
static void lowerAlwaysInlineOperation(Operation *op, const LoweringOptions &options)
static void replacePortWithWire(ImplicitLocOpBuilder &builder, Operation *op, Value result, StringRef name)
static bool reuseExistingInOut(Operation *op, const LoweringOptions &options)
If exactly one use of this op is an assign, replace the other uses with a read from the assigned wire...
static std::pair< Block *, Block::iterator > findLogicOpInsertionPoint(Operation *op)
static bool isMovableDeclaration(Operation *op)
Check whether an op is a declaration that can be moved.
static LogicalResult legalizeHWModule(Block &block, const LoweringOptions &options)
For each module we emit, do a prepass over the structure, pre-lowering and otherwise rewriting operat...
static Value lowerFullyAssociativeOp(Operation &op, OperandRange operands, SmallVector< Operation * > &newOps)
Lower a variadic fully-associative operation into an expression tree.
static bool shouldSpillWire(Operation &op, const LoweringOptions &options)
static void applyWireLowerings(Block &block, ArrayRef< WireLowering > wireLowerings)
Materialize the SV wire declaration and assignment operations in the locations previously determined ...
static Block * getBodyBlock(FModuleLike mod)
This class handles information about AST structures of each expressions.
DenseMap< Value, EmittedExpressionState > expressionStates
EmittedExpressionState visitUnhandledSV(Operation *op)
EmittedExpressionStateManager(const LoweringOptions &options)
EmittedExpressionState visitInvalidComb(Operation *op)
EmittedExpressionState visitUnhandledTypeOp(Operation *op)
EmittedExpressionState getExpressionState(Value value)
EmittedExpressionState visitUnhandledComb(Operation *op)
EmittedExpressionState mergeOperandsStates(Operation *op)
EmittedExpressionState visitUnhandledExpr(Operation *op)
bool shouldSpillWireBasedOnState(Operation &op)
Return true if it is beneficial to spill the operation under the specified spilling heuristic.
EmittedExpressionState visitInvalidTypeOp(Operation *op)
Signals that an operation's regions are procedural.
This helps visit TypeOp nodes.
Definition HWVisitors.h:25
create(data_type, value)
Definition hw.py:433
create(elements, Type result_type=None)
Definition hw.py:547
create(struct_value, str field_name)
Definition hw.py:571
create(dest, src)
Definition sv.py:135
create(value)
Definition sv.py:151
create(data_type, name=None, sym_name=None)
Definition sv.py:125
create(data_type, name=None, sym_name=None)
Definition sv.py:63
LogicalResult prepareHWModule(Block &block, const LoweringOptions &options)
For each module we emit, do a prepass over the structure, pre-lowering and otherwise rewriting operat...
void pruneZeroValuedLogic(hw::HWEmittableModuleLike module)
bool isExpressionEmittedInline(Operation *op, const LoweringOptions &options)
Return true if this expression should be emitted inline into any statement that uses it.
bool isVerilogExpression(Operation *op)
This predicate returns true if the specified operation is considered a potentially inlinable Verilog ...
StringAttr inferStructuralNameForTemporary(Value expr)
Given an expression that is spilled into a temporary wire, try to synthesize a better name than "_T_4...
static bool isConstantExpression(Operation *op)
Return whether an operation is a constant.
bool isZeroBitType(Type type)
Return true if this is a zero bit type, e.g.
bool isSimpleReadOrPort(Value v)
Check if the value is from read of a wire or reg or is a port.
static bool isExpressionAlwaysInline(Operation *op)
Return true for operations that must always be inlined into a containing expression for correctness.
BaseTy type_dyn_cast(Type type)
Definition HWTypes.h:234
The InstanceGraph op interface, see InstanceGraphInterface.td for more details.
Definition comb.py:1
Definition hw.py:1
Definition sv.py:1
static EmittedExpressionState getBaseState()
void mergeState(const EmittedExpressionState &state)
Block::iterator declarePoint
Block::iterator assignPoint
Options which control the emission from CIRCT to Verilog.
bool mitigateVivadoArrayIndexConstPropBug
If true, every expression used as an array index is driven by a wire, and the wire is marked as (* ke...
bool disallowLocalVariables
If true, do not emit SystemVerilog locally scoped "automatic" or logic declarations - emit top level ...
bool disallowExpressionInliningInPorts
If true, every expression passed to an instance port is driven by a wire.
bool fixUpEmptyModules
If true, add a dummy wire to empty modules to prevent tools from regarding the module as blackbox.
bool disallowPackedStructAssignments
If true, eliminate packed struct assignments in favor of a wire + assignments to the individual field...