CIRCT 23.0.0git
Loading...
Searching...
No Matches
LowerState.cpp
Go to the documentation of this file.
1//===- LowerState.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
18#include "mlir/Analysis/TopologicalSortUtils.h"
19#include "mlir/Dialect/Func/IR/FuncOps.h"
20#include "mlir/Dialect/LLVMIR/LLVMAttrs.h"
21#include "mlir/Dialect/LLVMIR/LLVMDialect.h"
22#include "mlir/Dialect/SCF/IR/SCF.h"
23#include "mlir/IR/IRMapping.h"
24#include "mlir/IR/ImplicitLocOpBuilder.h"
25#include "mlir/IR/SymbolTable.h"
26#include "mlir/Interfaces/SideEffectInterfaces.h"
27#include "mlir/Pass/Pass.h"
28#include "llvm/ADT/TypeSwitch.h"
29#include "llvm/Support/Debug.h"
30
31#define DEBUG_TYPE "arc-lower-state"
32
33namespace circt {
34namespace arc {
35#define GEN_PASS_DEF_LOWERSTATEPASS
36#include "circt/Dialect/Arc/ArcPasses.h.inc"
37} // namespace arc
38} // namespace circt
39
40using namespace circt;
41using namespace arc;
42using namespace hw;
43using namespace mlir;
44using llvm::SmallDenseSet;
45
46namespace {
47enum class Phase { Initial, Old, New, Final };
48
49template <class OS>
50OS &operator<<(OS &os, Phase phase) {
51 switch (phase) {
52 case Phase::Initial:
53 return os << "initial";
54 case Phase::Old:
55 return os << "old";
56 case Phase::New:
57 return os << "new";
58 case Phase::Final:
59 return os << "final";
60 }
61}
62
63struct ModuleLowering;
64
65/// All state associated with lowering a single operation. Instances of this
66/// struct are kept on a worklist to perform a depth-first traversal of the
67/// module being lowered.
68///
69/// The actual lowering occurs in `lower()`. This function is called exactly
70/// twice. A first time with `initial` being true, where other values and
71/// operations that have to be lowered first may be marked with `addPending`. No
72/// actual lowering or error reporting should occur when `initial` is true. The
73/// worklist then ensures that all `pending` ops are lowered before `lower()` is
74/// called a second time with `initial` being false. At this point the actual
75/// lowering and error reporting should occur.
76///
77/// The `initial` variable is used to allow for a single block of code to mark
78/// values and ops as dependencies and actually do the lowering based on them.
79struct OpLowering {
80 Operation *op;
81 Phase phase;
82 ModuleLowering &module;
83
84 bool initial = true;
85 SmallVector<std::pair<Operation *, Phase>, 2> pending;
86
87 OpLowering(Operation *op, Phase phase, ModuleLowering &module)
88 : op(op), phase(phase), module(module) {}
89
90 // Operation Lowering.
91 LogicalResult lower();
92 LogicalResult lowerDefault();
93 LogicalResult lower(StateOp op);
94 LogicalResult lower(sim::DPICallOp op);
95 LogicalResult
96 lowerStateful(Value clock, Value enable, Value reset, ValueRange inputs,
97 ResultRange results,
98 llvm::function_ref<ValueRange(ValueRange)> createMapping);
99 LogicalResult lower(MemoryOp op);
100 LogicalResult lower(TapOp op);
101 LogicalResult lower(InstanceOp op);
102 LogicalResult lower(hw::OutputOp op);
103 LogicalResult lower(seq::InitialOp op);
104 LogicalResult lower(llhd::FinalOp op);
105 LogicalResult lower(llhd::CurrentTimeOp op);
106 LogicalResult lower(sim::ClockedTerminateOp op);
107
108 scf::IfOp createIfClockOp(Value clock);
109
110 // Value Lowering. These functions are called from the `lower()` functions
111 // above. They handle values used by the `op`. This can generate reads from
112 // state and memory storage on-the-fly, or mark other ops as dependencies to
113 // be lowered first.
114 Value lowerValue(Value value, Phase phase);
115 Value lowerValue(InstanceOp op, OpResult result, Phase phase);
116 Value lowerValue(StateOp op, OpResult result, Phase phase);
117 Value lowerValue(sim::DPICallOp op, OpResult result, Phase phase);
118 Value lowerValue(MemoryReadPortOp op, OpResult result, Phase phase);
119 Value lowerValue(seq::InitialOp op, OpResult result, Phase phase);
120 Value lowerValue(seq::FromImmutableOp op, OpResult result, Phase phase);
121
122 void addPending(Value value, Phase phase);
123 void addPending(Operation *op, Phase phase);
124};
125
126/// All state associated with lowering a single module.
127struct ModuleLowering {
128 /// The module being lowered.
129 HWModuleOp moduleOp;
130 /// The builder for the main body of the model.
131 OpBuilder builder;
132 /// The builder for state allocation ops.
133 OpBuilder allocBuilder;
134 /// The builder for the initial phase.
135 OpBuilder initialBuilder;
136 /// The builder for the final phase.
137 OpBuilder finalBuilder;
138
139 /// The storage value that can be used for `arc.alloc_state` and friends.
140 Value storageArg;
141
142 /// A worklist of pending op lowerings.
143 SmallVector<OpLowering> opsWorklist;
144 /// The set of ops currently in the worklist. Used to detect cycles.
145 SmallDenseSet<std::pair<Operation *, Phase>> opsSeen;
146 /// The ops that have already been lowered.
147 DenseSet<std::pair<Operation *, Phase>> loweredOps;
148 /// The values that have already been lowered.
149 DenseMap<std::pair<Value, Phase>, Value> loweredValues;
150
151 /// The allocated input ports.
152 SmallVector<Value> allocatedInputs;
153 /// The allocated states as a mapping from op results to `arc.alloc_state`
154 /// results.
155 DenseMap<Value, Value> allocatedStates;
156 /// The allocated storage for instance inputs and top module outputs.
157 DenseMap<OpOperand *, Value> allocatedOutputs;
158 /// The allocated storage for values computed during the initial phase.
159 DenseMap<Value, Value> allocatedInitials;
160 /// The allocated storage for taps.
161 DenseMap<Operation *, Value> allocatedTaps;
162
163 /// A mapping from unlowered clocks to a value indicating a posedge. This is
164 /// used to not create an excessive number of posedge detectors.
165 DenseMap<Value, Value> loweredPosedges;
166 /// The previous enable and the value it was lowered to. This is used to reuse
167 /// previous if ops for the same enable value.
168 std::pair<Value, Value> prevEnable;
169 /// The previous reset and the value it was lowered to. This is used to reuse
170 /// previous if ops for the same reset value.
171 std::pair<Value, Value> prevReset;
172
173 ModuleLowering(HWModuleOp moduleOp)
174 : moduleOp(moduleOp), builder(moduleOp), allocBuilder(moduleOp),
175 initialBuilder(moduleOp), finalBuilder(moduleOp) {}
176 LogicalResult run();
177 LogicalResult lowerOp(Operation *op);
178 Value getAllocatedState(OpResult result);
179 Value detectPosedge(Value clock);
180 OpBuilder &getBuilder(Phase phase);
181 Value requireLoweredValue(Value value, Phase phase, Location useLoc);
182};
183} // namespace
184
185//===----------------------------------------------------------------------===//
186// Module Lowering
187//===----------------------------------------------------------------------===//
188
189LogicalResult ModuleLowering::run() {
190 LLVM_DEBUG(llvm::dbgs() << "Lowering module `" << moduleOp.getModuleName()
191 << "`\n");
192
193 // Create the replacement `ModelOp`.
194 auto modelOp =
195 ModelOp::create(builder, moduleOp.getLoc(), moduleOp.getModuleNameAttr(),
196 TypeAttr::get(moduleOp.getModuleType()),
197 FlatSymbolRefAttr{}, FlatSymbolRefAttr{}, ArrayAttr{});
198 auto &modelBlock = modelOp.getBody().emplaceBlock();
199 storageArg = modelBlock.addArgument(
200 StorageType::get(builder.getContext(), {}), modelOp.getLoc());
201 builder.setInsertionPointToStart(&modelBlock);
202
203 // Create the `arc.initial` op to contain the ops for the initialization
204 // phase.
205 auto initialOp = InitialOp::create(builder, moduleOp.getLoc());
206 initialBuilder.setInsertionPointToStart(&initialOp.getBody().emplaceBlock());
207
208 // Create the `arc.final` op to contain the ops for the finalization phase.
209 auto finalOp = FinalOp::create(builder, moduleOp.getLoc());
210 finalBuilder.setInsertionPointToStart(&finalOp.getBody().emplaceBlock());
211
212 // Position the alloc builder such that allocation ops get inserted above the
213 // initial op.
214 allocBuilder.setInsertionPoint(initialOp);
215
216 // Allocate storage for the inputs.
217 for (auto arg : moduleOp.getBodyBlock()->getArguments()) {
218 auto name = moduleOp.getArgName(arg.getArgNumber());
219 auto state =
220 RootInputOp::create(allocBuilder, arg.getLoc(),
221 StateType::get(arg.getType()), name, storageArg);
222 allocatedInputs.push_back(state);
223 }
224
225 // Lower the ops.
226 for (auto &op : moduleOp.getOps()) {
227 if (mlir::isMemoryEffectFree(&op) &&
228 !isa<hw::OutputOp, sim::ClockedTerminateOp>(op))
229 continue;
230 if (isa<MemoryReadPortOp, MemoryWritePortOp>(op))
231 continue; // handled as part of `MemoryOp`
232 if (failed(lowerOp(&op)))
233 return failure();
234 }
235
236 // Clean up any dead ops. The lowering inserts a few defensive
237 // `arc.state_read` ops that may remain unused. This cleans them up.
238 for (auto &op : llvm::make_early_inc_range(llvm::reverse(modelBlock)))
239 if (mlir::isOpTriviallyDead(&op))
240 op.erase();
241
242 return success();
243}
244
245/// Lower an op and its entire fan-in cone.
246LogicalResult ModuleLowering::lowerOp(Operation *op) {
247 LLVM_DEBUG(llvm::dbgs() << "- Handling " << *op << "\n");
248
249 // Pick in which phases the given operation has to perform some work.
250 SmallVector<Phase, 2> phases = {Phase::New};
251 if (isa<seq::InitialOp>(op))
252 phases = {Phase::Initial};
253 if (isa<llhd::FinalOp>(op))
254 phases = {Phase::Final};
255 if (isa<StateOp>(op))
256 phases = {Phase::Initial, Phase::New};
257
258 for (auto phase : phases) {
259 if (loweredOps.contains({op, phase}))
260 return success();
261 opsWorklist.push_back(OpLowering(op, phase, *this));
262 opsSeen.insert({op, phase});
263 }
264
265 auto dumpWorklist = [&] {
266 for (auto &opLowering : llvm::reverse(opsWorklist))
267 opLowering.op->emitRemark()
268 << "computing " << opLowering.phase << " phase here";
269 };
270
271 while (!opsWorklist.empty()) {
272 auto &opLowering = opsWorklist.back();
273
274 // Collect an initial list of operands that need to be lowered.
275 if (opLowering.initial) {
276 if (failed(opLowering.lower())) {
277 dumpWorklist();
278 return failure();
279 }
280 std::reverse(opLowering.pending.begin(), opLowering.pending.end());
281 opLowering.initial = false;
282 }
283
284 // Push operands onto the worklist.
285 if (!opLowering.pending.empty()) {
286 auto [defOp, phase] = opLowering.pending.pop_back_val();
287 if (loweredOps.contains({defOp, phase}))
288 continue;
289 if (!opsSeen.insert({defOp, phase}).second) {
290 defOp->emitOpError("is on a combinational loop");
291 dumpWorklist();
292 return failure();
293 }
294 opsWorklist.push_back(OpLowering(defOp, phase, *this));
295 continue;
296 }
297
298 // At this point all operands are available and the op itself can be
299 // lowered.
300 LLVM_DEBUG(llvm::dbgs() << " - Lowering " << opLowering.phase << " "
301 << *opLowering.op << "\n");
302 if (failed(opLowering.lower())) {
303 dumpWorklist();
304 return failure();
305 }
306 loweredOps.insert({opLowering.op, opLowering.phase});
307 opsSeen.erase({opLowering.op, opLowering.phase});
308 opsWorklist.pop_back();
309 }
310
311 return success();
312}
313
314/// Return the `arc.alloc_state` associated with the given state op result.
315/// Creates the allocation op if it does not yet exist.
316Value ModuleLowering::getAllocatedState(OpResult result) {
317 if (auto alloc = allocatedStates.lookup(result))
318 return alloc;
319
320 // Handle memories.
321 if (auto memOp = dyn_cast<MemoryOp>(result.getOwner())) {
322 auto alloc =
323 AllocMemoryOp::create(allocBuilder, memOp.getLoc(), memOp.getType(),
324 storageArg, memOp->getAttrs());
325 allocatedStates.insert({result, alloc});
326 return alloc;
327 }
328
329 // Create the allocation op.
330 auto alloc =
331 AllocStateOp::create(allocBuilder, result.getLoc(),
332 StateType::get(result.getType()), storageArg);
333 allocatedStates.insert({result, alloc});
334
335 // HACK: If the result comes from an instance op, add the instance and port
336 // name as an attribute to the allocation. This will make it show up in the C
337 // headers later. Get rid of this once we have proper debug dialect support.
338 if (auto instOp = dyn_cast<InstanceOp>(result.getOwner()))
339 alloc->setAttr(
340 "name", builder.getStringAttr(
341 instOp.getInstanceName() + "/" +
342 instOp.getOutputName(result.getResultNumber()).getValue()));
343
344 // HACK: If the result comes from an op that has a "names" attribute, use that
345 // as a name for the allocation. This should no longer be necessary once we
346 // properly support the Debug dialect.
347 if (isa<StateOp, sim::DPICallOp>(result.getOwner()))
348 if (auto names = result.getOwner()->getAttrOfType<ArrayAttr>("names"))
349 if (result.getResultNumber() < names.size())
350 alloc->setAttr("name", names[result.getResultNumber()]);
351
352 return alloc;
353}
354
355/// Allocate the necessary storage, reads, writes, and comparisons to detect a
356/// rising edge on a clock value.
357Value ModuleLowering::detectPosedge(Value clock) {
358 auto loc = clock.getLoc();
359 if (isa<seq::ClockType>(clock.getType()))
360 clock = seq::FromClockOp::create(builder, loc, clock);
361
362 // Allocate storage to store the previous clock value.
363 auto oldStorage = AllocStateOp::create(
364 allocBuilder, loc, StateType::get(builder.getI1Type()), storageArg);
365
366 // Read the old clock value from storage and write the new clock value to
367 // storage.
368 auto oldClock = StateReadOp::create(builder, loc, oldStorage);
369 StateWriteOp::create(builder, loc, oldStorage, clock, Value{});
370
371 // Detect a rising edge.
372 auto edge = comb::XorOp::create(builder, loc, oldClock, clock);
373 return comb::AndOp::create(builder, loc, edge, clock);
374}
375
376/// Get the builder appropriate for the given phase.
377OpBuilder &ModuleLowering::getBuilder(Phase phase) {
378 switch (phase) {
379 case Phase::Initial:
380 return initialBuilder;
381 case Phase::Old:
382 case Phase::New:
383 return builder;
384 case Phase::Final:
385 return finalBuilder;
386 }
387}
388
389/// Get the lowered value, or emit a diagnostic and return null.
390Value ModuleLowering::requireLoweredValue(Value value, Phase phase,
391 Location useLoc) {
392 if (auto lowered = loweredValues.lookup({value, phase}))
393 return lowered;
394 auto d = emitError(value.getLoc()) << "value has not been lowered";
395 d.attachNote(useLoc) << "value used here";
396 return {};
397}
398
399//===----------------------------------------------------------------------===//
400// Operation Lowering
401//===----------------------------------------------------------------------===//
402
403/// Create a new `scf.if` operation with the given builder, or reuse a previous
404/// `scf.if` if the builder's insertion point is located right after it.
405static scf::IfOp createOrReuseIf(OpBuilder &builder, Value condition,
406 bool withElse) {
407 if (auto ip = builder.getInsertionPoint(); ip != builder.getBlock()->begin())
408 if (auto ifOp = dyn_cast<scf::IfOp>(*std::prev(ip)))
409 if (ifOp.getCondition() == condition)
410 return ifOp;
411 return scf::IfOp::create(builder, condition.getLoc(), condition, withElse);
412}
413
414/// This function is called from the lowering worklist in order to perform a
415/// depth-first traversal of the surrounding module. These functions call
416/// `lowerValue` to mark their operands as dependencies in the depth-first
417/// traversal, and to map them to the lowered value in one go.
418LogicalResult OpLowering::lower() {
419 return TypeSwitch<Operation *, LogicalResult>(op)
420 // Operations with special lowering.
421 .Case<StateOp, sim::DPICallOp, MemoryOp, TapOp, InstanceOp, hw::OutputOp,
422 seq::InitialOp, llhd::FinalOp, llhd::CurrentTimeOp,
423 sim::ClockedTerminateOp>([&](auto op) { return lower(op); })
424
425 // Operations that should be skipped entirely and never land on the
426 // worklist to be lowered.
427 .Case<MemoryWritePortOp, MemoryReadPortOp>([&](auto op) {
428 assert(false && "ports must be lowered by memory op");
429 return failure();
430 })
431
432 // All other ops are simply cloned into the lowered model.
433 .Default([&](auto) { return lowerDefault(); });
434}
435
436/// Called for all operations for which there is no special lowering. Simply
437/// clones the operation.
438LogicalResult OpLowering::lowerDefault() {
439 // Make sure that all operand values are lowered first.
440 IRMapping mapping;
441 auto anyFailed = false;
442 op->walk([&](Operation *nestedOp) {
443 for (auto operand : nestedOp->getOperands()) {
444 if (op->isAncestor(operand.getParentBlock()->getParentOp()))
445 continue;
446 auto lowered = lowerValue(operand, phase);
447 if (!lowered)
448 anyFailed = true;
449 mapping.map(operand, lowered);
450 }
451 });
452 if (initial)
453 return success();
454 if (anyFailed)
455 return failure();
456
457 // Clone the operation.
458 auto *clonedOp = module.getBuilder(phase).clone(*op, mapping);
459
460 // Keep track of the results.
461 for (auto [oldResult, newResult] :
462 llvm::zip(op->getResults(), clonedOp->getResults()))
463 module.loweredValues[{oldResult, phase}] = newResult;
464
465 return success();
466}
467
468/// Lower a state to a corresponding storage allocation and `write` of the
469/// state's new value to it. This function uses the `Old` phase to get the
470/// values at the state input before the current update, and then uses them to
471/// compute the `New` value.
472LogicalResult OpLowering::lower(StateOp op) {
473 // Handle initialization.
474 if (phase == Phase::Initial) {
475 // Ensure the initial values of the register have been lowered before.
476 if (initial) {
477 for (auto initial : op.getInitials())
478 lowerValue(initial, Phase::Initial);
479 return success();
480 }
481
482 // Write the initial values to the allocated storage in the initial block.
483 if (op.getInitials().empty())
484 return success();
485 for (auto [initial, result] :
486 llvm::zip(op.getInitials(), op.getResults())) {
487 auto value = lowerValue(initial, Phase::Initial);
488 if (!value)
489 return failure();
490 auto state = module.getAllocatedState(result);
491 if (!state)
492 return failure();
493 StateWriteOp::create(module.initialBuilder, value.getLoc(), state, value,
494 Value{});
495 }
496 return success();
497 }
498
499 assert(phase == Phase::New);
500
501 if (!initial) {
502 if (!op.getClock())
503 return op.emitOpError() << "must have a clock";
504 if (op.getLatency() > 1)
505 return op.emitOpError("latencies > 1 not supported yet");
506 }
507
508 return lowerStateful(op.getClock(), op.getEnable(), op.getReset(),
509 op.getInputs(), op.getResults(), [&](ValueRange inputs) {
510 return CallOp::create(module.builder, op.getLoc(),
511 op.getResultTypes(), op.getArc(),
512 inputs)
513 .getResults();
514 });
515}
516
517/// Lower a DPI call to a corresponding storage allocation and write of the
518/// state's new value to it. This function uses the `Old` phase to get the
519/// values at the state input before the current update, and then uses them to
520/// compute the `New` value.
521LogicalResult OpLowering::lower(sim::DPICallOp op) {
522 // Handle unclocked DPI calls.
523 if (!op.getClock()) {
524 // Make sure that all operands have been lowered.
525 SmallVector<Value> inputs;
526 for (auto operand : op.getInputs())
527 inputs.push_back(lowerValue(operand, phase));
528 if (initial)
529 return success();
530 if (llvm::is_contained(inputs, Value{}))
531 return failure();
532 if (op.getEnable())
533 return op.emitOpError() << "without clock cannot have an enable";
534
535 // Lower the op to a regular function call.
536 auto callOp =
537 func::CallOp::create(module.getBuilder(phase), op.getLoc(),
538 op.getCalleeAttr(), op.getResultTypes(), inputs);
539 for (auto [oldResult, newResult] :
540 llvm::zip(op.getResults(), callOp.getResults()))
541 module.loweredValues[{oldResult, phase}] = newResult;
542 return success();
543 }
544
545 assert(phase == Phase::New);
546
547 return lowerStateful(op.getClock(), op.getEnable(), /*reset=*/{},
548 op.getInputs(), op.getResults(), [&](ValueRange inputs) {
549 return func::CallOp::create(
550 module.builder, op.getLoc(),
551 op.getCalleeAttr(), op.getResultTypes(),
552 inputs)
553 .getResults();
554 });
555}
556
557/// Lower a state to a corresponding storage allocation and `write` of the
558/// state's new value to it. This function uses the `Old` phase to get the
559/// values at the state input before the current update, and then uses them to
560/// compute the `New` value.
561LogicalResult OpLowering::lowerStateful(
562 Value clock, Value enable, Value reset, ValueRange inputs,
563 ResultRange results,
564 llvm::function_ref<ValueRange(ValueRange)> createMapping) {
565 // Ensure all operands are lowered before we lower the op itself. State ops
566 // are special in that they require the "old" value of their inputs and
567 // enable, in order to compute the updated "new" value. The clock needs to be
568 // the "new" value though, such that other states can act as a clock source.
569 if (initial) {
570 lowerValue(clock, Phase::New);
571 if (enable)
572 lowerValue(enable, Phase::Old);
573 if (reset)
574 lowerValue(reset, Phase::Old);
575 for (auto input : inputs)
576 lowerValue(input, Phase::Old);
577 return success();
578 }
579
580 // Check if we're inserting right after an `if` op for the same clock edge, in
581 // which case we can reuse that op. Otherwise, create the new `if` op.
582 auto ifClockOp = createIfClockOp(clock);
583 if (!ifClockOp)
584 return failure();
585 OpBuilder::InsertionGuard guard(module.builder);
586 module.builder.setInsertionPoint(ifClockOp.thenYield());
587
588 // Make sure we have the state storage available such that we can read and
589 // write from and to them.
590 SmallVector<Value> states;
591 for (auto result : results) {
592 auto state = module.getAllocatedState(result);
593 if (!state)
594 return failure();
595 states.push_back(state);
596 }
597
598 // Handle the reset.
599 if (reset) {
600 // Check if we can reuse a previous reset value.
601 auto &[unloweredReset, loweredReset] = module.prevReset;
602 if (unloweredReset != reset ||
603 loweredReset.getParentBlock() != module.builder.getBlock()) {
604 unloweredReset = reset;
605 loweredReset = lowerValue(reset, Phase::Old);
606 if (!loweredReset)
607 return failure();
608 }
609
610 // Check if we're inserting right after an if op for the same reset, in
611 // which case we can reuse that op. Otherwise create the new if op.
612 auto ifResetOp = createOrReuseIf(module.builder, loweredReset, true);
613 module.builder.setInsertionPoint(ifResetOp.thenYield());
614
615 // Generate the zero value writes.
616 for (auto state : states) {
617 auto type = cast<StateType>(state.getType()).getType();
618 Value value = ConstantOp::create(
619 module.builder, loweredReset.getLoc(),
620 module.builder.getIntegerType(hw::getBitWidth(type)), 0);
621 if (value.getType() != type)
622 value = BitcastOp::create(module.builder, loweredReset.getLoc(), type,
623 value);
624 StateWriteOp::create(module.builder, loweredReset.getLoc(), state, value,
625 Value{});
626 }
627 module.builder.setInsertionPoint(ifResetOp.elseYield());
628 }
629
630 // Handle the enable.
631 if (enable) {
632 // Check if we can reuse a previous enable value.
633 auto &[unloweredEnable, loweredEnable] = module.prevEnable;
634 if (unloweredEnable != enable ||
635 loweredEnable.getParentBlock() != module.builder.getBlock()) {
636 unloweredEnable = enable;
637 loweredEnable = lowerValue(enable, Phase::Old);
638 if (!loweredEnable)
639 return failure();
640 }
641
642 // Check if we're inserting right after an if op for the same enable, in
643 // which case we can reuse that op. Otherwise create the new if op.
644 auto ifEnableOp = createOrReuseIf(module.builder, loweredEnable, false);
645 module.builder.setInsertionPoint(ifEnableOp.thenYield());
646 }
647
648 // Get the transfer function inputs. This potentially inserts read ops.
649 SmallVector<Value> loweredInputs;
650 for (auto input : inputs) {
651 auto lowered = lowerValue(input, Phase::Old);
652 if (!lowered)
653 return failure();
654 loweredInputs.push_back(lowered);
655 }
656
657 // Compute the transfer function and write its results to the state's storage.
658 auto loweredResults = createMapping(loweredInputs);
659 for (auto [state, value] : llvm::zip(states, loweredResults))
660 StateWriteOp::create(module.builder, value.getLoc(), state, value, Value{});
661
662 // Since we just wrote the new state value to storage, insert read ops just
663 // before the if op that keep the old value around for any later ops that
664 // still need it.
665 module.builder.setInsertionPoint(ifClockOp);
666 for (auto [state, result] : llvm::zip(states, results)) {
667 auto oldValue = StateReadOp::create(module.builder, result.getLoc(), state);
668 module.loweredValues[{result, Phase::Old}] = oldValue;
669 }
670
671 return success();
672}
673
674/// Lower a memory and its read and write ports to corresponding
675/// `arc.memory_write` operations. Reads are also executed at this point and
676/// stored in `loweredValues` for later operations to pick up.
677LogicalResult OpLowering::lower(MemoryOp op) {
678 assert(phase == Phase::New);
679
680 // Collect all the reads and writes.
681 SmallVector<MemoryReadPortOp> reads;
682 SmallVector<MemoryWritePortOp> writes;
683
684 for (auto *user : op->getUsers()) {
685 if (auto read = dyn_cast<MemoryReadPortOp>(user)) {
686 reads.push_back(read);
687 } else if (auto write = dyn_cast<MemoryWritePortOp>(user)) {
688 writes.push_back(write);
689 } else {
690 auto d = op.emitOpError()
691 << "users must all be memory read or write port ops";
692 d.attachNote(user->getLoc())
693 << "but found " << user->getName() << " user here";
694 return d;
695 }
696 }
697
698 // Ensure all operands are lowered before we lower the memory itself.
699 if (initial) {
700 for (auto read : reads)
701 lowerValue(read, Phase::Old);
702 for (auto write : writes) {
703 if (write.getClock())
704 lowerValue(write.getClock(), Phase::New);
705 for (auto input : write.getInputs())
706 lowerValue(input, Phase::Old);
707 }
708 return success();
709 }
710
711 // Get the allocated storage for the memory.
712 auto state = module.getAllocatedState(op->getResult(0));
713
714 // Since we are going to write new values into storage, insert read ops that
715 // keep the old values around for any later ops that still need them.
716 for (auto read : reads) {
717 auto oldValue = lowerValue(read, Phase::Old);
718 if (!oldValue)
719 return failure();
720 module.loweredValues[{read, Phase::Old}] = oldValue;
721 }
722
723 // Lower the writes.
724 for (auto write : writes) {
725 if (!write.getClock())
726 return write.emitOpError() << "must have a clock";
727 if (write.getLatency() > 1)
728 return write.emitOpError("latencies > 1 not supported yet");
729
730 // Create the if op for the clock edge.
731 auto ifClockOp = createIfClockOp(write.getClock());
732 if (!ifClockOp)
733 return failure();
734 OpBuilder::InsertionGuard guard(module.builder);
735 module.builder.setInsertionPoint(ifClockOp.thenYield());
736
737 // Call the arc that computes the address, data, and enable.
738 SmallVector<Value> inputs;
739 for (auto input : write.getInputs()) {
740 auto lowered = lowerValue(input, Phase::Old);
741 if (!lowered)
742 return failure();
743 inputs.push_back(lowered);
744 }
745 auto callOp =
746 CallOp::create(module.builder, write.getLoc(),
747 write.getArcResultTypes(), write.getArc(), inputs);
748
749 // If the write has an enable, wrap the remaining logic in an if op.
750 if (write.getEnable()) {
751 auto ifEnableOp = createOrReuseIf(
752 module.builder, callOp.getResult(write.getEnableIdx()), false);
753 module.builder.setInsertionPoint(ifEnableOp.thenYield());
754 }
755
756 // If the write is masked, read the current
757 // value in the memory and merge it with the updated value.
758 auto address = callOp.getResult(write.getAddressIdx());
759 auto data = callOp.getResult(write.getDataIdx());
760 if (write.getMask()) {
761 auto mask = callOp.getResult(write.getMaskIdx(write.getEnable()));
762 auto maskInv = module.builder.createOrFold<comb::XorOp>(
763 write.getLoc(), mask,
764 ConstantOp::create(module.builder, write.getLoc(), mask.getType(),
765 -1),
766 true);
767 auto oldData =
768 MemoryReadOp::create(module.builder, write.getLoc(), state, address);
769 auto oldMasked = comb::AndOp::create(module.builder, write.getLoc(),
770 maskInv, oldData, true);
771 auto newMasked =
772 comb::AndOp::create(module.builder, write.getLoc(), mask, data, true);
773 data = comb::OrOp::create(module.builder, write.getLoc(), oldMasked,
774 newMasked, true);
775 }
776
777 // Actually write to the memory.
778 MemoryWriteOp::create(module.builder, write.getLoc(), state, address,
779 Value{}, data);
780 }
781
782 return success();
783}
784
785/// Lower a tap by allocating state storage for it and writing the current value
786/// observed by the tap to it.
787LogicalResult OpLowering::lower(TapOp op) {
788 assert(phase == Phase::New);
789
790 auto value = lowerValue(op.getValue(), phase);
791 if (initial)
792 return success();
793 if (!value)
794 return failure();
795
796 auto &state = module.allocatedTaps[op];
797 if (!state) {
798 auto alloc = AllocStateOp::create(module.allocBuilder, op.getLoc(),
799 StateType::get(value.getType()),
800 module.storageArg, true);
801 alloc->setAttr("names", op.getNamesAttr());
802 state = alloc;
803 }
804 StateWriteOp::create(module.builder, op.getLoc(), state, value, Value{});
805 return success();
806}
807
808/// Lower an instance by allocating state storage for each of its inputs and
809/// writing the current value into that storage. This makes instance inputs
810/// behave like outputs of the top-level module.
811LogicalResult OpLowering::lower(InstanceOp op) {
812 assert(phase == Phase::New);
813
814 // Get the current values flowing into the instance's inputs.
815 SmallVector<Value> values;
816 for (auto operand : op.getOperands())
817 values.push_back(lowerValue(operand, Phase::New));
818 if (initial)
819 return success();
820 if (llvm::is_contained(values, Value{}))
821 return failure();
822
823 // Then allocate storage for each instance input and assign the corresponding
824 // value.
825 for (auto [value, name] : llvm::zip(values, op.getArgNames())) {
826 auto state = AllocStateOp::create(module.allocBuilder, value.getLoc(),
827 StateType::get(value.getType()),
828 module.storageArg);
829 state->setAttr("name", module.builder.getStringAttr(
830 op.getInstanceName() + "/" +
831 cast<StringAttr>(name).getValue()));
832 StateWriteOp::create(module.builder, value.getLoc(), state, value, Value{});
833 }
834
835 // HACK: Also ensure that storage has been allocated for all outputs.
836 // Otherwise only the actually used instance outputs would be allocated, which
837 // would make the optimization user-visible. Remove this once we use the debug
838 // dialect.
839 for (auto result : op.getResults())
840 module.getAllocatedState(result);
841
842 return success();
843}
844
845/// Lower the main module's outputs by allocating storage for each and then
846/// writing the current value into that storage.
847LogicalResult OpLowering::lower(hw::OutputOp op) {
848 assert(phase == Phase::New);
849
850 // First get the current value of all outputs.
851 SmallVector<Value> values;
852 for (auto operand : op.getOperands())
853 values.push_back(lowerValue(operand, Phase::New));
854 if (initial)
855 return success();
856 if (llvm::is_contained(values, Value{}))
857 return failure();
858
859 // Then allocate storage for each output and assign the corresponding value.
860 for (auto [value, name] :
861 llvm::zip(values, module.moduleOp.getOutputNames())) {
862 auto state = RootOutputOp::create(
863 module.allocBuilder, value.getLoc(), StateType::get(value.getType()),
864 cast<StringAttr>(name), module.storageArg);
865 StateWriteOp::create(module.builder, value.getLoc(), state, value, Value{});
866 }
867 return success();
868}
869
870/// Lower `seq.initial` ops by inlining them into the `arc.initial` op.
871LogicalResult OpLowering::lower(seq::InitialOp op) {
872 assert(phase == Phase::Initial);
873
874 // First get the initial value of all operands.
875 SmallVector<Value> operands;
876 for (auto operand : op.getOperands())
877 operands.push_back(lowerValue(operand, Phase::Initial));
878 if (initial)
879 return success();
880 if (llvm::is_contained(operands, Value{}))
881 return failure();
882
883 // Expose the `seq.initial` operands as values for the block arguments.
884 for (auto [arg, operand] : llvm::zip(op.getBody().getArguments(), operands))
885 module.loweredValues[{arg, Phase::Initial}] = operand;
886
887 // Lower each op in the body. We maintain a mapping from original values
888 // defined in the body to their cloned counterparts.
889 IRMapping bodyMapping;
890 auto *initialBlock = module.initialBuilder.getBlock();
891
892 // Pre-lower all llhd.current_time ops inside the body. This reuses the
893 // existing lower(llhd::CurrentTimeOp) logic which handles Phase::Initial
894 // by replacing with constant 0 time.
895 auto result = op.walk([&](llhd::CurrentTimeOp timeOp) {
896 if (failed(lower(timeOp)))
897 return WalkResult::interrupt();
898 auto loweredTime = module.loweredValues.lookup({timeOp.getResult(), phase});
899 timeOp.replaceAllUsesWith(loweredTime);
900 timeOp.erase();
901 return WalkResult::advance();
902 });
903 if (result.wasInterrupted())
904 return failure();
905
906 for (auto &bodyOp : op.getOps()) {
907 if (isa<seq::YieldOp>(bodyOp))
908 continue;
909
910 // Clone the operation.
911 auto *clonedOp = module.initialBuilder.clone(bodyOp, bodyMapping);
912 auto result = clonedOp->walk([&](Operation *nestedClonedOp) {
913 for (auto &operand : nestedClonedOp->getOpOperands()) {
914 // Skip operands defined within the cloned tree.
915 if (clonedOp->isAncestor(operand.get().getParentBlock()->getParentOp()))
916 continue;
917 // Skip operands defined within the initial block (e.g., results of
918 // previously lowered ops like our zeroTime).
919 if (auto *defOp = operand.get().getDefiningOp())
920 if (defOp->getBlock() == initialBlock)
921 continue;
922 auto value = module.requireLoweredValue(operand.get(), Phase::Initial,
923 nestedClonedOp->getLoc());
924 if (!value)
925 return WalkResult::interrupt();
926 operand.set(value);
927 }
928 return WalkResult::advance();
929 });
930 if (result.wasInterrupted())
931 return failure();
932
933 // Keep track of the results in both mappings.
934 for (auto [result, lowered] :
935 llvm::zip(bodyOp.getResults(), clonedOp->getResults())) {
936 bodyMapping.map(result, lowered);
937 module.loweredValues[{result, Phase::Initial}] = lowered;
938 }
939 }
940
941 // Expose the operands of `seq.yield` as results from the initial op.
942 auto *terminator = op.getBodyBlock()->getTerminator();
943 for (auto [result, operand] :
944 llvm::zip(op.getResults(), terminator->getOperands())) {
945 auto value = module.requireLoweredValue(operand, Phase::Initial,
946 terminator->getLoc());
947 if (!value)
948 return failure();
949 module.loweredValues[{result, Phase::Initial}] = value;
950 }
951
952 return success();
953}
954
955/// Lower `llhd.final` ops into `scf.execute_region` ops in the `arc.final` op.
956LogicalResult OpLowering::lower(llhd::FinalOp op) {
957 assert(phase == Phase::Final);
958
959 // Determine the uses of values defined outside the op.
960 SmallVector<Value> externalOperands;
961 op.walk([&](Operation *nestedOp) {
962 for (auto value : nestedOp->getOperands())
963 if (!op->isAncestor(value.getParentBlock()->getParentOp()))
964 externalOperands.push_back(value);
965 });
966
967 // Make sure that all uses of external values are lowered first.
968 IRMapping mapping;
969 for (auto operand : externalOperands) {
970 auto lowered = lowerValue(operand, Phase::Final);
971 if (!initial && !lowered)
972 return failure();
973 mapping.map(operand, lowered);
974 }
975 if (initial)
976 return success();
977
978 // Pre-lower all llhd.current_time ops inside the body. This reuses the
979 // existing lower(llhd::CurrentTimeOp) logic which handles Phase::Final
980 // by replacing with arc.current_time.
981 auto result = op.walk([&](llhd::CurrentTimeOp timeOp) {
982 if (failed(lower(timeOp)))
983 return WalkResult::interrupt();
984 auto loweredTime = module.loweredValues.lookup({timeOp.getResult(), phase});
985 timeOp.replaceAllUsesWith(loweredTime);
986 timeOp.erase();
987 return WalkResult::advance();
988 });
989 if (result.wasInterrupted())
990 return failure();
991
992 // Handle the simple case where the final op contains only one block, which we
993 // can inline directly.
994 if (op.getBody().hasOneBlock()) {
995 for (auto &bodyOp : op.getBody().front().without_terminator())
996 module.finalBuilder.clone(bodyOp, mapping);
997 return success();
998 }
999
1000 // Create a new `scf.execute_region` op and clone the entire `llhd.final` body
1001 // region into it. Replace `llhd.halt` ops with `scf.yield`.
1002 auto executeOp = scf::ExecuteRegionOp::create(module.finalBuilder,
1003 op.getLoc(), TypeRange{});
1004 module.finalBuilder.cloneRegionBefore(op.getBody(), executeOp.getRegion(),
1005 executeOp.getRegion().begin(), mapping);
1006 executeOp.walk([&](llhd::HaltOp haltOp) {
1007 auto builder = OpBuilder(haltOp);
1008 scf::YieldOp::create(builder, haltOp.getLoc());
1009 haltOp.erase();
1010 });
1011
1012 return success();
1013}
1014
1015/// Lower `llhd.current_time` based on the current phase:
1016/// - Phase::Initial: Replace with constant 0 time.
1017/// - Phase::Old, Phase::New, Phase::Final: Replace with `arc.current_time`
1018/// followed by `llhd.int_to_time`.
1019LogicalResult OpLowering::lower(llhd::CurrentTimeOp op) {
1020 if (initial)
1021 return success();
1022
1023 auto loc = op.getLoc();
1024 Value time;
1025
1026 switch (phase) {
1027 case Phase::Initial: {
1028 // During initialization, time is always 0.
1029 auto zeroInt = hw::ConstantOp::create(
1030 module.initialBuilder, loc, module.initialBuilder.getI64Type(), 0);
1031 time = llhd::IntToTimeOp::create(module.initialBuilder, loc, zeroInt);
1032 break;
1033 }
1034 case Phase::Old:
1035 case Phase::New:
1036 case Phase::Final: {
1037 // Get the current time from storage.
1038 auto &builder = module.getBuilder(phase);
1039 auto timeInt = CurrentTimeOp::create(builder, loc, module.storageArg);
1040 time = llhd::IntToTimeOp::create(builder, loc, timeInt);
1041 break;
1042 }
1043 }
1044
1045 module.loweredValues[{op.getResult(), phase}] = time;
1046 return success();
1047}
1048
1049LogicalResult OpLowering::lower(sim::ClockedTerminateOp op) {
1050 if (phase != Phase::New)
1051 return success();
1052
1053 if (initial)
1054 return success();
1055
1056 auto ifClockOp = createIfClockOp(op.getClock());
1057 if (!ifClockOp)
1058 return failure();
1059
1060 OpBuilder::InsertionGuard guard(module.builder);
1061 module.builder.setInsertionPoint(ifClockOp.thenYield());
1062
1063 auto loc = op.getLoc();
1064 Value cond = lowerValue(op.getCondition(), phase);
1065 if (!cond)
1066 return op.emitOpError("Failed to lower condition");
1067
1068 auto ifOp = createOrReuseIf(module.builder, cond, false);
1069 if (!ifOp)
1070 return op.emitOpError("Failed to create condition block");
1071
1072 module.builder.setInsertionPoint(ifOp.thenYield());
1073
1074 arc::TerminateOp::create(module.builder, loc, module.storageArg,
1075 op.getSuccessAttr());
1076
1077 return success();
1078}
1079
1080/// Create the operations necessary to detect a posedge on the given clock,
1081/// potentially reusing a previous posedge detection, and create an `scf.if`
1082/// operation for that posedge. This also tries to reuse an `scf.if` operation
1083/// immediately before the builder's insertion point if possible.
1084scf::IfOp OpLowering::createIfClockOp(Value clock) {
1085 auto &posedge = module.loweredPosedges[clock];
1086 if (!posedge) {
1087 auto loweredClock = lowerValue(clock, Phase::New);
1088 if (!loweredClock)
1089 return {};
1090 posedge = module.detectPosedge(loweredClock);
1091 }
1092 return createOrReuseIf(module.builder, posedge, false);
1093}
1094
1095//===----------------------------------------------------------------------===//
1096// Value Lowering
1097//===----------------------------------------------------------------------===//
1098
1099/// Lower a value being used by the current operation. This will mark the
1100/// defining operation as to be lowered first (through `addPending`) in most
1101/// cases. Some operations and values have special handling though. For example,
1102/// states and memory reads are immediately materialized as a new read op.
1103Value OpLowering::lowerValue(Value value, Phase phase) {
1104 // Handle module inputs. They read the same in all phases.
1105 if (auto arg = dyn_cast<BlockArgument>(value)) {
1106 if (initial)
1107 return {};
1108 auto state = module.allocatedInputs[arg.getArgNumber()];
1109 return StateReadOp::create(module.getBuilder(phase), arg.getLoc(), state);
1110 }
1111
1112 // Check if the value has already been lowered.
1113 if (auto lowered = module.loweredValues.lookup({value, phase}))
1114 return lowered;
1115
1116 // At this point the value is the result of an op. (Block arguments are
1117 // handled above.)
1118 auto result = cast<OpResult>(value);
1119 auto *op = result.getOwner();
1120
1121 // Special handling for some ops.
1122 if (auto instOp = dyn_cast<InstanceOp>(op))
1123 return lowerValue(instOp, result, phase);
1124 if (auto stateOp = dyn_cast<StateOp>(op))
1125 return lowerValue(stateOp, result, phase);
1126 if (auto dpiOp = dyn_cast<sim::DPICallOp>(op); dpiOp && dpiOp.getClock())
1127 return lowerValue(dpiOp, result, phase);
1128 if (auto readOp = dyn_cast<MemoryReadPortOp>(op))
1129 return lowerValue(readOp, result, phase);
1130 if (auto initialOp = dyn_cast<seq::InitialOp>(op))
1131 return lowerValue(initialOp, result, phase);
1132 if (auto castOp = dyn_cast<seq::FromImmutableOp>(op))
1133 return lowerValue(castOp, result, phase);
1134
1135 // Otherwise we mark the defining operation as to be lowered first. This will
1136 // cause the lookup in `loweredValues` above to return a value the next time
1137 // (i.e. when initial is false).
1138 if (initial) {
1139 addPending(op, phase);
1140 return {};
1141 }
1142 emitError(result.getLoc()) << "value has not been lowered";
1143 return {};
1144}
1145
1146/// Handle instance outputs. They behave essentially like a top-level module
1147/// input, and read the same in all phases.
1148Value OpLowering::lowerValue(InstanceOp op, OpResult result, Phase phase) {
1149 if (initial)
1150 return {};
1151 auto state = module.getAllocatedState(result);
1152 return StateReadOp::create(module.getBuilder(phase), result.getLoc(), state);
1153}
1154
1155/// Handle uses of a state. This creates an `arc.state_read` op to read from the
1156/// state's storage. If the new value after all updates is requested, marks the
1157/// state as to be lowered first (which will perform the writes). If the old
1158/// value is requested, asserts that no new values have been written.
1159Value OpLowering::lowerValue(StateOp op, OpResult result, Phase phase) {
1160 if (initial) {
1161 // Ensure that the new or initial value has been written by the lowering of
1162 // the state op before we attempt to read it.
1163 if (phase == Phase::New || phase == Phase::Initial)
1164 addPending(op, phase);
1165 return {};
1166 }
1167
1168 // If we want to read the old value, no writes must have been lowered yet.
1169 if (phase == Phase::Old)
1170 assert(!module.loweredOps.contains({op, Phase::New}) &&
1171 "need old value but new value already written");
1172
1173 auto state = module.getAllocatedState(result);
1174 return StateReadOp::create(module.getBuilder(phase), result.getLoc(), state);
1175}
1176
1177/// Handle uses of a DPI call. This creates an `arc.state_read` op to read from
1178/// the state's storage. If the new value after all updates is requested, marks
1179/// the state as to be lowered first (which will perform the writes). If the old
1180/// value is requested, asserts that no new values have been written.
1181Value OpLowering::lowerValue(sim::DPICallOp op, OpResult result, Phase phase) {
1182 if (initial) {
1183 // Ensure that the new or initial value has been written by the lowering of
1184 // the state op before we attempt to read it.
1185 if (phase == Phase::New || phase == Phase::Initial)
1186 addPending(op, phase);
1187 return {};
1188 }
1189
1190 // If we want to read the old value, no writes must have been lowered yet.
1191 if (phase == Phase::Old)
1192 assert(!module.loweredOps.contains({op, Phase::New}) &&
1193 "need old value but new value already written");
1194
1195 auto state = module.getAllocatedState(result);
1196 return StateReadOp::create(module.getBuilder(phase), result.getLoc(), state);
1197}
1198
1199/// Handle uses of a memory read operation. This creates an `arc.memory_read` op
1200/// to read from the memory's storage. Similar to the `StateOp` handling
1201/// otherwise.
1202Value OpLowering::lowerValue(MemoryReadPortOp op, OpResult result,
1203 Phase phase) {
1204 auto memOp = op.getMemory().getDefiningOp<MemoryOp>();
1205 if (!memOp) {
1206 if (!initial)
1207 op->emitOpError() << "memory must be defined locally";
1208 return {};
1209 }
1210
1211 auto address = lowerValue(op.getAddress(), phase);
1212 if (initial) {
1213 // Ensure that all new values are written before we attempt to read them.
1214 if (phase == Phase::New)
1215 addPending(memOp.getOperation(), Phase::New);
1216 return {};
1217 }
1218 if (!address)
1219 return {};
1220
1221 if (phase == Phase::Old) {
1222 // If we want to read the old value, no writes must have been lowered yet.
1223 assert(!module.loweredOps.contains({memOp, Phase::New}) &&
1224 "need old memory value but new value already written");
1225 } else {
1226 assert(phase == Phase::New);
1227 }
1228
1229 auto state = module.getAllocatedState(memOp->getResult(0));
1230 return MemoryReadOp::create(module.getBuilder(phase), result.getLoc(), state,
1231 address);
1232}
1233
1234/// Handle uses of `seq.initial` values computed during the initial phase. This
1235/// ensures that the interesting value is stored into storage during the initial
1236/// phase, and then reads it back using an `arc.state_read` op.
1237Value OpLowering::lowerValue(seq::InitialOp op, OpResult result, Phase phase) {
1238 // Ensure the op has been lowered first.
1239 if (initial) {
1240 addPending(op, Phase::Initial);
1241 return {};
1242 }
1243 auto value = module.loweredValues.lookup({result, Phase::Initial});
1244 if (!value) {
1245 emitError(result.getLoc()) << "value has not been lowered";
1246 return {};
1247 }
1248
1249 // If we are using the value of `seq.initial` in the initial phase directly,
1250 // there is no need to write it so any temporary storage.
1251 if (phase == Phase::Initial)
1252 return value;
1253
1254 // If necessary, allocate storage for the computed value and store it in the
1255 // initial phase.
1256 auto &state = module.allocatedInitials[result];
1257 if (!state) {
1258 state = AllocStateOp::create(module.allocBuilder, value.getLoc(),
1259 StateType::get(value.getType()),
1260 module.storageArg);
1261 OpBuilder::InsertionGuard guard(module.initialBuilder);
1262 module.initialBuilder.setInsertionPointAfterValue(value);
1263 StateWriteOp::create(module.initialBuilder, value.getLoc(), state, value,
1264 Value{});
1265 }
1266
1267 // Read back the value computed during the initial phase.
1268 return StateReadOp::create(module.getBuilder(phase), state.getLoc(), state);
1269}
1270
1271/// The `seq.from_immutable` cast is just a passthrough.
1272Value OpLowering::lowerValue(seq::FromImmutableOp op, OpResult result,
1273 Phase phase) {
1274 return lowerValue(op.getInput(), phase);
1275}
1276
1277/// Mark a value as to be lowered before the current op.
1278void OpLowering::addPending(Value value, Phase phase) {
1279 auto *defOp = value.getDefiningOp();
1280 assert(defOp && "block args should never be marked as a dependency");
1281 addPending(defOp, phase);
1282}
1283
1284/// Mark an operation as to be lowered before the current op. This adds that
1285/// operation to the `pending` list if the operation has not yet been lowered.
1286void OpLowering::addPending(Operation *op, Phase phase) {
1287 auto pair = std::make_pair(op, phase);
1288 if (!module.loweredOps.contains(pair))
1289 if (!llvm::is_contained(pending, pair))
1290 pending.push_back(pair);
1291}
1292
1293//===----------------------------------------------------------------------===//
1294// Pass Infrastructure
1295//===----------------------------------------------------------------------===//
1296
1297namespace {
1298struct LowerStatePass : public arc::impl::LowerStatePassBase<LowerStatePass> {
1299 using LowerStatePassBase::LowerStatePassBase;
1300 void runOnOperation() override;
1301};
1302} // namespace
1303
1304void LowerStatePass::runOnOperation() {
1305 auto op = getOperation();
1306 for (auto moduleOp : llvm::make_early_inc_range(op.getOps<HWModuleOp>())) {
1307 if (failed(ModuleLowering(moduleOp).run()))
1308 return signalPassFailure();
1309 moduleOp.erase();
1310 }
1311
1312 SymbolTable symbolTable(op);
1313 for (auto extModuleOp :
1314 llvm::make_early_inc_range(op.getOps<HWModuleExternOp>())) {
1315 // Make sure that we're not leaving behind a dangling reference to this
1316 // module
1317 auto uses = symbolTable.getSymbolUses(extModuleOp, op);
1318 if (!uses->empty()) {
1319 extModuleOp->emitError("Failed to remove external module because it is "
1320 "still referenced/instantiated");
1321 return signalPassFailure();
1322 }
1323 extModuleOp.erase();
1324 }
1325}
assert(baseType &&"element must be base type")
static bool isAncestor(Block *block, Block *other)
Definition LayerSink.cpp:57
static scf::IfOp createOrReuseIf(OpBuilder &builder, Value condition, bool withElse)
Create a new scf.if operation with the given builder, or reuse a previous scf.if if the builder's ins...
static Location getLoc(DefSlot slot)
Definition Mem2Reg.cpp:216
static Block * getBodyBlock(FModuleLike mod)
create(data_type, value)
Definition hw.py:441
create(data_type, value)
Definition hw.py:433
Definition arc.py:1
OS & operator<<(OS &os, const InnerSymTarget &target)
Printing InnerSymTarget's.
The InstanceGraph op interface, see InstanceGraphInterface.td for more details.
int run(Type[Generator] generator=CppGenerator, cmdline_args=sys.argv)
Definition codegen.py:879
Definition hw.py:1
write(addr, data)
Definition xrt_cosim.py:30
read(addr)
Definition xrt_cosim.py:23